diff --git a/Cargo.lock b/Cargo.lock index 1befa39f..8bad56c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -851,10 +851,11 @@ dependencies = [ [[package]] name = "craft-mesh" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +source = "git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a#70e562aa88436b6b79a997215b4fa4f6a6b1838a" dependencies = [ - "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52)", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a)", "miniz_oxide 0.9.1", + "serde_json", ] [[package]] @@ -970,7 +971,7 @@ dependencies = [ [[package]] name = "craft-zip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=b952ca0231867c8ad6749ac44cab5fc903c3ad52#b952ca0231867c8ad6749ac44cab5fc903c3ad52" +source = "git+https://github.com/storytold/craft-libs?rev=70e562aa88436b6b79a997215b4fa4f6a6b1838a#70e562aa88436b6b79a997215b4fa4f6a6b1838a" dependencies = [ "flate2", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 2f7e212e..983ec031 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,7 +73,7 @@ craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774 # Isolated aligned writer; existing archive readers retain their pin and behavior. craft-zip-usdz = { package = "craft-zip", git = "https://github.com/storytold/craft-libs", rev = "5631e99fe126cffb74c673eb458db04299f2bb9b" } craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } -craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "b952ca0231867c8ad6749ac44cab5fc903c3ad52", default-features = false, features = ["stl", "ply", "fbx", "obj"] } +craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "70e562aa88436b6b79a997215b4fa4f6a6b1838a", default-features = false, features = ["stl", "ply", "fbx", "obj", "gltf"] } craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" } # Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs). craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] } diff --git a/README.md b/README.md index dc354a99..345c32c1 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ The full list of what's in it is in [`docs/features.md`](docs/features.md). git clone https://github.com/storytold/texturecraft cd texturecraft -cargo run --release -p texturecraft # desktop app (opens a sample project) +cargo run --release -p texturecraft # desktop app (starts with no project) cargo run --release -p texturecraft -- model.glb # a new project from a mesh cargo run --release -p texturecraft -- --control 7878 # + JSON control channel cargo run --release -p texturecraft-cli -- mcp # MCP server (stdio) @@ -157,8 +157,8 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with a baked sample project and a start window (new project, open, recent projects); **File ▸ New project** starts -from your own mesh file and a project template (UVs are generated if it has none). +You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). +**File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none. Japanese, Chinese, Korean and Arabic interface text uses the fonts of [storytold/craft-fonts](https://github.com/storytold/craft-fonts) where it has them, an optional diff --git a/apps/texturecraft-web/src/web.rs b/apps/texturecraft-web/src/web.rs index bc1372a5..7740db12 100644 --- a/apps/texturecraft-web/src/web.rs +++ b/apps/texturecraft-web/src/web.rs @@ -40,9 +40,11 @@ pub fn start() { } async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { - // The WebAssembly has downloaded and compiled when this runs. - step(0.5, "Preparing the sample project…").await; - let session = initial_session()?; + // The WebAssembly has downloaded and compiled when this runs + step(0.5, "Preparing the app…").await; + + // The app starts with no project, like File > Close + let session = Session::closed().map_err(|e| e.to_string())?; step(0.8, "Starting the renderer…").await; let mut options = eframe::WebOptions::default(); if query().contains("webgl") @@ -50,13 +52,13 @@ async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> { { create.instance_descriptor.backends = eframe::wgpu::Backends::GL; } + eframe::WebRunner::new() .start( canvas, options, Box::new(|cc| { let mut app = TextureCraftApp::new(cc, session); - app.ui.windows.start = app.ui.prefs.start_window; if let Some(rs) = &cc.wgpu_render_state { let backend = rs.adapter.get_info().backend; log::info!("TextureCraft: wgpu backend {backend:?}"); @@ -137,18 +139,6 @@ fn guard_unsaved_changes() { on_unload.forget(); } -/// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are -/// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a -/// fast desktop CPU, 128 ~7.5 s). -fn initial_session() -> Result { - texturecraft_engine::sample_session(1024, 128) - .or_else(|e| { - log::warn!("sample project failed: {e}"); - Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 1024) - }) - .map_err(|e| e.to_string()) -} - fn query() -> String { web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default() } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 2deac956..d05b6cad 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -38,6 +38,7 @@ fn version() -> String { struct Args { file: Option, control: Option, + /// With `--control`: start with an empty material ball instead of the sample project empty: bool, gpu: Option, power_pref: Option, @@ -84,21 +85,34 @@ fn parse_args_from>(it: I) -> Result } fn initial_session(args: &Args) -> Session { - if let Some(f) = &args.file { - match texturecraft_engine::file_cmds::open_path(f) { - Ok(s) => return s, - Err(e) => eprintln!("texturecraft: could not open {f}: {e}"), + if let Some(path) = &args.file { + match texturecraft_engine::file_cmds::open_path(path) { + Ok(session) => return session, + Err(error) => eprintln!("texturecraft: could not open {path}: {error}"), } } - if !args.empty - && let Ok(s) = texturecraft_engine::sample_session(2048, 512) - { - return s; + + // Control runs retain their sample project; interactive runs start empty + if args.control.is_some() { + if !args.empty + && let Ok(session) = texturecraft_engine::sample_session(2048, 512) + { + return session; + } + + return match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { + Ok(session) => session, + Err(error) => { + eprintln!("texturecraft: {error}"); + std::process::exit(1); + } + }; } - match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) { - Ok(s) => s, - Err(e) => { - eprintln!("texturecraft: {e}"); + + match Session::closed() { + Ok(session) => session, + Err(error) => { + eprintln!("texturecraft: {error}"); std::process::exit(1); } } @@ -176,7 +190,7 @@ fn checks_for_updates_at_start(control: Option) -> bool { } fn main() { - // Windows: the update helper is a copy of this program started with `--finish-update`. + // Windows: the update helper is a copy of this program started with `--finish-update` #[cfg(windows)] if let Some(result) = craft_update::self_update::finish(&texturecraft_ui_egui::UPDATE_APP, &std::env::args_os().skip(1).collect::>()) { std::process::exit(i32::from(result.is_err())); @@ -189,14 +203,16 @@ fn main() { std::process::exit(2); } }; + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); - let prev = std::panic::take_hook(); + let previous_hook = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); - prev(info); + previous_hook(info); })); + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); @@ -220,9 +236,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app - let start = args.file.is_none() && control.is_none(); - let r = eframe::run_native( + let result = eframe::run_native( APP_NAME, options, Box::new(move |cc| { @@ -230,7 +244,8 @@ fn main() { if let Some(w) = cc.winit_window() { set_taskbar_icon(w); } - // winit's Quit ends the process without asking; this menu's asks like the close button. + + // winit's Quit ends the process without asking; this menu's asks like the close button #[cfg(target_os = "macos")] if let Err(e) = craft_menu::mac::install_app_menu(&cc.egui_ctx, APP_NAME) { log::warn!("the app menu could not be installed: {e}"); @@ -238,7 +253,6 @@ fn main() { let window_frame = window_frame::service(cc, matches!(title_bar, TitleBar::App(_))); let mut app = TextureCraftApp::new(cc, session); app.title_bar = title_bar; - app.ui.windows.start = start && app.ui.prefs.start_window; app.set_startup_update_check(checks_for_updates_at_start(control)); if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); @@ -251,7 +265,7 @@ fn main() { })) }), ); - if let Err(e) = r { + if let Err(e) = result { fatal(&e.to_string(), true); std::process::exit(1); } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 438a4f25..a5b3c761 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -101,6 +101,11 @@ impl Headless { matches!(self.fs, Filesystem::TrustedLocal) } + /// Commands that act on the project refuse after `file.close`, as in the app + fn require_project(&self) -> Result<(), AutomationError> { + if self.session.project_open { Ok(()) } else { Err(bad("no project is open")) } + } + fn read(&self, path: &str) -> Result, AutomationError> { match &self.fs { Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root ")), @@ -205,12 +210,15 @@ impl Headless { /// Add a high-definition mesh for baking from `path` (or, with `cage`, set the bake cage). pub fn add_bake_mesh(&mut self, path: &str, cage: bool) -> Result { + self.require_project()?; + let f = self.read_mesh(path)?; Ok(self.session.add_bake_mesh(f, cage)?) } /// Reimport the mesh from `path`, or from the project's own copy, keeping the project. pub fn reimport_mesh(&mut self, path: Option<&str>, preserve_strokes: bool) -> Result { + self.require_project()?; let file = path.map(|p| self.read_mesh(p)).transpose()?; Ok(self.session.reimport_mesh(file, preserve_strokes)?) } @@ -218,6 +226,7 @@ impl Headless { /// Export the working mesh to `path` (obj, glb, usda, usdc or usdz, from `format` or the /// extension); obj writes its .mtl and textures, usda and usdc their textures, next to it. pub fn export_mesh(&mut self, path: &str, format: Option<&str>) -> Result { + self.require_project()?; let out = self.session.mesh_export(path, format)?; let dir = Path::new(&out.path).parent().and_then(|d| d.to_str()).filter(|d| !d.is_empty()).unwrap_or("."); self.create_dir_all(dir)?; @@ -233,12 +242,14 @@ impl Headless { /// Import an image file as a project resource (for `layer.add.image`, `tool.stencil`). pub fn import_resource(&mut self, path: &str) -> Result { + self.require_project()?; let bytes = self.read(path)?; Ok(json!({ "name": self.session.import_resource_bytes(path, bytes)? })) } /// Save a layer (default: the selected one) as a smart material file (`.tcmat`). pub fn material_save(&mut self, p: &Value) -> Result { + self.require_project()?; let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?; let s = &self.session; let id = match p.get("layer").and_then(Value::as_u64) { @@ -258,12 +269,14 @@ impl Headless { /// Add a smart material from a `.tcmat` file above the selection. pub fn material_load(&mut self, path: &str) -> Result { + self.require_project()?; let bytes = self.read(path)?; Ok(json!({ "layer": self.session.add_smart_material_bytes(&bytes)?.0 })) } /// Save as `.tcraft` to `path`, or to the project's own file. pub fn save(&mut self, path: Option<&str>) -> Result { + self.require_project()?; let target = match path.or(self.session.path.as_deref()) { Some(p) if ext_of(p) == PROJECT_EXT => p.to_string(), Some(p) => format!("{p}.{PROJECT_EXT}"), @@ -277,6 +290,7 @@ impl Headless { /// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…). pub fn export(&mut self, p: &Value) -> Result { + self.require_project()?; let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?; let opts = file_cmds::export_options(&self.session, p, "textures.export")?; let n = self.session.set_count(); @@ -299,39 +313,43 @@ impl Headless { /// Render the session to PNG. The viewport needs a GPU adapter; path tracing (`samples`) /// runs on the GPU when it has compute shaders and falls back to the CPU. - pub fn render_png(&mut self, o: &RenderOptions) -> Result { - let s = &self.session; - let kind = match o.view.as_deref().unwrap_or("3d") { + pub fn render_png(&mut self, options: &RenderOptions) -> Result { + self.require_project()?; + + let session = &self.session; + let kind = match options.view.as_deref().unwrap_or("3d") { "3d" => ViewKind::Scene, - "2d" | "uv" => ViewKind::Uv { ts: s.ts(), zoom: 1.0, pan: [0.0, 0.0] }, + "2d" | "uv" => ViewKind::Uv { ts: session.ts(), zoom: 1.0, pan: [0.0, 0.0] }, other => return Err(bad(format!("unknown view `{other}` (3d, 2d or uv)"))), }; - let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE }; - let side = |v: Option, d: f32| { + let max_side = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE }; + let checked_side = |v: Option, d: f32| { let v = v.unwrap_or(d.round() as u32); - if (16..=max).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max} pixels"))) } + if (16..=max_side).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max_side} pixels"))) } }; - let size = [side(o.width, s.viewport.x)?, side(o.height, s.viewport.y)?]; - let mut camera = s.camera; - for (v, slot, lim) in [(o.yaw, &mut camera.yaw, 1e6), (o.pitch, &mut camera.pitch, 89.0)] { + let size = [checked_side(options.width, session.viewport.x)?, checked_side(options.height, session.viewport.y)?]; + let mut camera = session.camera; + for (v, slot, max_degrees) in [(options.yaw, &mut camera.yaw, 1e6), (options.pitch, &mut camera.pitch, 89.0)] { if let Some(v) = v { if !v.is_finite() { return Err(bad("camera angles must be finite")); } - *slot = v.clamp(-lim, lim).to_radians(); + + *slot = v.clamp(-max_degrees, max_degrees).to_radians(); } } - if let Some(samples) = o.samples { - if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || o.view.as_deref().is_some_and(|v| v != "3d") { + if let Some(samples) = options.samples { + if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || options.view.as_deref().is_some_and(|v| v != "3d") { return Err(bad(format!("path tracing renders the 3D view with 1 to {MAX_TRACE_SAMPLES} samples"))); } - let settings = texturecraft_render::trace::TraceSettings { bounces: o.bounces.unwrap_or(6).clamp(1, 32) }; + + let settings = texturecraft_render::trace::TraceSettings { bounces: options.bounces.unwrap_or(6).clamp(1, 32) }; let mut traced = None; let mut by = "CPU path tracer".to_string(); - if !o.cpu + if !options.cpu && let Ok(gpu) = self.gpu.get_or_insert_with(Gpu::new) { - // Last-resort guard, as for viewport renders below. + // Last-resort guard, as for viewport renders below let session = &mut self.session; match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.path_trace(session, size, camera, samples, &settings))) { Ok(Ok(px)) => { @@ -355,11 +373,13 @@ impl Headless { } return Ok(Rendered { width: w, height: h, png, by }); } + let gpu = match self.gpu.get_or_insert_with(Gpu::new) { Ok(g) => g, Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))), }; - // Last-resort guard: wgpu panics on device errors; drop the device and report instead. + + // Last-resort guard: wgpu panics on device errors; drop the device and report instead let session = &mut self.session; let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.render(session, kind, size, camera))); let (w, h, rgba) = match out { @@ -396,6 +416,25 @@ pub fn batch_reply(results: Vec, failed: Option<(usize, &str, String)>) - mod tests { use super::*; + #[test] + fn closed_session_rejects_bake_mesh_before_reading_it() { + let mut client = Headless::new(Session::closed().unwrap(), Filesystem::Denied); + + let error = client.add_bake_mesh("missing.obj", false).unwrap_err(); + + assert!(error.to_string().contains("no project is open"), "{error}"); + } + + #[test] + fn closed_session_rejects_render_before_view_validation() { + let mut client = Headless::new(Session::closed().unwrap(), Filesystem::Denied); + let options = RenderOptions { view: Some("unknown".into()), ..RenderOptions::default() }; + + let error = client.render_png(&options).err().unwrap(); + + assert!(error.to_string().contains("no project is open"), "{error}"); + } + #[test] fn fresh_headless_session_loads_saved_brushes() { let brush_dir = std::env::temp_dir().join(format!("tc-headless-brush-{}", std::process::id())); diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 1061db2d..a1f18ab9 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -238,7 +238,7 @@ mod tests { for id in ["file.open", "file.new", "file.save", "file.saveAs", "file.saveCopy", "file.exportTextures"] { assert!(authorize_command(id, &json!({})).is_err(), "{id}"); } - for id in ["resource.import", "material.save", "material.load", "anything.new"] { + for id in ["resource.import", "material.save", "material.load", "mask.smart.create", "mask.smart.apply", "anything.new"] { assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}"); assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}"); } diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs index e9f5c682..3faa0c39 100644 --- a/crates/automation/tests/agent_tasks.rs +++ b/crates/automation/tests/agent_tasks.rs @@ -430,13 +430,15 @@ async fn mesh_files_export_bake_and_reimport_in_the_workspace() { assert!(!textures.is_empty() && textures.iter().all(|t| base.join(t.as_str().unwrap()).is_file()), "{usda}"); assert_eq!(tool(&c, "mesh_export", json!({"path": "out/cube.glb"})).await["path"], "out/cube.glb"); assert!(base.join("out/cube.usda").is_file() && base.join("out/cube.glb").is_file()); - // The loose usda arrives packaged with its textures. + + // The loose usda arrives packaged with its textures let high = tool(&c, "bake_mesh_add", json!({"path": "out/cube.usda"})).await; assert_eq!(high["name"], "cube.usdz", "{high}"); let cage = tool(&c, "bake_mesh_add", json!({"path": "out/cube.glb", "cage": true})).await; assert_eq!(cage["meshes"]["cage"]["name"], "cube.glb", "{cage}"); assert_eq!(inspect(&c).await["bakeMeshes"]["highPoly"][0]["name"], "cube.usdz"); - // A built-in mesh has no file to re-read; a file does. + + // A built-in mesh has no file to re-read; a file does assert!(tool_err(&c, "mesh_reimport", json!({})).await.contains("built-in")); tool(&c, "mesh_reimport", json!({"path": "out/cube.glb", "preserveStrokes": true})).await; assert_eq!(inspect(&c).await["mesh"]["source"], "mesh.glb"); diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 81868e66..4a2187ed 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -143,11 +143,7 @@ impl StackKey { let mut referenced_images = BTreeSet::new(); if !images.is_empty() { let mut record_image_reference = |source: &Source| { - if let Source::Image { name, .. } = source - && let Some((name, _)) = images.get_key_value(name) - { - referenced_images.insert(name); - } + referenced_images.extend(source.images().into_iter().filter_map(|name| images.get_key_value(name)).map(|(name, _)| name)); }; for layer in render_tree.iter().filter_map(|id| project.layers.get(id)) { if let LayerKind::Fill(fill) = &layer.kind { diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 7bea1c3d..8bb323e9 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -21,7 +21,8 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois use crate::below::{Band, BelowCache, Level, StackKey}; use crate::curvature_sizes::CurvatureSizes; use crate::held_fields::HeldFields; -use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise}; +use crate::pattern::{Coords, decal_uv_symmetric, image_samples, pattern_pixels, procedural_in, world_noise}; +use crate::pattern_context::PatternContext; use crate::store::{BakedMaps, ImageStore, PixelStore, decode}; const NCH: usize = Channel::ALL.len(); @@ -72,6 +73,10 @@ impl Stencil { } } +/// The channel under which a clone or smudge stroke on a mask carries its mask values (the mask +/// has no channels of its own; any scalar channel works). +pub const MASK_CHANNEL: Channel = Channel::Roughness; + /// The stroke being drawn, shown before it is committed. #[derive(Clone, Debug)] pub struct StrokePreview { @@ -89,6 +94,8 @@ pub struct StrokePreview { pub stencil: Option, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). pub carried: BTreeMap, + /// Mask coverage sampled by a mask pickup. + pub carried_mask: Option, } /// Everything the evaluator reads. @@ -118,6 +125,11 @@ impl Inputs<'_> { fn tile_res(&self) -> u32 { self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1)) } + + /// The current UV tile can occupy only part of its atlas block + fn tile_res_at(&self, x: u32, y: u32) -> u32 { + ((self.tile_res() as f32 * self.block_scales.at(x, y)).round() as u32).max(1) + } } /// The composited channels of one texture set. @@ -1269,8 +1281,8 @@ struct Texel<'a, 'b> { stroke: f32, /// `eval` stops when it reaches this layer. stop: Option, - /// Stack values recorded by the anchor points evaluated so far. - anchors: Vec<(LayerId, Acc)>, + /// Stack values recorded by the anchor points evaluated so far; true marks a mask anchor (gray, not channel values). + anchors: Vec<(LayerId, Acc, bool)>, /// Where `eval` takes layer masks and content from. tape: Tape<'b>, } @@ -1394,8 +1406,10 @@ impl<'a, 'b> Texel<'a, 'b> { /// position in the decal's frame (then sampled as UVs) and the decal's coverage. fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) { let c = self.coords(); + let (lo, hi) = self.inp.bounds; + let center = (lo + hi) * 0.5; match proj { - Projection::Decal(d) => match self.world().and_then(|p| decal_uv(d, p, c.nrm)) { + Projection::Decal(d) => match self.world().and_then(|p| decal_uv_symmetric(d, p, c.nrm, center)) { Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w), None => (c, &DECAL_UV, 0.0), }, @@ -1417,14 +1431,47 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } + /// The stack value anchor point `anchor` recorded for `channel` (the channel default for an + /// anchor not evaluated yet) + fn anchored(&self, anchor: LayerId, channel: Channel) -> [f32; 3] { + let values = self.anchors.iter().rev().find(|(id, ..)| *id == anchor).and_then(|(_, values, _)| values.get(channel.index()).copied()); + values.unwrap_or_else(|| channel.default_value()) + } + + /// Whether anchor point `anchor` sits in a mask, where every channel holds the mask's gray. + fn is_mask_anchor(&self, anchor: LayerId) -> bool { + self.anchors.iter().rev().find(|(id, ..)| *id == anchor).is_some_and(|(_, _, mask)| *mask) + } + /// The value `source` gives this texel through `projection`, read as a channel of `kind` fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { match source { Source::Uniform(value) => *value, - Source::Procedural { pattern, low, high } => { + + Source::Anchor { anchor, channel, ramp } if kind == ChannelKind::Color && !ramp.is_empty() => { + let value = self.anchored(*anchor, *channel); + + // Signed values (height) span -1..1; a mask anchor's gray already spans 0..1 in every channel + let signed = channel.kind() == ChannelKind::Signed && !self.is_mask_anchor(*anchor); + let lightness = if signed { lum(value) * 0.5 + 0.5 } else { lum(value) }; + texturecraft_core::gradient(ramp, lightness).unwrap_or_default() + } + Source::Procedural { pattern, low, high, ramp } => { let (coords, projection, _) = self.projected(projection); - let amount = procedural(pattern, projection, &coords); - mix3(*low, *high, amount) + let pixels = if pattern.resolution.can_reduce() { + let uv_tile = self.inp.tile_res_at(self.x, self.y); + let texture_set = self.inp.project.texture_set(self.inp.ts).map_or(uv_tile, |set| set.resolution); + pattern_pixels(pattern, uv_tile, texture_set) + } else { + None + }; + let amount = procedural_in(pattern, projection, &coords, &PatternContext { pixels, images: Some(self.inp.images) }); + + if kind == ChannelKind::Color && !ramp.is_empty() { + texturecraft_core::gradient(ramp, amount).unwrap_or_default() + } else { + mix3(*low, *high, amount) + } } Source::Image { name, normal_format } => { let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; @@ -1450,7 +1497,7 @@ impl<'a, 'b> Texel<'a, 'b> { ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], } } - Source::Anchor { anchor, channel } => self.anchor_value(*anchor, *channel, kind), + Source::Anchor { anchor, channel, .. } => self.anchor_value(*anchor, *channel, kind), } } @@ -1458,8 +1505,7 @@ impl<'a, 'b> Texel<'a, 'b> { /// where a scalar is needed). An anchor not evaluated yet (above this layer, hidden) reads the /// channel default. fn anchor_value(&self, anchor: LayerId, channel: Channel, kind: ChannelKind) -> [f32; 3] { - let value = self.anchors.iter().rev().find(|(id, _)| *id == anchor).and_then(|(_, channels)| channels.get(channel.index()).copied()); - let value = value.unwrap_or_else(|| channel.default_value()); + let value = self.anchored(anchor, channel); let needs_gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); if needs_gray { [lum(value); 3] } else { value } } @@ -1615,7 +1661,9 @@ impl<'a, 'b> Texel<'a, 'b> { painted *= 1.0 - stroke; coverage *= 1.0 - stroke; } else { - painted = preview.mask_value * stroke + painted * (1.0 - stroke); + // Clone and smudge show the values they carry instead of the mask gray + let deposited = preview.carried_mask.as_ref().map_or(preview.mask_value, |carried| from_u16(carried.get(self.x, self.y)[0])); + painted = deposited * stroke + painted * (1.0 - stroke); coverage = stroke + coverage * (1.0 - stroke); } } @@ -1655,7 +1703,7 @@ impl<'a, 'b> Texel<'a, 'b> { } // Every channel of a mask anchor reads the mask's gray - EffectKind::Anchor => self.anchors.push((effect.id, [[value.clamp(0.0, 1.0); 3]; NCH])), + EffectKind::Anchor => self.anchors.push((effect.id, [[value.clamp(0.0, 1.0); 3]; NCH], true)), // Content-only effects EffectKind::Material(_) => {} @@ -1671,15 +1719,16 @@ impl<'a, 'b> Texel<'a, 'b> { if self.stop == Some(n.id) { return true; } + let m = self.tape_mask(n); match &n.content { - // A masked-out group still runs when it records anchors (they hold its inner - // stack) or may hold the stop layer. + // Masked-out groups still run when they record anchors or hold the stop layer Content::Group(children) if m > 0.0 || n.has_anchor || self.stop.is_some() => { let mut inner = *acc; if self.eval(children, &mut inner) { return true; } + if m > 0.0 { mix_group(acc, &inner, &n.chans, m); } @@ -1691,7 +1740,8 @@ impl<'a, 'b> Texel<'a, 'b> { apply(acc, c, v, cov, m); } } - // Anchors inside the content stack: the stack with the content cut there. + + // Anchors inside the content stack read the stack cut at that point for (a, cut) in &n.anchors { let rec = match (cut, before) { (Some(k), Some(mut b)) => { @@ -1704,14 +1754,14 @@ impl<'a, 'b> Texel<'a, 'b> { } _ => *acc, }; - self.anchors.push((*a, rec)); + self.anchors.push((*a, rec, false)); } continue; } _ => {} } for (a, _) in &n.anchors { - self.anchors.push((*a, *acc)); + self.anchors.push((*a, *acc, false)); } } false @@ -2325,6 +2375,7 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) if (dmap.width, dmap.height) != (w, h) { return written; } + let (nx, ny) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64); let mut set = std::collections::BTreeSet::new(); for &(tx, ty) in tiles { @@ -2341,8 +2392,8 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) for img in out.channels.values_mut() { let comps = img.comps(); let src: &TileImage = img; - // Padding writes only uncovered texels and reads only covered ones, so tiles pad - // independently (in parallel) from the unpadded image. + + // Each tile pads from the original image, so parallel writes stay independent let padded: Vec<((u32, u32), Vec)> = set .par_iter() .filter_map(|&(tx, ty)| { @@ -2353,10 +2404,12 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) if x >= w || y >= h { continue; } + let Some((sx, sy)) = dmap.source(x, y) else { continue }; if (sx, sy) == (x, y) { continue; } + let v = src.get(sx, sy); let d = data.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec)); let o = (ly * TILE + lx) as usize * comps; @@ -2376,7 +2429,41 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) written } +/// The layer mask over the whole texture set as `0..=1` values, row by row from the top (the +/// orientation of the exported maps), `gbuf.width × gbuf.height` of them; black outside the mesh +/// Returns None without an enabled mask +pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option> { + let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; + let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let coordinates = all_tiles(width, height); + + // A hidden layer's mask is left out of the stack's preparation + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + + let fields = neighbourhood_fields(inputs, &channels, &coordinates); + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut output = vec![0.0f32; width_usize * height as usize]; + + // Write each tile into disjoint atlas rows without temporary tile buffers + output.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, (tile_x, tile_y as u32), 0..TILE_AREA) { + let x = tile_x as usize * tile_side + offset % tile_side; + if x < width_usize + && let Some(destination) = rows.get_mut((offset / tile_side) * width_usize + x) + { + *destination = value; + } + } + } + }); + Some(output) +} + /// The layer mask as a square grayscale image, using nearest texels and black outside the mesh +/// Keep preview tiles at 8 bits instead of retaining the export's full float atlas /// Returns None without an enabled mask pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?; @@ -2388,27 +2475,35 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); let fields = neighbourhood_fields(inputs, &channels, &coordinates); - let tiles: HashMap<(u32, u32), Vec> = coordinates - .par_iter() - .map(|&tile| { - let mut values = vec![0u8; TILE_AREA]; - for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) { - if let Some(destination) = values.get_mut(offset) { + let width_usize = width as usize; + let tile_side = TILE as usize; + let mut atlas = vec![0u8; width_usize * height as usize]; + + // Write each tile row into disjoint atlas rows + atlas.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| { + for tile_x in 0..width.div_ceil(TILE) { + for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, (tile_x, tile_y as u32), 0..TILE_AREA) { + let x = tile_x as usize * tile_side + offset % tile_side; + if x < width_usize + && let Some(destination) = rows.get_mut((offset / tile_side) * width_usize + x) + { *destination = (value * 255.0 + 0.5) as u8; } } - (tile, values) - }) - .collect(); + } + }); let size = size.max(1); + if width == size && height == size { + return Some(atlas); + } + let mut output = vec![0u8; (size * size) as usize]; for y in 0..size { for x in 0..size { let sample_x = (u64::from(x) * u64::from(width) / u64::from(size)) as u32; let sample_y = (u64::from(y) * u64::from(height) / u64::from(size)) as u32; - if let Some(tile) = tiles.get(&(sample_x / TILE, sample_y / TILE)) - && let Some(value) = tile.get(((sample_y % TILE) * TILE + sample_x % TILE) as usize) + if let Some(value) = atlas.get(sample_y as usize * width_usize + sample_x as usize) && let Some(destination) = output.get_mut((y * size + x) as usize) { *destination = *value; @@ -2418,6 +2513,41 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option> { Some(output) } +/// The layer mask as one-component values at the texture set's full resolution over `tiles` +/// (uncovered texels read zero). Clone and smudge read it. Unlike [`mask_image`] it also reads a +/// disabled mask; None when the layer has no mask. +pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option { + let mut image = TileImage::new(inputs.gbuf.width, inputs.gbuf.height, 1); + mask_values_into(inputs, id, tiles, &mut image)?; + Some(image) +} + +/// Evaluate requested tiles directly into the stroke's mask image. +pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> { + let mask = layer_mask(inputs.project, id)?; + let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list(); + prepare_mask_curvature_sizes(inputs, std::iter::once(mask)); + + let fields = neighbourhood_fields(inputs, &channels, tiles); + let computed: Vec<((u32, u32), Vec)> = tiles + .par_iter() + .map(|&tile| { + let mut values = vec![0u16; TILE_AREA]; + for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) { + if let Some(destination) = values.get_mut(offset) { + *destination = to_u16(value.clamp(0.0, 1.0)); + } + } + (tile, values) + }) + .collect(); + + for ((tx, ty), values) in computed { + image.set_tile(tx, ty, Some(std::sync::Arc::new(values))); + } + Some(()) +} + /// Mask values at texture-set coordinates, in request order; None without an enabled mask /// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option> { @@ -2701,6 +2831,39 @@ mod tests { out } + #[test] + fn procedural_resolution_uses_each_uv_tiles_scale() { + let mut fixture = fixture(); + let set = &mut fixture.project.texture_sets[0]; + set.uv_tiles = vec![1001, 1002]; + set.resolution = 64; + set.tile_resolutions.insert(1002, 32); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 64); + let block_scales = set.block_scales(); + let images = ImageStore::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales, + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + + assert_eq!(inputs.tile_res_at(0, 0), 64); + assert_eq!(inputs.tile_res_at(64, 0), 32); + + let mut pattern = Procedural::new(ProceduralKind::Checker); + pattern.resolution.factor = -1; + + assert_eq!(pattern_pixels(&pattern, inputs.tile_res_at(0, 0), 64), Some(32)); + assert_eq!(pattern_pixels(&pattern, inputs.tile_res_at(64, 0), 64), Some(16)); + } + fn fill_layer(p: &mut Project, color: [f32; 3], rough: f32) -> LayerId { let id = p.alloc_id(); let mut fill = Fill::default(); @@ -2823,14 +2986,15 @@ mod tests { let id = f.project.alloc_id(); let l = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]); f.project.insert_layer(0, l, None, false).unwrap(); - // Half-covered red texel: premul (0.5, 0, 0), coverage 0.5. + + // Half-covered red texel has premultiplied color and 0.5 coverage let img = f.pixels.layer_mut(id, Channel::BaseColor, (64, 64)); img.set(3, 3, &[to_u16(0.5), 0, 0, to_u16(0.5)]); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 3, 3), [0.75, 0.25, 0.25])); assert!(close(out.value(Channel::BaseColor, 4, 3), [0.5; 3])); - // A live stroke painting blue at full alpha on texel (4, 3). + // A live stroke paints blue at full alpha on texel (4, 3) let mut alpha = TileImage::new(64, 64, 1); alpha.set(4, 3, &[to_u16(1.0)]); let pv = StrokePreview { @@ -2842,11 +3006,12 @@ mod tests { mask_value: 1.0, stencil: None, carried: BTreeMap::new(), + carried_mask: None, }; let out = run(&f, Some(&pv)); assert!(close(out.value(Channel::BaseColor, 4, 3), [0.0, 0.0, 1.0])); - // A black mask hides the layer. + // A black mask hides the layer f.project.layer_mut(id).unwrap().mask = Some(Mask::new(MaskBackground::Black)); let out = run(&f, None); assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3])); @@ -2861,7 +3026,7 @@ mod tests { let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( eid, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, )); f.project.layer_mut(id).unwrap().mask = Some(mask); let out = run(&f, None); @@ -2911,7 +3076,7 @@ mod tests { let pattern = Procedural::new(ProceduralKind::Checker); mask.effects.push(Effect::new( effect, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, )); fixture.project.layer_mut(layer).unwrap().mask = Some(mask); @@ -2928,6 +3093,51 @@ mod tests { assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none()); } + #[test] + fn mask_image_resamples_a_non_square_atlas() { + let mut fixture = fixture(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 64); + fixture.project.texture_sets[0].resolution = 128; + let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); + let effect = fixture.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new( + effect, + EffectKind::Fill { + source: Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + projection: Projection::default(), + }, + )); + fixture.project.layer_mut(layer).unwrap().mask = Some(mask); + let images = ImageStore::default(); + let inputs = Inputs { + project: &fixture.project, + ts: 0, + mesh: &fixture.mesh, + gbuf: &fixture.gbuf, + pixels: &fixture.pixels, + baked: &fixture.baked, + block_scales: fixture.project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: fixture.mesh.bounds(), + }; + let sampled_texels: Vec<_> = (0..64).flat_map(|y| (0..64).map(move |x| (x * 2, y))).collect(); + + let preview = mask_image(&inputs, layer, 64).unwrap(); + let sparse = mask_at(&inputs, layer, &sampled_texels).unwrap(); + let atlas = mask_texels(&inputs, layer).unwrap(); + + assert_eq!(preview.len(), 64 * 64); + assert_eq!(atlas.len(), 128 * 64); + assert!(preview.contains(&0)); + assert!(preview.contains(&255)); + for ((&preview_value, &sparse_value), &(x, y)) in preview.iter().zip(&sparse).zip(&sampled_texels) { + assert!((f32::from(preview_value) / 255.0 - sparse_value).abs() <= 0.5 / 255.0 + 1e-6); + assert!((atlas[(y * 128 + x) as usize] - sparse_value).abs() <= 1e-6); + } + } + #[test] fn mask_at_ignores_out_of_range_texels_before_resampling_paint() { let mut fixture = fixture(); @@ -2953,13 +3163,16 @@ mod tests { let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0); let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind else { panic!("expected a fill layer") }; - fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + fill.sources.insert( + Channel::BaseColor, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + ); let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor); let upper = fill_layer(&mut fixture.project, [1.0; 3], 1.0); let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(Effect::new( fixture.project.alloc_id(), - EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor }, projection: Projection::default() }, + EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }, projection: Projection::default() }, )); fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone()); let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); @@ -2981,7 +3194,7 @@ mod tests { fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128); fixture.project.texture_sets[0].resolution = 128; let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0); - let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect(); let mut masked = |filters: &[Filter]| { @@ -3006,7 +3219,10 @@ mod tests { let layer = fill_layer(&mut fixture.project, [0.0; 3], 1.0); let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(layer).unwrap().kind else { panic!("expected a fill layer") }; - fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + fill.sources.insert( + Channel::BaseColor, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + ); let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 }; let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp)); let row = |fixture: &Fixture| -> Vec { @@ -3101,7 +3317,7 @@ mod tests { fn generator_blur_softens_only_the_generator_not_the_stack_below() { let (mut fixture, layer) = ridge_fixture(100); let mut row_with = |blur: f32| { - let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }); let mut generator = ridge_generator(); generator.global.blur = blur; @@ -3235,7 +3451,7 @@ mod tests { let (e1, e2) = (f.project.alloc_id(), f.project.alloc_id()); mask.effects.push(Effect::new( e1, - EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() }, + EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() }, )); f.project.layer_mut(id).unwrap().mask = Some(mask.clone()); let hard: Vec = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect(); @@ -3321,7 +3537,10 @@ soft {soft:?}" let mut f = fixture(); let id = f.project.alloc_id(); let mut fill = Fill::default(); - fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + fill.sources.insert( + Channel::Roughness, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + ); f.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap(); let row = |f: &Fixture| { let out = run(f, None); @@ -3337,7 +3556,7 @@ soft {soft:?}" #[test] fn high_pass_edge_detect_directional_warp_grayscale_and_normal_invert() { - // Uniform content: high pass is mid gray (0 for height), edge detect black. + // Uniform content gives mid gray high pass and black edge detection let mut f = fixture(); let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2); let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0 })); @@ -3347,11 +3566,15 @@ soft {soft:?}" f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != hp); content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 })); assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.0; 3])); - // A checker: its borders light up, the middle of its cells stays black. + + // A checker's borders light up while cell interiors stay black let mut f = fixture(); let id = f.project.alloc_id(); let mut fill = Fill::default(); - fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + fill.sources.insert( + Channel::Roughness, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + ); f.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap(); let plain = run(&f, None); let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 })); @@ -3364,12 +3587,14 @@ soft {soft:?}" let warped = run(&f, None); let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2)); assert!(differs, "the warp moves the checker"); - // Point filters. + + // Point filters assert!(close(Filter::Grayscale.point(ChannelKind::Color, [1.0, 0.0, 0.0]).unwrap(), [lum([1.0, 0.0, 0.0]); 3])); assert_eq!(Filter::Grayscale.point(ChannelKind::Scalar, [0.3; 3]), Some([0.3; 3])); assert_eq!(Filter::NormalInvert.point(ChannelKind::NormalMap, [0.5, 0.25, 1.0]), Some([0.5, 0.75, 1.0])); assert_eq!(Filter::NormalInvert.point(ChannelKind::Color, [0.5, 0.25, 1.0]), Some([0.5, 0.25, 1.0])); - // Replace color: near colors shift (keeping their offset), far ones and scalars stay. + + // Replace color shifts near colors while far colors and scalars stay let rc = Filter::ReplaceColor { from: [0.8, 0.1, 0.1], to: [0.1, 0.1, 0.8], tolerance: 0.1, softness: 0.1 }; assert!(close(rc.point(ChannelKind::Color, [0.85, 0.1, 0.1]).unwrap(), [0.15, 0.1, 0.8])); assert!(close(rc.point(ChannelKind::Color, [0.1, 0.8, 0.1]).unwrap(), [0.1, 0.8, 0.1])); @@ -3383,7 +3608,10 @@ soft {soft:?}" let checker = |f: &mut Fixture| { let id = f.project.alloc_id(); let mut fill = Fill::default(); - fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }); + fill.sources.insert( + Channel::Roughness, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, + ); f.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap(); id }; @@ -3394,20 +3622,23 @@ soft {soft:?}" let mut f = fixture(); let id = checker(&mut f); let plain = values(&f); - // Bevel: never above the shape, and its edges become ramps. + + // Bevel stays below the shape and turns edges into ramps let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Bevel { width: 128.0 })); let bevel = values(&f); let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.05 && **x < 0.95).count(); assert!(bevel.iter().zip(&plain).all(|(b, p)| *b <= p + 1e-4 && *b >= 0.0), "a bevel only lowers values"); assert!(mids(&bevel) > mids(&plain) + 64, "{} vs {}", mids(&bevel), mids(&plain)); - // Mosaic: fewer changes from one texel to the next. + + // Mosaic reduces changes between adjacent texels f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != fx); let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 768.0 })); let mosaic = values(&f); let steps = |v: &[f32]| v.windows(2).filter(|w| (w[0] - w[1]).abs() > 0.01).count(); assert!(steps(&mosaic) < steps(&plain), "{} vs {}", steps(&mosaic), steps(&plain)); assert!(mosaic.iter().all(|v| (0.0..=1.0).contains(v))); - // Glow on uniform content adds its own blur: 0.2 + 0.2. + + // Glow on uniform content adds its own blur f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != fx); let mut f = fixture(); let id = fill_layer(&mut f.project, [0.1; 3], 0.2); @@ -3426,7 +3657,8 @@ soft {soft:?}" (out.value(Channel::BaseColor, 30, 30), out.value(Channel::Roughness, 30, 30)) }; let n = primitives::plane(2.0, 2).normals[0]; - // Facing the light: ambient + light = 1 (unchanged); facing away: ambient only. + + // Facing the light adds illumination; facing away keeps ambient only let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 }); assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}"); let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 }); @@ -3439,7 +3671,8 @@ soft {soft:?}" #[test] fn geometry_masks_show_layers_on_chosen_parts_only() { let mut f = fixture(); - // Two parts of the plane's one material: the first half of its triangles and the rest. + + // The plane's material spans both triangle groups let n = f.mesh.indices.len() as u32 / 6 * 3; f.mesh.submeshes = vec![ texturecraft_geom::SubMesh { name: "Lid".into(), material: 0, start: 0, count: n }, @@ -3469,13 +3702,15 @@ soft {soft:?}" material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3])); content_fx(&mut f, id, EffectKind::Material(material)); let paint = content_fx(&mut f, id, EffectKind::Paint); - // Roughness 0.9 painted at half coverage (premultiplied). + + // Roughness 0.9 is painted at half coverage f.pixels.layer_mut(paint, Channel::Roughness, (64, 64)).set(3, 3, &[to_u16(0.45), to_u16(0.5)]); let out = run(&f, None); assert!(close(out.value(Channel::Roughness, 10, 10), [0.2; 3]), "the fill effect covers the empty paint layer"); assert!(close(out.value(Channel::Roughness, 3, 3), [0.55; 3]), "{:?}", out.value(Channel::Roughness, 3, 3)); assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]), "channels without a source stay untouched"); - // Flattening bakes the content effects in. + + // Flattening bakes in the content effects let images = Default::default(); let inp = Inputs { project: &f.project, @@ -3506,15 +3741,17 @@ soft {soft:?}" let anchor = content_fx(&mut f, low, EffectKind::Anchor); let top = fill_layer(&mut f.project, [1.0; 3], 0.5); let mut mask = Mask::new(MaskBackground::Black); - let source = Source::Anchor { anchor, channel: Channel::Height }; + let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); f.project.layer_mut(top).unwrap().mask = Some(mask.clone()); assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); - // Under a blur the anchor is read by the field pre-pass too: a flat height stays flat. + + // The field pre-pass reads anchors under blur, preserving flat height mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 }))); f.project.layer_mut(top).unwrap().mask = Some(mask); assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3])); - // An anchor above its reader is not evaluated yet: it reads the channel default (0). + + // An anchor above its reader is not evaluated yet, so it reads the channel default f.project.move_layer(low, 1).unwrap(); assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3])); } @@ -3523,7 +3760,7 @@ soft {soft:?}" fn anchor_reader(fixture: &mut Fixture, anchor: LayerId) -> LayerId { let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5); let mut mask = Mask::new(MaskBackground::Black); - let source = Source::Anchor { anchor, channel: Channel::Roughness }; + let source = Source::Anchor { anchor, channel: Channel::Roughness, ramp: Vec::new() }; mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })); fixture.project.layer_mut(top).unwrap().mask = Some(mask); top @@ -3564,7 +3801,7 @@ soft {soft:?}" let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0); let anchor = fixture.project.alloc_id(); let mut mask = Mask::new(MaskBackground::Black); - let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] }; + let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }; mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() })); mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 }))); mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); @@ -3676,6 +3913,8 @@ soft {soft:?}" rotation: 0.0, offset: [0.0; 2], depth: 0.5, + symmetry: None, + flip: [false; 2], }; let id = f.project.alloc_id(); let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; @@ -3707,6 +3946,226 @@ soft {soft:?}" assert!(close(half.value(Channel::BaseColor, 32, 32), [0.75, 0.25, 0.25]), "the image alpha shapes the decal"); } + /// Composites a cube with a decal of a four-colored image, and checks each texel of the + /// faces picked by `expect` against the image at the coordinates it gives (None: the texel + /// is not part of the check). Returns how many texels were checked. + fn cube_decal_texels(d: texturecraft_core::Decal, expect: impl Fn(Vec3, Vec3) -> Option>) -> usize { + let mesh = primitives::cube(2.0); + let gbuf = UvGBuffer::new(&mesh, 0, 64, 64); + let mut project = Project::new("t", "builtin:cube"); + project.texture_sets.push(TextureSet::new("Cube", 0, 64)); + let id = project.alloc_id(); + let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + fill.sources.insert(Channel::BaseColor, Source::image("decal")); + project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + + // Top left red, top right blue, bottom left green, bottom right yellow + let img = crate::store::ImageRes { + width: 2, + height: 2, + rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], + srgb: false, + }; + let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img.clone()))].into_iter().collect(); + let pixels = PixelStore::default(); + let baked = BakedMaps::default(); + let inp = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + let mut out = Composite::new(&project.texture_sets[0].channel_list(), 64); + composite_tiles(&inp, &mut out, &all_tiles(64, 64)); + + let mut checked = 0; + for i in 0..64 * 64 { + let Some(surface) = gbuf.surface(&mesh, i) else { continue }; + let Some(want) = expect(surface.pos, surface.nrm) else { continue }; + let got = out.value(Channel::BaseColor, (i % 64) as u32, (i / 64) as u32); + let want = want.map_or([0.5; 3], |(u, v)| { + let c = img.sample(u, v); + [c[0], c[1], c[2]] + }); + assert!(close(got, want), "texel at {:?} on a face turned to {:?}: {got:?}, expected {want:?}", surface.pos, surface.nrm); + checked += 1; + } + checked + } + + /// A 1 by 1 decal on the cube's +X face (the image's right runs toward -Z, its up toward +Y) + fn cube_decal(center: [f32; 3], size: f32, symmetry: Option) -> texturecraft_core::Decal { + texturecraft_core::Decal { + center, + normal: [1.0, 0.0, 0.0], + up: [0.0, 1.0, 0.0], + size: [size; 2], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry, + flip: [false; 2], + } + } + + /// What the decal of `size` centered at (cy, cz) on the +X face gives the point (y, z) of + /// that face: the image coordinates well inside the frame, None for a bare texel clearly + /// outside it, and None for texels near its edge (not part of the checks). + fn face_expect(y: f32, z: f32, (cy, cz): (f32, f32), size: f32) -> Option> { + let (u, v) = (0.5 - (z - cz) / size, 0.5 - (y - cy) / size); + let off = (u - 0.5).abs().max((v - 0.5).abs()); + if off < 0.4 { + Some(Some((u, v))) + } else if off > 0.6 { + Some(None) + } else { + None + } + } + + #[test] + fn a_mirrored_decal_lands_on_the_opposite_cube_face_with_its_flip() { + use texturecraft_core::{DecalFlip, DecalSymmetry}; + let at = (0.1, -0.2); + let on_x = |flip| { + cube_decal_texels(cube_decal([1.0, at.0, at.1], 1.0, Some(DecalSymmetry { axis: 0, flip, offset: 0.0 })), |p, n| { + if n.x > 0.99 { + face_expect(p.y, p.z, at, 1.0) + } else if n.x < -0.99 { + // The mirror image: the point's reflection, then the flip of the copy + face_expect(p.y, p.z, at, 1.0).map(|texel| { + texel.map(|(u, v)| match flip { + DecalFlip::None => (u, v), + DecalFlip::U => (1.0 - u, v), + DecalFlip::V => (u, 1.0 - v), + }) + }) + } else { + Some(None) + } + }) + }; + for flip in [DecalFlip::None, DecalFlip::U, DecalFlip::V] { + assert!(on_x(flip) > 800, "{flip:?}: most of the cube was checked"); + } + + // No symmetry: the -X face stays bare + let bare = cube_decal_texels(cube_decal([1.0, at.0, at.1], 1.0, None), |p, n| if n.x > 0.99 { face_expect(p.y, p.z, at, 1.0) } else { Some(None) }); + assert!(bare > 800); + + // Mirrored across Z, the copy sits on the same face on the other side of the Z = 0 plane + let at = (0.1, -0.5); + let across_z = Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.0 }); + let on_z = cube_decal_texels(cube_decal([1.0, at.0, at.1], 0.4, across_z), |p, n| { + if n.x > 0.99 { + match (face_expect(p.y, p.z, at, 0.4), face_expect(p.y, -p.z, at, 0.4)) { + (Some(Some(texel)), _) | (_, Some(Some(texel))) => Some(Some(texel)), + (Some(None), Some(None)) => Some(None), + _ => None, + } + } else { + Some(None) + } + }); + assert!(on_z > 800); + } + + #[test] + fn the_mirror_plane_can_be_moved_along_its_axis() { + use texturecraft_core::{DecalFlip, DecalSymmetry}; + + // Mirrored across Z with the plane at z = 0.3: a decal at z = -0.2 gets its copy at z = 0.8 + let at = (0.1, -0.2); + let moved = Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.3 }); + let checked = cube_decal_texels(cube_decal([1.0, at.0, at.1], 0.4, moved), |p, n| { + if n.x > 0.99 { + match (face_expect(p.y, p.z, at, 0.4), face_expect(p.y, 0.6 - p.z, at, 0.4)) { + (Some(Some(texel)), _) | (_, Some(Some(texel))) => Some(Some(texel)), + (Some(None), Some(None)) => Some(None), + _ => None, + } + } else { + Some(None) + } + }); + assert!(checked > 800); + } + + #[test] + fn moving_the_decal_moves_its_mirrored_copy() { + use texturecraft_core::{DecalFlip, DecalSymmetry}; + let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 }); + for at in [(0.5, 0.3), (-0.4, -0.5)] { + let checked = + cube_decal_texels( + cube_decal([1.0, at.0, at.1], 0.4, symmetry), + |p, n| { + if n.x.abs() > 0.99 { face_expect(p.y, p.z, at, 0.4) } else { Some(None) } + }, + ); + assert!(checked > 800, "{at:?}"); + } + } + + #[test] + fn flipping_a_decal_mirrors_its_image_inside_the_frame() { + let mut f = fixture(); + let s = f.gbuf.surface(&f.mesh, 32 * 64 + 32).unwrap(); + + // The frame's center sits a quarter of its width to the right of the texel, so the texel reads the image's left half + let d = texturecraft_core::Decal { + center: s.pos.to_array(), + normal: s.nrm.to_array(), + up: s.nrm.any_orthonormal_vector().to_array(), + size: [1.0, 1.0], + rotation: 0.0, + offset: [0.25, 0.0], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let id = f.project.alloc_id(); + let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() }; + fill.sources.insert(Channel::BaseColor, Source::image("decal")); + f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + + // Left half red, right half blue + let img = crate::store::ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], srgb: false }; + let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect(); + let texel = |f: &Fixture, flip: [bool; 2]| { + let mut project = f.project.clone(); + if let Ok(layer) = project.layer_mut(id) + && let LayerKind::Fill(fill) = &mut layer.kind + { + fill.projection = Projection::Decal(texturecraft_core::Decal { flip, ..d }); + } + let inp = Inputs { + project: &project, + ts: 0, + mesh: &f.mesh, + gbuf: &f.gbuf, + pixels: &f.pixels, + baked: &f.baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: f.mesh.bounds(), + }; + let mut out = Composite::new(&project.texture_sets[0].channel_list(), 64); + composite_tiles(&inp, &mut out, &all_tiles(64, 64)); + out.value(Channel::BaseColor, 32, 32) + }; + assert!(close(texel(&f, [false, false]), [1.0, 0.0, 0.0]), "the left half shows red"); + assert!(close(texel(&f, [true, false]), [0.0, 0.0, 1.0]), "Flip U shows the right half there"); + assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half"); + } + #[test] fn anchors_read_colors_as_gray_in_fill_layers() { let mut f = fixture(); @@ -3714,9 +4173,102 @@ soft {soft:?}" let anchor = content_fx(&mut f, low, EffectKind::Anchor); let id = f.project.alloc_id(); let mut fill = Fill::default(); - fill.sources.insert(Channel::Roughness, Source::Anchor { anchor, channel: Channel::BaseColor }); + fill.sources.insert(Channel::Roughness, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }); f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap(); let expect = texturecraft_core::lum([0.2, 0.4, 0.6]); assert!(close(run(&f, None).value(Channel::Roughness, 9, 9), [expect; 3])); } + + const RAMP: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + + #[test] + fn an_anchor_gradient_map_recolors_the_stack_below_by_its_lightness() { + // The stops at 0, 0.5 and 1, and halfway between them + for (gray, want) in [(0.0, [1.0, 0.0, 0.0]), (0.25, [0.5, 0.5, 0.0]), (0.5, [0.0, 1.0, 0.0]), (0.75, [0.0, 0.5, 0.5]), (1.0, [0.0, 0.0, 1.0])] { + let mut f = fixture(); + let low = fill_layer(&mut f.project, [gray; 3], 0.5); + let anchor = content_fx(&mut f, low, EffectKind::Anchor); + let id = f.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: RAMP.to_vec() }); + + // A scalar channel reading the same anchor with stops keeps reading its gray + fill.sources.insert(Channel::Roughness, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: RAMP.to_vec() }); + fill.sources.insert(Channel::Metallic, Source::Uniform([0.3; 3])); + let channels = [Channel::BaseColor, Channel::Roughness, Channel::Metallic]; + f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &channels), None, false).unwrap(); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 9, 9), want), "gray {gray}: {:?}", out.value(Channel::BaseColor, 9, 9)); + assert!(close(out.value(Channel::Roughness, 9, 9), [gray; 3]), "gray {gray}: {:?}", out.value(Channel::Roughness, 9, 9)); + assert!(close(out.value(Channel::Metallic, 9, 9), [0.3; 3])); + } + } + + #[test] + fn an_anchor_gradient_map_reads_signed_height_from_minus_one_to_one() { + for (height, want) in [(-1.0, [1.0, 0.0, 0.0]), (0.0, [0.0, 1.0, 0.0]), (0.5, [0.0, 0.5, 0.5])] { + let mut f = fixture(); + let low = f.project.alloc_id(); + let mut below = Fill::default(); + below.sources.insert(Channel::Height, Source::Uniform([height; 3])); + f.project.insert_layer(0, Layer::new(low, "Below", LayerKind::Fill(below), &[Channel::Height]), None, false).unwrap(); + let anchor = content_fx(&mut f, low, EffectKind::Anchor); + let id = f.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel: Channel::Height, ramp: RAMP.to_vec() }); + f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 9, 9), want), "height {height}: {:?}", out.value(Channel::BaseColor, 9, 9)); + } + } + + #[test] + fn a_gradient_map_reads_a_mask_anchors_gray_from_zero_to_one_in_every_channel() { + for channel in [Channel::BaseColor, Channel::Height] { + for (gray, want) in [(0.0, [1.0, 0.0, 0.0]), (0.25, [0.5, 0.5, 0.0]), (0.5, [0.0, 1.0, 0.0]), (1.0, [0.0, 0.0, 1.0])] { + let mut f = fixture(); + let low = fill_layer(&mut f.project, [0.0; 3], 0.5); + let anchor = f.project.alloc_id(); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects + .push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source: Source::Uniform([gray; 3]), projection: Projection::default() })); + mask.effects.push(Effect::new(anchor, EffectKind::Anchor)); + f.project.layer_mut(low).unwrap().mask = Some(mask); + let id = f.project.alloc_id(); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel, ramp: RAMP.to_vec() }); + f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let out = run(&f, None); + assert!(close(out.value(Channel::BaseColor, 9, 9), want), "{channel:?}, gray {gray}: {:?}", out.value(Channel::BaseColor, 9, 9)); + } + } + } + + #[test] + fn a_procedural_gradient_map_replaces_low_and_high_and_no_stops_keep_them() { + let (low, high) = ([0.2, 0.3, 0.4], [0.8, 0.7, 0.6]); + let composite = |ramp: Vec<[f32; 3]>, lo: [f32; 3], hi: [f32; 3]| { + let mut f = fixture(); + let id = f.project.alloc_id(); + let mut fill = Fill::default(); + let pattern = Procedural::new(ProceduralKind::Gradient); + fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: pattern.clone(), low: lo, high: hi, ramp: ramp.clone() }); + fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: lo, high: hi, ramp }); + f.project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor, Channel::Roughness]), None, false).unwrap(); + let out = run(&f, None); + (0..64).map(|x| (out.value(Channel::BaseColor, x, 20), out.value(Channel::Roughness, x, 20))).collect::>() + }; + + // The pattern's own 0..1 values, then the same pattern through low and high and through the stops + let gray = composite(Vec::new(), [0.0; 3], [1.0; 3]); + let plain = composite(Vec::new(), low, high); + let mapped = composite(RAMP.to_vec(), low, high); + let near = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-3); + assert!(gray.iter().any(|(v, _)| v[0] < 0.25) && gray.iter().any(|(v, _)| v[0] > 0.75), "the gradient spans dark to light"); + for (((t, _), (p, _)), (m, rough)) in gray.iter().zip(&plain).zip(&mapped) { + assert!(near(*p, mix3(low, high, t[0])), "no stops: low to high"); + assert!(near(*m, texturecraft_core::gradient(&RAMP, t[0]).unwrap()), "{t:?} -> {m:?}"); + assert!((rough[0] - mix3(low, high, t[0])[0]).abs() < 1e-3, "roughness ignores the stops: {rough:?}"); + } + } } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 9b6b78c1..35f65bac 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -16,14 +16,20 @@ pub mod eval; mod held_fields; mod image_identity; pub mod pattern; +mod pattern_context; +pub mod solo; pub mod store; pub mod thumb; +mod tile_pattern; +mod tile_random_stream; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, kinds_for, tile_bytes}; pub use eval::{ - BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, - flatten_layer, mask_at, mask_image, pad_tiles, stack_reads_neighbours, + BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, + effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; +pub use pattern_context::PatternContext; +pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs index 44c33692..4cfac5be 100644 --- a/crates/compose/src/pattern.rs +++ b/crates/compose/src/pattern.rs @@ -1,9 +1,14 @@ //! Procedural patterns and projections. -use texturecraft_core::{Decal, Procedural, ProceduralKind, Projection}; +use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_texel::noise; +use crate::pattern_context::PatternContext; + +/// Smaller pattern scales are read as this: a pattern stretched over ten thousand repeats of its projection +const MIN_PATTERN_SCALE: f32 = 1e-4; + /// Where a texel is, for pattern evaluation. #[derive(Clone, Copy, Debug)] pub struct Coords { @@ -26,7 +31,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { ((n - 0.45) * 4.0 + 0.5).clamp(0.0, 1.0) } ProceduralKind::Scratches => { - // Long thin streaks: noise stretched along one axis, sharpened to lines. + // Stretch noise along one axis to make thin streaks let q = Vec3::new(p.x * 0.15, p.y * 6.0, p.z * 6.0); let n = noise::perlin(q.to_array(), seed); let line = 1.0 - ((n - 0.5).abs() * 40.0).min(1.0); @@ -43,8 +48,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { } ProceduralKind::Gradient => p.x.rem_euclid(1.0), ProceduralKind::Wood => { - // Rings across Y (warped by low-frequency noise), latewood darkening sharply before - // each ring boundary; fine fibers stretched along X. + // Warp ring boundaries and add fine fibers along X let warp = noise::fbm([p.x * 0.18, p.y * 0.6, p.z], 3, seed, noise::perlin); let t = ((p.y + (warp - 0.5) * 0.9) * 5.0).rem_euclid(1.0); let ring = 1.0 - smoothstep(0.45, 1.0, t); @@ -53,8 +57,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { (ring * 0.6 + fiber * 0.25 + tone * 0.15).clamp(0.0, 1.0) } ProceduralKind::Bricks => { - // Bricks 1 × 0.5 in running bond; per-brick tone in the top 15 % so low/high map to - // mortar/brick colors without washing the bricks out. + // Keep per-brick tone near its high value so mortar stays distinct let row = (p.y * 2.0).floor(); let x = p.x + if (row as i32).rem_euclid(2) == 1 { 0.5 } else { 0.0 }; let (col, fx, fy) = (x.floor(), x.rem_euclid(1.0), (p.y * 2.0).rem_euclid(1.0)); @@ -68,10 +71,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed)) } ProceduralKind::Weave | ProceduralKind::Twill => { - // Warp along X, weft along Y: in each cell the thread on top shows its round - // cross-section, bulging mid-span. A plain weave alternates every cell; a 2/2 twill - // floats over two cells and steps one cell per row, so the floats line up in diagonal - // ribs, the weft darker than the warp. + // Alternate top threads for plain weave or step them into twill ribs let c = (p * 2.0).floor(); let f = p * 2.0 - c; let pi = std::f32::consts::PI; @@ -112,8 +112,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { } ProceduralKind::Voronoi => noise::cellular(a, seed).2, ProceduralKind::Streaks => { - // Drips: thin columns along Y, each segment starting at a random height and fading - // as it runs down (Y is up), over two offset column grids. + // Offset column grids make sparse drips that fade downwards let drip = |x: f32, salt: u32| { let cx = x * 6.0; let col = cx.floor() as i32; @@ -129,7 +128,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { (drip(p.x, 0).max(drip(p.x + 0.37, 1) * 0.8) * (0.6 + 0.4 * fine)).clamp(0.0, 1.0) } ProceduralKind::Smudges => { - // Sparse elliptical prints with concentric ridges, over soft greasy smudges. + // Blend ridged elliptical prints with soft smudges let w = noise::perlin((p * 1.3).to_array(), seed ^ 0x61) - 0.5; let q = Vec3::new(p.x * 1.15 + w * 0.3, p.y * 0.85 + w * 0.3, p.z); let (f1, _, id) = noise::cellular(q.to_array(), seed); @@ -143,6 +142,7 @@ fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 { let (g1, _, _) = noise::cellular((p * 2.7 + Vec3::splat(13.0)).to_array(), seed ^ 0x6B); smoothstep(0.08, 0.16, f1).min(smoothstep(0.06, 0.12, g1)) } + ProceduralKind::TileGenerator => crate::tile_pattern::value(&crate::tile_pattern::DEFAULT, p.truncate(), seed, None), ProceduralKind::Chips => { let (f1, _, _) = noise::cellular((p * 2.0).to_array(), seed ^ 0x45); let n = noise::fbm(a, 5, seed, noise::perlin) + (f1 - 0.5) * 0.25; @@ -200,16 +200,22 @@ fn shape(pr: &Procedural, v: f32) -> f32 { if pr.invert { 1.0 - v } else { v } } -/// Evaluate a procedural through a projection. +/// Evaluate a procedural through a projection, at full resolution and without images pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords) -> f32 { - let pattern_scale = pattern.scale.max(1e-4); + procedural_in(pattern, projection, coords, &PatternContext::default()) +} + +/// Evaluate a procedural through a projection with what `context` gives it: its resolution and the images it reads +pub fn procedural_in(pattern: &Procedural, projection: &Projection, coords: &Coords, context: &PatternContext) -> f32 { + let pattern_scale = pattern.scale.max(MIN_PATTERN_SCALE); + let sample = |point: Vec3| plane_value(pattern, point, context); let value = match projection { Projection::Uv { scale, rotation, offset } => { let (sn, cs) = rotation.to_radians().sin_cos(); let uv = Vec2::new(coords.uv.x * cs - coords.uv.y * sn, coords.uv.x * sn + coords.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset); // Evaluate two-dimensional patterns on a slice of the volume - raw(pattern.kind, (uv * pattern_scale).extend(0.0), pattern.seed) + sample((uv * pattern_scale).extend(0.0)) } Projection::Triplanar { scale, sharpness, offset } => { let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); @@ -217,7 +223,7 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords // Shape scales the blend by the contrast let w = triplanar_weights(coords.nrm, *sharpness, pattern.contrast); let planes = [(w.x, Vec3::new(p.z, p.y, 0.0)), (w.y, Vec3::new(p.x, p.z, 0.0)), (w.z, Vec3::new(p.x, p.y, 0.0))]; - planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| raw(pattern.kind, q, pattern.seed) * w).sum() + planes.into_iter().filter(|(w, _)| *w > 0.0).map(|(w, q)| sample(q) * w).sum() } Projection::Planar { scale, axis, offset } => { let p = coords.pos * *scale * pattern_scale + Vec3::from(*offset); @@ -226,13 +232,13 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords 1 => Vec3::new(p.x, p.z, 0.0), _ => Vec3::new(p.x, p.y, 0.0), }; - raw(pattern.kind, q, pattern.seed) + sample(q) } Projection::Spherical { scale } => { let d = coords.pos.try_normalize().unwrap_or(Vec3::Y); let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5; let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; - raw(pattern.kind, Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale, pattern.seed) + sample(Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * pattern_scale) } Projection::Cylindrical { scale, axis } => { let p = coords.pos; @@ -242,15 +248,50 @@ pub fn procedural(pattern: &Procedural, projection: &Projection, coords: &Coords _ => (p.x, p.y, p.z), }; let u = b.atan2(a) / std::f32::consts::TAU + 0.5; - raw(pattern.kind, Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale, pattern.seed) + sample(Vec3::new(u * 4.0, h, 0.0) * *scale * pattern_scale) } + // The decal already supplied coordinates in its local frame - Projection::Decal(_) => raw(pattern.kind, (coords.uv * pattern_scale).extend(0.0), pattern.seed), + Projection::Decal(_) => sample((coords.uv * pattern_scale).extend(0.0)), }; shape(pattern, value) } +/// The texels per side `pattern`'s resolution draws it at for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`, when that is coarser than the UV tile (a finer image changes nothing: patterns are evaluated per texel) +pub fn pattern_pixels(pattern: &Procedural, uv_tile: u32, texture_set: u32) -> Option { + if !pattern.resolution.can_reduce() { + return None; + } + + let size = pattern.resolution.output_size(uv_tile, texture_set); + (size < uv_tile).then_some(size) +} + +/// The pattern at `point` of its plane, read from an image of `context.pixels` texels per repeat (bilinear) when given +fn plane_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f32 { + let cells = context.pixels.map(|pixels| pixels as f32 / pattern.scale.max(MIN_PATTERN_SCALE)).filter(|cells| cells.is_finite() && *cells > 0.0); + let Some(cells) = cells else { return pattern_value(pattern, point, context) }; + + let grid = point.truncate() * cells - 0.5; + let base = grid.floor(); + let fraction = grid - base; + let at = |dx: f32, dy: f32| pattern_value(pattern, ((base + Vec2::new(dx, dy) + 0.5) / cells).extend(point.z), context); + let top_left = at(0.0, 0.0); + let bottom_left = at(0.0, 1.0); + let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x; + let bottom = bottom_left + (at(1.0, 1.0) - bottom_left) * fraction.x; + top + (bottom - top) * fraction.y +} + +/// The pattern at `point` of its plane, exactly +fn pattern_value(pattern: &Procedural, point: Vec3, context: &PatternContext) -> f32 { + match (&pattern.tile, pattern.kind) { + (Some(tile), ProceduralKind::TileGenerator) => crate::tile_pattern::value(tile, point.truncate(), pattern.seed, context.images), + _ => raw(pattern.kind, point, pattern.seed), + } +} + /// Texture coordinates (and blend weights) at which an image is sampled for a projection /// (unused slots weigh 0; no allocation per texel). pub fn image_samples(projection: &Projection, coords: &Coords) -> [(Vec2, f32); 3] { @@ -332,8 +373,38 @@ pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> { if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) { return None; } + let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz)); - Some((Vec2::new(lx + 0.5, 0.5 - ly), w)) + Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w)) +} + +/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame. +fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 { + Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y }) +} + +/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the +/// point more. The copy is the decal reflected through the plane across `center` (the mesh +/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked. +pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> { + let direct = decal_uv(d, p, nrm); + let Some(symmetry) = d.symmetry else { return direct }; + let axis = usize::from(symmetry.axis.min(2)); + let (mut mirrored_position, mut mirrored_normal) = (p, nrm); + mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis]; + mirrored_normal[axis] = -nrm[axis]; + let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| { + let uv = match symmetry.flip { + DecalFlip::None => uv, + DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y), + DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y), + }; + (uv, w) + }); + match (direct, mirrored) { + (Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }), + (a, b) => a.or(b), + } } /// World-space noise used by generators (seamless across UV islands). @@ -344,6 +415,32 @@ pub fn world_noise(pos: Vec3, scale: f32, seed: u32) -> f32 { #[cfg(test)] mod tests { use super::*; + use texturecraft_core::{OutputResolution, ResolutionMode}; + + #[test] + fn a_pattern_is_drawn_coarser_only_below_the_uv_tiles_resolution() { + let with = |resolution: OutputResolution| pattern_pixels(&Procedural { resolution, ..Procedural::new(ProceduralKind::Clouds) }, 1024, 2048); + assert_eq!(with(OutputResolution::default()), None, "by default a pattern is evaluated per texel"); + assert_eq!(with(OutputResolution { factor: -1, ..OutputResolution::default() }), Some(512)); + assert_eq!(with(OutputResolution { mode: ResolutionMode::Custom, custom: 256, factor: 0 }), Some(256)); + assert_eq!(with(OutputResolution { mode: ResolutionMode::Custom, custom: 2048, factor: 0 }), None, "a finer image than the UV tile changes nothing"); + } + + #[test] + fn a_coarser_pattern_reads_its_cells_bilinearly() { + let pattern = Procedural { scale: 1.0, ..Procedural::new(ProceduralKind::Clouds) }; + let coarse = PatternContext { pixels: Some(4), ..PatternContext::default() }; + let at = |x: f32, context: &PatternContext| { + procedural_in(&pattern, &Projection::default(), &Coords { uv: Vec2::new(x, 0.375), pos: Vec3::ZERO, nrm: Vec3::Y }, context) + }; + let exact = PatternContext::default(); + + // Coarse reads are exact at cell centers and blend between them + assert!((at(0.375, &coarse) - at(0.375, &exact)).abs() < 1e-5); + let blended = (at(0.125, &exact) + at(0.375, &exact)) * 0.5; + assert!((at(0.25, &coarse) - blended).abs() < 1e-5, "{} vs {blended}", at(0.25, &coarse)); + assert!((at(0.25, &exact) - blended).abs() > 1e-3, "the exact pattern is not the blend, so the coarse read shows"); + } #[test] fn every_pattern_and_projection_stays_in_range() { @@ -361,6 +458,8 @@ mod tests { rotation: 0.0, offset: [0.0; 2], depth: 1.0, + symmetry: None, + flip: [false; 2], }), ]; for k in ProceduralKind::ALL { @@ -461,14 +560,25 @@ mod tests { #[test] fn decals_cover_their_frame_facing_them() { - let d = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [2.0, 1.0], rotation: 0.0, offset: [0.0; 2], depth: 0.5 }; + let d = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [2.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; let z = Vec3::Z; let (uv, w) = decal_uv(&d, Vec3::new(0.5, 0.25, 0.0), z).unwrap(); assert!((uv - Vec2::new(0.75, 0.25)).length() < 1e-5 && (w - 1.0).abs() < 1e-5, "{uv} {w}"); assert!(decal_uv(&d, Vec3::new(1.1, 0.0, 0.0), z).is_none(), "outside the frame"); assert!(decal_uv(&d, Vec3::ZERO, -z).is_none(), "back faces"); assert!(decal_uv(&d, Vec3::new(0.0, 0.0, 0.6), z).is_none(), "beyond the depth"); - // Rotated a quarter turn and shifted: the frame turns with it. + + // Rotated a quarter turn and shifted: the frame turns with it let r = Decal { rotation: 90.0, offset: [1.0, 0.0], ..d }; let (uv, _) = decal_uv(&r, Vec3::new(1.0, 0.9, 0.0), z).unwrap(); assert!((uv.x - 0.95).abs() < 1e-4 && (uv.y - 0.5).abs() < 1e-4, "{uv}"); @@ -478,6 +588,32 @@ mod tests { assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none()); } + #[test] + fn decals_mirror_their_image_inside_the_frame() { + let d = Decal { + center: [0.0; 3], + normal: [0.0, 0.0, 1.0], + up: [0.0, 1.0, 0.0], + size: [2.0, 1.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 0.5, + symmetry: None, + flip: [false; 2], + }; + let (left, top) = (Vec3::new(-0.5, 0.25, 0.0), Vec3::Z); + let uv = |flip: [bool; 2]| decal_uv(&Decal { flip, ..d }, left, top).unwrap().0; + assert!((uv([false, false]) - Vec2::new(0.25, 0.25)).length() < 1e-5); + assert!((uv([true, false]) - Vec2::new(0.75, 0.25)).length() < 1e-5, "Flip U mirrors left to right only"); + assert!((uv([false, true]) - Vec2::new(0.25, 0.75)).length() < 1e-5, "Flip V mirrors top to bottom only"); + assert!((uv([true, true]) - Vec2::new(0.75, 0.75)).length() < 1e-5); + + // The frame itself does not move: coverage is the same flipped or not + let covered = |flip: [bool; 2], p: Vec3| decal_uv(&Decal { flip, ..d }, p, top).map(|(_, w)| w); + assert_eq!(covered([true, true], left), covered([false, false], left)); + assert_eq!(covered([true, true], Vec3::new(1.1, 0.0, 0.0)), None); + } + #[test] fn twill_floats_run_in_diagonal_ribs() { // The value at the centre of cell (x, y); cells are half a unit. diff --git a/crates/compose/src/pattern_context.rs b/crates/compose/src/pattern_context.rs new file mode 100644 index 00000000..09b6b0a1 --- /dev/null +++ b/crates/compose/src/pattern_context.rs @@ -0,0 +1,12 @@ +//! What evaluating a pattern needs besides the texel: the resolution it is drawn at and the images it reads + +use crate::store::ImageStore; + +/// What a pattern reads beyond the texel's coordinates (fields can be added; build it with `..PatternContext::default()`) +#[derive(Clone, Copy, Default)] +pub struct PatternContext<'a> { + /// Texels per side of the image the pattern is drawn as over one repeat of the projection (see [`crate::pattern::pattern_pixels`]); None draws it exactly + pub pixels: Option, + /// The image resources a pattern's inputs name; None reads them as empty + pub images: Option<&'a ImageStore>, +} diff --git a/crates/compose/src/solo.rs b/crates/compose/src/solo.rs new file mode 100644 index 00000000..3703ba57 --- /dev/null +++ b/crates/compose/src/solo.rs @@ -0,0 +1,169 @@ +//! The view-only "solo" of one layer: the project as the viewport shows it while a layer is +//! isolated. The document itself is never changed; the compositor reads this copy instead. + +use std::collections::BTreeSet; + +use texturecraft_core::project::MAX_DEPTH; +use texturecraft_core::{LayerId, Mask, MaskBackground, Project}; + +/// `project` as shown while `layer` is soloed: every other layer of its texture set hidden, the +/// layer and the folders around it shown (even if their eyes are off), and with `ignore_mask` +/// the layer and its folders drawn at full coverage. Other texture sets stay as they are. +/// None when `layer` is in no stack. +pub fn solo_project(project: &Project, layer: LayerId, ignore_mask: bool) -> Option { + let (ts, mut parent, _) = project.locate(layer)?; + let set = project.texture_sets.get(ts)?; + + // The layer and the folders holding it + let mut shown = vec![layer]; + for _ in 0..=MAX_DEPTH { + let Some(folder) = parent else { break }; + shown.push(folder); + parent = project.locate(folder).and_then(|located| located.1); + } + + // What stays drawn: those, and a soloed folder's contents + let mut kept: BTreeSet = shown.iter().copied().collect(); + contents(project, &[layer], &mut kept, 0); + + // A soloed instance draws its source's contents, which must stay visible too + kept.extend(project.render_tree(&[layer])); + let mut every = BTreeSet::new(); + contents(project, &set.stack, &mut every, 0); + + let mut view = project.clone(); + for id in every.difference(&kept) { + if let Some(hidden) = view.layers.get_mut(id) { + hidden.visible = false; + } + } + for id in &shown { + let Some(drawn) = view.layers.get_mut(id) else { continue }; + drawn.visible = true; + if !ignore_mask { + continue; + } + + let instance = drawn.instance_source().is_some(); + match drawn.mask.as_mut() { + Some(mask) => mask.enabled = false, + + // An instance without its own mask draws its source's: an own, disabled one overrides it + None if instance => drawn.mask = Some(Mask { enabled: false, ..Mask::new(MaskBackground::White) }), + None => {} + } + } + Some(view) +} + +/// `roots` and everything in the folders among them (instances' sources are not followed: +/// they may belong to another texture set). +fn contents(project: &Project, roots: &[LayerId], out: &mut BTreeSet, depth: usize) { + if depth > MAX_DEPTH { + return; + } + + for id in roots { + out.insert(*id); + if let Some(layer) = project.layers.get(id) { + contents(project, layer.children(), out, depth + 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_core::{Channel, Layer, LayerKind, TextureSet}; + + const CHANNELS: [Channel; 1] = [Channel::BaseColor]; + + fn project() -> Project { + let mut p = Project::new("t", ""); + p.texture_sets.push(TextureSet::new("a", 0, 64)); + p.texture_sets.push(TextureSet::new("b", 0, 64)); + p + } + + fn add(p: &mut Project, ts: usize, kind: LayerKind, above: Option, inside: bool) -> LayerId { + let id = p.alloc_id(); + p.insert_layer(ts, Layer::new(id, "layer", kind, &CHANNELS), above, inside).unwrap(); + id + } + + fn masked(p: &mut Project, id: LayerId) { + p.layer_mut(id).unwrap().mask = Some(Mask::new(MaskBackground::Black)); + } + + #[test] + fn solo_hides_the_others_and_leaves_the_original_alone() { + let mut p = project(); + let (below, rust, other_set) = + (add(&mut p, 0, LayerKind::Paint, None, false), add(&mut p, 0, LayerKind::Paint, None, false), add(&mut p, 1, LayerKind::Paint, None, false)); + p.layer_mut(rust).unwrap().visible = false; + let before = p.clone(); + let view = solo_project(&p, rust, false).unwrap(); + assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off"); + assert!(!view.layers[&below].visible, "the others are hidden"); + assert!(view.layers[&other_set].visible, "another texture set keeps its layers"); + assert_eq!(p, before, "the project itself is untouched"); + } + + #[test] + fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() { + let mut p = project(); + let outside = add(&mut p, 0, LayerKind::Paint, None, false); + let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); + let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false); + let view = solo_project(&p, inner, false).unwrap(); + assert!(view.layers[&folder].visible && view.layers[&inner].visible); + assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible); + let whole = solo_project(&p, folder, false).unwrap(); + assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents"); + assert!(!whole.layers[&outside].visible); + } + + #[test] + fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() { + let mut p = project(); + let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); + let other = add(&mut p, 0, LayerKind::Paint, None, false); + for id in [folder, inner, other] { + masked(&mut p, id); + } + let kept = solo_project(&p, inner, false).unwrap(); + assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays"); + let view = solo_project(&p, inner, true).unwrap(); + assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled); + assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched"); + assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask"); + } + + #[test] + fn an_instance_gets_its_own_disabled_mask_instead_of_changing_its_source() { + let mut p = project(); + let source = add(&mut p, 0, LayerKind::Paint, None, false); + masked(&mut p, source); + let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false); + let view = solo_project(&p, instance, true).unwrap(); + assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled); + assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask"); + } + + #[test] + fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() { + let mut p = project(); + let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false); + let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true); + let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false); + let view = solo_project(&p, instance, false).unwrap(); + assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible); + } + + #[test] + fn a_layer_in_no_stack_gives_nothing() { + assert!(solo_project(&project(), LayerId(99), true).is_none()); + } +} diff --git a/crates/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs new file mode 100644 index 00000000..c756072f --- /dev/null +++ b/crates/compose/src/tile_pattern.rs @@ -0,0 +1,658 @@ +//! The Tile Generator pattern: shapes in a grid of tiles over one repeating unit, x right and y down as a texture's rows + +use std::sync::LazyLock; + +use texturecraft_core::{TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry}; +use texturecraft_geom::glam::Vec2; + +use crate::store::{ImageRes, ImageStore}; +use crate::tile_random_stream::TileRandomStream; + +/// The settings a Tile Generator pattern saved without its own reads +pub(crate) static DEFAULT: LazyLock = LazyLock::new(TileGenerator::default); + +/// The output size the pixel size mode measures shapes against +const PIXEL_REFERENCE: f32 = 2048.0; +/// Position random moves a tile up to this many cells times its amount, either way +const POSITION_RANDOM_CELLS: f32 = 1.0; +/// Capsule shape: the radius of its round ends +const CAPSULE_RADIUS: f32 = 0.2225; +/// Half bell shape: the width of its squashed half at a specific of 0 +const HALF_BELL_WIDTH: f32 = 1.24; +/// Gaussian shape: the falloff exponent, 2^(−k·r²) +const GAUSSIAN_FALLOFF: f32 = 16.0; +/// Crescent shape: scales its ring r²(1 − r²)² to a peak of 1 +const CRESCENT_GAIN: f32 = 6.75; +/// Waves shape: cycles across the tile at a specific of 0, and the cycles a specific of 1 adds +const WAVES_BASE_CYCLES: f32 = 1.5; +const WAVES_SPECIFIC_CYCLES: f32 = 6.0; +/// Narrower than this, a size or a bevel is none +const EPSILON: f32 = 1e-6; +/// Valid tile settings reach at most three neighboring copies along an axis +const MAX_PERIODIC_COPY: f32 = 3.0; + +fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} + +fn bell(r: f32) -> f32 { + (1.0 - r * r).clamp(0.0, 1.0).powi(4) +} + +/// The shape's value at (u, v) of its square (−1..1 both ways; 0 outside it). `specific` changes some shapes +fn shape(kind: TileShape, u: f32, v: f32, specific: f32) -> f32 { + if u.abs() > 1.0 || v.abs() > 1.0 { + return 0.0; + } + + let r = u.hypot(v); + match kind { + TileShape::Square => 1.0, + TileShape::Disc => f32::from(u8::from(r <= 1.0)), + TileShape::Paraboloid => (1.0 - r * r).clamp(0.0, 1.0), + TileShape::Bell => bell(r), + TileShape::Gaussian => (-GAUSSIAN_FALLOFF * r * r).exp2(), + TileShape::Thorn => (1.0 - r).clamp(0.0, 1.0).powi(4), + TileShape::Pyramid => (1.0 - u.abs().max(v.abs())).clamp(0.0, 1.0), + TileShape::Cone => (1.0 - r).clamp(0.0, 1.0), + TileShape::Brick if specific <= EPSILON => 1.0, + TileShape::Brick => smoothstep((1.0 - u.abs()) / specific) * smoothstep((1.0 - v.abs()) / specific), + TileShape::Gradation => (u + 1.0) * 0.5 * (1.0 - specific), + TileShape::Waves => { + let cycles = WAVES_BASE_CYCLES + WAVES_SPECIFIC_CYCLES * specific; + (1.0 - r * r).clamp(0.0, 1.0) * (0.5 + 0.5 * (std::f32::consts::TAU * cycles * u).cos()) + } + TileShape::HalfBell => { + let width = HALF_BELL_WIDTH * (1.0 - specific); + let cut = match (u > 0.0, width > EPSILON) { + (false, _) => 1.0, + (true, true) => bell(u / width), + (true, false) => 0.0, + }; + bell(r) * cut + } + TileShape::RidgedBell => bell(r) * (1.0 - u.abs()).powi(2), + TileShape::Crescent if specific >= 1.0 => 0.0, + TileShape::Crescent => { + let shifted = (u + 1.0) / (1.0 - specific) - 1.0; + let ring = (1.0 - r * r).clamp(0.0, 1.0); + CRESCENT_GAIN * r * r * ring * ring * smoothstep((1.0 - shifted) * 0.5) + } + TileShape::Capsule => { + let half_length = specific * (1.0 - CAPSULE_RADIUS); + let distance = (u.abs() - half_length).max(0.0).hypot(v); + (1.0 - (distance / CAPSULE_RADIUS).powi(2)).clamp(0.0, 1.0) + } + + // The image shape draws an input image instead (see `pattern`): without one it is empty + TileShape::Image => 0.0, + } +} + +/// `point` turned clockwise on screen by `turns` undone (y runs down) +fn unrotate(point: Vec2, turns: f32) -> Vec2 { + if turns == 0.0 { + return point; + } + + let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos(); + Vec2::new(cos * point.x + sin * point.y, -sin * point.x + cos * point.y) +} + +/// The pattern section: tile-local (u, v) through the shape's tiling, angle, scale, size and 45° turn, then the shape (`input` for the image shape) +fn pattern(tile: &TileGenerator, mut local: Vec2, input: Option<&ImageRes>) -> f32 { + if local.x.abs() > 1.0 || local.y.abs() > 1.0 { + return 0.0; + } + + if tile.shape_tiling > 1 { + // Tiling shows the copy just above and left of center + let count = tile.shape_tiling as f32; + let shown = (tile.shape_tiling.div_ceil(2) - 1) as f32; + let cell = (local + 1.0) * 0.5 * count; + if cell.x.floor() != shown || cell.y.floor() != shown { + return 0.0; + } + + local = (cell - shown) * 2.0 - 1.0; + } + local = unrotate(local, tile.shape_angle / 360.0); + let size = Vec2::from(tile.shape_size) * tile.shape_scale; + if size.x <= EPSILON || size.y <= EPSILON { + return 0.0; + } + + local /= size; + if tile.shape_diagonal { + local = unrotate(local, 0.125) * std::f32::consts::SQRT_2; + } + if tile.shape == TileShape::Image { + return input.map_or(0.0, |image| image_shape(image, local)); + } + + let samples = Vec2::new(tile.shape_resolution[0] as f32, tile.shape_resolution[1] as f32); + sampled_shape(tile, local, samples) +} + +/// An input image over the shape's square, as gray (the average of its color) +fn image_shape(image: &ImageRes, local: Vec2) -> f32 { + if local.x.abs() > 1.0 || local.y.abs() > 1.0 { + return 0.0; + } + + let at = (local + 1.0) * 0.5; + gray(image.sample(at.x, at.y)) +} + +/// The gray of an image texel: the average of its color +fn gray([red, green, blue, _]: [f32; 4]) -> f32 { + ((red + green + blue) / 3.0).clamp(0.0, 1.0) +} + +/// The shape read from an image of `samples` texels over its square, bilinearly, as the shape is drawn at its own resolution +fn sampled_shape(tile: &TileGenerator, local: Vec2, samples: Vec2) -> f32 { + let grid = (local + 1.0) * 0.5 * samples - 0.5; + let base = grid.floor(); + let fraction = grid - base; + let at = |dx: f32, dy: f32| { + let texel = (base + Vec2::new(dx, dy) + 0.5) / samples * 2.0 - 1.0; + shape(tile.shape, texel.x, texel.y, tile.specific) + }; + let top_left = at(0.0, 0.0); + let bottom_left = at(0.0, 1.0); + let top = top_left + (at(1.0, 0.0) - top_left) * fraction.x; + let bottom = bottom_left + (at(1.0, 1.0) - bottom_left) * fraction.x; + top + (bottom - top) * fraction.y +} + +/// The start and width, in cells, of cell `index` along an axis whose middle size is `middle` (cells pair up) +fn cell_span(index: i32, middle: f32) -> (f32, f32) { + let pair = index.div_euclid(2) as f32 * 2.0; + if index.rem_euclid(2) == 0 { (pair, 2.0 * middle) } else { (pair + 2.0 * middle, 2.0 * (1.0 - middle)) } +} + +/// `delta` wrapped into −span/2..span/2 (the pattern repeats every `span`) +fn wrap(delta: f32, span: f32) -> f32 { + delta - (delta / span).round() * span +} + +/// What one tile gives a texel (its shape times its luminance), or None when hidden or out of reach; `inputs` are its input images +fn tile_value( + tile: &TileGenerator, + seed: u32, + (column, row): (i32, i32), + (columns, rows): (i32, i32), + (point, inputs): (Vec2, &[Option<&ImageRes>]), +) -> Option { + let total = columns * rows; + let number = column * rows + row; + let index = (if tile.reverse_order { total - 1 - number } else { number }) as u32; + if hidden(tile, seed, (column, row), index) { + return None; + } + + let (start_x, width) = cell_span(column, tile.middle_size[0]); + let (start_y, height) = cell_span(row, tile.middle_size[1]); + let mut center = Vec2::new(start_x + width * 0.5, start_y + height * 0.5); + if tile.vertical_offset { + center.y += line_shift(tile, column); + } else { + center.x += line_shift(tile, row); + } + center.x += (TileRandomStream::PositionX.draw(seed, index) - 0.5) * 2.0 * POSITION_RANDOM_CELLS * tile.position_random[0]; + center.y += (TileRandomStream::PositionY.draw(seed, index) - 0.5) * 2.0 * POSITION_RANDOM_CELLS * tile.position_random[1]; + let counts = Vec2::new(columns as f32, rows as f32); + let center = center / counts + Vec2::from(tile.global_offset); + + let scale_factor = 1.0 - tile.scale_random * TileRandomStream::Scale.draw(tile.scale_random_seed, index); + let size = tile_size(tile, seed, index, Vec2::new(width, height) / counts) * tile.scale * scale_factor; + if size.x <= EPSILON || size.y <= EPSILON { + return None; + } + + let delta = Vec2::new(wrap(point.x - center.x, 1.0), wrap(point.y - center.y, 1.0)); + let turns = (tile.rotation + tile.rotation_random * TileRandomStream::Rotation.draw(seed, index) * 360.0) / 360.0; + let (sin, cos) = (turns * std::f32::consts::TAU).sin_cos(); + let radius = Vec2::new(cos.abs() * size.x + sin.abs() * size.y, sin.abs() * size.x + cos.abs() * size.y) * 0.5; + let first = (-radius - delta).ceil().max(Vec2::splat(-MAX_PERIODIC_COPY)); + let last = (radius - delta).floor().min(Vec2::splat(MAX_PERIODIC_COPY)); + let quarter_turns = quarter_turns(tile, seed, (column, row), index); + let mirrors = tile.symmetry_random * 0.5; + let mirror_x = tile.symmetry != TileSymmetry::Vertical && TileRandomStream::MirrorX.draw(seed, index) < mirrors; + let mirror_y = tile.symmetry != TileSymmetry::Horizontal && TileRandomStream::MirrorY.draw(seed, index) < mirrors; + + let input = match tile.input_distribution { + _ if inputs.is_empty() => None, + TileInputDistribution::Random => inputs.get((TileRandomStream::Input.draw(seed, index) * inputs.len() as f32) as usize).copied().flatten(), + TileInputDistribution::ByNumber => inputs.get(number as usize % inputs.len()).copied().flatten(), + }; + let mut value = 0.0f32; + // A rotated shape may cross a repeat boundary even when the nearest copy misses it + for copy_y in first.y as i32..=last.y as i32 { + let y = delta.y + copy_y as f32; + if y.abs() > radius.y { + continue; + } + for copy_x in first.x as i32..=last.x as i32 { + let x = delta.x + copy_x as f32; + if x.abs() > radius.x { + continue; + } + let mut local = Vec2::new(cos * x + sin * y, -sin * x + cos * y) * 2.0 / size; + for _ in 0..quarter_turns { + local = Vec2::new(local.y, -local.x); + } + if mirror_x { + local.x = -local.x; + } + if mirror_y { + local.y = -local.y; + } + value = value.max(pattern(tile, local, input)); + } + } + if value <= 0.0 { + return None; + } + + let mut luminance = 1.0 - tile.luminance_random * TileRandomStream::Luminance.draw(seed, index); + if tile.luminance_by_number { + luminance *= (number + 1) as f32 / total as f32; + } + if tile.luminance_by_scale { + luminance *= scale_factor; + } + Some(value * luminance) +} + +/// Whether the masks hide tile (column, row), whose randoms are at `index` +fn hidden(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), index: u32) -> bool { + let masked = (tile.checker_mask && (column + row).rem_euclid(2) == 1) + || (tile.horizontal_mask && row.rem_euclid(2) == 1) + || (tile.vertical_mask && column.rem_euclid(2) == 0) + || (tile.random_mask > 0.0 && TileRandomStream::Mask.draw(seed, index) < tile.random_mask); + masked != tile.invert_mask +} + +/// The tile's width and height on the plane before its scale, for a cell `cell` wide and high +fn tile_size(tile: &TileGenerator, seed: u32, index: u32, cell: Vec2) -> Vec2 { + match tile.size_mode { + TileSizeMode::NormalInterstice => { + let gap_x = tile.interstice[0] * (1.0 - tile.interstice_random[0] * TileRandomStream::IntersticeX.draw(seed, index)); + let gap_y = tile.interstice[1] * (1.0 - tile.interstice_random[1] * TileRandomStream::IntersticeY.draw(seed, index)); + cell * Vec2::new(1.0 - gap_x, 1.0 - gap_y) + } + TileSizeMode::NormalSize => cell * Vec2::from(tile.size), + TileSizeMode::KeepRatio => Vec2::splat(cell.x.min(cell.y)), + TileSizeMode::Absolute | TileSizeMode::Pixel => { + let size = if tile.size_mode == TileSizeMode::Absolute { Vec2::from(tile.size_absolute) } else { Vec2::from(tile.size_pixel) / PIXEL_REFERENCE }; + let random_x = 1.0 - tile.size_random[0] * TileRandomStream::SizeX.draw(seed, index); + let random_y = 1.0 - tile.size_random[1] * TileRandomStream::SizeY.draw(seed, index); + size * Vec2::new(random_x, random_y) + } + } +} + +/// The quarter turns clockwise of tile (column, row): the set ones, the quincunx pinwheel and the random ones +fn quarter_turns(tile: &TileGenerator, seed: u32, (column, row): (i32, i32), index: u32) -> u32 { + let mut turns = u32::from(tile.quarter_turns); + if tile.quincunx_flip { + turns += match (column.rem_euclid(2), row.rem_euclid(2)) { + (0, 0) => 0, + (1, 0) => 3, + (0, _) => 1, + _ => 2, + }; + } + if tile.quarter_turn_random > 0.0 && TileRandomStream::QuarterTurnApplies.draw(seed, index) < tile.quarter_turn_random { + turns += (TileRandomStream::QuarterTurn.draw(seed, index) * 4.0) as u32; + } + turns % 4 +} + +/// How far, in cells along each axis, a tile's center can be from a texel its shape reaches: half its largest size turned, plus its random move and the shift of its center by the middle size +fn reach(tile: &TileGenerator, counts: Vec2) -> Vec2 { + let widest = Vec2::new(tile.middle_size[0].max(1.0 - tile.middle_size[0]), tile.middle_size[1].max(1.0 - tile.middle_size[1])) * 2.0; + let largest = match tile.size_mode { + TileSizeMode::NormalInterstice | TileSizeMode::KeepRatio => widest / counts, + TileSizeMode::NormalSize => widest / counts * Vec2::from(tile.size), + TileSizeMode::Absolute => Vec2::from(tile.size_absolute), + TileSizeMode::Pixel => Vec2::from(tile.size_pixel) / PIXEL_REFERENCE, + } * tile.scale; + let radius = largest.length() * 0.5 * counts; + let moved = Vec2::from(tile.position_random) * POSITION_RANDOM_CELLS; + let middle = Vec2::new((tile.middle_size[0] - 0.5).abs(), (tile.middle_size[1] - 0.5).abs()); + radius + moved + middle +} + +/// The cells along an axis of `count` whose centers can be within `reach` of `position` (in cells): each once, at most `count` +fn near(position: f32, reach: f32, count: i32) -> impl Iterator { + let first = (position - reach - 0.5).floor(); + let last = (position + reach - 0.5).ceil(); + + // A reach past the whole grid visits each cell once; float math keeps a hostile reach from overflowing + let span = (last - first + 1.0).min(count as f32).max(1.0) as i32; + let first = first as i32; + (first..first.saturating_add(span)).map(move |index| index.rem_euclid(count)) +} + +/// The shift along its line of line `line` (a row, or a column with a vertical offset), in cells +fn line_shift(tile: &TileGenerator, line: i32) -> f32 { + tile.offset * line as f32 + tile.offset_random * TileRandomStream::Offset.draw(tile.offset_random_seed, line as u32) +} + +/// The pattern's value at `point` of its plane (one unit = the whole grid, repeating); `images` holds the images its inputs name +pub(crate) fn value(tile: &TileGenerator, point: Vec2, seed: u32, images: Option<&ImageStore>) -> f32 { + let image = |name: &str| images.and_then(|images| images.get(name)).map(|image| &**image); + let mut slots: [Option<&ImageRes>; TileGenerator::MAX_INPUTS] = [None; TileGenerator::MAX_INPUTS]; + let count = tile.inputs.len().min(TileGenerator::MAX_INPUTS); + if tile.shape == TileShape::Image { + for (slot, name) in slots.iter_mut().zip(&tile.inputs) { + *slot = image(name); + } + } + let inputs = &slots[..count]; + let background = tile.background_image.as_deref().and_then(image); + + // Commands and saved projects keep the settings in range; the counts are guarded as they size the loops + let (columns, rows) = (tile.amount[0].clamp(1, *TileGenerator::AMOUNT.end()) as i32, tile.amount[1].clamp(1, *TileGenerator::AMOUNT.end()) as i32); + let counts = Vec2::new(columns as f32, rows as f32); + let point = Vec2::new(point.x.rem_euclid(1.0), point.y.rem_euclid(1.0)); + let cell = (point - Vec2::from(tile.global_offset)) * counts; + let reach = reach(tile, counts); + + let mut sum = 0.0f32; + let mut colored = 0.0f32; + let mut add = |value: f32| match tile.blending { + TileBlending::Max => { + sum = sum.max(value); + colored = colored.max(value * tile.color); + } + TileBlending::Add => { + sum += value; + colored += value * tile.color; + } + TileBlending::AddSub => { + sum += value; + colored += value * (2.0 * tile.color - 1.0); + } + }; + + // Each shifted line needs its own nearby tile search + if tile.vertical_offset { + for column in near(cell.x, reach.x, columns) { + for row in near(cell.y - line_shift(tile, column), reach.y, rows) { + if let Some(value) = tile_value(tile, seed, (column, row), (columns, rows), (point, inputs)) { + add(value); + } + } + } + } else { + for row in near(cell.y, reach.y, rows) { + for column in near(cell.x - line_shift(tile, row), reach.x, columns) { + if let Some(value) = tile_value(tile, seed, (column, row), (columns, rows), (point, inputs)) { + add(value); + } + } + } + } + let background = background.map_or(tile.background, |image| gray(image.sample(point.x, point.y))); + finish(tile, sum, colored, background) +} + +/// The combined tiles over `background`, through the pattern's opacity and its position/contrast window +fn finish(tile: &TileGenerator, sum: f32, colored: f32, background: f32) -> f32 { + let alpha = sum.clamp(0.0, 1.0) * tile.opacity; + let color = colored.clamp(0.0, 1.0) * tile.opacity; + let value = (background * (1.0 - alpha) + color).clamp(0.0, 1.0); + let windowed = window(value, tile.position, tile.contrast); + + // Out-of-range settings drawn as they are must not leave a non-number in the texture + if windowed.is_finite() { windowed } else { 0.0 } +} + +/// The position/contrast window: position picks the input range stretched to 0..1 (0.5 keeps it), contrast narrows it around its middle +fn window(value: f32, position: f32, contrast: f32) -> f32 { + let low = (1.0 - 2.0 * position).clamp(0.0, 1.0); + let high = (2.0 - 2.0 * position).clamp(0.0, 1.0); + let middle = (low + high) * 0.5; + let half = (high - low) * 0.5 * (1.0 - contrast); + if half <= EPSILON { + return f32::from(u8::from(value >= middle)); + } + + ((value - (middle - half)) / (2.0 * half)).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(tile: &TileGenerator, x: f32, y: f32) -> f32 { + value(tile, Vec2::new(x, y), 1, None) + } + + #[test] + fn rotated_tiles_cover_the_repeat_boundary_once() { + let tile = TileGenerator { + shape: TileShape::Square, + amount: [1, 1], + size_mode: TileSizeMode::NormalSize, + size: [1.0, 0.1], + scale: 2.0, + rotation: 45.0, + blending: TileBlending::Add, + ..TileGenerator::default() + }; + + assert!(at(&tile, 0.99, 0.01) > 0.99); + assert!(at(&tile, 0.99, 0.01) <= 1.0); + } + + #[test] + fn overlapping_periodic_copies_contribute_one_tile_value() { + let tile = TileGenerator { + shape: TileShape::Square, + amount: [1, 1], + size_mode: TileSizeMode::NormalSize, + size: [1.0, 1.0], + scale: 2.0, + color: 0.4, + blending: TileBlending::Add, + ..TileGenerator::default() + }; + + assert!((at(&tile, 0.5, 0.5) - 0.4).abs() < EPSILON); + } + + /// Bell shapes peak only at their tile's center, so the brightest texel of a cell shows where its tile is + fn bells(amount: [u32; 2]) -> TileGenerator { + TileGenerator { shape: TileShape::Bell, amount, ..TileGenerator::default() } + } + + #[test] + fn tile_centers_follow_the_amounts() { + let tile = bells([4, 2]); + + // Cell (i, j) of a 4 × 2 grid is centered at ((i + 0.5) / 4, (j + 0.5) / 2) + for (x, y) in [(0.125, 0.25), (0.375, 0.75), (0.875, 0.25)] { + assert!(at(&tile, x, y) > 0.99, "a tile center at ({x}, {y})"); + } + assert!(at(&tile, 0.25, 0.25) < 0.01, "the bells meet at zero between cells"); + } + + #[test] + fn the_offset_shifts_each_row_along_by_its_share_of_a_cell() { + let tile = TileGenerator { offset: 0.5, ..bells([4, 4]) }; + + // Row 0 stays; row 1 (y 0.375) moves half a cell (0.125) to the right + assert!(at(&tile, 0.125, 0.125) > 0.99); + assert!(at(&tile, 0.25, 0.375) > 0.99, "row 1's first tile is centered at x 0.25"); + assert!(at(&tile, 0.125, 0.375) < 0.5); + + let columns = TileGenerator { vertical_offset: true, ..tile }; + assert!(at(&columns, 0.375, 0.25) > 0.99, "a vertical offset moves column 1 down instead"); + } + + #[test] + fn a_free_rotation_turns_the_shape_clockwise() { + // The half bell's bright side is to the left (−x); turned a quarter clockwise it is at the top + let tile = TileGenerator { shape: TileShape::HalfBell, specific: 1.0, amount: [1, 1], ..TileGenerator::default() }; + assert!(at(&tile, 0.3, 0.5) > at(&tile, 0.7, 0.5)); + let turned = TileGenerator { rotation: 90.0, ..tile }; + assert!(at(&turned, 0.5, 0.3) > at(&turned, 0.5, 0.7), "the bright side moved from the left to the top"); + } + + /// Whether a disc of a 2 × 1 grid's first tile, centered at (0.25, 0.5), covers the point `right` and `down` of its center + fn first_disc_covers(tile: &TileGenerator, right: f32, down: f32) -> bool { + at(tile, 0.25 + right, 0.5 + down) > 0.5 + } + + #[test] + fn each_size_mode_sizes_the_shape_its_own_way() { + let discs = TileGenerator { shape: TileShape::Disc, amount: [2, 1], ..TileGenerator::default() }; + assert!(first_disc_covers(&discs, 0.2, 0.0) && first_disc_covers(&discs, 0.0, 0.4), "without a gap the disc fills its 0.5 × 1 cell"); + + // Half the cell: 0.25 wide and 0.5 high, so the disc ends 0.125 right and 0.25 below its center + let halved = TileGenerator { size_mode: TileSizeMode::NormalSize, size: [0.5, 0.5], ..discs.clone() }; + assert!(first_disc_covers(&halved, 0.1, 0.0) && !first_disc_covers(&halved, 0.15, 0.0)); + assert!(first_disc_covers(&halved, 0.0, 0.2) && !first_disc_covers(&halved, 0.0, 0.3)); + + // The largest square of the cell is 0.5 wide and high, whatever the size is set to + let square = TileGenerator { size_mode: TileSizeMode::KeepRatio, ..halved.clone() }; + assert!(first_disc_covers(&square, 0.2, 0.0) && first_disc_covers(&square, 0.0, 0.2) && !first_disc_covers(&square, 0.0, 0.3)); + + // A fifth of the pattern has the same extent in absolute and reference pixels + let absolute = TileGenerator { size_mode: TileSizeMode::Absolute, size_absolute: [0.2, 0.2], ..discs.clone() }; + let pixel = TileGenerator { size_mode: TileSizeMode::Pixel, size_pixel: [0.2 * PIXEL_REFERENCE; 2], ..discs.clone() }; + for sized in [&absolute, &pixel] { + assert!(first_disc_covers(sized, 0.08, 0.0) && !first_disc_covers(sized, 0.12, 0.0), "{:?}", sized.size_mode); + assert!(first_disc_covers(sized, 0.0, 0.08) && !first_disc_covers(sized, 0.0, 0.12), "{:?}", sized.size_mode); + } + } + + #[test] + fn size_randomness_shrinks_shapes_sized_absolutely_or_in_pixels_only() { + // Sixteen texels across each of the 4 × 4 cells: enough for the covered count to move when the discs shrink + const SAMPLES_PER_SIDE: usize = 64; + let center = |sample: usize| (sample as f32 + 0.5) / SAMPLES_PER_SIDE as f32; + let covered = |tile: &TileGenerator| { + (0..SAMPLES_PER_SIDE).flat_map(|y| (0..SAMPLES_PER_SIDE).map(move |x| (x, y))).filter(|(x, y)| at(tile, center(*x), center(*y)) > 0.5).count() + }; + let fifth = [0.2, 0.2]; + let discs = TileGenerator { + shape: TileShape::Disc, + amount: [4, 4], + size: [0.8, 0.8], + size_absolute: fifth, + size_pixel: fifth.map(|share| share * PIXEL_REFERENCE), + ..TileGenerator::default() + }; + let random = TileGenerator { size_random: [1.0, 1.0], ..discs.clone() }; + + for mode in [TileSizeMode::NormalInterstice, TileSizeMode::NormalSize, TileSizeMode::KeepRatio] { + let (plain, random) = (TileGenerator { size_mode: mode, ..discs.clone() }, TileGenerator { size_mode: mode, ..random.clone() }); + assert_eq!(covered(&plain), covered(&random), "{mode:?} ignores the size randomness"); + } + for mode in [TileSizeMode::Absolute, TileSizeMode::Pixel] { + let (plain, random) = (TileGenerator { size_mode: mode, ..discs.clone() }, TileGenerator { size_mode: mode, ..random.clone() }); + assert!(covered(&random) < covered(&plain), "{mode:?}: random sizes shrink the discs"); + } + } + + #[test] + fn masks_hide_their_rows_columns_and_checkers() { + let checker = TileGenerator { checker_mask: true, ..bells([2, 2]) }; + assert!(at(&checker, 0.25, 0.25) > 0.99 && at(&checker, 0.75, 0.25) < 0.01, "odd (i + j) is hidden"); + let rows = TileGenerator { horizontal_mask: true, ..bells([2, 2]) }; + assert!(at(&rows, 0.25, 0.25) > 0.99 && at(&rows, 0.25, 0.75) < 0.01, "the horizontal mask hides odd rows"); + let columns = TileGenerator { vertical_mask: true, ..bells([2, 2]) }; + assert!(at(&columns, 0.25, 0.25) < 0.01 && at(&columns, 0.75, 0.25) > 0.99, "the vertical mask hides even columns"); + let inverted = TileGenerator { invert_mask: true, ..columns }; + assert!(at(&inverted, 0.25, 0.25) > 0.99, "invert mask shows what the masks hid"); + } + + #[test] + fn the_position_window_stretches_a_range_and_contrast_makes_a_step() { + assert_eq!(window(0.3, 0.5, 0.0), 0.3, "the middle position leaves the value"); + assert_eq!(window(0.75, 0.25, 0.0), 0.5, "position 0.25 stretches 0.5..1 to 0..1"); + assert_eq!(window(0.49, 0.5, 1.0), 0.0); + assert_eq!(window(0.51, 0.5, 1.0), 1.0, "full contrast cuts at the middle of the range"); + } + + #[test] + fn every_shape_stays_in_range_and_outside_its_square_is_empty() { + for shape_kind in TileShape::ALL { + for specific in [0.0, 0.5, 1.0] { + for step in 0..41 { + let u = step as f32 / 20.0 - 1.0; + let value = shape(shape_kind, u, u * 0.7, specific); + assert!((0.0..=1.0 + 1e-5).contains(&value), "{shape_kind:?} at {u}: {value}"); + } + assert_eq!(shape(shape_kind, 1.2, 0.0, specific), 0.0); + } + } + } + + /// An image `size` texels wide whose left half is `left` and right half `right` + fn halves(left: f32, right: f32) -> std::sync::Arc { + let size = 8; + let rgba = (0..size * size).map(|texel| if texel % size < size / 2 { [left, left, left, 1.0] } else { [right, right, right, 1.0] }).collect(); + std::sync::Arc::new(ImageRes { width: size as u32, height: size as u32, rgba, srgb: false }) + } + + #[test] + fn the_image_shape_draws_its_inputs_in_turn_by_pattern_number() { + let images: ImageStore = [("dark".to_string(), halves(0.2, 0.2)), ("bright".to_string(), halves(0.9, 0.9))].into(); + let tile = TileGenerator { + shape: TileShape::Image, + amount: [2, 1], + inputs: vec!["dark".into(), "bright".into()], + input_distribution: TileInputDistribution::ByNumber, + ..TileGenerator::default() + }; + + // Tile 0 (left) draws the first input, tile 1 the second + let left = value(&tile, Vec2::new(0.25, 0.5), 1, Some(&images)); + let right = value(&tile, Vec2::new(0.75, 0.5), 1, Some(&images)); + assert!((left - 0.2).abs() < 0.01 && (right - 0.9).abs() < 0.01, "{left} {right}"); + assert_eq!(value(&tile, Vec2::new(0.25, 0.5), 1, None), 0.0, "missing images draw nothing"); + } + + #[test] + fn an_image_input_keeps_its_orientation_in_the_tile() { + let images: ImageStore = [("halves".to_string(), halves(0.0, 1.0))].into(); + let tile = TileGenerator { shape: TileShape::Image, amount: [1, 1], inputs: vec!["halves".into()], ..TileGenerator::default() }; + assert!(value(&tile, Vec2::new(0.3, 0.5), 1, Some(&images)) < 0.05, "the image's left half is on the tile's left"); + assert!(value(&tile, Vec2::new(0.7, 0.5), 1, Some(&images)) > 0.95); + } + + #[test] + fn the_background_image_shows_between_the_shapes() { + let images: ImageStore = [("ground".to_string(), halves(0.4, 0.4))].into(); + let tile = TileGenerator { background_image: Some("ground".into()), interstice: [0.5, 0.5], ..bells([2, 2]) }; + + // Between the bells only the background is left + assert!((value(&tile, Vec2::new(0.0, 0.0), 1, Some(&images)) - 0.4).abs() < 0.01); + assert_eq!(value(&tile, Vec2::new(0.0, 0.0), 1, None), 0.0, "without the image the background value stays"); + } + + #[test] + fn hostile_settings_neither_crash_nor_leave_the_range() { + let hostile = TileGenerator { + amount: [0, u32::MAX], + scale: f32::INFINITY, + size_mode: TileSizeMode::Pixel, + size_pixel: [f32::NAN, 1e30], + position_random: [1.0, 1.0], + offset: f32::NAN, + middle_size: [0.0, 1.0], + ..TileGenerator::default() + }; + for step in 0..20 { + let value = at(&hostile, step as f32 * 0.37, -(step as f32) * 1.3); + assert!((0.0..=1.0).contains(&value)); + } + } +} diff --git a/crates/compose/src/tile_random_stream.rs b/crates/compose/src/tile_random_stream.rs new file mode 100644 index 00000000..57b0236b --- /dev/null +++ b/crates/compose/src/tile_random_stream.rs @@ -0,0 +1,85 @@ +//! The random streams of a Tile Generator + +/// The random streams of a Tile Generator, so the randoms of one tile are independent of each other +#[derive(Clone, Copy)] +pub(crate) enum TileRandomStream { + Luminance = 0, + Scale, + Offset, + PositionX, + PositionY, + Rotation, + QuarterTurn, + QuarterTurnApplies, + MirrorX, + MirrorY, + Mask, + SizeX, + SizeY, + IntersticeX, + IntersticeY, + Input, +} + +/// Odd multipliers spreading the seed, the stream and the index over the hash, and its start (the golden ratio's and xxHash32's primes) +const SEED_MIX: u32 = 0x9E37_79B1; +const STREAM_MIX: u32 = 0x85EB_CA77; +const INDEX_MIX: u32 = 0xC2B2_AE3D; +const HASH_START: u32 = 0x27D4_EB2F; +/// The finalizer's multipliers ("lowbias32", an integer hash whose output bits all depend on every input bit) and its rounds +const FINALIZER_MIX_A: u32 = 0x7FEB_352D; +const FINALIZER_MIX_B: u32 = 0x846C_A68B; +const FINALIZER_ROUNDS: usize = 3; +/// The bits a draw keeps: an f32's precision, so every value is exact and below 1 +const DRAW_BITS: u32 = 24; + +impl TileRandomStream { + /// A uniform value in 0..1 per (seed, stream, index): an integer hash, so a tile's randoms do not depend on evaluation order + pub(crate) fn draw(self, seed: u32, index: u32) -> f32 { + let mut hash = seed + .wrapping_mul(SEED_MIX) + .wrapping_add((self as u32).wrapping_mul(STREAM_MIX)) + .wrapping_add(index.wrapping_mul(INDEX_MIX)) + .wrapping_add(HASH_START); + for _ in 0..FINALIZER_ROUNDS { + hash ^= hash >> 16; + hash = hash.wrapping_mul(FINALIZER_MIX_A); + hash ^= hash >> 15; + hash = hash.wrapping_mul(FINALIZER_MIX_B); + hash ^= hash >> 16; + } + (hash >> (u32::BITS - DRAW_BITS)) as f32 / (1u32 << DRAW_BITS) as f32 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A draw keeps 24 bits, so `bits / 2^24` is the value exactly + fn exact(bits: u32) -> f32 { + bits as f32 / (1u32 << DRAW_BITS) as f32 + } + + /// Saved projects keep only the seed and the settings, so a changed draw would move the tiles of existing textures + #[test] + fn draws_stay_the_values_saved_projects_were_made_with() { + assert_eq!(TileRandomStream::Luminance.draw(0, 0), exact(6_969_297)); + assert_eq!(TileRandomStream::Rotation.draw(1, 7), exact(11_123_133)); + assert_eq!(TileRandomStream::Input.draw(u32::MAX, u32::MAX), exact(6_943_220)); + } + + #[test] + fn draws_are_below_one_and_differ_by_seed_stream_and_index() { + let first = TileRandomStream::Scale.draw(3, 5); + + assert_eq!(first, TileRandomStream::Scale.draw(3, 5), "the same seed, stream and index draw the same value"); + assert_ne!(first, TileRandomStream::Scale.draw(4, 5)); + assert_ne!(first, TileRandomStream::Offset.draw(3, 5)); + assert_ne!(first, TileRandomStream::Scale.draw(3, 6)); + for index in 0..1000 { + let value = TileRandomStream::Mask.draw(index, index); + assert!((0.0..1.0).contains(&value), "draw {index} is {value}"); + } + } +} diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index ead117eb..08f971be 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -31,7 +31,7 @@ fn fixture() -> Fixture { } fn procedural(kind: ProceduralKind, low: f32, high: f32) -> Source { - Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3] } + Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3], ramp: Vec::new() } } fn add(f: &mut Fixture, ts: usize, kind: LayerKind, mask: Option) -> LayerId { @@ -196,11 +196,11 @@ fn instances_draw_their_source_across_texture_sets() { #[test] fn mask_with_height_follows_the_layer_height() { let mut f = fixture(); - // A white layer over the default gray, half masked, its height falling from 0.25 (left) to - // -0.25 (right). + + // Half masking makes the height fall from 0.25 at left to -0.25 at right let mut ramp = Procedural::new(ProceduralKind::Gradient); ramp.scale = 1.0; - let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3] }; + let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() }; let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None); let mut mask = Mask::new(MaskBackground::Black); mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() })); @@ -214,7 +214,8 @@ fn mask_with_height_follows_the_layer_height() { assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray"); assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left)); assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right)); - // Without a mask there is nothing to combine. + + // Without a mask there is nothing to combine f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false; assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3); } @@ -332,6 +333,7 @@ fn stroke(target: LayerId) -> StrokePreview { mask_value: 1.0, stencil: None, carried: BTreeMap::new(), + carried_mask: None, } } @@ -406,9 +408,10 @@ fn anchor_readers_fall_back_to_full_evaluation() { let mut f = fixture(); let n = nested_stack(&mut f); let anchor = effect(&mut f, EffectKind::Anchor); - let source = Source::Anchor { anchor: anchor.id, channel: Channel::Height }; + let source = Source::Anchor { anchor: anchor.id, channel: Channel::Height, ramp: Vec::new() }; f.project.layer_mut(n.base).unwrap().content_effects.push(anchor); - // A mask above the hot layer reads the stack below it. + + // A mask above the hot layer reads the stack below it let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() }); f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader); for hot in [n.deep, n.top] { @@ -512,21 +515,25 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() { f.project.layer_mut(low).unwrap().content_effects.extend([mid, raise, end]); let top = add(&mut f, 0, LayerKind::Paint, None); paint_rect(&mut f, top, (0, 0), (60, 60), 0.3); - // Without readers the stack is cached (anchors are still recorded) and exact. + + // Without readers the stack is cached (anchors are still recorded) and exact assert!(!check_cached(&f, 0, top).is_empty()); - // Readers: roughness reads the anchor inside the stack, metallic the one at its end. + + // Readers: roughness reads the anchor inside the stack, metallic the one at its end for (c, anchor) in [(Channel::Roughness, mid_id), (Channel::Metallic, end_id)] { - let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height })]), None); + let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() })]), None); f.project.layer_mut(reader).unwrap().channels.retain(|x, _| *x == c); } let out = reference(&f, 0); let at = |c| out.value(c, 128, 128)[0]; - // Half opacity over the default height 0: 0.4 before the raise, 0.8 after it. + + // Half opacity over the default height 0: 0.4 before the raise, 0.8 after it assert!((at(Channel::Roughness) - 0.2).abs() < 2e-3, "inside the stack: {}", at(Channel::Roughness)); assert!((at(Channel::Metallic) - 0.4).abs() < 2e-3, "at the end: {}", at(Channel::Metallic)); assert!((at(Channel::Height) - 0.4).abs() < 2e-3); assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything"); - // Behind a blur the cut reads the filtered field; before it, the unfiltered content. + + // Behind a blur the cut reads the filtered field; before it, the unfiltered content let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 })); f.project.layer_mut(low).unwrap().content_effects.insert(0, blur); let blurred = reference(&f, 0); @@ -742,6 +749,46 @@ fn a_live_stroke_releases_the_fields_kept_before_it_started() { assert!(live == run_with(&fixture, 0, &all, None, Some(&preview)), "a stroke that starts during a sliced pass differs"); } +#[test] +fn cached_stack_tracks_the_images_a_tile_generator_reads() { + use std::sync::Arc; + use texturecraft_compose::{ImageRes, ImageStore}; + + let mut fixture = fixture(); + let hot_layer = heavy_stack(&mut fixture); + let bottom_layer = fixture.project.texture_sets[0].stack[0]; + let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(bottom_layer).unwrap().kind else { panic!("expected fill") }; + let mut pattern = Procedural::new(ProceduralKind::TileGenerator); + pattern.tile.get_or_insert_with(Box::default).background_image = Some("plate".into()); + fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }); + + let image_with_value = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false }); + let mut images = ImageStore::default(); + let baked = Default::default(); + let tiles = all_tiles(RES, RES); + let mut cache = BelowCache::default(); + cache.set_hot(Some(hot_layer)); + let mut output = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + + for (stage, background) in [("cold", None), ("added", Some(1.0)), ("replaced", Some(0.4))] { + if let Some(value) = background { + images.insert("plate".into(), image_with_value(value)); + } + + fixture.pixels.layer_mut(hot_layer, Channel::BaseColor, (RES, RES)).set(5, 5, &[stage.len() as u16, 0, 0, u16::MAX]); + let input = inputs(&fixture, 0, &images, &baked); + composite_tiles_cached(&input, &mut output, &tiles[..1], Some(&mut cache)); + assert!(!cache.is_empty(), "{stage}: first tile should be cached"); + let retained = cache.len() - 1; + composite_tiles_cached(&input, &mut output, &tiles[1..], Some(&mut cache)); + assert_eq!(retained, 0, "{stage}: the layers below are drawn again with the new image"); + + let mut expected = Composite::new(&fixture.project.texture_sets[0].channel_list(), RES); + composite_tiles(&input, &mut expected, &tiles); + assert!(output == expected, "{stage}"); + } +} + #[test] fn cached_stack_tracks_referenced_images_only() { use std::sync::Arc; diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 4eede134..965fd283 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -8,17 +8,33 @@ use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum}; mod curvature_detail; mod curvature_mode; +mod decal_flip; +mod decal_symmetry; mod generator_global; mod micro_detail; mod output_resolution; mod resolution_mode; +mod tile_blending; +mod tile_generator; +mod tile_input_distribution; +mod tile_shape; +mod tile_size_mode; +mod tile_symmetry; pub use curvature_detail::CurvatureDetail; pub use curvature_mode::CurvatureMode; +pub use decal_flip::DecalFlip; +pub use decal_symmetry::DecalSymmetry; pub use generator_global::GeneratorGlobal; pub use micro_detail::MicroDetail; pub use output_resolution::OutputResolution; pub use resolution_mode::ResolutionMode; +pub use tile_blending::TileBlending; +pub use tile_generator::TileGenerator; +pub use tile_input_distribution::TileInputDistribution; +pub use tile_shape::TileShape; +pub use tile_size_mode::TileSizeMode; +pub use tile_symmetry::TileSymmetry; /// Id of a layer or effect (one id space per project). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -192,6 +208,18 @@ pub struct Decal { pub offset: [f32; 2], /// How far in front of and behind the frame the decal reaches (world units). pub depth: f32, + /// A mirrored copy of the decal on the other side of the mesh (None: no copy). The copy + /// follows this frame, so moving, scaling or turning the decal moves it too. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub symmetry: Option, + /// Mirror the image inside the frame: left to right (`[0]`), top to bottom (`[1]`). Old projects have neither. + #[serde(default, skip_serializing_if = "not_flipped")] + pub flip: [bool; 2], +} + +/// Serde helper: a decal that mirrors nothing saves without the field +fn not_flipped(flip: &[bool; 2]) -> bool { + !flip[0] && !flip[1] } impl Default for Projection { @@ -262,10 +290,12 @@ pub enum ProceduralKind { Pores, /// Sharp-edged paint chips. Chips, + /// Shapes laid out in a grid of tiles, with the settings in [`Procedural::tile`] + TileGenerator, } impl ProceduralKind { - pub const ALL: [ProceduralKind; 23] = [ + pub const ALL: [ProceduralKind; 24] = [ ProceduralKind::Clouds, ProceduralKind::Perlin, ProceduralKind::Noise, @@ -289,6 +319,7 @@ impl ProceduralKind { ProceduralKind::Smudges, ProceduralKind::Pores, ProceduralKind::Chips, + ProceduralKind::TileGenerator, ]; pub fn label(self) -> &'static str { match self { @@ -315,6 +346,7 @@ impl ProceduralKind { ProceduralKind::Smudges => "Fingerprints", ProceduralKind::Pores => "Pores", ProceduralKind::Chips => "Paint chips", + ProceduralKind::TileGenerator => "Tile Generator", } } pub fn parse(s: &str) -> Option { @@ -335,11 +367,34 @@ pub struct Procedural { /// Shifts the pattern brighter (+) or darker (−). pub balance: f32, pub invert: bool, + /// The Tile Generator's settings; `None` for other kinds (and reads as the defaults); loaded in range, as drawing trusts them + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "tile_in_range")] + pub tile: Option>, + /// The resolution the pattern is computed at before it is sampled onto the texture set + #[serde(default, skip_serializing_if = "OutputResolution::is_default")] + pub resolution: OutputResolution, +} + +/// Saved Tile Generator settings brought into range (a saved project is hostile input) +fn tile_in_range<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result>, D::Error> { + let saved: Option> = Deserialize::deserialize(deserializer)?; + Ok(saved.map(|tile| Box::new(tile.clamped()))) } impl Procedural { + /// The scales a command accepts (repeats per projection unit) + pub const MIN_SCALE: f32 = 0.001; + pub const MAX_SCALE: f32 = 1000.0; + /// The strongest contrast a command accepts, and the furthest balance either way + pub const MAX_CONTRAST: f32 = 20.0; + pub const MAX_BALANCE: f32 = 1.0; + pub fn new(kind: ProceduralKind) -> Procedural { - Procedural { kind, scale: 4.0, seed: 1, contrast: 1.0, balance: 0.0, invert: false } + let tile = (kind == ProceduralKind::TileGenerator).then(Box::default); + + // The Tile Generator lays its whole grid over one projection unit, as its tile counts set its frequency + let scale = if tile.is_some() { 1.0 } else { 4.0 }; + Procedural { kind, scale, seed: 1, contrast: 1.0, balance: 0.0, invert: false, tile, resolution: OutputResolution::default() } } } @@ -348,8 +403,15 @@ impl Procedural { pub enum Source { /// A constant value (linear RGB for colors; `[v, v, v]` for scalars). Uniform([f32; 3]), - /// A procedural pattern mixing two values. - Procedural { pattern: Procedural, low: [f32; 3], high: [f32; 3] }, + /// A procedural pattern mixing two values, or on a color channel colored by `ramp` when it + /// has stops (a gradient map: dark to light through evenly spaced linear RGB colors). + Procedural { + pattern: Procedural, + low: [f32; 3], + high: [f32; 3], + #[serde(default, skip_serializing_if = "Vec::is_empty")] + ramp: Vec<[f32; 3]>, + }, /// An imported image resource, by name. `normal_format` is the convention of a normal map /// image (DirectX images have their green flipped where a normal channel samples them). Image { @@ -358,8 +420,14 @@ pub enum Source { normal_format: crate::NormalFormat, }, /// The stack value recorded by an anchor point effect (`anchor` is the effect id) for - /// `channel`; colors read as gray where a scalar is needed. - Anchor { anchor: LayerId, channel: Channel }, + /// `channel`; colors read as gray where a scalar is needed. On a color channel a `ramp` with + /// stops recolors the value by its lightness (a gradient map). + Anchor { + anchor: LayerId, + channel: Channel, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + ramp: Vec<[f32; 3]>, + }, } impl Source { @@ -372,6 +440,23 @@ impl Source { Source::Image { name: name.into(), normal_format: crate::NormalFormat::OpenGl } } + /// The image resources this source reads: its image, or the images of a Tile Generator pattern + pub fn images(&self) -> Vec<&str> { + match self { + Source::Image { name, .. } => vec![name.as_str()], + Source::Procedural { pattern, .. } => pattern.tile.iter().flat_map(|tile| tile.images()).collect(), + Source::Uniform(_) | Source::Anchor { .. } => Vec::new(), + } + } + + /// The gradient map stops of a procedural or anchor source (empty: none). + pub fn ramp(&self) -> &[[f32; 3]] { + match self { + Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => ramp, + _ => &[], + } + } + /// The anchor point this source reads, if any. pub fn anchor(&self) -> Option { match self { @@ -1045,6 +1130,10 @@ pub enum EffectKind { pub struct PathShape { /// Surface positions (3D view) or texture coordinates with z = 0 (2D view). pub points: Vec<[f32; 3]>, + /// Per point: the curve turns sharply there instead of passing smoothly through. Empty (and absent from old + /// projects) when every point is smooth; a missing entry is smooth too. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub corners: Vec, pub uv: bool, pub closed: bool, /// A closed path fills its interior instead of stroking the curve. @@ -1114,7 +1203,7 @@ impl EffectKind { let mut anchors: Vec<_> = sources .into_iter() .filter_map(|source| match source { - Source::Anchor { anchor, channel } => Some((*anchor, *channel)), + Source::Anchor { anchor, channel, .. } => Some((*anchor, *channel)), _ => None, }) .collect(); @@ -1126,7 +1215,7 @@ impl EffectKind { anchors } - /// The image resources this effect's sources read (a fill, material or generator input). + /// The image resources this effect's sources read (a fill, its patterns, a material or a generator input) pub fn images_read(&self) -> impl Iterator { let sources: Vec<&Source> = match self { EffectKind::Fill { source, .. } => vec![source], @@ -1134,10 +1223,7 @@ impl EffectKind { EffectKind::Generator(generator) => generator.inputs.values().collect(), _ => Vec::new(), }; - sources.into_iter().filter_map(|source| match source { - Source::Image { name, .. } => Some(name.as_str()), - _ => None, - }) + sources.into_iter().flat_map(Source::images) } } @@ -1164,7 +1250,7 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { - // Generators and fills that build a mask usually add on top of the background. + // Generators and fills that build a mask usually add on top of the background Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0 } } } @@ -1173,6 +1259,27 @@ impl Effect { mod tests { use super::*; + #[test] + fn a_decal_saved_without_symmetry_loads_unchanged_and_saves_without_it() { + let old = r#"{"center":[0.0,0.0,1.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":0.5}"#; + let decal: Decal = serde_json::from_str(old).unwrap(); + assert_eq!(decal.symmetry, None); + assert_eq!(serde_json::to_string(&decal).unwrap(), old.replace(' ', ""), "nothing new is written for a decal without a copy"); + + let mirrored = Decal { symmetry: Some(DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: 0.0 }), ..decal }; + let json = serde_json::to_string(&mirrored).unwrap(); + assert!(json.contains(r#""symmetry":{"axis":2,"flip":"v"}"#), "{json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), mirrored); + let without_flip = json.replace(r#","flip":"v""#, ""); + assert_eq!(serde_json::from_str::(&without_flip).unwrap().symmetry, Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.0 })); + + // The plane's offset is written only when it is not zero + let moved = Decal { symmetry: Some(DecalSymmetry { axis: 1, flip: DecalFlip::None, offset: -0.25 }), ..decal }; + let json = serde_json::to_string(&moved).unwrap(); + assert!(json.contains(r#""offset":-0.25}"#), "{json}"); + assert_eq!(serde_json::from_str::(&json).unwrap(), moved); + } + #[test] fn material_effect_images_are_reported_as_used() { let mut fill = Fill::default(); @@ -1206,6 +1313,42 @@ mod tests { } } + #[test] + fn patterns_saved_before_tile_settings_keep_their_form() { + let saved = serde_json::json!({"kind": "Clouds", "scale": 4.0, "seed": 1, "contrast": 1.0, "balance": 0.0, "invert": false}); + + let loaded: Procedural = serde_json::from_value(saved.clone()).unwrap(); + + assert_eq!(loaded, Procedural::new(ProceduralKind::Clouds)); + assert_eq!(serde_json::to_value(&loaded).unwrap(), saved, "a pattern at its defaults saves as before"); + + let tile = serde_json::to_value(Procedural::new(ProceduralKind::TileGenerator)).unwrap(); + + assert!( + tile.get("tile").is_some() && tile.get("resolution").is_none(), + "only the Tile Generator carries tile settings, and a default resolution is not saved" + ); + } + + #[test] + fn tile_settings_saved_with_missing_or_hostile_values_load_in_range() { + let tile = serde_json::json!({"amount": [0, 4000], "specific": 7.0, "quarter_turns": 6, "inputs": ["a", "b", "c", "d", "e", "f", "g"]}); + let saved = serde_json::json!({"kind": "TileGenerator", "scale": 1.0, "seed": 1, "contrast": 1.0, "balance": 0.0, "invert": false, "tile": tile}); + + let loaded: Procedural = serde_json::from_value(saved).unwrap(); + let tile = loaded.tile.unwrap(); + + assert_eq!(tile.amount, [1, 64]); + assert_eq!(tile.specific, 1.0); + assert_eq!(tile.quarter_turns, 2); + assert_eq!(tile.inputs.len(), TileGenerator::MAX_INPUTS); + assert_eq!(tile.middle_size, TileGenerator::default().middle_size, "a missing setting reads its default"); + + let not_finite = TileGenerator { scale: f32::NAN, rotation: f32::INFINITY, ..TileGenerator::default() }.clamped(); + + assert_eq!((not_finite.scale, not_finite.rotation), (1.0, 0.0)); + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); @@ -1296,6 +1439,29 @@ mod tests { assert!(nan.point(c, [0.5; 3]).unwrap().iter().all(|v| v.is_finite())); } + #[test] + fn gradient_map_stops_round_trip_and_sources_without_them_save_as_before() { + let ramp = vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]; + let procedural = |ramp: Vec<[f32; 3]>| Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.25; 3], high: [0.75; 3], ramp }; + let anchor = |ramp: Vec<[f32; 3]>| Source::Anchor { anchor: LayerId(7), channel: Channel::BaseColor, ramp }; + for source in [procedural(ramp.clone()), anchor(ramp.clone())] { + let json = serde_json::to_value(&source).unwrap(); + assert!(json.to_string().contains("\"ramp\""), "{json}"); + assert_eq!(serde_json::from_value::(json).unwrap(), source); + assert_eq!(source.ramp(), ramp.as_slice()); + } + + // Empty ramps preserve older projects' JSON shape + let old_procedural = serde_json::json!({"Procedural": {"pattern": serde_json::to_value(Procedural::new(ProceduralKind::Clouds)).unwrap(), "low": [0.25, 0.25, 0.25], "high": [0.75, 0.75, 0.75]}}); + let old_anchor = serde_json::json!({"Anchor": {"anchor": 7, "channel": "BaseColor"}}); + for (old, source) in [(old_procedural, procedural(Vec::new())), (old_anchor, anchor(Vec::new()))] { + assert_eq!(serde_json::to_value(&source).unwrap(), old); + assert_eq!(serde_json::from_value::(old).unwrap(), source); + assert!(source.ramp().is_empty()); + } + assert!(Source::Uniform([0.5; 3]).ramp().is_empty()); + } + #[test] fn effect_targets_and_anchor_reads() { assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks"); @@ -1303,7 +1469,7 @@ mod tests { assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None); let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]); assert!(!fill_layer.reads_anchor()); - let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height }; + let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() }; fill_layer.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) @@ -1336,6 +1502,22 @@ mod tests { assert_eq!(hm.apply(0.5, f32::NAN), 0.5); } + #[test] + fn old_decals_load_unflipped_and_save_unchanged() { + let old = r#"{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,2.0],"rotation":0.0,"offset":[0.0,0.0],"depth":0.5}"#; + let decal: Decal = serde_json::from_str(old).unwrap(); + assert_eq!(decal.flip, [false, false]); + assert_eq!( + serde_json::from_str::(&serde_json::to_string(&decal).unwrap()).unwrap(), + serde_json::from_str::(old).unwrap() + ); + + let flipped = Decal { flip: [true, false], ..decal }; + let saved = serde_json::to_string(&flipped).unwrap(); + assert!(saved.contains(r#""flip":[true,false]"#), "{saved}"); + assert_eq!(serde_json::from_str::(&saved).unwrap(), flipped); + } + #[test] fn generator_kinds_parse() { for k in GeneratorKind::ALL { diff --git a/crates/core/src/layer/decal_flip.rs b/crates/core/src/layer/decal_flip.rs new file mode 100644 index 00000000..9db2356c --- /dev/null +++ b/crates/core/src/layer/decal_flip.rs @@ -0,0 +1,14 @@ +use serde::{Deserialize, Serialize}; + +/// How the mirrored decal's image is turned over +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum DecalFlip { + /// Only the reflection: the copy is the decal's mirror image + #[default] + None, + /// The image's left and right swapped + U, + /// The image's top and bottom swapped + V, +} diff --git a/crates/core/src/layer/decal_symmetry.rs b/crates/core/src/layer/decal_symmetry.rs new file mode 100644 index 00000000..e0968ada --- /dev/null +++ b/crates/core/src/layer/decal_symmetry.rs @@ -0,0 +1,26 @@ +use serde::{Deserialize, Deserializer, Serialize}; + +use super::DecalFlip; + +/// The mirrored copy of a decal: reflected through the plane perpendicular to `axis`, across the mesh center (moved by `offset`) +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct DecalSymmetry { + /// Axis the mirror plane is perpendicular to (0 = X, 1 = Y, 2 = Z) + #[serde(deserialize_with = "deserialize_axis")] + pub axis: u8, + /// Extra flip of the image on the mirrored copy, on top of the reflection itself + #[serde(default)] + pub flip: DecalFlip, + /// Where the mirror plane sits, relative to the mesh center along `axis` (world units, as the brush symmetry's offset) + #[serde(default, skip_serializing_if = "is_zero")] + pub offset: f32, +} + +fn deserialize_axis<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + // Recover malformed projects with the same Z plane used by the renderer + Ok(u8::deserialize(deserializer)?.min(2)) +} + +fn is_zero(value: &f32) -> bool { + *value == 0.0 +} diff --git a/crates/core/src/layer/tile_blending.rs b/crates/core/src/layer/tile_blending.rs new file mode 100644 index 00000000..9f42f021 --- /dev/null +++ b/crates/core/src/layer/tile_blending.rs @@ -0,0 +1,23 @@ +use serde::{Deserialize, Serialize}; + +/// How a Tile Generator combines shapes that overlap +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileBlending { + #[default] + Add, + Max, + /// Adds bright shapes and subtracts dark ones + AddSub, +} + +impl TileBlending { + pub const ALL: [TileBlending; 3] = [TileBlending::Add, TileBlending::Max, TileBlending::AddSub]; + + pub fn label(self) -> &'static str { + match self { + TileBlending::Add => "Add", + TileBlending::Max => "Max", + TileBlending::AddSub => "Add sub", + } + } +} diff --git a/crates/core/src/layer/tile_generator.rs b/crates/core/src/layer/tile_generator.rs new file mode 100644 index 00000000..6836fcd9 --- /dev/null +++ b/crates/core/src/layer/tile_generator.rs @@ -0,0 +1,265 @@ +use serde::{Deserialize, Serialize}; + +use super::tile_blending::TileBlending; +use super::tile_input_distribution::TileInputDistribution; +use super::tile_shape::TileShape; +use super::tile_size_mode::TileSizeMode; +use super::tile_symmetry::TileSymmetry; + +/// The settings of a Tile Generator pattern: shapes laid out in a grid of tiles, in the reference app's sections (pattern, size, position, rotation, color); pairs are `[horizontal, vertical]`; angles are in degrees; the seeds of the random settings are separate from the pattern's seed, as in the reference app +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct TileGenerator { + /// The level the output is cut at (0.5 leaves it unchanged) + pub position: f32, + /// How sharply the output is cut at [`TileGenerator::position`] (0 unchanged, 1 a hard step) + pub contrast: f32, + /// Tiles across and down + pub amount: [u32; 2], + /// The reference app's Non Square Expansion, kept with the settings: its outputs match with it on and off, so drawing ignores it + pub non_square_expansion: bool, + + pub shape: TileShape, + /// Texels per side the shape is drawn at before it is laid out + pub shape_resolution: [u32; 2], + /// Changes the shape in its own way (roundness, falloff, ripple count…) + pub specific: f32, + pub shape_angle: f32, + pub shape_scale: f32, + pub shape_size: [f32; 2], + /// Repeats of the shape inside each tile + pub shape_tiling: u32, + /// Turns the shape 45 degrees + pub shape_diagonal: bool, + /// As [`TileGenerator::non_square_expansion`], for the shape itself + pub shape_non_square_expansion: bool, + /// Input images, read when [`TileGenerator::shape`] is [`TileShape::Image`] + pub inputs: Vec, + pub input_distribution: TileInputDistribution, + /// Quarter turns of every shape (0 to 3) + pub quarter_turns: u8, + /// The share of shapes turned by a random number of quarter turns + pub quarter_turn_random: f32, + /// Turns every other shape a quarter turn + pub quincunx_flip: bool, + /// The share of shapes mirrored + pub symmetry_random: f32, + pub symmetry: TileSymmetry, + + pub size_mode: TileSizeMode, + /// Where the boundary between alternating columns (rows) falls; 0.5 makes them equal + pub middle_size: [f32; 2], + /// The gap between shapes, in [`TileSizeMode::NormalInterstice`] + pub interstice: [f32; 2], + pub interstice_random: [f32; 2], + /// The shape's size as a share of its cell, in [`TileSizeMode::NormalSize`] + pub size: [f32; 2], + /// The shape's size as a share of the pattern, in [`TileSizeMode::Absolute`] + pub size_absolute: [f32; 2], + /// The shape's size in pixels, in [`TileSizeMode::Pixel`] + pub size_pixel: [f32; 2], + /// How much each shape's size shrinks at random, in [`TileSizeMode::Absolute`] and [`TileSizeMode::Pixel`] + pub size_random: [f32; 2], + pub scale: f32, + pub scale_random: f32, + pub scale_random_seed: u32, + + /// Shift of each row (column) from the one before, as a share of a tile + pub offset: f32, + pub offset_random: f32, + pub offset_random_seed: u32, + /// Shifts columns instead of rows + pub vertical_offset: bool, + pub position_random: [f32; 2], + pub global_offset: [f32; 2], + + pub rotation: f32, + pub rotation_random: f32, + + /// The shapes' brightness + pub color: f32, + pub luminance_random: f32, + /// Brightness rises tile after tile + pub luminance_by_number: bool, + /// Bigger shapes are brighter + pub luminance_by_scale: bool, + /// Hides every other tile + pub checker_mask: bool, + /// Hides the odd rows + pub horizontal_mask: bool, + /// Hides the even columns + pub vertical_mask: bool, + /// The share of tiles hidden at random + pub random_mask: f32, + /// Shows the hidden tiles instead + pub invert_mask: bool, + pub blending: TileBlending, + pub background: f32, + /// An image under the shapes instead of [`TileGenerator::background`] + pub background_image: Option, + pub opacity: f32, + /// Gives tile n the randoms of the last tile but n (the reference app's Reverse Rendering Order: its blendings don't depend on order) + pub reverse_order: bool, +} + +impl TileGenerator { + /// Tiles per side: the reference app's slider range + pub const AMOUNT: std::ops::RangeInclusive = 1..=64; + /// Shape resolutions offered (the reference app's 256 to 4096) + pub const SHAPE_RESOLUTIONS: [u32; 5] = [256, 512, 1024, 2048, 4096]; + pub const SHAPE_TILING: std::ops::RangeInclusive = 1..=16; + pub const MAX_SCALE: f32 = 2.0; + pub const MAX_RANDOM_SEED: u32 = 1000; + /// The largest shape in the pixel size mode: the largest shape resolution + pub const MAX_SIZE_PIXELS: f32 = 4096.0; + /// Input images a pattern reads + pub const MAX_INPUTS: usize = 6; + + pub fn is_default(&self) -> bool { + *self == TileGenerator::default() + } + + /// The settings inside their ranges, with non-finite numbers at their defaults (saved projects and commands are hostile input) + pub fn clamped(&self) -> TileGenerator { + TileGenerator { + inputs: self.inputs.iter().take(TileGenerator::MAX_INPUTS).cloned().collect(), + background_image: self.background_image.clone(), + ..self.clamped_numbers() + } + } + + /// [`TileGenerator::clamped`] without the input images + fn clamped_numbers(&self) -> TileGenerator { + let default = TileGenerator::default(); + let unit = |value: f32, fallback: f32| if value.is_finite() { value.clamp(0.0, 1.0) } else { fallback }; + let unit_pair = |pair: [f32; 2], fallback: [f32; 2]| [unit(pair[0], fallback[0]), unit(pair[1], fallback[1])]; + let angle = |value: f32| if value.is_finite() { value.rem_euclid(360.0) } else { 0.0 }; + let amount = |count: u32| count.clamp(*TileGenerator::AMOUNT.start(), *TileGenerator::AMOUNT.end()); + let resolution = |size: u32| { + let largest = TileGenerator::SHAPE_RESOLUTIONS[TileGenerator::SHAPE_RESOLUTIONS.len() - 1]; + size.clamp(TileGenerator::SHAPE_RESOLUTIONS[0], largest).next_power_of_two().min(largest) + }; + TileGenerator { + position: unit(self.position, default.position), + contrast: unit(self.contrast, default.contrast), + amount: self.amount.map(amount), + shape_resolution: self.shape_resolution.map(resolution), + specific: unit(self.specific, default.specific), + shape_angle: angle(self.shape_angle), + shape_scale: unit(self.shape_scale, default.shape_scale), + shape_size: unit_pair(self.shape_size, default.shape_size), + shape_tiling: self.shape_tiling.clamp(*TileGenerator::SHAPE_TILING.start(), *TileGenerator::SHAPE_TILING.end()), + inputs: Vec::new(), + quarter_turns: self.quarter_turns % 4, + quarter_turn_random: unit(self.quarter_turn_random, 0.0), + symmetry_random: unit(self.symmetry_random, 0.0), + middle_size: unit_pair(self.middle_size, default.middle_size), + interstice: unit_pair(self.interstice, default.interstice), + interstice_random: unit_pair(self.interstice_random, default.interstice_random), + size: unit_pair(self.size, default.size), + size_absolute: unit_pair(self.size_absolute, default.size_absolute), + size_pixel: self + .size_pixel + .map(|pixels| if pixels.is_finite() { pixels.clamp(0.0, TileGenerator::MAX_SIZE_PIXELS) } else { default.size_pixel[0] }), + size_random: unit_pair(self.size_random, default.size_random), + scale: if self.scale.is_finite() { self.scale.clamp(0.0, TileGenerator::MAX_SCALE) } else { default.scale }, + scale_random: unit(self.scale_random, 0.0), + scale_random_seed: self.scale_random_seed.min(TileGenerator::MAX_RANDOM_SEED), + offset: unit(self.offset, 0.0), + offset_random: unit(self.offset_random, 0.0), + offset_random_seed: self.offset_random_seed.min(TileGenerator::MAX_RANDOM_SEED), + position_random: unit_pair(self.position_random, default.position_random), + global_offset: unit_pair(self.global_offset, default.global_offset), + rotation: angle(self.rotation), + rotation_random: unit(self.rotation_random, 0.0), + color: unit(self.color, default.color), + luminance_random: unit(self.luminance_random, 0.0), + random_mask: unit(self.random_mask, 0.0), + background: unit(self.background, default.background), + opacity: unit(self.opacity, default.opacity), + background_image: None, + non_square_expansion: self.non_square_expansion, + shape: self.shape, + shape_diagonal: self.shape_diagonal, + shape_non_square_expansion: self.shape_non_square_expansion, + input_distribution: self.input_distribution, + quincunx_flip: self.quincunx_flip, + symmetry: self.symmetry, + size_mode: self.size_mode, + vertical_offset: self.vertical_offset, + luminance_by_number: self.luminance_by_number, + luminance_by_scale: self.luminance_by_scale, + checker_mask: self.checker_mask, + horizontal_mask: self.horizontal_mask, + vertical_mask: self.vertical_mask, + invert_mask: self.invert_mask, + blending: self.blending, + reverse_order: self.reverse_order, + } + } + + /// Every image the pattern reads + pub fn images(&self) -> impl Iterator { + self.inputs.iter().chain(&self.background_image).map(String::as_str) + } +} + +impl Default for TileGenerator { + fn default() -> Self { + TileGenerator { + position: 0.5, + contrast: 0.0, + amount: [10, 10], + non_square_expansion: true, + shape: TileShape::default(), + shape_resolution: [256, 256], + specific: 0.5, + shape_angle: 0.0, + shape_scale: 1.0, + shape_size: [1.0, 1.0], + shape_tiling: 1, + shape_diagonal: false, + shape_non_square_expansion: true, + inputs: Vec::new(), + input_distribution: TileInputDistribution::default(), + quarter_turns: 0, + quarter_turn_random: 0.0, + quincunx_flip: false, + symmetry_random: 0.0, + symmetry: TileSymmetry::default(), + size_mode: TileSizeMode::default(), + middle_size: [0.5, 0.5], + interstice: [0.0, 0.0], + interstice_random: [0.0, 0.0], + size: [1.0, 1.0], + size_absolute: [0.1, 0.1], + size_pixel: [1.0, 1.0], + size_random: [0.0, 0.0], + scale: 1.0, + scale_random: 0.0, + scale_random_seed: 0, + offset: 0.0, + offset_random: 0.0, + offset_random_seed: 0, + vertical_offset: false, + position_random: [0.0, 0.0], + global_offset: [0.0, 0.0], + rotation: 0.0, + rotation_random: 0.0, + color: 1.0, + luminance_random: 0.0, + luminance_by_number: false, + luminance_by_scale: false, + checker_mask: false, + horizontal_mask: false, + vertical_mask: false, + random_mask: 0.0, + invert_mask: false, + blending: TileBlending::default(), + background: 0.0, + background_image: None, + opacity: 1.0, + reverse_order: false, + } + } +} diff --git a/crates/core/src/layer/tile_input_distribution.rs b/crates/core/src/layer/tile_input_distribution.rs new file mode 100644 index 00000000..3830c87e --- /dev/null +++ b/crates/core/src/layer/tile_input_distribution.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// Which of a Tile Generator's input images each tile draws +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileInputDistribution { + /// A random input per tile + #[default] + Random, + /// The inputs in turn, tile after tile + ByNumber, +} + +impl TileInputDistribution { + pub const ALL: [TileInputDistribution; 2] = [TileInputDistribution::Random, TileInputDistribution::ByNumber]; + + pub fn label(self) -> &'static str { + match self { + TileInputDistribution::Random => "Random", + TileInputDistribution::ByNumber => "By pattern number", + } + } +} diff --git a/crates/core/src/layer/tile_shape.rs b/crates/core/src/layer/tile_shape.rs new file mode 100644 index 00000000..8ab1ba2c --- /dev/null +++ b/crates/core/src/layer/tile_shape.rs @@ -0,0 +1,67 @@ +use serde::{Deserialize, Serialize}; + +/// The shape a Tile Generator draws in each tile +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileShape { + /// One of the pattern's input images + Image, + Square, + Disc, + Paraboloid, + Bell, + Gaussian, + Thorn, + Pyramid, + #[default] + Brick, + Gradation, + Waves, + HalfBell, + RidgedBell, + Crescent, + Capsule, + Cone, +} + +impl TileShape { + /// In the reference app's menu order + pub const ALL: [TileShape; 16] = [ + TileShape::Image, + TileShape::Square, + TileShape::Disc, + TileShape::Paraboloid, + TileShape::Bell, + TileShape::Gaussian, + TileShape::Thorn, + TileShape::Pyramid, + TileShape::Brick, + TileShape::Gradation, + TileShape::Waves, + TileShape::HalfBell, + TileShape::RidgedBell, + TileShape::Crescent, + TileShape::Capsule, + TileShape::Cone, + ]; + + pub fn label(self) -> &'static str { + match self { + TileShape::Image => "Custom image input", + TileShape::Square => "Square", + TileShape::Disc => "Disc", + TileShape::Paraboloid => "Paraboloid", + TileShape::Bell => "Bell", + TileShape::Gaussian => "Gaussian", + TileShape::Thorn => "Thorn", + TileShape::Pyramid => "Pyramid", + TileShape::Brick => "Brick", + TileShape::Gradation => "Gradation", + TileShape::Waves => "Waves", + TileShape::HalfBell => "Half bell", + TileShape::RidgedBell => "Ridged bell", + TileShape::Crescent => "Crescent", + TileShape::Capsule => "Capsule", + TileShape::Cone => "Cone", + } + } +} diff --git a/crates/core/src/layer/tile_size_mode.rs b/crates/core/src/layer/tile_size_mode.rs new file mode 100644 index 00000000..efb56069 --- /dev/null +++ b/crates/core/src/layer/tile_size_mode.rs @@ -0,0 +1,32 @@ +use serde::{Deserialize, Serialize}; + +/// How a Tile Generator sizes its shapes +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileSizeMode { + /// Each shape fills its tile minus the interstice (the gap between shapes) + #[default] + NormalInterstice, + /// Each shape takes a size relative to its tile, whatever the gap + NormalSize, + /// Each shape is the largest square its tile holds; the size settings are not read + KeepRatio, + /// A size relative to the whole pattern, whatever the tile count + Absolute, + /// A size in pixels of a 2048 pixel output, whatever the output's resolution + Pixel, +} + +impl TileSizeMode { + pub const ALL: [TileSizeMode; 5] = + [TileSizeMode::NormalInterstice, TileSizeMode::NormalSize, TileSizeMode::KeepRatio, TileSizeMode::Absolute, TileSizeMode::Pixel]; + + pub fn label(self) -> &'static str { + match self { + TileSizeMode::NormalInterstice => "Normal - interstice", + TileSizeMode::NormalSize => "Normal - size", + TileSizeMode::KeepRatio => "Keep ratio", + TileSizeMode::Absolute => "Absolute", + TileSizeMode::Pixel => "Pixel", + } + } +} diff --git a/crates/core/src/layer/tile_symmetry.rs b/crates/core/src/layer/tile_symmetry.rs new file mode 100644 index 00000000..c9f92902 --- /dev/null +++ b/crates/core/src/layer/tile_symmetry.rs @@ -0,0 +1,22 @@ +use serde::{Deserialize, Serialize}; + +/// The mirrors a Tile Generator's random symmetry picks from +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum TileSymmetry { + #[default] + Both, + Horizontal, + Vertical, +} + +impl TileSymmetry { + pub const ALL: [TileSymmetry; 3] = [TileSymmetry::Both, TileSymmetry::Horizontal, TileSymmetry::Vertical]; + + pub fn label(self) -> &'static str { + match self { + TileSymmetry::Both => "Horizontal + vertical", + TileSymmetry::Horizontal => "Horizontal", + TileSymmetry::Vertical => "Vertical", + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index c43c9a68..65e55637 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -24,9 +24,10 @@ pub use bake::{ pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; pub use layer::{ - ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask, - Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural, - ProceduralKind, Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit, + ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, + GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, + PathShape, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, + TileSymmetry, gradient, hsl_adjust, per_unit, }; pub use project::{ AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project, diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index f669aa79..a06c3498 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -562,6 +562,11 @@ impl Project { } let (ts, parent, i) = self.locate(id).ok_or(CoreError::NoLayer(id))?; if let Some(t) = target { + let (target_set, _, _) = self.locate(t).ok_or(CoreError::NoLayer(t))?; + if target_set != ts { + return Err(CoreError::Invalid("layer move target belongs to another texture set".into())); + } + let mut sub = Vec::new(); self.collect_subtree(id, 0, &mut sub); if sub.contains(&t) { @@ -791,7 +796,7 @@ mod tests { ]; let id = p.insert_layer(0, l, None, false).unwrap(); let mut top = paint(&mut p, "y"); - let source = Source::Anchor { anchor, channel: Channel::Height }; + let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; top.mask = Some(Mask { effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) @@ -801,7 +806,8 @@ mod tests { let back: Project = serde_json::from_str(&json).unwrap(); assert_eq!(back, p); assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id)); - // Projects saved before content effects existed load with empty stacks. + + // Projects saved before content effects existed load with empty stacks let mut v: serde_json::Value = serde_json::from_str(&json).unwrap(); for l in v["layers"].as_object_mut().unwrap().values_mut() { l.as_object_mut().unwrap().remove("content_effects"); diff --git a/crates/engine/src/camera_cmds.rs b/crates/engine/src/camera_cmds.rs index 9c44c06e..44a9dd48 100644 --- a/crates/engine/src/camera_cmds.rs +++ b/crates/engine/src/camera_cmds.rs @@ -37,6 +37,23 @@ pub fn specs() -> Vec { cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)), cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)), cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)), + cmd!( + "camera.view", + "Fixed view", + [], + None, + "{view: front|back|left|right|top|bottom} → the camera (looks at the mesh from that side and frames it; the projection stays)", + always, + |s, p| fixed_view(s, strp(p, "view").ok_or_else(|| bad("camera.view", "`view` is required"))?) + ), + cmd!("camera.view.front", "Front view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "front")), + cmd!("camera.view.back", "Back view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "back")), + cmd!("camera.view.left", "Left view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "left")), + cmd!("camera.view.right", "Right view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "right")), + cmd!("camera.view.top", "Top view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "top")), + cmd!("camera.view.bottom", "Bottom view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "bottom")), + cmd!("camera.perspective", "Perspective", ["Viewport"], Some("F5"), "{}", always, |s, _| projection(s, false)), + cmd!("camera.orthographic", "Orthographic", ["Viewport"], Some("F6"), "{}", always, |s, _| projection(s, true)), cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at), ] } @@ -128,19 +145,48 @@ fn add(s: &mut Session, p: &Value) -> Result { fn select(s: &mut Session, p: &Value) -> Result { if u64p(p, "index").is_none() && strp(p, "name").is_none_or(|n| n == DEFAULT_CAMERA) { - // The default camera: fov and projection from the display settings, framing the mesh. + // The default camera: fov and projection from the display settings, framing the mesh s.camera.fov = s.doc.project.display.fov; s.camera.ortho = false; return crate::execute(s, "viewport.frame", &Value::Null); } + let i = which(s, "camera.select", p)?; if let Some(c) = s.doc.project.cameras.get(i).cloned() { + // A saved view is clamped against the whole mesh, not against a part framed with F + s.camera.scene_radius = s.mesh.radius(); apply(&mut s.camera, &c); } s.revision = s.revision.wrapping_add(1); Ok(crate::view_cmds::camera_json(s)) } +/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90 +/// on +X (the right side); top and bottom stop at the orbit's ±89° pitch limit. +pub const VIEWS: [(&str, f32, f32); 6] = + [("front", 0.0, 0.0), ("back", 180.0, 0.0), ("left", -90.0, 0.0), ("right", 90.0, 0.0), ("top", 0.0, 89.0), ("bottom", 0.0, -89.0)]; + +/// Look at the mesh from fixed view `name` and frame it, keeping the projection. The yaw is the +/// one nearest the current yaw, so the desktop UI's glide takes the short way round. +fn fixed_view(s: &mut Session, name: &str) -> Result { + let Some(&(_, yaw, pitch)) = VIEWS.iter().find(|(view, ..)| *view == name) else { + return Err(bad("camera.view", format!("unknown view `{name}`: one of front, back, left, right, top, bottom"))); + }; + + let current = if s.camera.yaw.is_finite() { s.camera.yaw } else { 0.0 }; + let turn = std::f32::consts::TAU; + s.camera.yaw = current + (yaw.to_radians() - current + turn * 0.5).rem_euclid(turn) - turn * 0.5; + s.camera.pitch = pitch.to_radians(); + crate::execute(s, "viewport.frame", &Value::Null) +} + +/// Switch to a perspective or orthographic projection; position and rotation stay. +fn projection(s: &mut Session, ortho: bool) -> Result { + s.camera.ortho = ortho; + s.revision = s.revision.wrapping_add(1); + Ok(crate::view_cmds::camera_json(s)) +} + /// Shortcut slot `slot` (0-based): the n-th saved camera, in list order. fn bookmark(s: &mut Session, slot: usize) -> Result { if slot >= s.doc.project.cameras.len() { @@ -238,6 +284,73 @@ mod tests { assert!(ids.iter().all(|c| c.shortcut.is_some())); } + #[test] + fn fixed_views_look_from_their_side_frame_the_mesh_and_keep_the_projection() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 37, "pitch": 21, "distance": 9, "target": [0.4, -0.3, 0.2]})).unwrap(); + let (lo, hi) = s.mesh.bounds(); + let mut framed = s.camera; + framed.frame(lo, hi); + let sides = [("front", Vec3::Z), ("back", Vec3::NEG_Z), ("left", Vec3::NEG_X), ("right", Vec3::X), ("top", Vec3::Y), ("bottom", Vec3::NEG_Y)]; + for ortho in [false, true] { + execute(&mut s, "camera.set", &json!({"ortho": ortho})).unwrap(); + for (view, side) in sides { + // Through the parameterized command and through the menu command alike + let menu_id = format!("camera.view.{view}"); + for (id, params) in [("camera.view", json!({"view": view})), (menu_id.as_str(), Value::Null)] { + execute(&mut s, "camera.orbit", &json!({"dx": 123, "dy": 17})).unwrap(); + let back = execute(&mut s, id, ¶ms).unwrap(); + let looking_from = (s.camera.eye() - s.camera.target).normalize(); + assert!(looking_from.dot(side) > 0.999, "{id} {view}: the eye is on the {side} side, not at {looking_from}"); + assert_eq!(s.camera.ortho, ortho, "{id} {view} keeps the projection"); + assert!((s.camera.target - framed.target).length() < 1e-5, "{view} centres the mesh"); + assert!((s.camera.distance - framed.distance).abs() < 1e-4, "{view} frames the mesh"); + assert_eq!(back["ortho"], ortho); + } + } + } + + // Orbit still works from a fixed view, and a view is not an undo step + let steps = s.history_labels().len(); + execute(&mut s, "camera.view.top", &Value::Null).unwrap(); + assert!((s.camera.pitch - 89f32.to_radians()).abs() < 1e-6, "top stops at the orbit limit"); + execute(&mut s, "camera.orbit", &json!({"dx": 30, "dy": -40})).unwrap(); + assert!((s.camera.pitch - 49f32.to_radians()).abs() < 1e-5 && s.camera.yaw.to_degrees().rem_euclid(360.0) > 1.0); + assert_eq!(s.history_labels().len(), steps); + } + + #[test] + fn fixed_views_take_the_nearest_turn_and_reject_unknown_views() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 715})).unwrap(); + execute(&mut s, "camera.view", &json!({"view": "front"})).unwrap(); + assert!((s.camera.yaw - 720f32.to_radians()).abs() < 1e-4, "two whole turns, not a spin back to 0: {}", s.camera.yaw.to_degrees()); + let before = s.camera; + assert!(execute(&mut s, "camera.view", &json!({"view": "sideways"})).is_err()); + assert!(execute(&mut s, "camera.view", &json!({})).is_err(), "`view` is required"); + assert!(execute(&mut s, "camera.view", &json!({"view": 3})).is_err()); + assert_eq!(s.camera, before, "a rejected view leaves the camera"); + let menu: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.view.")).collect(); + assert_eq!(menu.len(), 6); + assert!(menu.iter().all(|c| c.shortcut.is_none() && c.menu == ["Viewport"]), "no default keys: users bind their own"); + } + + #[test] + fn perspective_and_orthographic_change_only_the_projection() { + let mut s = session(); + execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "distance": 4})).unwrap(); + let before = s.camera; + let r = execute(&mut s, "camera.orthographic", &Value::Null).unwrap(); + assert!(s.camera.ortho && r["ortho"] == true); + assert_eq!(OrbitCamera { ortho: false, ..s.camera }, before, "position and rotation stay"); + execute(&mut s, "camera.orthographic", &Value::Null).unwrap(); + assert!(s.camera.ortho, "a second press keeps it orthographic: two actions, not a toggle"); + execute(&mut s, "camera.perspective", &Value::Null).unwrap(); + assert_eq!(s.camera, before); + let key = |id: &str| crate::find(id).and_then(|c| c.shortcut); + assert_eq!((key("camera.perspective"), key("camera.orthographic")), (Some("F5"), Some("F6"))); + } + #[test] fn cameras_round_trip_through_the_project_file() { let mut s = session(); diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 06b74adb..b0e5332f 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -24,6 +24,63 @@ pub struct CommandSpec { pub run: Run, } +impl CommandSpec { + /// Whether a keyboard shortcut can run this command: it acts with no parameters at all, or + /// every parameter in its first `params` form is optional (`name?`) and none of them is one + /// of several alternatives. Left out: commands that need a path, name or similar, commands + /// that only return data or do nothing without parameters, and the ones that replace the + /// open project (the menu asks to save first). + pub fn bindable(&self) -> bool { + const NOT_FROM_A_KEY: [&str; 13] = [ + "project.inspect", + "project.templates", + "project.new", + "tool.state", + "text.fonts", + "export.presets", + "edit.history", + "camera.get", + "textureSet.parts", + "bake.settings", + "bake.preview", + "camera.set", + "textureSet.settings", + ]; + const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"]; + !(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params) + } +} + +/// Whether the first `{...}` group of a `params` text has only optional entries. +fn params_all_optional(params: &str) -> bool { + let Some(body) = params.trim_start().strip_prefix('{') else { return false }; + let Some(end) = body.find('}') else { return false }; + + // `{a?} | {b}`: other forms exist, and the first one alone may not do anything + if body[end + 1..].trim_start().starts_with('|') { + return false; + } + + let (mut depth, mut start) = (0i32, 0); + let mut entries = Vec::new(); + for (i, c) in body[..end].char_indices() { + match c { + '(' | '[' => depth += 1, + ')' | ']' => depth -= 1, + ',' if depth == 0 => { + entries.push(&body[start..i]); + start = i + 1; + } + _ => {} + } + } + entries.push(&body[start..end]); + entries.iter().filter(|entry| !entry.trim().is_empty()).all(|entry| { + // `index? | name?` asks for one of the two, so it is not optional as a whole + !entry.contains(" | ") && entry.trim().split([':', ' ', '(']).next().is_some_and(|key| key.ends_with('?')) + }) +} + pub(crate) fn always(_: &Session) -> std::result::Result<(), String> { Ok(()) } @@ -57,12 +114,14 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::layer_ops::specs()); v.extend(crate::instance_cmds::specs()); v.extend(crate::mask_cmds::specs()); + v.extend(crate::mask_export::specs()); v.extend(crate::color_selection_cmds::specs()); v.extend(crate::effect_clipboard::specs()); v.extend(crate::tool_cmds::specs()); v.extend(crate::brush_preset_cmds::specs()); v.extend(crate::path_tool::specs()); v.extend(crate::view_cmds::specs()); + v.extend(crate::solo::specs()); v.extend(crate::camera_cmds::specs()); v.extend(crate::quick_mask::specs()); v.extend(crate::set_cmds::specs()); @@ -88,6 +147,40 @@ pub fn command_specs() -> &'static [CommandSpec] { }) } +/// Commands that run in the empty state (no project open): they open or create a project, or +/// only read the libraries and the user's presets, or only move the camera (`viewport.frame`, enabled on the reference app's blank screen). +fn works_without_project(id: &str) -> bool { + matches!( + id, + "file.open" + | "file.new" + | "project.new" + | "project.sample" + | "project.inspect" + | "viewport.frame" + | "project.templates" + | "export.presets" + | "export.preset.get" + | "export.preset.save" + | "export.preset.remove" + | "brush.preset.list" + | "alpha.list" + | "filter.list" + | "material.list" + | "mask.smart.list" + | "text.fonts" + ) +} + +/// Whether `spec` can run on `s`: no project open refuses everything but [`works_without_project`] +pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), String> { + if !s.project_open && !works_without_project(spec.id) { + return Err("no project is open".into()); + } + + (spec.enabled)(s) +} + pub fn find(id: &str) -> Option<&'static CommandSpec> { command_specs().iter().find(|c| c.id == id) } @@ -96,7 +189,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// `merge: true` its edits continue the previous undo step of the same label (drags). pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - (spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; + check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false)); let result = (spec.run)(s, params); s.merge_edits = outer; @@ -116,7 +209,7 @@ pub fn list(s: &Session, filter: Option<&str>) -> Value { "menu": c.menu, "shortcut": c.shortcut, "params": c.params, - "enabled": (c.enabled)(s).is_ok(), + "enabled": check_enabled(c, s).is_ok(), }) }) .collect(); @@ -199,7 +292,7 @@ pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result Result> { match p.get(key) { None | Some(Value::Null) => Ok(None), - Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\")"))), + Some(v) => color_of(v).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"))), } } @@ -234,6 +327,65 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> { mod tests { use super::*; + #[test] + fn only_commands_a_key_can_run_are_bindable() { + let bindable = |id: &str| find(id).unwrap_or_else(|| panic!("{id} is gone")).bindable(); + for id in [ + "layer.add.paint", + "layer.add.fill", + "layer.add.group", + "mask.invert", + "mask.clear", + "layer.visible", + "effect.add.paint", + "file.save", + "tool.paint", + "camera.add", + "effect.duplicate", + "effect.paste", + ] { + assert!(bindable(id), "{id} needs no parameters"); + } + for id in [ + "file.saveCopy", + "textureSet.select", + "layer.rename", + "tool.select", + "layer.select", + "viewport.focusAt", + "tool.stroke", + "mask.smart.apply", + "bake.skew.set", + "textureSet.resolution", + "effect.move", + "camera.remove", + "bake.highPoly.remove", + ] { + assert!(!bindable(id), "{id} needs a parameter"); + } + for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] { + assert!(!bindable(id), "{id} is a query or has several forms"); + } + } + + #[test] + fn params_texts_are_read_by_their_required_entries() { + for ok in ["{}", "{layer?}", "{enabled?: bool} \u{2014} toggles when omitted", "{effect?: the selected effect}"] { + assert!(params_all_optional(ok), "{ok}"); + } + for no in [ + "{path}", + "{layer?, name}", + "{x, y (viewport pixels), viewport?: [w, h]}", + "{a?} | {b}", + "{index? | name?}", + "{ts?, value?: 0..1 | path: image}", + "no braces", + ] { + assert!(!params_all_optional(no), "{no}"); + } + } + #[test] fn color_param_accepts_valid_forms() { let p = json!({ @@ -253,10 +405,10 @@ mod tests { #[test] fn color_param_rejects_invalid_forms() { let bad_cases = [ - ("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), - ("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), - ("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), - ("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\")"), + ("#fff", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"), + ("red", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"), + ("#12345", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"), + ("#gggggg", "`color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"), ]; for (input, expected_err) in bad_cases { let p = json!({ "color": input }); @@ -284,4 +436,18 @@ mod tests { assert_eq!(color_of(&json!("#GGGGGG")), None); assert!(color_of(&json!("#ff8000")).is_some()); } + + #[test] + fn no_bindable_command_asks_for_a_parameter() { + // Effect commands need a selected effect, which this session lacks + for spec in command_specs().iter().filter(|c| c.bindable() && c.shortcut.is_none() && !c.id.starts_with("effect.")) { + let mut session = crate::sample_session(256, 64).unwrap(); + if (spec.enabled)(&session).is_ok() + && let Err(err) = execute(&mut session, spec.id, &Value::Null) + { + let text = err.to_string(); + assert!(!text.contains("required") && !text.contains("give "), "{} asks for a parameter: {text}", spec.id); + } + } + } } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index f1cecf11..392da975 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -2,10 +2,12 @@ //! (a decal fill with a planar projection), as a fill layer with a decal projection. use serde_json::{Value, json}; -use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_core::{ + Channel, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source, +}; +use texturecraft_geom::glam::{Quat, Vec2, Vec3}; -use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3}; use crate::tool_cmds::viewport_of; use crate::{Result, Session, StackTarget, cmd}; @@ -16,7 +18,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), keepProportions?: true makes the height follow the width by the image's aspect, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, depth?, symmetry?: x|y|z|off (also place a mirrored copy across the mesh center, perpendicular to that axis; it follows this decal), symmetryFlip?: none|u|v (flip the copy's image on top of the reflection), symmetryOffset?: world units from the mesh center along the axis to the mirror plane (default 0, within the mesh), name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,8 +27,8 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", - has_layer, + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", + always, set ), ] @@ -91,6 +93,56 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) }) } +/// The mirrored copy asked for by `symmetry` (x, y, z or off) and `symmetryFlip` (none, u or v), +/// starting from `current` for what the params leave out +fn symmetry_param(cmd: &str, p: &Value, current: Option, bounds: (Vec3, Vec3)) -> Result> { + let axis = match strp(p, "symmetry").map(str::to_ascii_lowercase).as_deref() { + None => current.map(|symmetry| symmetry.axis.min(2)), + Some("off" | "none") => None, + Some("x") => Some(0), + Some("y") => Some(1), + Some("z") => Some(2), + Some(other) => return Err(bad(cmd, format!("unknown symmetry `{other}` (x, y, z or off)"))), + }; + + let flip = match strp(p, "symmetryFlip").map(str::to_ascii_lowercase).as_deref() { + None => current.map_or(DecalFlip::None, |symmetry| symmetry.flip), + Some("none" | "off") => DecalFlip::None, + Some("u") => DecalFlip::U, + Some("v") => DecalFlip::V, + Some(other) => return Err(bad(cmd, format!("unknown symmetryFlip `{other}` (none, u or v)"))), + }; + + // The plane stays within the mesh, as the brush symmetry's offset does + let (lo, hi) = bounds; + let half_extent = (hi - lo) * 0.5; + let offset = match (f32p(p, "symmetryOffset"), current) { + (Some(offset), _) if !offset.is_finite() => return Err(bad(cmd, "`symmetryOffset` must be a number")), + (Some(offset), _) => offset, + (None, Some(symmetry)) => symmetry.offset, + (None, None) => 0.0, + }; + + Ok(axis.map(|axis| { + let limit = half_extent[usize::from(axis)]; + DecalSymmetry { axis, flip, offset: offset.clamp(-limit, limit) } + })) +} + +/// The up of a decal moved from a surface facing `from.0` (up `from.1`) onto one facing `to`: the +/// old up turned by the smallest rotation that takes the old normal to the new one (parallel +/// transport), so it follows the surface smoothly and never degenerates. A surface turned +/// exactly away has no smallest rotation: the camera rule of a new decal decides there. +fn carried_up(s: &Session, from: (Vec3, Vec3), to: Vec3) -> Vec3 { + let (old_normal, old_up) = from; + let (Some(old_normal), Some(new_normal)) = (old_normal.try_normalize(), to.try_normalize()) else { return old_up }; + if old_normal.dot(new_normal) < -0.9999 { + return decal_up(s, "", &Value::Null, new_normal).unwrap_or(old_up); + } + + Quat::from_rotation_arc(old_normal, new_normal) * old_up +} + fn add(s: &mut Session, p: &Value) -> Result { let cmd = "layer.add.decal"; let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); @@ -112,7 +164,10 @@ fn add(s: &mut Session, p: &Value) -> Result { let mesh_diagonal = mesh_size(s); let default_height = mesh_diagonal * DEFAULT_HEIGHT; - let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); + let mut size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); + if boolp(p, "keepProportions") == Some(true) && p.get("size").is_some_and(Value::is_array) { + size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); + } let decal = Decal { center: center.to_array(), normal: normal.to_array(), @@ -120,8 +175,11 @@ fn add(s: &mut Session, p: &Value) -> Result { size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], + flip: [boolp(p, "flipU").unwrap_or(false), boolp(p, "flipV").unwrap_or(false)], + // By default it reaches half its larger side into the surface depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), + symmetry: symmetry_param(cmd, p, None, s.mesh.bounds())?, }; // A decal dropped on another texture set goes there and selects it, as a dropped material does @@ -169,6 +227,27 @@ fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Res } } +/// Width over height of the image the decal of fill layer `id` (or of mask fill effect `effect`) shows +/// (`new`: the image a call replaces it with, which then counts instead) +fn image_aspect(s: &Session, id: LayerId, effect: Option, new: Option<&str>) -> Option { + let name = match effect { + _ if new.is_some() => new?.to_string(), + Some(effect) => match &s.doc.project.effect(effect)?.1.kind { + EffectKind::Fill { source: Source::Image { name, .. }, .. } => name.clone(), + _ => return None, + }, + None => match &s.doc.project.layer(id).ok()?.kind { + LayerKind::Fill(fill) => fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + })?, + _ => return None, + }, + }; + let image = s.images.get(&name)?; + Some(image.width as f32 / image.height.max(1) as f32) +} + fn set(session: &mut Session, params: &Value) -> Result { let command = "layer.decal.set"; let effect = u64p(params, "effect").map(LayerId); @@ -192,14 +271,32 @@ fn set(session: &mut Session, params: &Value) -> Result { return Err(bad(command, "that surface belongs to another texture set")); } + // Carry up so a stale axis cannot lie in or flip on the new surface + let previous = (Vec3::from(decal.normal), Vec3::from(decal.up)); (decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); + if params.get("up").is_none() { + decal.up = carried_up(session, previous, normal).to_array(); + } } if params.get("up").is_some() { decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array(); } - if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) { + let keep = boolp(params, "keepProportions") == Some(true); + let ratio = decal.size[0] / decal.size[1].max(1e-6); + let aspect = if keep { image_aspect(session, layer_id, effect, strp(params, "image")).unwrap_or(ratio) } else { ratio }; + if let Some(mut size) = size_param(params, aspect, mesh_diagonal).or_else(|| keep.then_some(decal.size)) { + // A height sets the width through `aspect`; a pair or the current size sets the height from the width + if keep && params.get("size").is_none_or(Value::is_array) { + size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); + } decal.size = size; } + if let Some(flip) = boolp(params, "flipU") { + decal.flip[0] = flip; + } + if let Some(flip) = boolp(params, "flipV") { + decal.flip[1] = flip; + } if let Some(rotation) = f32p(params, "rotation") { decal.rotation = rotation.rem_euclid(360.0); } @@ -212,6 +309,7 @@ fn set(session: &mut Session, params: &Value) -> Result { if let Some(depth) = f32p(params, "depth") { decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); } + decal.symmetry = symmetry_param(command, params, decal.symmetry, session.mesh.bounds())?; let image = strp(params, "image").map(str::to_string); if let Some(name) = &image diff --git a/crates/engine/src/effect_clipboard.rs b/crates/engine/src/effect_clipboard.rs index fe79a383..ce397c40 100644 --- a/crates/engine/src/effect_clipboard.rs +++ b/crates/engine/src/effect_clipboard.rs @@ -127,7 +127,7 @@ fn paste(session: &mut Session, params: &Value) -> Result { // The target belongs to the active set's selection: a paste into another set leaves it if let Some((layer_set, _, _)) = session.doc.project.locate(layer) { - session.selected.insert(layer_set, layer); + session.select_one(layer_set, layer); if layer_set == session.ts() { session.target = StackTarget::Effect(pasted); } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index b5c215dc..168c438b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1,6 +1,8 @@ //! Files: projects (`.tcraft`), mesh import, texture export. Byte-based functions work on the //! web; path-based commands are native only. +use std::borrow::Cow; + use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] use texturecraft_core::{NormalFormat, PROJECT_EXT}; @@ -51,7 +53,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}", always, export_textures ), @@ -140,6 +142,7 @@ impl Session { /// for UV-tiled sets, or nothing for them without `tiled`). fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result>> { let opts = ExportOptions { atlas: true, ..opts }; + (0..materials) .map(|m| match self.texture_set_of_material(m) { Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts), @@ -155,20 +158,31 @@ impl Session { /// [`Session::from_mesh_bytes`] with a UV tile mode (see [`Session::new_project_tiled`]). pub fn from_mesh_bytes_tiled(file_name: &str, bytes: &[u8], resolution: u32, name: &str, uv_tiles: Option) -> Result { - let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?; - let ext = ext_of(file_name); - let mut s = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution, uv_tiles)?; - s.doc.project.mesh_file = leaf_of(file_name); - s.doc.project.cameras = imported.cameras; - s.log.extend(imported.report.warnings.iter().cloned()); - s.log.push(format!( + Self::from_mesh_source(file_name, Cow::Borrowed(bytes), resolution, name, uv_tiles) + } + + fn from_mesh_source(file_name: &str, bytes: Cow<'_, [u8]>, resolution: u32, name: &str, uv_tiles: Option) -> Result { + let imported = texturecraft_formats::import_mesh_bytes(file_name, &bytes).map_err(fe)?; + let extension = ext_of(file_name); + let mut session = Session::new_project_tiled(name, imported.mesh, &format!("mesh.{extension}"), None, resolution, uv_tiles)?; + + // Packed mesh files can have spare capacity that the project would otherwise retain + let mut source = bytes.into_owned(); + source.shrink_to_fit(); + session.mesh_source = Some((extension, source)); + session.doc.project.mesh_file = leaf_of(file_name); + session.doc.project.cameras = imported.cameras; + + session.log.extend(imported.report.warnings); + session.log.push(format!( "Imported {} ({} triangles, {} materials{})", file_name, imported.report.triangles, imported.report.materials, if imported.report.uvs_generated { ", UVs generated" } else { "" } )); - Ok(s) + + Ok(session) } /// Open a `.tcraft` project from bytes. @@ -236,17 +250,21 @@ impl Session { /// Render every export file for texture sets `sets` (in memory; works on the web). pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { - self.update(); + if self.solo.is_none() { + self.update(); + } + let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); let empty = Default::default(); for &ts in sets { let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; + let composite = self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?; let coverage = cache.gbuf.coverage_mask(); let input = ExportInput { project: &self.doc.project, ts, - composite: &cache.composite, + composite: &composite, baked: self.doc.baked.get(&ts).unwrap_or(&empty), coverage: &coverage, mesh_name: &mesh_name, @@ -275,6 +293,7 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result Some(crate::preset_cmds::preset_param(v, cmd)?), Some(_) => return Err(bad(cmd, "`preset` must be a preset name or a preset object")), }; + let preset = preset.ok_or_else(|| bad(cmd, format!("unknown export preset {}", p.get("preset").unwrap_or(&Value::Null))))?; let mut o = ExportOptions::new(preset); if let Some(f) = strp(p, "format") { @@ -305,7 +324,8 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result return Err(bad(cmd, format!("`colorSpace` is a name (sRGB, Linear Rec.709, ACEScg or ACES2065-1), not {other}"))), } Ok(o) @@ -315,10 +335,24 @@ fn sets_param(s: &Session, p: &Value, cmd: &str) -> Result> { match p.get("ts") { None => Ok((0..s.set_count()).collect()), Some(Value::String(a)) if a == "all" => Ok((0..s.set_count()).collect()), - Some(v) => Ok(vec![v.as_u64().map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))?]), + + // Several sets in one command, so a file name two of them share is found before anything is written + Some(Value::Array(a)) => { + let mut sets = a.iter().map(|v| set_index(s, v, cmd)).collect::>>()?; + + // A set listed twice is written once + let mut seen = std::collections::HashSet::new(); + sets.retain(|t| seen.insert(*t)); + Ok(sets) + } + Some(v) => Ok(vec![set_index(s, v, cmd)?]), } } +fn set_index(s: &Session, v: &Value, cmd: &str) -> Result { + v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`")) +} + fn plan(s: &mut Session, p: &Value) -> Result { let opts = export_options(s, p, "export.plan")?; let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:")); @@ -387,23 +421,29 @@ pub use native::{absolute, open_path, read_mesh}; /// `file.new {mesh, name?, resolution?, uvTiles?, template?, importCameras?}`: a new project from the /// mesh file `mesh`, remembering its path for Reimport mesh. #[cfg(not(target_arch = "wasm32"))] -fn new_from_mesh(s: &mut Session, p: &Value) -> Result { - let path = native::path_param(p, "mesh", "file.new")?; - let f = native::read_mesh("file.new", path)?; - let template = crate::template_cmds::template_param(s, p, "file.new")?; - let res = u64p(p, "resolution").or(template.as_ref().map(|t| u64::from(t.resolution))).unwrap_or(2048); - let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); - let mut next = Session::from_mesh_bytes_tiled(&f.name, &f.bytes, u32::try_from(res).unwrap_or(0), &name, crate::commands::boolp(p, "uvTiles"))?; +fn new_from_mesh(session: &mut Session, params: &Value) -> Result { + const DEFAULT_RESOLUTION_PX: u64 = 2048; + + let path = native::path_param(params, "mesh", "file.new")?; + let template = crate::template_cmds::template_param(session, params, "file.new")?; + let resolution = u64p(params, "resolution").or(template.as_ref().map(|template| u64::from(template.resolution))).unwrap_or(DEFAULT_RESOLUTION_PX); + let name = strp(params, "name").map(str::to_string).unwrap_or_else(|| stem_of(path)); + let uv_tiles = crate::commands::boolp(params, "uvTiles"); + let mesh_file = native::read_mesh("file.new", path)?; + + let mut next = Session::from_mesh_source(&mesh_file.name, Cow::Owned(mesh_file.bytes), u32::try_from(resolution).unwrap_or(0), &name, uv_tiles)?; next.doc.project.mesh_path = native::absolute(path); - next.log.extend(f.warnings); - if crate::commands::boolp(p, "importCameras") == Some(false) { + next.log.extend(mesh_file.warnings); + if crate::commands::boolp(params, "importCameras") == Some(false) { next.doc.project.cameras.clear(); } - if let Some(t) = &template { - next.apply_template(t); + if let Some(template) = &template { + next.apply_template(template); } - s.switch_to(next); - Ok(crate::inspect::session(s)) + + session.switch_to(next); + + Ok(crate::inspect::session(session)) } #[cfg(not(target_arch = "wasm32"))] @@ -549,7 +589,8 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: let mut textures: Vec = Vec::new(); for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? { let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue }; - // The first tile stands for all of them: its number is written as . + + // The first tile stands for all of them: its number is written as let file = f.udim_name.clone().unwrap_or_else(|| f.name.clone()); let colorspace = materialx::colorspace_name(opts.space_for(f.format)); if !textures.iter().any(|t| t.input == input) { @@ -561,8 +602,10 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name)); continue; } + let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); - // Case-insensitive: Windows and macOS file systems are. + + // Case-insensitive: Windows and macOS file systems are if !stems.insert(stem.to_ascii_lowercase()) { warnings.push(format!( "MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them", @@ -574,7 +617,8 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std: texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?; out.push(path); } - // The normalmap node only exists in a material that has a normal map. + + // The normalmap node only exists in a material that has a normal map if normal_map_written && opts.normal_format == Some(NormalFormat::DirectX) { warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into()); } @@ -663,8 +707,7 @@ use unsupported as export_textures; use unsupported as export_mesh; fn close(s: &mut Session, _: &Value) -> Result { - let next = Session::new_project("Untitled", primitives::material_ball(), "builtin:material_ball", None, 2048)?; - s.switch_to(next); + s.switch_to(Session::closed()?); Ok(Value::Null) } @@ -951,3 +994,17 @@ f 1/1 2/2 3/3 assert_eq!(parts(&mut old), json!(["mesh"])); } } + +#[cfg(all(test, target_pointer_width = "32"))] +mod index_tests { + use super::*; + + #[test] + fn export_rejects_an_index_that_would_wrap_to_the_first_set() { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let wrapped_index = u64::from(u32::MAX) + 1; + + assert!(crate::execute(&mut session, "export.plan", &json!({ "ts": wrapped_index })).is_err()); + assert!(crate::execute(&mut session, "export.plan", &json!({ "ts": [wrapped_index] })).is_err()); + } +} diff --git a/crates/engine/src/filter_lib.rs b/crates/engine/src/filter_lib.rs index 1e7c2b69..45aace1c 100644 --- a/crates/engine/src/filter_lib.rs +++ b/crates/engine/src/filter_lib.rs @@ -149,10 +149,11 @@ fn mat_finish(id: &str) -> Option { "matFinishHammered" => (ProceduralKind::Hammered, 6.0, [0.25, 0.45], 0.08), _ => return None, }; + let pattern = Procedural { scale, ..Procedural::new(kind) }; let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() }; - fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3] }); - fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3] }); + fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3], ramp: Vec::new() }); + fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3], ramp: Vec::new() }); Some(fill) } @@ -264,7 +265,7 @@ pub(crate) fn apply(p: &Value, f: &mut Filter, cmd: &str) -> Result<()> { let parsed: Option> = list.as_array().and_then(|a| a.iter().map(|c| color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect()); match parsed { Some(c) if (1..=16).contains(&c.len()) => *colors = c, - _ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\")")), + _ => return Err(bad(cmd, "`colors` must be 1 to 16 colors ([r, g, b] linear or \"#rrggbb\" sRGB)")), } } } diff --git a/crates/engine/src/frame_target.rs b/crates/engine/src/frame_target.rs new file mode 100644 index 00000000..dc3a1582 --- /dev/null +++ b/crates/engine/src/frame_target.rs @@ -0,0 +1,5 @@ +#[derive(Clone, Copy)] +pub(crate) enum FrameTarget { + All, + Selection, +} diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 3a2e348c..8fb0a3d8 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -7,18 +7,38 @@ use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, Laye use crate::Session; use crate::session::StackTarget; -fn source_json(s: &Source) -> Value { - match s { - Source::Uniform(v) => json!({ "uniform": v }), - Source::Procedural { pattern, low, high } => json!({ - "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high - }), +fn source_json(source: &Source) -> Value { + match source { + Source::Uniform(value) => json!({ "uniform": value }), + Source::Procedural { pattern, low, high, ramp } => { + let mut report = json!({ + "procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high + }); + + if !pattern.resolution.is_default() { + report["resolution"] = + json!({ "mode": format!("{:?}", pattern.resolution.mode), "custom": pattern.resolution.custom, "factor": pattern.resolution.factor }); + } + if let Some(tile) = &pattern.tile { + report["tile"] = crate::procedural_params::tile_report(tile); + } + + with_ramp(report, ramp) + } Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }), Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }), - Source::Anchor { anchor, channel } => json!({ "anchor": anchor.0, "channel": channel.id() }), + Source::Anchor { anchor, channel, ramp } => with_ramp(json!({ "anchor": anchor.0, "channel": channel.id() }), ramp), } } +/// `v` with the gradient map stops of its source as `colors`, when it has any. +fn with_ramp(mut v: Value, ramp: &[[f32; 3]]) -> Value { + if !ramp.is_empty() { + v["colors"] = json!(ramp); + } + v +} + fn fill_json(f: &Fill) -> Value { let mut v = json!({ "projection": f.projection.label(), @@ -182,26 +202,29 @@ pub fn texture_set(session: &Session, index: usize) -> Value { } /// The whole session. -pub fn session(s: &Session) -> Value { - let ts = s.ts(); +pub fn session(session: &Session) -> Value { + let texture_set = session.ts(); json!({ - "project": s.doc.project.name, - "mesh": { "source": s.doc.project.mesh, "triangles": s.mesh.triangle_count(), "vertices": s.mesh.vertex_count(), "materials": s.mesh.materials }, - "path": s.path, - "modified": s.modified, - "textureSets": texture_sets(s), - "bakeMeshes": crate::bake::meshes_json(s), - "activeTextureSet": ts, - "selectedLayer": s.selected_layer().map(|l| l.0), - "target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) }, - "layers": stack(s, ts), - "tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) }, - "view": s.view.label(), - "bakePreview": crate::bake_preview::preview_json(s), - "camera": crate::view_cmds::camera_json(s), - "display": s.doc.project.display, - "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, - "memoryBytes": s.memory().total(), - "pendingTiles": s.pending_tiles(), + "projectOpen": session.project_open, + "project": session.doc.project.name, + "mesh": { "source": session.doc.project.mesh, "triangles": session.mesh.triangle_count(), "vertices": session.mesh.vertex_count(), "materials": session.mesh.materials }, + "path": session.path, + "modified": session.modified, + "textureSets": texture_sets(session), + "bakeMeshes": crate::bake::meshes_json(session), + "activeTextureSet": texture_set, + "selectedLayer": session.selected_layer().map(|layer| layer.0), + "selectedLayers": crate::layer_selection::ids_json(&session.selected_layers()), + "target": match session.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(effect) => json!(effect.0) }, + "layers": stack(session, texture_set), + "tool": { "tool": session.tool.tool.id(), "brush": crate::tool_cmds::brush_json(session) }, + "view": session.view.label(), + "solo": session.solo.map(|solo| json!({ "layer": solo.layer.0, "ignoreMask": solo.ignore_mask })), + "bakePreview": crate::bake_preview::preview_json(session), + "camera": crate::view_cmds::camera_json(session), + "display": session.doc.project.display, + "history": { "undo": session.undo_label(), "redo": session.redo_label(), "depth": session.history_labels().len() }, + "memoryBytes": session.memory().total(), + "pendingTiles": session.pending_tiles(), }) } diff --git a/crates/engine/src/instance_cmds.rs b/crates/engine/src/instance_cmds.rs index a9307883..ebf839ef 100644 --- a/crates/engine/src/instance_cmds.rs +++ b/crates/engine/src/instance_cmds.rs @@ -49,7 +49,7 @@ pub(crate) fn make_instance(s: &mut Session, source: LayerId, ts: usize) -> Resu let sel = s.selected.get(&ts).copied().filter(|l| s.doc.project.locate(*l).is_some_and(|(t, _, _)| t == ts)); let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(Layer::is_group); s.doc.project.insert_layer(ts, Layer::new(id, name, LayerKind::Instance { source: src_id }, &[]), sel, inside)?; - s.selected.insert(ts, id); + s.select_one(ts, id); if ts == s.ts() { s.target = StackTarget::Content; } @@ -98,7 +98,7 @@ pub(crate) fn detach(s: &mut Session, src: &Document, inst: LayerId) -> Result Vec { vec![ cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint), - cmd!("layer.add.fill", "Add fill layer", ["Layers"], None, "{name?, color?, roughness?, metallic?}", always, add_fill), + cmd!( + "layer.add.fill", + "Add fill layer", + ["Layers"], + None, + "{name?, color?: [r,g,b] linear or \"#rrggbb\" sRGB, roughness?, metallic?}", + always, + add_fill + ), cmd!("layer.add.group", "Add folder", ["Layers"], None, "{name?}", always, add_group), - cmd!("layer.remove", "Remove layer(s)", ["Layers"], Some("Delete"), "{layer?}", has_layer, remove), - cmd!("layer.duplicate", "Duplicate layer(s)", ["Layers"], Some("Ctrl+D"), "{layer?}", has_layer, duplicate), - cmd!("layer.group", "Group layer(s)", ["Layers"], Some("Ctrl+G"), "{layer?}", has_layer, group), - cmd!("layer.select", "Select layer", [], None, "{layer, target?: content|mask|}", always, select), + cmd!( + "layer.remove", + "Remove layer(s)", + ["Layers"], + Some("Delete"), + "{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer", + has_layer, + remove + ), + cmd!( + "layer.duplicate", + "Duplicate layer(s)", + ["Layers"], + Some("Ctrl+D"), + "{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer", + has_layer, + duplicate + ), + cmd!( + "layer.group", + "Group layer(s)", + ["Layers"], + Some("Ctrl+G"), + "{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer", + has_layer, + group + ), + cmd!( + "layer.select", + "Select layer", + [], + None, + "{layer, target?: content|mask|} | {layer, toggle: true} (Ctrl+click: add or take out one layer) | {layer, range: true} (Shift+click: the rows from the last clicked layer) | {all: true} (Ctrl+A: every shown row of the active texture set, folder rows and the layers of open folders included) | {layers: [id], layer?} (select several; `layer` is the active one)", + always, + select + ), cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename), - cmd!("layer.visible", "Toggle layer visibility", [], None, "{layer?, visible?}", has_layer, visible), - cmd!("layer.move", "Move layer", [], None, "{layer?, index?} | {layer?, above?: id|null, inside?: bool} | {layer?, delta: ±n}", has_layer, move_layer), + cmd!( + "layer.visible", + "Toggle layer visibility", + [], + None, + "{layer?, layers?: [id], visible?} — default: every selected layer; with `layers`, `layer` is the one the others follow", + has_layer, + visible + ), + cmd!( + "layer.move", + "Move layer", + [], + None, + "{layer? | layers?: [id], index?} | {layer? | layers?: [id], above?: id|null, inside?: bool} | {layer?, delta: ±n}", + has_layer, + move_layer + ), cmd!("layer.blend", "Set channel blending", [], None, "{layer?, channel?: id|all, mode?, opacity?: 0..1, enabled?}", has_layer, blend), + cmd!( + "layer.blending.set", + "Set blending of several channels", + [], + None, + "{layer?, channels: {: {mode?, opacity?: 0..1}}} (only channels the layer has enabled; one undo step)", + has_layer, + blending_set + ), cmd!( "layer.fill.set", "Set fill source", [], None, - "{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}", + "{layer? | effect?: content fill effect id, channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true (alone, they edit the channel's pattern)|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\" sRGB; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}", has_layer, fill_set ), @@ -51,7 +120,7 @@ pub(crate) fn insert_selected(s: &mut Session, layer: Layer) -> Result let sel = s.selected_layer(); let inside = sel.and_then(|id| s.doc.project.layer(id).ok()).is_some_and(|l| l.is_group()); let id = s.doc.project.insert_layer(ts, layer, sel, inside)?; - s.selected.insert(ts, id); + s.select_one(ts, id); s.target = StackTarget::Content; Ok(id) } @@ -110,45 +179,66 @@ fn add_group(s: &mut Session, p: &Value) -> Result { } fn remove(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, "layer.remove", p)?; + let ids = batch_param(s, "layer.remove", p, true)?; let before = s.doc.clone(); let removed = s.edit("Remove layer", |s| { - let (ts, parent, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; - let removed = s.doc.project.remove_layer(id)?; - // Instances of what was removed keep their look as independent layers. + let mut removed = Vec::new(); + + // Top row first, so the layer under the lowest removed one is never removed after it is chosen + for id in &ids { + let (ts, parent, i) = s.doc.project.locate(*id).ok_or(EngineError::Other("layer not in a stack".into()))?; + removed.extend(s.doc.project.remove_layer(*id)?); + + // Select the layer below (or above) the removed one + let list = match parent { + Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(), + None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(), + }; + let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent); + match next { + Some(n) => s.select_one(ts, n), + None => s.select_none(ts), + } + } + + // Instances of what was removed keep their look as independent layers crate::instance_cmds::detach_orphans(s, &before)?; - // Select the layer below (or above) the removed one. - let list = match parent { - Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(), - None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(), - }; - let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent); - match next { - Some(n) => s.selected.insert(ts, n), - None => s.selected.remove(&ts), - }; Ok(removed) })?; Ok(json!({ "removed": removed.iter().map(|l| l.0).collect::>() })) } fn duplicate(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, "layer.duplicate", p)?; - let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; + let ids = batch_param(s, "layer.duplicate", p, true)?; + let first = ids.first().copied().ok_or_else(|| bad("layer.duplicate", "no layer to duplicate"))?; + let (ts, _, _) = s.doc.project.locate(first).ok_or(EngineError::Other("layer not in a stack".into()))?; let src = s.doc.clone(); - let new = s.edit("Duplicate layer", |s| { - let new = crate::layer_ops::copy_tree(&src, id, &mut s.doc, ts, Some(id), false, 0)?; - let name = format!("{} copy", src.project.layer(id)?.name); - s.doc.project.layer_mut(new)?.name = name; - Ok(new) + let copies = s.edit("Duplicate layer", |s| { + // Insert copies in order above the topmost selected layer, at its folder level + let mut copies = Vec::new(); + let mut above = first; + for id in ids.iter().rev() { + let new = crate::layer_ops::copy_tree(&src, *id, &mut s.doc, ts, Some(above), false, 0)?; + let name = format!("{} copy", src.project.layer(*id)?.name); + s.doc.project.layer_mut(new)?.name = name; + copies.insert(0, new); + above = new; + } + Ok(copies) })?; - s.selected.insert(ts, new); - Ok(json!({ "layer": new.0 })) + + // The copies are selected; the active layer's copy stays the active one + let active = + s.selected.get(&ts).and_then(|active| ids.iter().position(|id| id == active)).and_then(|i| copies.get(i)).or(copies.first()).copied().unwrap_or(first); + s.select_several(ts, active, active, copies.clone()); + Ok(json!({ "layer": active.0, "layers": ids_json(&copies) })) } fn group(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, "layer.group", p)?; + let ids = batch_param(s, "layer.group", p, true)?; let g = s.edit("Group layers", |s| { + // The folder takes the top layer's place and parent; the others follow it in, in stack order + let id = ids.first().copied().ok_or_else(|| bad("layer.group", "no layer to group"))?; let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; let gid = s.doc.project.alloc_id(); let name = s.doc.project.next_layer_name(ts, "Folder"); @@ -158,29 +248,51 @@ fn group(s: &mut Session, p: &Value) -> Result { b.mode = BlendMode::Passthrough; } s.doc.project.insert_layer(ts, gl, Some(id), false)?; - s.doc.project.move_above(id, Some(gid), true)?; - s.selected.insert(ts, gid); + move_stacked(&mut s.doc.project, &ids, Some(gid), true)?; + s.select_one(ts, gid); Ok(gid) })?; Ok(json!({ "layer": g.0 })) } fn select(s: &mut Session, p: &Value) -> Result { + if boolp(p, "all") == Some(true) { + return crate::layer_selection::select_all(s); + } + + if p.get("layers").is_some() { + return crate::layer_selection::select_list(s, p); + } + let id = layer_param(s, "layer.select", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?; // Paths paint into the active set if ts != s.ts() { s.finish_path()?; + + // The clone source is a point of the set it was picked in + s.tool.clone_source = None; + } + + // Shift+click and Ctrl/Cmd+click select several layers, each on its content + let range = boolp(p, "range") == Some(true); + if range || boolp(p, "toggle") == Some(true) { + s.active_set = ts; + let active = crate::layer_selection::extend(s, ts, id, range); + s.target = StackTarget::Content; + s.revision = s.revision.wrapping_add(1); + return Ok(json!({ "layer": active.map(|active| active.0), "textureSet": ts, "layers": ids_json(&s.selected_layers()) })); } s.active_set = ts; - s.selected.insert(ts, id); + s.select_one(ts, id); s.target = match p.get("target") { Some(Value::String(t)) if t == "mask" => { if s.doc.project.layer(s.doc.project.mask_owner(id))?.mask.is_none() { return Err(bad("layer.select", "the layer has no mask")); } + StackTarget::Mask } Some(Value::String(t)) if t == "content" => StackTarget::Content, @@ -192,7 +304,7 @@ fn select(s: &mut Session, p: &Value) -> Result { }; s.revision = s.revision.wrapping_add(1); - Ok(json!({ "layer": id.0, "textureSet": ts })) + Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] })) } fn rename(s: &mut Session, p: &Value) -> Result { @@ -209,33 +321,105 @@ fn rename(s: &mut Session, p: &Value) -> Result { } fn visible(s: &mut Session, p: &Value) -> Result { - let id = layer_param(s, "layer.visible", p)?; + let ids = batch_param(s, "layer.visible", p, false)?; + + // Use the clicked layer as lead, then the active or top layer if absent + let lead = u64p(p, "layer") + .map(LayerId) + .filter(|lead| ids.contains(lead)) + .or(s.selected_layer().filter(|active| ids.contains(active))) + .or(ids.first().copied()) + .ok_or_else(|| bad("layer.visible", "no layer given"))?; let v = s.edit("Layer visibility", |s| { - let l = s.doc.project.layer_mut(id)?; - l.visible = boolp(p, "visible").unwrap_or(!l.visible); - Ok(l.visible) + let v = boolp(p, "visible").unwrap_or(!s.doc.project.layer(lead)?.visible); + for id in &ids { + s.doc.project.layer_mut(*id)?.visible = v; + } + Ok(v) })?; Ok(json!({ "visible": v })) } +/// Move `ids` (top row first) above `target` (inside it when `inside`), keeping their order: +/// the lowest goes first and each next one above it. +fn move_stacked(project: &mut Project, ids: &[LayerId], target: Option, inside: bool) -> Result<()> { + let (mut target, mut inside) = (target, inside); + for id in ids.iter().rev() { + project.move_above(*id, target, inside)?; + (target, inside) = (Some(*id), false); + } + Ok(()) +} + +/// The positions of the moved layers determine whether a reorder needs an undo step. +fn apply_move(s: &mut Session, ids: &[LayerId], change: impl FnOnce(&mut Project) -> Result<()>) -> Result { + s.edit_if_changed("Move layer", s.merge_edits, |s| { + let project = &mut s.doc.project; + let previous: Vec<_> = ids.iter().map(|id| project.locate(*id)).collect(); + change(project)?; + let changed = ids.iter().map(|id| project.locate(*id)).ne(previous); + Ok((Value::Null, changed)) + }) +} + +/// `layer.move {layers, index | above}`: the listed layers move together, keeping their order. +fn move_layers(s: &mut Session, p: &Value) -> Result { + let ids = batch_param(s, "layer.move", p, true)?; + if let Some(i) = u64p(p, "index") { + // The lowest one goes to `index` of the texture set's stack, the others right above it in their order + let to = usize::try_from(i).unwrap_or(usize::MAX); + apply_move(s, &ids, |project| { + let mut below = None; + for id in ids.iter().rev() { + match below { + None => { + project.move_above(*id, None, false)?; + project.move_layer(*id, to)?; + } + Some(below) => project.move_above(*id, Some(below), false)?, + } + below = Some(*id); + } + Ok(()) + }) + } else if p.get("above").is_some() { + let above = u64p(p, "above").map(LayerId); + if above.is_some_and(|above| ids.contains(&above)) { + return Err(bad("layer.move", "`above` is one of the moved layers")); + } + + let inside = boolp(p, "inside").unwrap_or(false); + apply_move(s, &ids, |project| move_stacked(project, &ids, above, inside)) + } else { + Err(bad("layer.move", "give `index` or `above` with `layers`")) + } +} + fn move_layer(s: &mut Session, p: &Value) -> Result { + if p.get("layers").is_some() { + return move_layers(s, p); + } + let id = layer_param(s, "layer.move", p)?; - s.edit("Move layer", |s| { + apply_move(s, &[id], |project| { if let Some(d) = p.get("delta").and_then(Value::as_i64) { - let (_, _, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; - let to = (i as i64 + d).max(0) as usize; - s.doc.project.move_layer(id, to)?; + let (_, _, i) = project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?; + + // Saturate hostile deltas before the sibling-list clamp + let distance = usize::try_from(d.unsigned_abs()).unwrap_or(usize::MAX); + let to = if d < 0 { i.saturating_sub(distance) } else { i.saturating_add(distance) }; + project.move_layer(id, to)?; } else if let Some(i) = u64p(p, "index") { - s.doc.project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?; + project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?; } else if p.get("above").is_some() { let above = u64p(p, "above").map(LayerId); - s.doc.project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?; + project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?; } else { return Err(bad("layer.move", "give `delta`, `index` or `above`")); } + Ok(()) - })?; - Ok(Value::Null) + }) } fn blend(s: &mut Session, p: &Value) -> Result { @@ -278,6 +462,35 @@ fn blend(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// `layer.blending.set`: each listed channel gets its own mode and opacity in one undo step. Channels the layer +/// has disabled stay disabled, and channels not listed stay as they are. +fn blending_set(s: &mut Session, p: &Value) -> Result { + let id = content_param(s, "layer.blending.set", p)?; + let listed = p.get("channels").and_then(Value::as_object).ok_or_else(|| bad("layer.blending.set", "`channels` is required"))?; + let mut edits: Vec<(Channel, Option, Option)> = Vec::new(); + for (key, value) in listed { + let channel = Channel::parse(key).ok_or_else(|| bad("layer.blending.set", format!("unknown channel `{key}`")))?; + let mode = blend_param("layer.blending.set", value, "mode")?; + let opacity = f32p(value, "opacity").map(|o| o.clamp(0.0, 1.0)); + edits.push((channel, mode, opacity)); + } + s.edit("Layer blending", |s| { + let l = s.doc.project.layer_mut(id)?; + for (channel, mode, opacity) in edits { + if let Some(b) = l.channels.get_mut(&channel) { + if let Some(m) = mode { + b.mode = m; + } + if let Some(o) = opacity { + b.opacity = o; + } + } + } + Ok(()) + })?; + Ok(Value::Null) +} + /// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's /// (`effect`). #[derive(Clone, Copy)] @@ -309,89 +522,77 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> { } } -fn fill_set(s: &mut Session, p: &Value) -> Result { - let target = fill_target(s, p, "layer.fill.set")?; - let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?; - // `solo`: this channel on, every other one off. - let solo = boolp(p, "solo") == Some(true); - let enabled = if solo { Some(true) } else { boolp(p, "enabled") }; - let normal_format = normal_format_param("layer.fill.set", p)?; - let low = color_param("layer.fill.set", p, "low")?.unwrap_or([0.0; 3]); - let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]); - let color = color_param("layer.fill.set", p, "color")?; - let value = color_param("layer.fill.set", p, "value")?; - let source = if let Some(kind) = strp(p, "procedural") { - let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?; - let mut pr = Procedural::new(kind); - if let Some(v) = f32p(p, "scale") { - pr.scale = v.clamp(0.001, 1000.0); - } - if let Some(v) = u64p(p, "seed") { - pr.seed = v as u32; - } - if let Some(v) = f32p(p, "contrast") { - pr.contrast = v.clamp(0.0, 20.0); - } - if let Some(v) = f32p(p, "balance") { - pr.balance = v.clamp(-1.0, 1.0); - } - pr.invert = boolp(p, "invert").unwrap_or(false); - Some(Source::Procedural { pattern: pr, low, high }) - } else if let Some(c) = color.or(value) { - Some(Source::Uniform(c)) - } else if let Some(name) = strp(p, "image") { - Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() }) - } else if let Some(a) = u64p(p, "anchor") { - let reader = match target { - FillTarget::Layer(id) => Some(id), - FillTarget::Effect(e) => s.doc.project.effect(e).map(|(owner, _)| owner), - }; - let reader = reader.ok_or_else(|| bad("layer.fill.set", "the fill is not in a layer"))?; - let anchor_channel = channel_param("layer.fill.set", p, "anchorChannel")?.unwrap_or(ch); - Some(crate::mask_cmds::anchor_source(s, "layer.fill.set", reader, LayerId(a), anchor_channel)?) - } else if enabled.is_some() || normal_format.is_some() { - None - } else { - return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `normalFormat`, `enabled` or `solo`")); - }; - if normal_format.is_some() && source.as_ref().is_some_and(|src| !matches!(src, Source::Image { .. })) { - return Err(bad("layer.fill.set", "`normalFormat` goes with `image` or alone")); +fn fill_set(session: &mut Session, params: &Value) -> Result { + const CMD: &str = "layer.fill.set"; + let target = fill_target(session, params, CMD)?; + let channel = channel_param(CMD, params, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?; + + // `solo`: this channel on, every other one off + let solo = boolp(params, "solo") == Some(true); + let enabled = if solo { Some(true) } else { boolp(params, "enabled") }; + let normal_format = normal_format_param(CMD, params)?; + let colors = ramp_param(params, channel)?; + let init_ramp = boolp(params, "gradientMap") == Some(true); + if init_ramp && colors.is_some() { + return Err(bad(CMD, "give `gradientMap` or `colors`, not both")); } - // A format-only edit leaves the channel on or off. + + let source = fill_source_from(session, params, (target, channel), normal_format)?; + if source.is_none() && enabled.is_none() && normal_format.is_none() && colors.is_none() && !init_ramp { + return Err(bad( + CMD, + "give `color`, `value`, `procedural`, `image`, `anchor`, pattern settings (`tile`, `resolution`…), `colors`, `gradientMap`, `normalFormat`, `enabled` or `solo`", + )); + } + + if normal_format.is_some() && source.as_ref().is_some_and(|source| !matches!(source, Source::Image { .. })) { + return Err(bad(CMD, "`normalFormat` goes with `image` or alone")); + } + + // Changing only the normal format or gradient stops leaves the layer channel on or off let touches_channel = source.is_some() || enabled.is_some(); - s.edit("Set fill", |s| { - let f = fill_mut(s, target)?; - // `normalFormat` alone: the convention of the channel's image. - if let (None, Some(nf)) = (&source, normal_format) { - match f.sources.get_mut(&ch) { - Some(Source::Image { normal_format, .. }) => *normal_format = nf, - _ => return Err(bad("layer.fill.set", "`normalFormat` needs an image on the channel")), + session.edit("Set fill", |session| { + let fill = fill_mut(session, target)?; + + // `normalFormat` alone: the convention of the channel's image + if let (None, Some(format)) = (&source, normal_format) { + match fill.sources.get_mut(&channel) { + Some(Source::Image { normal_format, .. }) => *normal_format = format, + _ => return Err(bad(CMD, "`normalFormat` needs an image on the channel")), } } + + let current = fill.sources.get(&channel); + let colors = if init_ramp { initial_ramp(channel, source.as_ref(), current)? } else { colors }; + let source = with_ramp(channel, current, source, colors)?; + match target { - // A fill effect's channel is on while it has a source. + // A fill effect's channel is on while it has a source FillTarget::Effect(_) if enabled == Some(false) => { - f.sources.remove(&ch); + fill.sources.remove(&channel); } + + // Removing stops (`colors: []`) from a channel the fill does not have adds nothing + FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && current.is_none() => {} FillTarget::Effect(_) => { - let src = source.unwrap_or_else(|| f.source(ch)); - f.sources.insert(ch, src); + let source = source.unwrap_or_else(|| fill.source(channel)); + fill.sources.insert(channel, source); if solo { - f.sources.retain(|c, _| *c == ch); + fill.sources.retain(|kept, _| *kept == channel); } } FillTarget::Layer(id) => { - if let Some(src) = source { - f.sources.insert(ch, src); + if let Some(source) = source { + fill.sources.insert(channel, source); } - let l = s.doc.project.layer_mut(id)?; + let layer = session.doc.project.layer_mut(id)?; if enabled == Some(false) { - l.channels.remove(&ch); + layer.channels.remove(&channel); } else if touches_channel { - l.channels.entry(ch).or_default(); + layer.channels.entry(channel).or_default(); } if solo { - l.channels.retain(|c, _| *c == ch); + layer.channels.retain(|kept, _| *kept == channel); } } } @@ -400,6 +601,136 @@ fn fill_set(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The source `params` give fill channel `channel` of `target`, or None when they only switch it or set its image's normal format +fn fill_source_from( + session: &mut Session, + params: &Value, + (target, channel): (FillTarget, Channel), + normal_format: Option, +) -> Result> { + const CMD: &str = "layer.fill.set"; + let low = color_param(CMD, params, "low")?.unwrap_or([0.0; 3]); + let high = color_param(CMD, params, "high")?.unwrap_or([1.0; 3]); + let uniform = color_param(CMD, params, "color")?.or(color_param(CMD, params, "value")?); + + if let Some(name) = strp(params, "procedural") { + let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?; + let mut pattern = Procedural::new(kind); + crate::procedural_params::pattern_basics_from(params, &mut pattern); + + // A pattern of the same kind keeps its resolution and Tile Generator settings + let current = fill_mut(session, target)?.sources.get(&channel); + if let Some(Source::Procedural { pattern: current, .. }) = current + && current.kind == kind + { + pattern.resolution = current.resolution; + pattern.tile = current.tile.clone(); + } + + crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; + return Ok(Some(Source::Procedural { pattern, low, high, ramp: Vec::new() })); + } + + if let Some(color) = uniform { + return Ok(Some(Source::Uniform(color))); + } + + if let Some(name) = strp(params, "image") { + return Ok(Some(Source::Image { name: name.to_string(), normal_format: normal_format.unwrap_or_default() })); + } + + if let Some(anchor) = u64p(params, "anchor") { + let reader = match target { + FillTarget::Layer(id) => Some(id), + FillTarget::Effect(effect) => session.doc.project.effect(effect).map(|(owner, _)| owner), + }; + let reader = reader.ok_or_else(|| bad(CMD, "the fill is not in a layer"))?; + let anchor_channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(channel); + return Ok(Some(crate::mask_cmds::anchor_source(session, CMD, reader, LayerId(anchor), anchor_channel)?)); + } + + if !crate::procedural_params::has_pattern_settings(params) { + return Ok(None); + } + + // Pattern settings alone edit the channel's current pattern + let Some(Source::Procedural { pattern, low, high, .. }) = fill_mut(session, target)?.sources.get(&channel) else { + return Err(bad(CMD, "the channel has no pattern: give `procedural` with its settings")); + }; + + let mut pattern = pattern.clone(); + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; + + Ok(Some(Source::Procedural { pattern, low: *low, high: *high, ramp: Vec::new() })) +} + +/// The gradient map stops from `colors` (None when absent, empty to remove). +fn ramp_param(params: &Value, channel: Channel) -> Result>> { + const MAX_GRADIENT_STOPS: usize = 16; + let Some(list) = params.get("colors").filter(|value| !value.is_null()) else { return Ok(None) }; + + let invalid = || bad("layer.fill.set", "`colors` must be up to 16 colors ([r, g, b] linear or \"#rrggbb\")"); + let list = list.as_array().filter(|list| list.len() <= MAX_GRADIENT_STOPS).ok_or_else(invalid)?; + let colors: Vec<_> = list + .iter() + .map(|color| crate::commands::color_of(color).map(|rgb| rgb.map(|component| component.clamp(0.0, 1.0))).ok_or_else(invalid)) + .collect::>()?; + + if !colors.is_empty() && channel.kind() != ChannelKind::Color { + return Err(bad("layer.fill.set", "`colors` (a gradient map) goes on a color channel")); + } + + Ok(Some(colors)) +} + +/// The stops `gradientMap: true` turns on for channel `ch`: those the source already has, else a +/// procedural's low, midpoint and high (so its look holds) or an anchor's black, gray and white. +/// `source` is the one the call sets, else the channel's `current` one. +fn initial_ramp(channel: Channel, source: Option<&Source>, current: Option<&Source>) -> Result>> { + if channel.kind() != ChannelKind::Color { + return Err(bad("layer.fill.set", "`gradientMap` goes on a color channel")); + } + + if let Some(kept) = current.map(Source::ramp).filter(|r| !r.is_empty()) { + return Ok(Some(kept.to_vec())); + } + + match source.or(current) { + Some(Source::Procedural { low, high, .. }) => Ok(Some(vec![*low, std::array::from_fn(|k| (low[k] + high[k]) * 0.5), *high])), + Some(Source::Anchor { .. }) => Ok(Some(vec![[0.0; 3], [0.5; 3], [1.0; 3]])), + _ => Err(bad("layer.fill.set", "`gradientMap` needs a procedural or an anchor on the channel")), + } +} + +/// `source` (or, for `colors` alone, the channel's `current` source) with its gradient map stops: +/// `colors` when given, else those of `current`, so picking another pattern or anchor keeps them. +/// Only color channels keep stops, so a source copied onto another channel loses them; removing +/// stops (`colors: []`) where there are none changes nothing. +fn with_ramp(channel: Channel, current: Option<&Source>, source: Option, colors: Option>) -> Result> { + let adds = colors.as_ref().is_some_and(|colors| !colors.is_empty()); + let needs = || bad("layer.fill.set", "`colors` needs a procedural or an anchor on the channel"); + let mut source = match (source, current) { + (Some(source), _) => source, + (None, Some(current)) if colors.is_some() => current.clone(), + _ if adds => return Err(needs()), + _ => return Ok(None), + }; + + match &mut source { + Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => { + *ramp = colors.unwrap_or_else(|| match current { + Some(current) if channel.kind() == ChannelKind::Color => current.ramp().to_vec(), + _ => Vec::new(), + }); + } + _ if adds => return Err(needs()), + _ => {} + } + + Ok(Some(source)) +} + /// The projection `p` asks for. Fields it does not give keep their values from `current` when /// that is of the same kind (or `p` names no kind), and the kind's defaults otherwise. pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>) -> Result { diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 9493009b..a69b0881 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -128,7 +128,7 @@ fn paste(s: &mut Session, _: &Value) -> Result { let sel = s.selected_layer(); let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group()); let new = copy_tree(&src, id, &mut s.doc, ts, sel, inside, 0)?; - s.selected.insert(ts, new); + s.select_one(ts, new); s.target = StackTarget::Content; Ok(new) })?; @@ -147,8 +147,8 @@ fn to_all_sets(s: &mut Session, p: &Value) -> Result { let new = if copy { copy_tree(&src, id, &mut s.doc, ts, None, false, 0)? } else { - // On top of the set: clear its selection first. - s.selected.remove(&ts); + // On top of the set: clear its selection first + s.select_none(ts); crate::instance_cmds::make_instance(s, id, ts)? }; made.push(new.0); diff --git a/crates/engine/src/layer_selection.rs b/crates/engine/src/layer_selection.rs new file mode 100644 index 00000000..e4012afc --- /dev/null +++ b/crates/engine/src/layer_selection.rs @@ -0,0 +1,260 @@ +//! Several selected layers, as in the reference app: Shift+click selects the rows between the +//! last clicked layer and the clicked one, Ctrl/Cmd+click adds or removes one layer, and the +//! batch layer commands (remove, duplicate, group, visibility, move) act on every selected layer. +//! +//! The selected layer (`Session::selected`) stays the active one the properties panel shows. The +//! layers picked with it live beside it and count only while it is still the layer they were +//! picked with, so any command that selects another layer leaves a single selection without +//! having to know about this one. + +use serde_json::{Value, json}; +use texturecraft_core::project::MAX_DEPTH; +use texturecraft_core::{LayerId, LayerKind, Project}; + +use crate::commands::{bad, u64p}; +use crate::session::StackTarget; +use crate::{Result, Session}; + +mod multi_selection; + +pub use multi_selection::MultiSelection; + +impl Session { + /// Every selected layer of the active texture set, top row first: the selected layer and the + /// layers picked with it (Shift/Ctrl+click), or the selected layer alone. + pub fn selected_layers(&self) -> Vec { + let ts = self.ts(); + let picked = self.selection_in(ts); + if picked.len() < 2 { + return picked; + } + + stack_rows(&self.doc.project, ts, false).into_iter().filter(|id| picked.contains(id)).collect() + } + + /// Whether `id` is one of the [`Session::selected_layers`]. + pub fn is_layer_selected(&self, id: LayerId) -> bool { + let ts = self.ts(); + let Some(active) = self.active_in(ts) else { return false }; + + match self.multi.get(&ts).filter(|multi| multi.active == active) { + Some(multi) => multi.layers.contains(&id) && self.doc.project.locate(id).is_some_and(|(set, _, _)| set == ts), + None => active == id, + } + } + + /// The selected layer of texture set `ts`, if it is still in that set's stack. + fn active_in(&self, ts: usize) -> Option { + self.selected.get(&ts).copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts)) + } + + /// The layers picked with the selected layer of `ts`, while it is still the one they were + /// picked with. + fn multi_in(&self, ts: usize) -> Option<&MultiSelection> { + let active = self.active_in(ts)?; + self.multi.get(&ts).filter(|multi| multi.active == active) + } + + /// The selected layers of texture set `ts` in the order they were picked. + fn selection_in(&self, ts: usize) -> Vec { + match self.multi_in(ts) { + Some(multi) => multi.layers.iter().copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts)).collect(), + None => self.active_in(ts).into_iter().collect(), + } + } + + /// Select layer `id` alone in texture set `ts`. + pub(crate) fn select_one(&mut self, ts: usize, id: LayerId) { + self.selected.insert(ts, id); + self.multi.remove(&ts); + } + + /// Select no layer in texture set `ts`. + pub(crate) fn select_none(&mut self, ts: usize) { + self.selected.remove(&ts); + self.multi.remove(&ts); + } + + /// Select `layers` of texture set `ts` with `active` as the active layer (one of them) and + /// `anchor` where the next Shift+click range starts. + pub(crate) fn select_several(&mut self, ts: usize, active: LayerId, anchor: LayerId, layers: Vec) { + self.selected.insert(ts, active); + if layers.len() > 1 { + self.multi.insert(ts, MultiSelection { active, anchor, layers }); + } else { + self.multi.remove(&ts); + } + } +} + +/// The rows of texture set `ts` from the top, as the Layers panel lists them: each layer, then +/// its children unless `expanded_only` and the folder is collapsed. +pub fn stack_rows(project: &Project, ts: usize, expanded_only: bool) -> Vec { + let mut rows = Vec::new(); + if let Some(set) = project.texture_sets.get(ts) { + push_rows(project, &set.stack, expanded_only, 0, &mut rows); + } + rows +} + +fn push_rows(project: &Project, list: &[LayerId], expanded_only: bool, depth: usize, rows: &mut Vec) { + if depth > MAX_DEPTH { + return; + } + + for id in list.iter().rev() { + let Some(layer) = project.layers.get(id) else { continue }; + rows.push(*id); + if let LayerKind::Group { children, collapsed } = &layer.kind + && !(expanded_only && *collapsed) + { + push_rows(project, children, expanded_only, depth + 1, rows); + } + } +} + +/// `layer.select` with `toggle` (Ctrl/Cmd+click) or `range` (Shift+click) on `id` of texture set +/// `ts`. Returns the layer that becomes the active one (none when nothing stays selected). +/// +/// A range covers the rows shown between the anchor and `id` (a collapsed folder's layers are +/// not shown, so they are not selected); `id` becomes active and the anchor stays. A toggle adds +/// `id` and makes it the active layer and the anchor, or takes it out when it was selected (the +/// active layer and the anchor stay, or the last picked layer takes their place when it was them); +/// taking out the only selected layer leaves an empty selection. +pub(crate) fn extend(s: &mut Session, ts: usize, id: LayerId, range: bool) -> Option { + let current = s.selection_in(ts); + let anchor = s.multi_in(ts).map(|multi| multi.anchor).filter(|anchor| current.contains(anchor)).or_else(|| s.active_in(ts)); + if range { + let rows = stack_rows(&s.doc.project, ts, true); + let span = anchor.and_then(|anchor| Some((anchor, rows.iter().position(|row| *row == anchor)?, rows.iter().position(|row| *row == id)?))); + match span { + Some((anchor, from, to)) => { + let layers = rows.get(from.min(to)..=from.max(to)).map(<[LayerId]>::to_vec).unwrap_or_else(|| vec![id]); + s.select_several(ts, id, anchor, layers); + } + + // Nothing to range from (or it is hidden in a collapsed folder): start over at `id` + None => s.select_several(ts, id, id, vec![id]), + } + return Some(id); + } + + let mut layers = current; + if layers.contains(&id) { + layers.retain(|layer| *layer != id); + + // Taking out the only selected layer leaves nothing selected + let Some(last) = layers.last().copied() else { + s.select_none(ts); + return None; + }; + + let kept = |layer: Option| layer.filter(|layer| layers.contains(layer)).unwrap_or(last); + let (active, anchor) = (kept(s.active_in(ts)), kept(anchor)); + s.select_several(ts, active, anchor, layers); + Some(active) + } else { + layers.push(id); + s.select_several(ts, id, id, layers); + Some(id) + } +} + +/// `layer.select {layers, layer?}`: select every layer in `layers` at once, with `layer` (one of +/// them; default the last) as the active one. +pub(crate) fn select_list(s: &mut Session, p: &Value) -> Result { + let (ts, layers) = ids_param(s, "layer.select", p)?; + let active = match u64p(p, "layer").map(LayerId) { + Some(active) if layers.contains(&active) => active, + Some(_) => return Err(bad("layer.select", "`layer` must be one of `layers`")), + None => layers.last().copied().ok_or_else(|| bad("layer.select", "`layers` is empty"))?, + }; + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + s.tool.clone_source = None; + } + + s.active_set = ts; + s.select_several(ts, active, active, layers); + s.target = StackTarget::Content; + s.revision = s.revision.wrapping_add(1); + Ok(json!({ "layer": active.0, "textureSet": ts, "layers": ids_json(&s.selected_layers()) })) +} + +/// `layer.select {all: true}` (Ctrl/Cmd+A in the Layers panel): every row shown in the active +/// texture set: the folder rows and the layers inside open folders, but not the layers inside +/// collapsed ones. The active layer and the Shift+click anchor stay when they are among them, +/// else the top row takes their place. An empty stack changes nothing. +pub(crate) fn select_all(s: &mut Session) -> Result { + let ts = s.ts(); + let rows = stack_rows(&s.doc.project, ts, true); + let Some(top) = rows.first().copied() else { + return Ok(json!({ "layer": Value::Null, "textureSet": ts, "layers": [] })); + }; + + let active = s.active_in(ts).filter(|active| rows.contains(active)).unwrap_or(top); + let anchor = s.multi_in(ts).map(|multi| multi.anchor).filter(|anchor| rows.contains(anchor)).unwrap_or(active); + s.select_several(ts, active, anchor, rows); + s.target = StackTarget::Content; + s.revision = s.revision.wrapping_add(1); + Ok(json!({ "layer": active.0, "textureSet": ts, "layers": ids_json(&s.selected_layers()) })) +} + +/// The `layers` param: ids of layers in one texture set's stack, without repeats. +fn ids_param(s: &Session, cmd: &str, p: &Value) -> Result<(usize, Vec)> { + let list = p.get("layers").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`layers` must be a list of layer ids"))?; + let mut set = None; + let mut ids = Vec::new(); + for value in list { + let id = value.as_u64().map(LayerId).ok_or_else(|| bad(cmd, "`layers` must be a list of layer ids"))?; + let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad(cmd, format!("no layer {} in a stack", id.0)))?; + if *set.get_or_insert(ts) != ts { + return Err(bad(cmd, "`layers` must all be in one texture set")); + } + + if !ids.contains(&id) { + ids.push(id); + } + } + let ts = set.ok_or_else(|| bad(cmd, "`layers` is empty"))?; + Ok((ts, ids)) +} + +/// The layers a batch command acts on, top row first: `layers`, else `layer` alone, else every +/// selected layer. With `outermost`, a layer whose folder is also in the list is left out (the +/// folder takes it along). +pub(crate) fn batch_param(s: &Session, cmd: &str, p: &Value, outermost: bool) -> Result> { + let ids = if p.get("layers").is_some() { + ids_param(s, cmd, p)?.1 + } else if u64p(p, "layer").is_some() { + vec![crate::commands::layer_param(s, cmd, p)?] + } else { + s.selected_layers() + }; + if ids.len() < 2 { + return if ids.is_empty() { Err(bad(cmd, "no layer selected and no `layer` given")) } else { Ok(ids) }; + } + + let project = &s.doc.project; + let Some((ts, _, _)) = ids.first().and_then(|id| project.locate(*id)) else { return Ok(ids) }; + Ok(stack_rows(project, ts, false).into_iter().filter(|id| ids.contains(id) && !(outermost && in_listed_folder(project, *id, &ids))).collect()) +} + +/// Whether a folder holding `id` (at any depth) is in `ids`. +fn in_listed_folder(project: &Project, id: LayerId, ids: &[LayerId]) -> bool { + let mut at = id; + for _ in 0..=MAX_DEPTH { + match project.locate(at) { + Some((_, Some(parent), _)) if ids.contains(&parent) => return true, + Some((_, Some(parent), _)) => at = parent, + _ => return false, + } + } + false +} + +pub(crate) fn ids_json(ids: &[LayerId]) -> Vec { + ids.iter().map(|id| id.0).collect() +} diff --git a/crates/engine/src/layer_selection/multi_selection.rs b/crates/engine/src/layer_selection/multi_selection.rs new file mode 100644 index 00000000..8f3547c7 --- /dev/null +++ b/crates/engine/src/layer_selection/multi_selection.rs @@ -0,0 +1,12 @@ +use texturecraft_core::LayerId; + +/// The layers selected in one texture set together with the active one. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MultiSelection { + /// The active layer these were picked with; another selected layer ends the selection. + pub active: LayerId, + /// Where a Shift+click range starts: the last layer clicked without Shift. + pub anchor: LayerId, + /// Every selected layer, the active one included, in the order they were picked. + pub layers: Vec, +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 34b6bf3a..6f89804a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -20,12 +20,16 @@ pub mod file_cmds; pub mod fill_hit_test; pub mod fill_mode; pub mod filter_lib; +mod frame_target; pub mod inspect; pub mod instance_cmds; pub mod layer_cmds; pub mod layer_ops; +pub mod layer_selection; pub mod link_cmds; +mod mask_bitmap; pub mod mask_cmds; +pub mod mask_export; mod mask_preview_pixel; pub mod material_lib; mod material_preview_pixel; @@ -42,36 +46,47 @@ pub mod path_tool; pub mod pbr_cmds; mod polygon_fill; mod polygon_fill_drag; +mod polygon_fill_mirror; +mod stencil_look; // Mesh reimport reads files on native targets only #[cfg(not(target_arch = "wasm32"))] mod preserve; pub mod preset_cmds; pub mod preview; +mod procedural_params; pub mod project_cmds; pub mod quick_mask; pub mod resource_cmds; pub mod session; pub mod set_cmds; pub mod smart_masks; +mod solo; pub mod template_cmds; pub mod text_cmds; pub mod thumbs; mod tool_availability; pub mod tool_cmds; +pub mod tool_settings; mod triangle_partition; mod uv_stroke_state; +mod uv_symmetry; pub mod uv_tile_cmds; pub mod view_cmds; pub use bake::{BakeMesh, BakeMeshes, BakeTask, StreamedBake, StreamedMap}; pub use bake_preview::{BakePreview, PreviewShow}; -pub use commands::{CommandSpec, command_specs, execute, find}; +pub use commands::{CommandSpec, check_enabled, command_specs, execute, find}; pub use fill_hit_test::FillHitTest; pub use fill_mode::FillMode; pub use path_tool::PathState; pub use project_cmds::sample_session; -pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode}; +pub use session::{ + CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label, + stroke_template, +}; pub use set_cmds::{ResizeOutput, ResizeTask}; +pub use solo::Solo; +pub use tool_settings::ToolSettings; pub use texturecraft_compose as compose; pub use texturecraft_core as core; diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 603cd0fa..f8599b32 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -312,16 +312,42 @@ impl LinkJob { } } -/// Decode every map of `m` (validating them) with the channel it feeds. +/// Most texels one map may have: 8192 x 8192, the largest texture set. Decoded as RGBA f32 that is +/// 1 GiB, so without this a single 16384 x 16384 map (a tiny PNG) would decode to 4 GiB. +const MAX_MAP_TEXELS: u64 = texturecraft_formats::MAX_RESOURCE_TEXELS; +/// Most texels all of a material's maps may decode to together: nine 4096 x 4096 images (151 M texels). +/// A decoded texel is an RGBA `f32` (16 bytes) and the decoded maps stay in the session, so this holds one +/// `.mcmat` to about 2.25 GiB of pixels however small the file is (a blank 8192 x 8192 PNG is a few hundred +/// KiB). This is a per-import memory policy, not the number of supported channels. It fits nine 4K maps, +/// or an 8K base colour with five 4K maps; larger imports are refused, never shrunk silently. +const MAX_DECODED_TEXELS: u64 = 9 * 4096 * 4096; + +/// Decode every map of `m` (validating them) with the channel it feeds. A usage listed more than +/// once is decoded once (the last listing wins, as it did when each listing was painted over the +/// one before), and the maps together stay within [`MAX_DECODED_TEXELS`], so a `.mcmat` can't +/// multiply one small image into gigabytes of pixels. fn decoded_maps(m: &PortableMaterial) -> Result, texturecraft_formats::DecodedImage)>> { - m.maps - .iter() - .filter_map(|(usage, bytes)| Some((Channel::ALL.into_iter().find(|c| c.id() == usage)?, bytes))) - .map(|(c, bytes)| { - let img = texturecraft_formats::decode_image(bytes).map_err(|e| EngineError::Other(format!("{} map: {e}", c.id())))?; - Ok((c, bytes.clone(), img)) - }) - .collect() + decoded_maps_within(m, MAX_DECODED_TEXELS, MAX_MAP_TEXELS) +} + +/// Decode the maps of `m` (one per usage, the last listing wins) within a total budget of `max_texels`, +/// each map at most `max_map_texels`. The size of each map is checked from its header before decoding: a +/// map over its limit, or one that no longer fits in what is left of the budget, is refused with an error +/// that names the map. +fn decoded_maps_within(m: &PortableMaterial, max_texels: u64, max_map_texels: u64) -> Result, texturecraft_formats::DecodedImage)>> { + let listed: Vec<(Channel, &Vec)> = + m.maps.iter().filter_map(|(usage, bytes)| Some((Channel::ALL.into_iter().find(|c| c.id() == usage)?, bytes))).collect(); + let mut left = max_texels; + let mut out = Vec::new(); + for (i, (c, bytes)) in listed.iter().enumerate() { + if listed.iter().skip(i + 1).any(|(later, _)| later == c) { + continue; + } + let img = texturecraft_formats::decode_image_within(bytes, left.min(max_map_texels)).map_err(|e| EngineError::Other(format!("{} map: {e}", c.id())))?; + left = left.saturating_sub(u64::from(img.width) * u64::from(img.height)); + out.push((*c, (*bytes).clone(), img)); + } + Ok(out) } impl Session { @@ -351,6 +377,7 @@ impl Session { if maps.is_empty() { return Err(EngineError::Other(format!("{} has no maps TextureCraft can paint with", m.manifest.name))); } + let label = format!("Add {}", m.manifest.name); let (id, names) = self.edit(&label, |s| { let ts = s.ts(); @@ -376,7 +403,7 @@ impl Session { let name = s.doc.project.next_layer_name(ts, &m.manifest.name); let lid = crate::layer_cmds::insert_selected(s, Layer::new(lid, name, LayerKind::Fill(fill), &channels))?; place.apply(s, lid)?; - s.selected.insert(ts, lid); + s.select_one(ts, lid); s.target = crate::session::StackTarget::Content; Ok((lid, names)) })?; @@ -557,6 +584,93 @@ esac #[cfg(test)] mod tests { + use super::*; + use texturecraft_formats::mcmat::{Manifest, MapEntry}; + + /// A blank `side` x `side` RGBA PNG, as bytes. + fn png(side: u32) -> Vec { + let mut out = Vec::new(); + image::RgbaImage::new(side, side).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + /// A portable material that lists the given (usage, image bytes) maps in order. + fn material(maps: Vec<(&str, Vec)>) -> PortableMaterial { + let manifest = Manifest { + format: "craft-material".into(), + version: 1, + name: "M".into(), + graph: "M".into(), + size: [4, 4], + maps: maps.iter().map(|(usage, _)| MapEntry { usage: usage.to_string(), file: "m.png".into() }).collect(), + parameters: vec![], + inputs: vec![], + presets: vec![], + source: "source.mcraft".into(), + }; + PortableMaterial { manifest, maps: maps.into_iter().map(|(u, b)| (u.to_string(), b)).collect(), source: vec![] } + } + + /// However many times one usage is listed, it is decoded only once. + #[test] + fn a_usage_listed_many_times_is_decoded_once() { + let m = material((0..64).map(|_| ("baseColor", png(4))).collect()); + assert_eq!(decoded_maps(&m).unwrap().len(), 1, "64 listings of one usage, one decoded image"); + } + + /// When a usage is listed twice, the later image is the one that is kept. + #[test] + fn the_last_listing_of_a_usage_wins() { + let m = material(vec![("baseColor", png(4)), ("roughness", png(2)), ("baseColor", png(8))]); + let maps = decoded_maps(&m).unwrap(); + let base = maps.iter().find(|(c, ..)| *c == Channel::BaseColor).unwrap(); + assert_eq!(base.2.width, 8); + assert_eq!(maps.len(), 2); + } + + /// A single map over the per-map limit is refused even when the total budget would allow it; one exactly at it is kept. + #[test] + fn one_map_over_the_per_map_limit_is_refused_though_the_total_would_allow_it() { + let m = material(vec![("baseColor", png(5))]); + assert!(decoded_maps_within(&m, 1000, 24).is_err(), "25 texels over a per-map limit of 24, total 1000"); + assert_eq!(decoded_maps_within(&m, 1000, 25).unwrap().len(), 1, "exactly at the per-map limit"); + // The real limits: one map is at most 8192 x 8192, and the total holds nine maps at 4096 x 4096. + assert_eq!(MAX_MAP_TEXELS, 8192 * 8192); + assert_eq!(MAX_DECODED_TEXELS, 9 * 4096 * 4096); + } + + /// The maps together stay within the total budget, exactly: three 8 x 8 maps fit in 192 texels but not in 191. + #[test] + fn decoded_pixels_are_bounded_across_maps() { + let m = material(vec![("baseColor", png(8)), ("roughness", png(8)), ("metallic", png(8))]); + assert_eq!(decoded_maps_within(&m, 192, 64).unwrap().len(), 3, "at the budget"); + assert!(decoded_maps_within(&m, 191, 64).is_err(), "one texel under: the third map goes over"); + } + /// Shared version-2/SBS parsing retains its behavior before duplicate decode filtering. + #[test] + fn shared_version_two_archive_keeps_sbs_and_decodes_repeated_usage_once() { + use std::io::Write; + + let manifest = serde_json::json!({ + "format": "craft-material", "version": 2, "name": "M", "graph": "Second", "size": [4, 4], + "maps": (0..64).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/base.png"})).collect::>(), + "source": "source.sbs" + }); + let mut archive = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in [("material.json", manifest.to_string().into_bytes()), ("maps/base.png", png(4)), ("source.sbs", b"source package".to_vec())] { + archive.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + archive.write_all(&bytes).unwrap(); + } + let material = read_mcmat(&archive.finish().unwrap().into_inner()).unwrap(); + assert_eq!(material.manifest.version, 2); + assert_eq!(material.manifest.graph, "Second"); + assert_eq!(material.manifest.source, "source.sbs"); + assert_eq!(material.source, b"source package"); + let maps = decoded_maps(&material).unwrap(); + assert_eq!(maps.len(), 1); + assert_eq!((maps[0].2.width, maps[0].2.height), (4, 4)); + } + use super::typed; use serde_json::json; use texturecraft_core::layer::LinkParam; diff --git a/crates/engine/src/mask_bitmap.rs b/crates/engine/src/mask_bitmap.rs new file mode 100644 index 00000000..4259a511 --- /dev/null +++ b/crates/engine/src/mask_bitmap.rs @@ -0,0 +1,28 @@ +use crate::{EngineError, Result}; + +/// An evaluated mask: `width × height` values in `0..=1`, row by row from the top +#[derive(Clone, Debug, PartialEq)] +pub struct MaskBitmap { + /// UDIM number of the tile (None: the whole texture set) + pub tile: Option, + pub width: u32, + pub height: u32, + pub values: Vec, +} + +impl MaskBitmap { + /// The values as 16-bit gray levels + pub fn gray16(&self) -> Vec { + self.values.iter().map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).collect() + } + + /// The values as 8-bit gray levels + pub fn gray8(&self) -> Vec { + self.values.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).collect() + } + + /// A 16-bit grayscale PNG + pub fn to_png16(&self) -> Result> { + texturecraft_formats::gray16_png(self.width, self.height, self.values.iter().copied()).map_err(|error| EngineError::Other(error.to_string())) + } +} diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index fe79c845..4faef611 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use texturecraft_core::{ BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, - MaskBackground, MicroDetail, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source, + MaskBackground, MicroDetail, Procedural, ProceduralKind, Project, Source, }; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Add mask with color selection", ["Layers", "Mask"], None, - "{layer?, color?: [r,g,b] ID color, tolerance?}", + "{layer?, color?: ID color as [r,g,b] linear or \"#rrggbb\" sRGB, tolerance?}", has_layer, add_color_mask ), @@ -40,7 +40,7 @@ pub fn specs() -> Vec { "Add fill", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed? | anchor?: anchor effect id, anchorChannel?: channel (height); content: color?, roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}", + "{layer?, target?: mask|content, name?, mask: value?: 0..1 | image?: resource name | procedural?: kind, scale?, seed?, contrast?, balance?, invert?, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3, tile?: {Tile Generator settings in camelCase, as project.inspect shows them}, tileDefaults?: true | anchor?: anchor effect id, anchorChannel?: channel (height); content: color? ([r,g,b] linear or \"#rrggbb\" sRGB), roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}", has_layer, add_fill ), @@ -67,7 +67,7 @@ pub fn specs() -> Vec { "Add filter", ["Layers", "Effects"], None, - "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b]|\"#rrggbb\", ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", + "{layer?, target?: mask|content, name?, filter?: id from filter.list (invert, threshold, blur, sharpen, hsl, levels, contrastLuminosity, colorBalance, gradientMap, posterize, clamp, histogramScan|Range|Shift, warp, blurDirectional, slopeBlur, matFinishGrind|Raw|Sanded|Hammered), level?, radius?, amount?, hue?: turns -1..1, saturation?, lightness?, contrast?, luminosity?, shadows?|midtones?|highlights?: [r,g,b] -1..1, colors?: [[r,g,b] linear or \"#rrggbb\" sRGB, ...], levels?, min?, max?, position?, range?, offset?, intensity?, scale?, seed?, angle?} — material finishes go on the content", has_layer, add_filter ), @@ -94,7 +94,7 @@ pub fn specs() -> Vec { "Edit effect", [], None, - "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", + "{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, microAnchor?: id|null, microAmount?, value?, uniform?: 0..1 (a mask fill reads that value, whatever its source), procedural?: kind (a mask fill) with scale?, seed?, contrast?, balance?, invert?, resolution?, tile?, tileDefaults? (alone, they edit its pattern), image?: resource name (a fill's source), projection?: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, offset?, axis?, sharpness? (a fill effect's projection; while it reads a pattern, scale is the pattern's), anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b] linear, ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}", has_layer, set ), @@ -273,11 +273,12 @@ pub(crate) fn anchor_source(s: &Session, cmd: &str, reader: LayerId, anchor: Lay Some((owner, e)) if matches!(e.kind, EffectKind::Anchor) => owner, _ => return Err(bad(cmd, format!("{} is not an anchor point", anchor.0))), }; + let (ts, _, _) = s.doc.project.locate(reader).ok_or_else(|| bad(cmd, "layer not in a stack"))?; let order: Vec = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect(); let pos = |id: LayerId| order.iter().position(|x| *x == id); match (pos(owner), pos(reader)) { - (Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel }), + (Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel, ramp: Vec::new() }), _ => Err(bad(cmd, "the anchor point must be on a layer below this one in the same texture set")), } } @@ -294,9 +295,6 @@ fn image_source(session: &Session, command: &str, name: &str) -> Result fn add_fill(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.add.fill"; - const MIN_PATTERN_SCALE: f32 = 0.001; - const MAX_PATTERN_SCALE: f32 = 1000.0; - let projection = projection_from(params, CMD, None)?; let blend = blend_param(CMD, params, "blend")?.unwrap_or(BlendMode::Normal); let layer = layer_param(session, CMD, params)?; @@ -327,14 +325,10 @@ fn add_fill(session: &mut Session, params: &Value) -> Result { Some(name) => { let kind = ProceduralKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown procedural `{name}`")))?; let mut pattern = Procedural::new(kind); - if let Some(scale) = f32p(params, "scale") { - pattern.scale = scale.clamp(MIN_PATTERN_SCALE, MAX_PATTERN_SCALE); - } - if let Some(seed) = u64p(params, "seed") { - pattern.seed = seed as u32; - } + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(CMD, params, &mut pattern)?; - Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] } + Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() } } None => Source::Uniform([f32p(params, "value").unwrap_or(1.0).clamp(0.0, 1.0); 3]), }; @@ -377,17 +371,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(contrast) = f32p(params, "contrast") { generator.global.contrast = contrast.clamp(0.0, 1.0); } - if let Some(value) = params.get("resolution") { - let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; - generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; - } - if let Some(custom) = u64p(params, "customResolution") { - generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; - } - if let Some(factor) = params.get("resolutionFactor") { - let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; - generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; - } + crate::procedural_params::resolution_from(command, params, &mut generator.resolution)?; // A mode or sizes also give a curvature generator saved before detail sizes its detail let mode = params @@ -401,6 +385,7 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if mode.is_none() && weights.is_none() { return Ok(()); } + if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) { return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes")); } @@ -591,7 +576,7 @@ fn set(session: &mut Session, params: &Value) -> Result { let anchor = match session.doc.project.effect(effect) { Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => { let (current, channel) = match source { - Source::Anchor { anchor, channel } => (Some(*anchor), *channel), + Source::Anchor { anchor, channel, .. } => (Some(*anchor), *channel), _ => (None, Channel::Height), }; let channel_param = channel_param(CMD, params, "anchorChannel")?; @@ -687,18 +672,32 @@ fn set(session: &mut Session, params: &Value) -> Result { EffectKind::Filter(_) if swaps_filter => {} EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?, EffectKind::Fill { source, projection } => { + // `uniform` picks the source, so it outranks settings that would edit the current pattern + let uniform = f32p(params, "uniform").filter(|_| strp(params, "procedural").is_none()); if let Some(anchor) = anchor { *source = anchor; } else if let Some(image) = image { *source = image; + } else if let Some(value) = uniform { + *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); + } else if let Some(pattern) = fill_pattern(CMD, params, source)? { + *source = pattern; } else if let Some(value) = f32p(params, "value") && matches!(source, Source::Uniform(_) | Source::Anchor { .. } | Source::Image { .. }) { *source = Source::Uniform([value.clamp(0.0, 1.0); 3]); } + // While the fill reads a pattern, `scale` is the pattern's and leaves the projection alone + let mut placement = params.clone(); + if matches!(source, Source::Procedural { .. }) + && let Some(fields) = placement.as_object_mut() + { + fields.remove("scale"); + } + // Preserve projection fields that the edit does not supply - *projection = projection_from(params, CMD, Some(&*projection))?; + *projection = projection_from(&placement, CMD, Some(&*projection))?; } EffectKind::ColorSelection { colors, tolerance } => crate::color_selection_cmds::apply_params(params, colors, tolerance)?, EffectKind::Compare { tolerance, .. } => { @@ -715,6 +714,36 @@ fn set(session: &mut Session, params: &Value) -> Result { Ok(Value::Null) } +/// The pattern a mask fill reads after `params`: `procedural` picks one (a pattern of the kind it already reads keeps its settings), pattern settings alone edit the current one +fn fill_pattern(command: &str, params: &Value, current: &Source) -> Result> { + let (current, range) = match current { + Source::Procedural { pattern, low, high, .. } => (Some(pattern), (*low, *high)), + _ => (None, ([0.0; 3], [1.0; 3])), + }; + let mut pattern = match strp(params, "procedural") { + Some(name) => { + let kind = ProceduralKind::parse(name).ok_or_else(|| bad(command, format!("unknown procedural `{name}`")))?; + current.filter(|pattern| pattern.kind == kind).cloned().unwrap_or_else(|| Procedural::new(kind)) + } + None => { + let has_settings = crate::procedural_params::has_pattern_settings(params); + let edits_pattern = has_settings || ["scale", "seed", "contrast", "balance", "invert"].iter().any(|key| params.get(key).is_some()); + match current { + Some(pattern) if edits_pattern => pattern.clone(), + None if has_settings => { + return Err(bad(command, "the mask fill reads no pattern: give `procedural` with its settings")); + } + _ => return Ok(None), + } + } + }; + + crate::procedural_params::pattern_basics_from(params, &mut pattern); + crate::procedural_params::pattern_settings_from(command, params, &mut pattern)?; + + Ok(Some(Source::Procedural { pattern, low: range.0, high: range.1, ramp: Vec::new() })) +} + /// The library id of the filter effect `effect` is, if it is one fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> { match &s.doc.project.effect(effect)?.1.kind { diff --git a/crates/engine/src/mask_export.rs b/crates/engine/src/mask_export.rs new file mode 100644 index 00000000..724cc40e --- /dev/null +++ b/crates/engine/src/mask_export.rs @@ -0,0 +1,115 @@ +//! Mask export: a layer's evaluated mask as a grayscale bitmap at the texture set's resolution +//! (`mask.export`, and the layer menu's "Copy mask to clipboard"). +//! +//! The bitmap has the orientation of the exported texture maps (row 0 is the top of the UV +//! square) and is black where the mesh does not cover the texture. A classic texture set gives one +//! bitmap; a UV-tiled set gives one per tile (what the texture export does) or, for the clipboard, +//! one of the whole tile atlas. + +use serde_json::Value; +#[cfg(not(target_arch = "wasm32"))] +use serde_json::json; +use texturecraft_core::LayerId; + +use crate::commands::{CommandSpec, bad, has_layer}; +#[cfg(not(target_arch = "wasm32"))] +use crate::commands::{layer_param, strp}; +pub use crate::mask_bitmap::MaskBitmap; +use crate::{EngineError, Result, Session, cmd}; + +pub fn specs() -> Vec { + vec![cmd!( + "mask.export", + "Export mask to file...", + [], + None, + "{layer?, path: .png file} → {files}. Writes the evaluated mask as a 16-bit grayscale PNG at the texture set's resolution, black outside the mesh and oriented like the exported textures. A UV-tiled set writes one file per tile with the tile number before the extension (mask.1001.png). A layer without an enabled mask is an error", + has_layer, + export + )] +} + +impl Session { + /// Layer `id`'s evaluated mask: one bitmap per UV tile (`per_tile`) or one of the whole + /// texture set. A tile smaller than its atlas block gives its own size. Errors without an + /// enabled mask. + pub fn mask_bitmaps(&mut self, id: LayerId, per_tile: bool) -> Result> { + let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("no layer {}", id.0)))?; + self.update(); + let atlas = self + .with_inputs(ts, |inputs| texturecraft_compose::mask_texels(inputs, id).map(|values| (inputs.gbuf.width, inputs.gbuf.height, values))) + .ok_or_else(|| EngineError::Other("the layer has no enabled mask".into()))?; + let (width, height, values) = atlas; + let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; + let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) }; + let block = set.block_resolution(); + set.uv_tiles + .iter() + .map(|&tile| { + let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?; + + // A tile smaller than its block fills the block's top-left corner + let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block); + let mut tile_values = Vec::with_capacity(side as usize * side as usize); + for row in 0..side { + let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize; + tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[])); + } + Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values }) + }) + .collect() + } +} + +/// `path` as a `.png` path, with `tile` before the extension for a UV tile. +#[cfg(not(target_arch = "wasm32"))] +fn file_path(path: &str, tile: Option) -> std::path::PathBuf { + let path = std::path::Path::new(path); + let is_png = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("png")); + let name = path.file_name().map_or_else(|| "mask".into(), |n| n.to_string_lossy().into_owned()); + let stem = if is_png { name[..name.len() - 4].to_string() } else { name }; + let named = match tile { + Some(tile) => format!("{stem}.{tile}.png"), + None => format!("{stem}.png"), + }; + path.with_file_name(named) +} + +#[cfg(not(target_arch = "wasm32"))] +fn export(s: &mut Session, p: &Value) -> Result { + let path = strp(p, "path").filter(|path| !path.trim().is_empty()).ok_or_else(|| bad("mask.export", "`path` is required"))?; + let id = layer_param(s, "mask.export", p)?; + let bitmaps = s.mask_bitmaps(id, true)?; + let mut files = Vec::new(); + for bitmap in &bitmaps { + let file = file_path(path, bitmap.tile); + texturecraft_formats::write_atomic(&file, &bitmap.to_png16()?).map_err(|e| bad("mask.export", format!("cannot write {}: {e}", file.display())))?; + files.push(file.display().to_string()); + } + s.log.push(format!("Exported the mask to {}", files.join(", "))); + Ok(json!({ "files": files })) +} + +#[cfg(target_arch = "wasm32")] +fn export(_: &mut Session, _: &Value) -> Result { + Err(bad("mask.export", "writing files is not available in the browser")) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::file_path; + + #[test] + fn the_tile_number_goes_before_the_png_extension() { + // Compared as paths: Windows writes the folder with backslashes + let name = |path: &str, tile| { + let file = file_path(path, tile); + assert_eq!(file.parent(), std::path::Path::new(path).parent(), "the folder is kept"); + file.file_name().unwrap().to_string_lossy().into_owned() + }; + assert_eq!(name("/a/mask.png", None), "mask.png"); + assert_eq!(name("/a/mask", None), "mask.png"); + assert_eq!(name("/a/mask.PNG", Some(1002)), "mask.1002.png"); + assert_eq!(name("/a/skin.v2", Some(1001)), "skin.v2.1001.png"); + } +} diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 8c5c819f..10c664d4 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Add smart material from file", [], None, - "{path: .tcmat smart material, .mcmat MaterialCraft material or .mcraft package, above?: layer id, inside?: bool, index?: n} — above the selection by default, or placed like material.apply", + "{path: .tcmat smart material, .mcmat MaterialCraft material or .mcraft package, above?: layer id, inside?: bool, below?: layer id, top?: true, index?: n} — above the selection by default, or placed like material.apply", always, load ), @@ -36,19 +36,16 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and mask or content effects). +/// Image resources a layer subtree uses (fill sources and their patterns, mask fills and generator inputs) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; } + let Some(layer) = project.layers.get(&id) else { return }; if let LayerKind::Fill(fill) = &layer.kind { - for source in fill.sources.values() { - if let Source::Image { name, .. } = source { - out.push(name.clone()); - } - } + out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); out.extend(fill.link.as_ref().map(|link| link.package.clone())); } for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { @@ -59,24 +56,33 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, } } +/// An empty document with one texture set shaped like `src_set` (size, tiles, channels): what a saved library file holds. +pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { + let mut project = Project::new(name, "builtin:none"); + let mut set = TextureSet::new(name, 0, src_set.resolution); + set.uv_tiles = src_set.uv_tiles.clone(); + set.tile_resolutions = src_set.tile_resolutions.clone(); + set.channels = src_set.channels.clone(); + project.texture_sets.push(set); + Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() } +} + impl Session { /// Serialize layer `id` (with children, pixels and images) as a smart material file. pub fn smart_material_bytes(&self, id: LayerId, name: &str) -> Result> { let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; - let src_set = self.doc.project.texture_set(ts)?; - let mut project = Project::new(name, "builtin:none"); - let mut set = TextureSet::new(name, 0, src_set.resolution); - set.uv_tiles = src_set.uv_tiles.clone(); - set.tile_resolutions = src_set.tile_resolutions.clone(); - set.channels = src_set.channels.clone(); - project.texture_sets.push(set); - let mut mini = Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }; + let mut mini = one_set_document(self.doc.project.texture_set(ts)?, name); let new = crate::layer_ops::copy_tree(&self.doc, id, &mut mini, 0, None, false, 0)?; if let Ok(l) = mini.project.layer_mut(new) { l.name = name.to_string(); } + self.file_bytes(mini, new) + } + + /// The smart material file holding `mini` (a document from [`one_set_document`]) and the images layer `root` of it uses. + pub(crate) fn file_bytes(&self, mini: Document, root: LayerId) -> Result> { let mut used = Vec::new(); - images_used(&mini.project, new, &mut used, 0); + images_used(&mini.project, root, &mut used, 0); let resources = used.iter().filter_map(|n| self.doc.resources.get(n).map(|b| (n.clone(), b.as_ref().clone()))).collect(); let pf = texturecraft_formats::ProjectFile { project: mini.project, @@ -104,6 +110,7 @@ impl Session { if texturecraft_formats::mcmat::is_mcmat(bytes) || texturecraft_formats::mcmat::is_mcraft(bytes) { return self.add_linked_material_bytes_at(bytes, place); } + let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?; let root = pf .project @@ -122,7 +129,7 @@ impl Session { let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group()); let id = crate::layer_ops::copy_tree(&src, root, &mut s.doc, ts, sel, inside, 0)?; place.apply(s, id)?; - s.selected.insert(ts, id); + s.select_one(ts, id); s.target = StackTarget::Content; Ok(id) })?; diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 1d4e717a..b13f03b0 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -166,8 +166,9 @@ fn rgb(c: [f32; 3]) -> Source { Source::Uniform(c) } +/// A pattern between colors `low` and `high` (short: the material catalog calls it on almost every line) fn pat(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32, low: [f32; 3], high: [f32; 3]) -> Source { - Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high } + Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low, high, ramp: Vec::new() } } /// A scalar pattern between `lo` and `hi`. @@ -241,7 +242,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { use ProceduralKind as P; let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?; let one = |b: &mut Builder, s: Sources| -> Result> { Ok(vec![b.fill(m.label, s)]) }; - // A simple metal: subtle cloudy tone and roughness variation around the table values. + + // A simple metal: subtle cloudy tone and roughness variation around the table values let plain_metal = |b: &mut Builder, rough: Source| { let lo = m.base.map(|v| v * 0.94); one(b, metal(pat(P::Clouds, 3.0, 5, 1.0, lo, m.base), rough)) @@ -253,9 +255,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum" | "cobalt" => plain_metal(b, clouds_rough(7)), "steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)), - // Zinc plate: large crystalline spangles. + + // Zinc plate: large crystalline spangles "zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))), - // Brushing lines run along X; the highlights stretch across them (a quarter turn). + + // Brushing lines run along X; the highlights stretch across them (a quarter turn) "steel_brushed_aniso" => one( b, plus( @@ -274,7 +278,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Hammered, 6.0, 1, -0.04, 0.0)), ), ), - // Iron oxide is a dielectric: rough, pitted, blotchy orange-brown. + + // Iron oxide is a dielectric: rough, pitted, blotchy orange-brown "rust" => one( b, plus( @@ -292,14 +297,17 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "sandstone" => { one(b, plus(dielectric(pat(P::Noise, 4.0, 13, 1.0, [0.42, 0.3, 0.18], [0.6, 0.45, 0.28]), u(0.9)), height(gray(P::Perlin, 6.0, 13, -0.01, 0.0)))) } - // Stone chips in a pale binder, polished flat. + + // Stone chips in a pale binder, polished flat "terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))), - // Fine grains in soft wind ripples. + + // Fine grains in soft wind ripples "sand" => one( b, plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))), ), - // Glossy wet patches over rougher, drier mud. + + // Glossy wet patches over rougher, drier mud "mud" => one( b, plus( @@ -307,7 +315,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)), ), ), - // Rounded stones with deep joints between them. + + // Rounded stones with deep joints between them "cobblestone" => one( b, plus( @@ -315,7 +324,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Cells, 6.0, 37, 0.0, -0.05)), ), ), - // Small loose stones of mixed tones. + + // Small loose stones of mixed tones "gravel" => one( b, plus( @@ -323,7 +333,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Cells, 30.0, 39, -0.03, 0.0)), ), ), - // Troweled wall: soft patches and a fine sandy tooth. + + // Troweled wall: soft patches and a fine sandy tooth "plaster" => one( b, plus( @@ -331,7 +342,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Clouds, 2.0, 41, -0.008, 0.0)), ), ), - // Low cushions of tiny leaves. + + // Low cushions of tiny leaves "moss" => one( b, plus( @@ -347,6 +359,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { plus(dielectric(pat(P::Clouds, 8.0, 19, 1.0, [0.78, 0.77, 0.73], [0.86, 0.85, 0.81]), u(0.92)), height(gray(P::Noise, 1.0, 19, -0.002, 0.0))), ), "galvanized" => one(b, metal(pat(P::Voronoi, 10.0, 4, 1.0, [0.6, 0.62, 0.63], [0.78, 0.8, 0.81]), gray(P::Voronoi, 10.0, 4, 0.5, 0.28))), + // ---- Woods (grain along X, rings across Y) --------------------------------------------- "wood" => one( b, @@ -374,12 +387,14 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))), - // Dark, deep furrows between gray-brown ridges. + + // Dark, deep furrows between gray-brown ridges "bark" => one( b, plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))), ), - // Pale, fine and even grain. + + // Pale, fine and even grain "wood_maple" => one( b, plus( @@ -387,7 +402,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Wood, 3.0, 31, -0.006, 0.0)), ), ), - // Reddish heartwood with a satin finish. + + // Reddish heartwood with a satin finish "wood_cherry" => one( b, plus( @@ -395,7 +411,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Wood, 2.2, 33, -0.008, 0.0)), ), ), - // Long straight fibres with a few raised ridges. + + // Long straight fibres with a few raised ridges "bamboo" => one( b, plus( @@ -410,6 +427,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { height(gray(P::Wood, 2.0, 7, -0.015, 0.0)), ), ), + // ---- Stone, masonry, earth ---------------------------------------------------------- "concrete" => one( b, @@ -446,11 +464,13 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { b, plus(dielectric(pat(P::Clouds, 5.0, 2, 1.0, [0.4, 0.15, 0.07], [0.5, 0.21, 0.11]), clouds_rough(2)), height(gray(P::Noise, 0.8, 3, -0.005, 0.005))), ), + // ---- Plastics, rubber, composites --------------------------------------------------- "plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))), "plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))), "rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))), - // Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark. + + // Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark "carbon_fiber" => one( b, plus( @@ -458,19 +478,23 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { [(CoatWeight, u(1.0)), (CoatRoughness, u(r * 0.2)), (Height, gray(P::Twill, 12.0, 1, 0.0, 0.002))], ), ), + // ---- Fabric and leather ------------------------------------------------------------- "fabric" => { one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0)))) } - // Indigo twill: diagonal ribs. + + // Indigo twill: diagonal ribs "denim" => { one(b, plus(dielectric(pat(P::Twill, 22.0, 5, 1.0, [0.015, 0.025, 0.07], [0.15, 0.2, 0.38]), u(r)), height(gray(P::Twill, 22.0, 5, -0.01, 0.0)))) } - // Coarse, slubby plain weave. + + // Coarse, slubby plain weave "linen" => { one(b, plus(dielectric(pat(P::Weave, 30.0, 45, 1.0, [0.58, 0.52, 0.42], [0.8, 0.74, 0.62]), u(r)), height(gray(P::Weave, 30.0, 45, -0.006, 0.0)))) } - // Fuzzy knit: no visible threads, a soft sheen at grazing angles. + + // Fuzzy knit: no visible threads, a soft sheen at grazing angles "wool" => one( b, plus( @@ -495,11 +519,12 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { "velvet" => one( b, plus( - // A pile, not a weave: soft crushed patches under a bright sheen. + // A pile, not a weave: soft crushed patches under a bright sheen dielectric(pat(P::Clouds, 3.0, 3, 1.0, [0.06, 0.006, 0.045], m.base), u(r)), [(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Noise, 1.0, 3, -0.002, 0.0))], ), ), + // ---- Coated and translucent --------------------------------------------------------- "car_paint" => one( b, @@ -516,14 +541,17 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])), + // ---- Glass (the Transmission channel; the base color tints the light going through) ---- "glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])), - // Clear with cloudy patches of trapped air. + + // Clear with cloudy patches of trapped air "ice" => one( b, plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]), ), - // Bright, rough and slightly translucent. + + // Bright, rough and slightly translucent "snow" => one( b, plus( @@ -531,7 +559,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { [(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))], ), ), - // Porous, ivory to tan, with a little light under the surface. + + // Porous, ivory to tan, with a little light under the surface "bone" => one( b, plus( @@ -540,6 +569,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { ), ), "glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])), + // ---- Smart materials ---------------------------------------------------------------- "steel_painted_worn" => { let mut v = build(b, "steel")?; @@ -715,6 +745,47 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result> { } } +/// The channel sources of simple material `id`: its single, unmasked fill layer. `None` for smart +/// materials (several layers, or a masked layer) and for unknown ids: a brush paints one fill's +/// sources, so those stay layers. +pub fn brush_sources(id: &str) -> Option> { + let m = find(id).filter(|m| !m.smart)?; + let mut scratch = Project::new("", ""); + let layers = build(&mut Builder { p: &mut scratch, channels: Channel::LOBES.to_vec() }, m.id).ok()?; + let [layer] = layers.as_slice() else { return None }; + let LayerKind::Fill(fill) = &layer.kind else { return None }; + if layer.mask.is_some() { + return None; + } + + Some(fill.sources.iter().map(|(channel, source)| (*channel, source.clone())).collect()) +} + +/// The brush's plain values for simple material `id`, one per channel it sets (what the tool's +/// material shows): a pattern counts as the middle between its two values. `None` as +/// [`brush_sources`]. +pub fn brush_values(id: &str) -> Option> { + let mean = |low: &[f32; 3], high: &[f32; 3]| std::array::from_fn(|i| (low[i] + high[i]) * 0.5); + Some( + brush_sources(id)? + .into_iter() + .filter_map(|(channel, source)| match source { + Source::Uniform(value) => Some((channel, value)), + Source::Procedural { low, high, .. } => Some((channel, mean(&low, &high))), + Source::Image { .. } | Source::Anchor { .. } => None, + }) + .collect(), + ) +} + +/// The fill a brush material paints through, as a layer: `sources` projected tri-planar at +/// `scale` (the same fill evaluation a layer with that material uses). +pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f32) -> Layer { + let channels: Vec = sources.iter().map(|(channel, _)| *channel).collect(); + let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3] }; + Layer::new(id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &channels) +} + /// Where [`apply_at`] puts a material. #[derive(Clone, Copy, Debug)] pub enum Place { @@ -724,6 +795,10 @@ pub enum Place { Above(LayerId, bool), /// At this index of the top-level stack (0 = bottom). Index(usize), + /// Directly below a layer, in the same stack or folder (a shelf drop on a layer row). + Below(LayerId), + /// At the top of the top-level stack (a shelf drop on the 3D or 2D view). + Top, } /// Add material `id` above the selection: a single fill layer, or a folder for multi-layer @@ -739,7 +814,8 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { s.edit(&label, |s| { let ts = s.ts(); let mut channels = s.doc.project.texture_set(ts)?.channel_list(); - // Lobe channels the material uses join the texture set (other channels it lacks are skipped). + + // Lobe channels the material uses join the texture set (other channels it lacks are skipped) let missing: Vec = Channel::LOBES.into_iter().filter(|c| !channels.contains(c)).collect(); let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, m.id)?; for c in missing.into_iter().filter(|c| layers.iter().any(|l| l.channels.contains_key(c))) { @@ -759,7 +835,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { for l in layers { s.doc.project.insert_layer(ts, l, Some(gid), true)?; } - s.selected.insert(ts, gid); + s.select_one(ts, gid); gid }; place.apply(s, top)?; @@ -770,10 +846,12 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result { impl Place { /// From `above` (+ `inside`) or `index` params; the selection by default. pub(crate) fn from_params(p: &serde_json::Value) -> Place { - match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "index")) { - (Some(above), _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)), - (None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)), - (None, None) => Place::Selection, + match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "below"), crate::commands::u64p(p, "index")) { + (Some(above), _, _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)), + (None, Some(below), _) => Place::Below(LayerId(below)), + (None, None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)), + (None, None, None) if crate::commands::boolp(p, "top") == Some(true) => Place::Top, + (None, None, None) => Place::Selection, } } @@ -786,6 +864,13 @@ impl Place { s.doc.project.move_above(top, None, false)?; s.doc.project.move_layer(top, i)?; } + Place::Below(target) => { + s.doc.project.move_above(top, Some(target), false)?; + if let Some((_, _, index)) = s.doc.project.locate(top) { + s.doc.project.move_layer(top, index.saturating_sub(1))?; + } + } + Place::Top => s.doc.project.move_above(top, None, false)?, } Ok(()) } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 5d5bfbf4..62010b50 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -4,17 +4,24 @@ use std::collections::{BTreeMap, BTreeSet}; use texturecraft_compose::PaintTarget; -use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground}; +use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, Source}; use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick, rasterize, }; -use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool}; +use crate::session::{ActiveStroke, CloneFrom, QUICK_MASK_STROKE_LABEL, Session, StackTarget, Tool, history_label, stroke_template}; use crate::uv_stroke_state::UvStrokeState; +use crate::uv_symmetry::UvMirror; use crate::{EngineError, Result}; +/// The brush size (as in `BrushSettings::size`) at which a brush material's pattern has its natural size; a smaller brush makes the pattern smaller in proportion +pub const BRUSH_PATTERN_SIZE: f32 = 0.1; + +/// Brush size floor for the pattern scale +const MIN_PATTERN_BRUSH_SIZE: f32 = 0.0005; + /// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke. const MIN_UV_STAMP_STEP: f32 = 1e-5; @@ -59,7 +66,8 @@ impl Session { /// when painting a mask. Must run inside the stroke's history snapshot. fn paint_target(&mut self) -> Result { let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to paint on".into()))?; - // Painting an instance paints its source (its own mask when it overrides the mask). + + // Painting an instance paints its source unless its own mask overrides the mask let p = &self.doc.project; let id = if self.target == StackTarget::Mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) }; match self.target { @@ -72,12 +80,13 @@ impl Session { } } StackTarget::Effect(e) => match self.doc.project.effect(e) { - // Content paint effects hold channel pixels like a paint layer. + // Content paint effects hold channel pixels like a paint layer Some((owner, eff)) if matches!(eff.kind, EffectKind::Paint) => { let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) } - // Path sublayers are painted only from their stored paths. + + // Path sublayers are painted only from their stored paths Some((owner, eff)) if matches!(eff.kind, EffectKind::Path(_)) && self.painting_paths => { let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e); Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) }) @@ -85,8 +94,8 @@ impl Session { Some((_, eff)) if matches!(eff.kind, EffectKind::Path(_)) => { Err(EngineError::Other("a path sublayer holds paths only: edit them with the Path tool, or paint on a paint sublayer".into())) } - // A filter (or another effect) is selected, e.g. just added from the shelf: paint - // what lies beneath it, so the new paint goes through it. + + // Paint below a selected non-paint effect so new paint passes through it Some((owner, _)) => self.paint_target_below(owner, e), None => Err(EngineError::Other("the selected effect is not a paint effect".into())), }, @@ -97,12 +106,26 @@ impl Session { if let Some(top) = mask.effects.last().filter(|e| matches!(e.kind, EffectKind::Paint)) { return Ok(PaintTarget::Mask(top.id)); } + mask.effects.push(Effect::new(eid, EffectKind::Paint)); Ok(PaintTarget::Mask(eid)) } } } + /// Whether the stroke the selection starts paints a mask (the layer's mask, or a paint or + /// filter sublayer inside it). + fn paints_mask(&self) -> bool { + match self.target { + StackTarget::Content => false, + StackTarget::Mask => true, + StackTarget::Effect(effect) => { + let project = &self.doc.project; + project.effect(effect).and_then(|(owner, _)| project.layers.get(&owner)).is_some_and(|l| !l.content_effects.iter().any(|e| e.id == effect)) + } + } + } + /// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the /// nearest paint effect below it in the same stack, else the paint layer's own pixels (for /// content) or a new paint effect inserted just below it (for a mask). @@ -133,11 +156,44 @@ impl Session { Ok(PaintTarget::Mask(eid)) } + /// The pattern of the brush's material (`tool.material`) as a pickup over the texture, for the + /// channels in `values`: the material's fill, evaluated with the compose fill code tri-planar + /// in world space, so it stays fixed to the surface and continuous across stamps and strokes. + /// Its size follows the brush size ([`BRUSH_PATTERN_SIZE`] is the natural size). Channels the + /// material lacks carry the tool's value. None without a brush material. + fn brush_pattern(&self, values: &BTreeMap) -> Option { + let id = self.tool.material.clone()?; + let mut sources = crate::materials::brush_sources(&id)?; + sources.retain(|(channel, _)| values.contains_key(channel)); + for (channel, value) in values { + if !sources.iter().any(|(set, _)| set == channel) { + sources.push((*channel, Source::Uniform(*value))); + } + } + let ts = self.ts(); + let set = self.doc.project.texture_sets.get(ts)?; + let mut project = crate::material_lib::one_set_document(set, "Brush material").project; + let layer_id = project.alloc_id(); + let scale = BRUSH_PATTERN_SIZE / self.tool.brush.size.max(MIN_PATTERN_BRUSH_SIZE); + project.insert_layer(0, crate::materials::brush_fill(layer_id, sources, scale), None, false).ok()?; + let snapshot = texturecraft_paint::pickup::PickupSnapshot { + project, + ts: 0, + target: PaintTarget::Layer(layer_id), + mesh: self.mesh.clone(), + bounds: self.mesh.bounds(), + pixels: Default::default(), + baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: Default::default(), + }; + Some(Pickup::from_snapshot(PickupMode::Clone { offset: [0; 2] }, snapshot, self.caches.get(ts)?.gbuf.clone(), values.keys().copied())) + } + fn stroke_values(&self, target: PaintTarget) -> BTreeMap { let ts = self.ts(); let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() }; let layer_channels = match target { - // A content paint effect paints its owner layer's channels. + // A content paint effect paints its owner layer's channels PaintTarget::Layer(id) => { let owner = self.doc.project.effect(id).map(|(owner, _)| owner).unwrap_or(id); self.doc.project.layer(owner).map(|l| l.channels.keys().copied().collect::>()).unwrap_or_default() @@ -162,13 +218,15 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; - if pickup.is_some() { - // Clone and smudge read the composite: bring it up to date first. + let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite); + if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() { + // Only a composite pickup reads the viewport cache self.update(); } - // Cloning from the selected layer reads that layer alone. + + // Cloning from the selected layer reads that layer alone let layer_source = match self.selected_layer() { - Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer => { + Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer && !self.paints_mask() => { Some(self.flatten(ts, id).ok_or_else(|| EngineError::Other("clone from a paint or fill layer (folders have no content of their own)".into()))?) } _ => None, @@ -186,11 +244,15 @@ impl Session { } }; let values = target.map(|t| self.stroke_values(t)).unwrap_or_default(); + + // Clone and smudge on a mask read the mask as it was before the stroke + let mask_owner = match target { + Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner), + _ => None, + }; let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None }; let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) { Some("no channel enabled to paint: enable channels in the tool's material") - } else if pickup.is_some() && matches!(target, Some(PaintTarget::Mask(_))) { - Some("the Clone and Smudge tools paint layer content: select the layer instead of its mask") } else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode { Some("the Projection tool needs a stencil: pick an image in the tool properties (tool.stencil)") } else { @@ -200,13 +262,9 @@ impl Session { self.doc = before; return Err(EngineError::Other(msg.into())); } + let depth = (!uv_mode).then(|| self.eye_depth(viewport)); - let mut brush = self.tool.brush.clone(); - if tool == Tool::Smudge { - // shortcut: smudge drags one stamp trail; mirrored trails would need one pickup each. - brush.symmetry = Default::default(); - } - let stroke = Stroke::new(&brush, &self.mesh); + let stroke = Stroke::new(&self.tool.brush, &self.mesh); let mut canvas = StrokeCanvas::new(size.0, size.1); if !quick_mask { canvas.limit = self.stroke_limit(ts, size); @@ -220,24 +278,49 @@ impl Session { } m => m, }; - canvas.pickup = Some(match &layer_source { - Some(flat) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()), - None => Pickup::new(mode, cache.composite.clone(), cache.gbuf.clone(), values.keys().copied()), - }); + let mut pickup = match (&layer_source, mask_owner) { + // On a mask the stroke reads the mask's own values + (_, Some(owner)) => { + let snapshot = texturecraft_paint::pickup::PickupSnapshot { + project: self.doc.project.clone(), + ts, + target: PaintTarget::Mask(owner), + mesh: self.mesh.clone(), + bounds: self.mesh.bounds(), + pixels: self.doc.pixels.clone(), + baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: self.images.clone(), + }; + Pickup::from_snapshot(mode, snapshot, cache.gbuf.clone(), []) + } + (Some(flat), None) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()), + (None, None) => Pickup::new( + mode, + self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.into_owned(), + cache.gbuf.clone(), + values.keys().copied(), + ), + }; + if tool == Tool::Smudge && stroke.settings.symmetry.any() { + // Every mirrored copy of a smudge drags its own trail, in the 3D and the 2D view + pickup.isolate_copies(); + } + canvas.pickup = Some(pickup); if tool == Tool::Clone + && self.tool.clone_aligned && let Some(src) = self.tool.clone_source.as_mut() { src.offset.get_or_insert(offset); } } + if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) { + canvas.pickup = self.brush_pattern(&values); + } let label = if quick_mask { - "Quick mask stroke" - } else if erase { - "Eraser stroke" - } else if matches!(target, Some(PaintTarget::Mask(_))) { - "Mask stroke" + QUICK_MASK_STROKE_LABEL.to_string() } else { - "Paint stroke" + let on_mask = matches!(target, Some(PaintTarget::Mask(_))); + history_label(stroke_template(tool, on_mask), &self.stroke_layer_name()) }; self.stroke = Some(ActiveStroke { ts, @@ -252,12 +335,20 @@ impl Session { erase, stencil, before, - label: label.to_string(), + label, staging: Staging::default(), }); Ok(()) } + /// The name of the layer a stroke paints on (the owner layer when an effect is selected) + fn stroke_layer_name(&self) -> String { + let p = &self.doc.project; + let Some(id) = self.selected_layer() else { return String::new() }; + let owner = p.effect(id).map_or(id, |(owner, _)| owner); + p.layer(owner).map(|l| l.name.clone()).unwrap_or_default() + } + /// Clone / smudge pickup for the current tool, with the clone offset (source minus /// destination) in texture coordinates. fn pickup_mode(&self, first_uv: Option) -> Result> { @@ -266,11 +357,15 @@ impl Session { Tool::Clone => { let src = self.tool.clone_source.ok_or_else(|| EngineError::Other("set a clone source first: V + click on the mesh (tool.cloneSource)".into()))?; - let offset = match (src.offset, first_uv) { + + // Not aligned: every stroke measures the offset from its own first point + let kept = if self.tool.clone_aligned { src.offset } else { None }; + let offset = match (kept, first_uv) { (Some(o), _) => o, (None, Some(p)) => [src.uv[0] - p.x, src.uv[1] - p.y], (None, None) => return Err(EngineError::Other("start the clone stroke on the mesh".into())), }; + Ok(Some((PickupMode::Clone { offset: [0; 2] }, offset))) } _ => Ok(None), @@ -284,6 +379,7 @@ impl Session { alpha: b.alpha, image: b.alpha_image.as_ref().and_then(|n| images.get(n)).map(|i| &**i), library: b.alpha_library.as_deref().and_then(texturecraft_paint::alphas::find).map(|a| a.image()), + params: b.alpha_params, level: 0, } } @@ -355,11 +451,18 @@ impl Session { // The first sample is one stamp; a later one stamps every `step` along the segment from the previous let (start, segment, mut distance) = match progress.last.replace(uv) { None => (uv, Vec2::ZERO, 0.0), + // Pressure can shrink the step below the carry from the preceding sample Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)), }; let length = segment.length(); let shape = Self::shape(&self.images, settings); + + // The copies of each dab: the Clone tool's pickup offset is fixed, so it paints none + let material = self.doc.project.texture_sets.get(active.ts).map(|t| t.material).unwrap_or(0); + let mirror = (self.tool.tool != Tool::Clone) + .then(|| UvMirror::new(&settings.symmetry, active.stroke.center(), &self.mesh, &self.bvh, &cache.gbuf, material)) + .flatten(); let mut batch = Vec::new(); let mut stamped = 0; while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE { @@ -368,11 +471,18 @@ impl Session { while distance <= length && batch.len() < batch_size { let center = start + segment * (distance / length.max(f32::MIN_POSITIVE)); let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32); - batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed }); + batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed, source: None }); distance += step; } stamped += batch.len(); + if let Some(mirror) = &mirror { + for index in 0..batch.len() { + if let Some(stamp) = batch.get(index).copied() { + mirror.add_copies(&stamp, &mut batch); + } + } + } texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch); } @@ -538,7 +648,7 @@ impl Session { pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> { let size = (canvas.alpha.width(), canvas.alpha.height()); let opacity = self.tool.brush.opacity; - let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None, carried_mask: None }; if self.quick_mask.editing { self.commit_quick_mask(ts, size, source); return Ok(()); @@ -562,12 +672,11 @@ impl Session { let (width, height) = (cache.size.0 as f32, cache.size.1 as f32); let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); - let mut picked = BTreeMap::new(); - for channel in cache.composite.channels.keys() { - let value = cache.composite.value(*channel, x, y); - self.tool.values.insert(*channel, value); - picked.insert(*channel, value); - } + let tile = (x / texturecraft_texel::TILE, y / texturecraft_texel::TILE); + let source = self.document_composite(texture_set, &[tile]).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let picked: BTreeMap<_, _> = source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect(); + self.tool.values.extend(&picked); + self.tool.material = None; Ok(picked) } @@ -576,17 +685,30 @@ impl Session { self.stroke.as_ref().map(|s| s.canvas.dirty.len()).unwrap_or(0) } - /// Where the Clone tool reads for destination `at` (texture coordinates) as a surface - /// point: the source itself until the first stroke fixes the offset, or when `at` is None. - pub fn clone_source_point(&self, at: Option) -> Option { + /// Where the Clone tool reads for destination `at` (texture coordinates), in texture + /// coordinates: the source itself until the first stroke fixes the offset, or when `at` is + /// None. None without a source or when that spot is outside the texture. The far edge + /// (1.0) counts as inside, so the 2D marker shows a source set on the edge; reads of the + /// surface use `clone_source_uv`, which stays half-open. + pub fn clone_source_marker_uv(&self, at: Option) -> Option { let src = self.tool.clone_source?; let uv = match (src.offset, at) { (Some(o), Some(p)) => Vec2::new(p.x + o[0], p.y + o[1]), _ => Vec2::from(src.uv), }; - if !((0.0..1.0).contains(&uv.x) && (0.0..1.0).contains(&uv.y)) { - return None; - } + ((0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)).then_some(uv) + } + + /// Like `clone_source_marker_uv`, but half-open: None on the far edge, where the G-buffer + /// has no texel. + pub fn clone_source_uv(&self, at: Option) -> Option { + self.clone_source_marker_uv(at).filter(|uv| uv.x < 1.0 && uv.y < 1.0) + } + + /// Where the Clone tool reads for destination `at` (texture coordinates) as a surface + /// point: the source itself until the first stroke fixes the offset, or when `at` is None. + pub fn clone_source_point(&self, at: Option) -> Option { + let uv = self.clone_source_uv(at)?; let g = &self.caches.get(self.ts())?.gbuf; let (x, y) = ((uv.x * g.width as f32) as usize, (uv.y * g.height as f32) as usize); Some(g.surface(&self.mesh, y * g.width as usize + x)?.pos) @@ -613,5 +735,6 @@ fn with_commit_source( }; let per_texel: Option = if st.stencil.is_some() { Some(&stencil_fn) } else { None }; let carried = st.canvas.pickup.as_ref().map(|p| &p.values); - f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried }) + let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values()); + f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask }) } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 745e3197..5398501f 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -15,7 +15,7 @@ use texturecraft_compose::{PaintTarget, PixelStore}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; -use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; +use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline_segments_with_corners, spline_with_corners}; use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; @@ -47,6 +47,10 @@ const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001; pub struct PathState { /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view) pub points: Vec, + /// Per control point: the curve turns sharply there (a corner). Empty or shorter than `points` means smooth; + /// read it through [`PathState::is_corner`] and [`PathState::corner_flags`] + #[serde(default)] + pub corners: Vec, /// The points are texture coordinates (placed in the 2D view) pub uv: bool, /// The curve loops back to its first point @@ -69,13 +73,38 @@ impl PathState { pub fn push(&mut self, point: Vec3, uv: bool) { if uv != self.uv { self.points.clear(); + self.corners.clear(); self.uv = uv; } if self.points.len() < MAX_PATH_POINTS { self.points.push(point); + if !self.corners.is_empty() { + self.corners.resize(self.points.len(), false); + } } } + /// Does the curve turn sharply at point `i`? + pub fn is_corner(&self, i: usize) -> bool { + self.corners.get(i).copied().unwrap_or(false) + } + + /// One flag per point for the curve and storage: empty when no point is a corner, so smooth paths look like old ones + pub fn corner_flags(&self) -> Vec { + if self.points.iter().enumerate().any(|(i, _)| self.is_corner(i)) { (0..self.points.len()).map(|i| self.is_corner(i)).collect() } else { Vec::new() } + } + + /// Make point `i` a corner or smooth; false when there is no such point or it already is + pub fn set_corner(&mut self, i: usize, corner: bool) -> bool { + if i >= self.points.len() || self.is_corner(i) == corner { + return false; + } + + self.corners.resize(self.points.len(), false); + self.corners[i] = corner; + true + } + /// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't pub fn insert(&mut self, at: usize, point: Vec3) -> Option { if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS { @@ -83,18 +112,23 @@ impl PathState { } self.points.insert(at, point); + if !self.corners.is_empty() { + self.corners.resize(self.points.len() - 1, false); + self.corners.insert(at, false); + } self.selected = Some(at); self.selected } /// The same curve (points, open or closed, filled, view) as `other` fn same_curve(&self, other: &PathState) -> bool { - (&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv) + (&self.points, self.corner_flags(), self.closed, self.fill, self.uv) == (&other.points, other.corner_flags(), other.closed, other.fill, other.uv) } /// Empty the tool for the next path: no points, open, nothing selected or edited pub fn clear(&mut self) { self.points.clear(); + self.corners.clear(); self.closed = false; self.selected = None; self.editing = None; @@ -106,6 +140,10 @@ impl PathState { let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1)); if let Some(i) = at { self.points.remove(i); + if !self.corners.is_empty() { + self.corners.resize(self.points.len() + 1, false); + self.corners.remove(i); + } } if self.closed && self.points.len() < 3 { self.closed = false; @@ -116,10 +154,10 @@ impl PathState { /// A path sublayer's pixels after painting its first paths (`below`), with the mesh and /// texture size they were painted for. #[derive(Clone)] -// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one -// leaves cached paths with the old alpha until a path below the edited one changes. pub(crate) struct PathCache { - eid: LayerId, + pub(crate) eid: LayerId, + // Alpha image resources are not part of this cache key + // Replacing an alpha takes effect when a cached path changes key: (u64, Option<(u32, u32)>), below: Vec, mask: Option, @@ -143,10 +181,19 @@ pub fn specs() -> Vec { "Path", ["Tools"], Some("7"), - "{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once", + "{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], corners?: [bool,...] up to one per point (true: the curve turns sharply there; missing entries are smooth; applies to supplied points or the current curve), viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once", always, path ), + cmd!( + "path.corner", + "Toggle path corner", + ["Tools"], + None, + "{index?: point (default: the selected point), corner?: bool (default: toggle)} — makes a control point of the Path tool's curve a corner (the curve turns sharply there) or smooth again; one undo step per change, repainting the edited path at once", + always, + path_corner + ), cmd!( "path.edit", "Edit path", @@ -171,35 +218,60 @@ pub fn specs() -> Vec { /// Set the curve from command parameters, then preview or commit it in the supplied viewport fn path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "tool.path"; + let viewport = viewport_of(s, p); + let clear = boolp(p, "clear") == Some(true); + + let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { + (Some(pixels), _) => { + if pixels.len() > MAX_PATH_POINTS { + return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points"))); + } + + Some(( + pixels + .iter() + .enumerate() + .map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) + .collect::>>()?, + false, + )) + } + (None, Some(uvs)) => { + if uvs.len() > MAX_PATH_POINTS { + return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points"))); + } + + Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)) + } + (None, None) => None, + }; + let point_count = placed.as_ref().map_or(if clear { 0 } else { s.tool.path.points.len() }, |(points, _)| points.len()); + let corners = match p.get("corners") { + Some(value) => { + let flags = value.as_array().ok_or_else(|| bad(CMD, "`corners` must be an array of booleans"))?; + if flags.len() > point_count || flags.len() > MAX_PATH_POINTS { + return Err(bad(CMD, "`corners` has more flags than control points")); + } + + Some(flags.iter().map(Value::as_bool).collect::>>().ok_or_else(|| bad(CMD, "`corners` must be an array of booleans"))?) + } + None => None, + }; + if s.tool.tool != Tool::Path { set_tool(s, Tool::Path)?; } - - let viewport = viewport_of(s, p); - if boolp(p, "clear") == Some(true) { + if clear { s.cancel_path(); } - - let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { - (Some(pixels), _) => Some(( - pixels - .iter() - .enumerate() - .map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) - .collect::>>()?, - false, - )), - (None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), - (None, None) => None, - }; if let Some((points, uv)) = placed { - if points.len() > MAX_PATH_POINTS { - return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points"))); - } - s.tool.path.points = points; + s.tool.path.corners.clear(); s.tool.path.uv = uv; } + if let Some(flags) = corners { + s.tool.path.corners = flags; + } if let Some(v) = boolp(p, "closed") { s.tool.path.closed = v; } @@ -224,6 +296,24 @@ fn path(s: &mut Session, p: &Value) -> Result { Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed })) } +/// Make a control point a corner or smooth (a toggle by default) as one undoable point edit +fn path_corner(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.corner"; + let path = &s.tool.path; + let index = match u64p(p, "index") { + Some(i) => usize::try_from(i).ok().filter(|i| *i < path.points.len()), + None => path.selected.filter(|i| *i < path.points.len()), + } + .ok_or_else(|| bad(CMD, "no such point: pass `index` or select a point of the Path tool's curve"))?; + let corner = boolp(p, "corner").unwrap_or(!path.is_corner(index)); + s.set_path_point_corner(index, corner); + s.revision = s.revision.wrapping_add(1); + if s.path_live()? { + s.update(); + } + Ok(json!({ "index": index, "corner": s.tool.path.is_corner(index) })) +} + /// The `effect` and `index` params naming a stored path, with the path. fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathShape)> { let eid = LayerId(u64p(p, "effect").ok_or_else(|| bad(cmd, "`effect` (a path sublayer id) is required"))?); @@ -282,7 +372,21 @@ fn read_paint(shape: &PathShape) -> Result { /// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); - PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() } + + // Points dropped as unreadable shift the later flags with them + let corners = if shape.corners.is_empty() { + Vec::new() + } else { + shape + .points + .iter() + .zip(shape.corners.iter().copied().chain(std::iter::repeat(false))) + .filter(|(p, _)| p.iter().all(|v| v.is_finite())) + .take(MAX_PATH_POINTS) + .map(|(_, c)| c) + .collect() + }; + PathState { points, corners, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() } } /// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation) @@ -358,6 +462,7 @@ impl Session { let paint = PathPaint { brush: t.brush.clone(), values: t.values.clone(), enabled: t.enabled.clone(), mask_value: t.mask_value, camera }; PathShape { points: path.points.iter().map(|p| p.to_array()).collect(), + corners: path.corner_flags(), uv: path.uv, closed: path.closed, fill: path.fill, @@ -399,7 +504,8 @@ impl Session { let shape = self.path_shape(self.camera, viewport); let editing = self.tool.path.editing; - let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1)); + let label = + editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(i + 1).to_string())); let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| { let (effect_id, index) = match editing { Some(at) => at, @@ -426,7 +532,11 @@ impl Session { // JSON round trips can change float representation without changing the paint settings read_paint(stored).is_ok_and(|paint| { let current = self.path_shape(paint.camera, Vec2::from_array(stored.viewport)); - (¤t.points, current.uv, current.closed, current.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) + + // Normalised like the current flags: a short, long or all-smooth stored list must not count as a change + let stored_corners = state_of(stored).corner_flags(); + (¤t.points, ¤t.corners, current.uv, current.closed, current.fill) + == (&stored.points, &stored_corners, stored.uv, stored.closed, stored.fill) && read_paint(¤t).is_ok_and(|current_paint| current_paint == paint) }) } @@ -457,16 +567,21 @@ impl Session { if self.path_draft.is_some() { self.cancel_path(); } else { - self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |session| { - if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) { - paths.remove(index); - } - session.render_paths(effect, index) - })?; + self.edit_merging( + &crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(index + 1).to_string()), + self.tool.path.edited, + |session| { + if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) { + paths.remove(index); + } + session.render_paths(effect, index) + }, + )?; self.cancel_path(); } return Ok(true); } + return Ok(false); } @@ -488,7 +603,7 @@ impl Session { None => { // The path's own repaint keeps its point changes undoable, unlike other steps let steps = std::mem::take(&mut self.path_steps); - self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited); + self.push_step(&crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(index + 1).to_string()), before, self.tool.path.edited); self.path_steps = steps; self.tool.path.edited = true; } @@ -588,6 +703,37 @@ impl Session { self.tool.path.remove_selected(); } + /// Make a point a corner or smooth again, with point undo; false when nothing changed + pub fn set_path_point_corner(&mut self, index: usize, corner: bool) -> bool { + if index >= self.tool.path.points.len() || self.tool.path.is_corner(index) == corner { + return false; + } + + self.path_checkpoint(); + self.tool.path.set_corner(index, corner) + } + + /// Switch the selected point between corner and smooth, with point undo; false without a selected point + pub fn toggle_selected_path_corner(&mut self) -> bool { + let Some(i) = self.tool.path.selected.filter(|i| *i < self.tool.path.points.len()) else { return false }; + let corner = !self.tool.path.is_corner(i); + self.set_path_point_corner(i, corner) + } + + /// Append a point that is a corner, selecting it; as [`Session::append_path_point`] + pub fn append_path_corner(&mut self, point: Vec3, uv: bool) -> Option { + let at = self.append_path_point(point, uv)?; + self.tool.path.set_corner(at, true); + Some(at) + } + + /// Insert a point that is a corner, selecting it; as [`Session::insert_path_point`] + pub fn insert_path_corner(&mut self, index: usize, point: Vec3) -> Option { + let at = self.insert_path_point(index, point)?; + self.tool.path.set_corner(at, true); + Some(at) + } + /// Change whether the path loops back to its first point, with point undo pub fn set_path_closed(&mut self, closed: bool) { if self.tool.path.closed != closed { @@ -823,8 +969,9 @@ impl Session { } _ => 0, }; - // Each path goes through the regular stroke and fill code with its own settings; their - // own history entries are dropped (the caller records one step). + + // Regular stroke and fill code paints each path with its own settings + // Discard its history entries because the caller records one undo step let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo)); self.target = StackTarget::Effect(eid); @@ -866,15 +1013,20 @@ impl Session { self.paint_path(viewport) } - /// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh) + /// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`texturecraft_paint::spline_segments`] (None off the mesh) pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec>> { + self.path_surface_with_corners(points, &[], closed, camera, viewport) + } + + /// [`Session::path_surface`] for a curve with corner points (`corners` as [`PathState::corners`]) + pub fn path_surface_with_corners(&self, points: &[Vec3], corners: &[bool], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec>> { let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::>>() else { return Vec::new(); }; let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport }; - spline_segments(&screen, closed, SURFACE_STEP_PX) + spline_segments_with_corners(&screen, corners, closed, SURFACE_STEP_PX) .into_iter() .zip(&screen) .map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect()) @@ -890,7 +1042,7 @@ impl Session { let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?); let path = state_of(shape); - Some(self.path_surface(&path.points, path.closed, camera, viewport)) + Some(self.path_surface_with_corners(&path.points, &path.corners, path.closed, camera, viewport)) } /// Paint the Path tool's curve with the current brush (or fill it when closed and filled) @@ -898,14 +1050,17 @@ impl Session { fn paint_path(&mut self, viewport: Vec2) -> Result { let (uv, closed) = (self.tool.path.uv, self.tool.path.closed); let fill = closed && self.tool.path.fill; - let pts: Vec = self.path_view_points(viewport).into_iter().flatten().collect(); + let (pts, corners): (Vec, Vec) = + self.path_view_points(viewport).into_iter().enumerate().filter_map(|(i, p)| Some((p?, self.tool.path.is_corner(i)))).unzip(); if pts.is_empty() { return Err(EngineError::Other("the path has no points: click the surface to add some".into())); } + if fill && pts.len() < 3 { return Err(EngineError::Other("a filled path needs at least three points".into())); } - let curve = spline(&pts, closed, if uv { STEP_UV } else { STEP_PX }); + + let curve = spline_with_corners(&pts, &corners, closed, if uv { STEP_UV } else { STEP_PX }); Ok(if fill { json!({ "filledTiles": self.lasso_fill(curve, uv, viewport)? }) } else if uv { @@ -1032,7 +1187,8 @@ mod tests { eid = r["committed"]["effect"].as_u64().unwrap(); } let eid = texturecraft_core::LayerId(eid); - // Live edits of the middle path reuse the bottom path's pixels. + + // Live edits of the middle path reuse the bottom path's pixels execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); for v in [0.4, 0.45] { execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); @@ -1045,6 +1201,32 @@ mod tests { s.render_paths(eid, 0).unwrap(); assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); + + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap(); + let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::()); + assert!(cached_tiles > 0); + + execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); + let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::()); + assert_eq!(remaining_tiles, 0); + assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles"); + } + + #[test] + fn failed_edit_releases_cached_path_tiles() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 12, 6), "builtin:test", None, 128).unwrap(); + let mut image = TileImage::new(64, 64, 1); + let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]); + let retained = Arc::downgrade(&tile); + image.set_tile(0, 0, Some(tile)); + session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() }); + + let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into()))); + + assert!(result.is_err()); + assert!(session.path_cache.is_none()); + assert!(retained.upgrade().is_none(), "the discarded document cannot retain the cache's tile"); } #[test] diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index af93f71c..64b5be85 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -104,6 +104,10 @@ impl Session { drag.last_box = Some((low, high)); let selected = self.box_selection(low, high); + let selected = match self.polygon_fill_drag.as_ref() { + Some(drag) => self.with_symmetry_copies(&drag.fill_groups, selected), + None => selected, + }; self.show_box_fill(selected) } @@ -178,11 +182,12 @@ impl Session { } } - /// Fill the fill-mode group holding `triangle` (one undo step) + /// Fill the fill-mode group holding `triangle` and its symmetry copies (one undo step) fn fill_group_of(&mut self, triangle: u32) -> Result { let ts = self.ts(); let groups = self.fill_partition(self.fill_material()?); let triangles: BTreeSet = groups.group(triangle).unwrap_or_default().iter().copied().collect(); + let triangles = self.with_symmetry_copies(&groups, triangles); let (gbuf, mut canvas) = self.fill_canvas(ts)?; fill_triangles(&mut canvas, &gbuf, &triangles); diff --git a/crates/engine/src/polygon_fill_mirror.rs b/crates/engine/src/polygon_fill_mirror.rs new file mode 100644 index 00000000..945d15bb --- /dev/null +++ b/crates/engine/src/polygon_fill_mirror.rs @@ -0,0 +1,240 @@ +//! Polygon fill with symmetry: the fill also reaches the faces the brush's mirror planes and radial copies map it onto. + +use std::collections::{BTreeSet, HashSet}; + +use texturecraft_geom::glam::Mat3; + +use crate::session::Session; +use crate::triangle_partition::TrianglePartition; + +/// How far a mirrored face centre may be from the surface and still count as on it, as a fraction of the mesh's bounding-box diagonal +const MIRROR_TOLERANCE: f32 = 1e-3; + +impl Session { + /// `selected` plus the faces the brush symmetry copies it onto: for each group of `groups` (the fill mode's grouping) in `selected`, the group holding the face its first triangle's centre maps to under each mirror plane and radial turn. + /// Copies that land on no face of the texture set (an asymmetric mesh, or the other side of a thin shell) are skipped + pub(crate) fn with_symmetry_copies(&self, groups: &TrianglePartition, selected: BTreeSet) -> BTreeSet { + let symmetry = self.tool.brush.sanitized().symmetry; + let copies: Vec = symmetry.transforms().into_iter().filter(|copy| *copy != Mat3::IDENTITY).collect(); + if copies.is_empty() || selected.is_empty() { + return selected; + } + + let mesh = &self.mesh; + let (low, high) = mesh.bounds(); + let tolerance = (high - low).length() * MIRROR_TOLERANCE; + let origin = symmetry.origin((low + high) * 0.5); + let corners = |triangle: u32| { + let [first, second, third] = mesh.tri(triangle as usize)?; + Some([*mesh.positions.get(first)?, *mesh.positions.get(second)?, *mesh.positions.get(third)?]) + }; + + let mut seen_groups = HashSet::new(); + let mut result = selected.clone(); + for seed in selected.iter().copied().filter(|triangle| groups.index_of(*triangle).is_some_and(|group| seen_groups.insert(group))) { + let Some([first, second, third]) = corners(seed) else { continue }; + let centre = (first + second + third) / 3.0; + let normal = (second - first).cross(third - first); + + for copy in &copies { + let target = origin + *copy * (centre - origin); + let target_normal = *copy * normal; + + // A face on the same side: a thin shell's other face lies at the same point but looks the other way + let faces_alike = |triangle: u32| { + groups.index_of(triangle).is_some() && corners(triangle).is_some_and(|[a, b, c]| (b - a).cross(c - a).dot(target_normal) > 0.0) + }; + if let Some(hit) = self.bvh.nearest(target, tolerance, &faces_alike) { + result.extend(groups.group(hit.tri).unwrap_or_default().iter().copied()); + } + } + } + + result + } +} + +#[cfg(test)] +mod tests { + use texturecraft_core::Channel; + use texturecraft_geom::glam::{Vec2, Vec3}; + use texturecraft_geom::mesh::Mesh; + + use crate::fill_hit_test::FillHitTest; + use crate::fill_mode::FillMode; + use crate::session::{Session, Tool}; + + /// The roughness the test fills paint, to tell filled texels apart + const FILL_ROUGHNESS: f32 = 0.9; + + /// The x ranges of the two quads on the right of the YZ plane; the left side mirrors them + const QUAD_RANGES: [(f32, f32); 2] = [(1.0, 2.0), (3.0, 4.0)]; + + /// Texture coordinate of the point `(x, y)` on the flat test mesh, each x its own place + fn uv_of(x: f32, y: f32) -> Vec2 { + Vec2::new((x + 4.0) / 8.0, 0.2 + 0.6 * y) + } + + /// Four quads facing +Z (two triangles each): [`QUAD_RANGES`] on the right and their mirror images on the left, each with its own vertices and UV place + fn mirrored_quads() -> Mesh { + let (mut positions, mut uvs, mut indices) = (Vec::new(), Vec::new(), Vec::new()); + for (low, high) in QUAD_RANGES { + for mirrored in [false, true] { + let sign = if mirrored { -1.0 } else { 1.0 }; + let first = positions.len() as u32; + for (x, y) in [(low, 0.0), (high, 0.0), (high, 1.0), (low, 1.0)] { + positions.push(Vec3::new(sign * x, y, 0.0)); + uvs.push(uv_of(sign * x, y)); + } + + // A mirror image has the opposite winding, so it keeps facing +Z + let corners = if mirrored { [0, 2, 1, 0, 3, 2] } else { [0, 1, 2, 0, 2, 3] }; + indices.extend(corners.map(|corner| first + corner)); + } + } + Mesh::from_parts(positions, None, uvs, indices, "m").unwrap() + } + + /// A fill session on [`mirrored_quads`] mirroring across X + fn mirrored_session(fill_mode: FillMode) -> Session { + let mut session = Session::new_project("t", mirrored_quads(), "test", None, 128).unwrap(); + session.tool.tool = Tool::PolygonFill; + session.tool.fill_mode = fill_mode; + session.tool.brush.symmetry.x = true; + session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]); + session.update(); + session + } + + /// Whether the texel at the point `(x, y)` of the flat test mesh shows the fill + fn filled_at(session: &Session, x: f32, y: f32) -> bool { + let uv = uv_of(x, y); + let (width, height) = session.caches[0].size; + let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32); + (roughness[0] - FILL_ROUGHNESS).abs() < 0.01 + } + + /// Whether the quad over the x range starting at `low` (negative: its mirror image on the left) shows the fill + fn quad_filled(session: &Session, low: f32) -> bool { + filled_at(session, if low < 0.0 { low - 0.5 } else { low + 0.5 }, 0.5) + } + + /// Which of the four quads show the fill: right near, left near, right far, left far + fn filled_quads(session: &Session) -> [bool; 4] { + [quad_filled(session, 1.0), quad_filled(session, -1.0), quad_filled(session, 3.0), quad_filled(session, -3.0)] + } + + #[test] + fn a_triangle_click_also_fills_the_mirrored_triangle() { + let mut session = mirrored_session(FillMode::Triangle); + + // The lower right triangle of the near quad + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "the triangle and its mirror image"); + session.update(); + + assert!(filled_at(&session, 1.8, 0.2) && filled_at(&session, -1.8, 0.2), "the clicked triangle and the one across the plane"); + assert!(!filled_at(&session, 1.2, 0.8) && !filled_at(&session, -1.2, 0.8), "the other triangle of each quad stays"); + assert!(!quad_filled(&session, 3.0) && !quad_filled(&session, -3.0), "the far quads stay"); + } + + #[test] + fn a_uv_island_click_fills_the_mirrored_island() { + let mut session = mirrored_session(FillMode::UvIsland); + + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 4, "both triangles of the quad and of its mirror image"); + session.update(); + + assert_eq!(filled_quads(&session), [true, true, false, false]); + } + + #[test] + fn a_mesh_click_fills_the_mirrored_connected_part_only() { + let mut session = mirrored_session(FillMode::Mesh); + + // Each quad is its own piece, as its vertices touch no other quad + assert_eq!(session.polygon_fill_uv(uv_of(3.5, 0.5)).unwrap(), 4); + session.update(); + + assert_eq!(filled_quads(&session), [false, false, true, true]); + } + + #[test] + fn a_rectangle_fills_the_mirrored_side_too() { + let mut session = mirrored_session(FillMode::UvIsland); + session.tool.fill_hit_test = FillHitTest::ContainedCenter; + + // Around the far right quad only + let filled = session.polygon_fill_box_uv(uv_of(2.9, -0.1), uv_of(4.1, 1.1)).unwrap(); + session.update(); + + assert_eq!(filled, 4); + assert_eq!(filled_quads(&session), [false, false, true, true]); + } + + #[test] + fn one_undo_takes_back_the_fill_and_its_mirror() { + let mut session = mirrored_session(FillMode::UvIsland); + let history = session.history_labels().len(); + + session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(); + session.update(); + assert_eq!(filled_quads(&session), [true, true, false, false], "the fill and its copy show"); + assert_eq!(session.history_labels().len(), history + 1, "one step for the fill and its copy"); + session.undo().unwrap(); + session.update(); + + assert_eq!(filled_quads(&session), [false; 4]); + } + + #[test] + fn symmetry_off_fills_only_what_was_clicked() { + let mut session = mirrored_session(FillMode::UvIsland); + session.tool.brush.symmetry.enabled = false; + + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2); + session.update(); + + assert_eq!(filled_quads(&session), [true, false, false, false]); + } + + #[test] + fn faces_without_a_mirror_match_are_skipped() { + let mut session = mirrored_session(FillMode::UvIsland); + + // Moving the plane to x = 10 sends every copy to x ~ 20, where there is no surface + session.tool.brush.symmetry.offset = [10.0, 0.0, 0.0]; + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "only the clicked quad"); + session.update(); + + assert_eq!(filled_quads(&session), [true, false, false, false]); + } + + #[test] + fn a_face_is_not_its_own_mirror_across_its_plane() { + let mut session = mirrored_session(FillMode::Triangle); + session.tool.brush.symmetry.x = false; + session.tool.brush.symmetry.z = true; + + // The flat mesh lies in the mirror plane z = 0: each triangle maps onto itself looking the other way + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 1); + } + + #[test] + fn a_radial_copy_turns_the_fill_around_the_axis() { + let mut session = mirrored_session(FillMode::UvIsland); + + // Half a turn around Z through the mesh centre (0, 0.5) sends the quad onto the quad on the left + session.tool.brush.symmetry = texturecraft_paint::Symmetry { x: false, radial: 2, axis: 2, ..Default::default() }; + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 4, "the turned copy lands on the left quad"); + session.update(); + assert_eq!(filled_quads(&session), [true, true, false, false]); + } + + #[test] + fn a_radial_copy_with_the_axis_moved_away_lands_on_no_face() { + let mut session = mirrored_session(FillMode::UvIsland); + + session.tool.brush.symmetry = texturecraft_paint::Symmetry { x: false, radial: 2, axis: 2, offset: [0.0, 5.0, 0.0], ..Default::default() }; + assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "the turned copy is far above the mesh"); + } +} diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index d33b670c..a74d2d68 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -23,13 +23,21 @@ pub struct UserPresets { pub fn specs() -> Vec { vec![ cmd!("export.presets", "Export presets", [], None, "{} → [{name, maps, builtin}]", always, list), - cmd!("export.preset.get", "Get an export preset", [], None, "{name} → {name, maps: [{file, format, bit_depth, channels}]}", always, get), + cmd!( + "export.preset.get", + "Get an export preset", + [], + None, + "{name} → {name, maps: [{file, format, bit_depth, channels, inverted?: [dest, ...]}]}", + always, + get + ), cmd!( "export.preset.save", "Save a user export preset", [], None, - "{preset: {name, maps}, unique?: true = add \" 2\", \" 3\"… on a name clash instead of failing, rename?: name of the user preset this one replaces} → {name}", + "{preset: {name, maps (a map may list `inverted` destinations such as [\"R\"] to write 1 minus the value)}, unique?: true = add \" 2\", \" 3\"… on a name clash instead of failing, rename?: name of the user preset this one replaces} → {name}", always, save ), @@ -282,7 +290,8 @@ mod tests { assert!((rough - 0.3).abs() < 0.01); let set = s.doc.project.texture_sets[0].name.clone(); let dir = std::env::temp_dir().join(format!("tc_user_preset_export_{}", std::process::id())); - // By name and as an inline object: the same files. + + // By name and as an inline object: the same files for preset in [json!("packed"), packed] { let _ = std::fs::remove_dir_all(&dir); let r = run(&mut s, "file.exportTextures", json!({"dir": dir.display().to_string(), "preset": preset, "ts": 0})).unwrap(); diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index ce45b9ff..55e4bde0 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -36,7 +36,7 @@ fn coords(n: Vec3) -> Coords { fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> { match s { Source::Uniform(v) => Some(*v), - Source::Procedural { pattern, low, high } => { + Source::Procedural { pattern, low, high, .. } => { let t = procedural(pattern, proj, c); Some([0, 1, 2].map(|k| low[k] + (high[k] - low[k]) * t)) } @@ -110,7 +110,8 @@ pub fn filter(id: &str, size: usize) -> Option>> { let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res); let mut p = Project::new("preview", ""); p.texture_sets.push(TextureSet::new("preview", 0, res)); - let procedural = |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high }; + let procedural = + |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high, ramp: Vec::new() }; let mut fill = Fill::default(); fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1])); fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3])); diff --git a/crates/engine/src/procedural_params.rs b/crates/engine/src/procedural_params.rs new file mode 100644 index 00000000..2e91b16f --- /dev/null +++ b/crates/engine/src/procedural_params.rs @@ -0,0 +1,142 @@ +//! Pattern settings in commands: the resolution a pattern is computed at and the Tile Generator's settings + +use serde_json::{Map, Value}; +use texturecraft_core::{ + OutputResolution, Procedural, ProceduralKind, ResolutionMode, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, +}; + +use crate::Result; +use crate::commands::{bad, boolp, f32p, u64p}; + +/// The pattern's `scale`, `seed`, `contrast`, `balance` and `invert` in `params`, applied to `pattern` in range +pub(crate) fn pattern_basics_from(params: &Value, pattern: &mut Procedural) { + if let Some(scale) = f32p(params, "scale") { + pattern.scale = scale.clamp(Procedural::MIN_SCALE, Procedural::MAX_SCALE); + } + if let Some(seed) = u64p(params, "seed") { + pattern.seed = u32::try_from(seed).unwrap_or(u32::MAX); + } + if let Some(contrast) = f32p(params, "contrast") { + pattern.contrast = contrast.clamp(0.0, Procedural::MAX_CONTRAST); + } + if let Some(balance) = f32p(params, "balance") { + pattern.balance = balance.clamp(-Procedural::MAX_BALANCE, Procedural::MAX_BALANCE); + } + if let Some(invert) = boolp(params, "invert") { + pattern.invert = invert; + } +} + +/// Whether `params` holds any pattern setting [`pattern_settings_from`] reads +pub(crate) fn has_pattern_settings(params: &Value) -> bool { + ["resolution", "customResolution", "resolutionFactor", "tile", "tileDefaults"].iter().any(|key| params.get(key).is_some()) +} + +/// Apply the resolution and Tile Generator settings in `params` to `pattern`, using `command` in errors +pub(crate) fn pattern_settings_from(command: &str, params: &Value, pattern: &mut Procedural) -> Result<()> { + resolution_from(command, params, &mut pattern.resolution)?; + let resets = boolp(params, "tileDefaults") == Some(true); + let edits = params.get("tile"); + if (resets || edits.is_some()) && pattern.kind != ProceduralKind::TileGenerator { + return Err(bad(command, "`tile` and `tileDefaults` go with the Tile Generator pattern")); + } + + if resets { + pattern.tile = Some(Box::default()); + } + if let Some(edits) = edits { + let current = pattern.tile.get_or_insert_with(Box::default); + **current = tile_from(command, edits, current)?; + } + Ok(()) +} + +/// The `resolution`, `customResolution` and `resolutionFactor` params applied to `resolution` +pub(crate) fn resolution_from(command: &str, params: &Value, resolution: &mut OutputResolution) -> Result<()> { + if let Some(value) = params.get("resolution") { + let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?; + resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?; + } + if let Some(custom) = u64p(params, "customResolution") { + resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32; + } + if let Some(factor) = params.get("resolutionFactor") { + let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?; + resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8; + } + Ok(()) +} + +/// `current` with the camelCase settings in `edits` applied (menu choices by label or id), in range +fn tile_from(command: &str, edits: &Value, current: &TileGenerator) -> Result { + let edits = edits.as_object().ok_or_else(|| bad(command, "`tile` must be an object"))?; + let mut merged = serde_json::to_value(current).map_err(|error| bad(command, error.to_string()))?; + let fields = merged.as_object_mut().ok_or_else(|| bad(command, "the Tile Generator settings are not an object"))?; + for (key, value) in edits { + let field = snake_case(key); + if !fields.contains_key(&field) { + return Err(bad(command, format!("unknown Tile Generator setting `{key}`"))); + } + + fields.insert(field.clone(), choice_id(command, &field, value)?); + } + let tile: TileGenerator = serde_json::from_value(merged).map_err(|error| bad(command, format!("bad Tile Generator setting: {error}")))?; + Ok(tile.clamped()) +} + +/// A menu setting's value as its saved id (`"Half bell"` → `"HalfBell"`); other values unchanged +fn choice_id(command: &str, field: &str, value: &Value) -> Result { + let Some(text) = value.as_str() else { return Ok(value.clone()) }; + let id = match field { + "shape" => find(&TileShape::ALL, TileShape::label, text), + "size_mode" => find(&TileSizeMode::ALL, TileSizeMode::label, text), + "input_distribution" => find(&TileInputDistribution::ALL, TileInputDistribution::label, text), + "symmetry" => find(&TileSymmetry::ALL, TileSymmetry::label, text), + "blending" => find(&TileBlending::ALL, TileBlending::label, text), + _ => return Ok(value.clone()), + }; + + id.map(Value::String).ok_or_else(|| bad(command, format!("unknown {} `{text}`", camel_case(field)))) +} + +/// The id of the choice in `all` whose label or id is `text` (any case, spaces optional) +fn find(all: &[T], label: fn(T) -> &'static str, text: &str) -> Option { + let normalize = |name: &str| name.to_ascii_lowercase().replace([' ', '_', '-', '+'], ""); + let wanted = normalize(text); + all.iter().find(|choice| normalize(label(**choice)) == wanted || normalize(&format!("{choice:?}")) == wanted).map(|choice| format!("{choice:?}")) +} + +/// The Tile Generator settings as `project.inspect` reports them: camelCase keys, as the commands take them +pub(crate) fn tile_report(tile: &TileGenerator) -> Value { + let Ok(Value::Object(fields)) = serde_json::to_value(tile) else { return Value::Null }; + Value::Object(fields.into_iter().map(|(key, value)| (camel_case(&key), value)).collect::>()) +} + +fn snake_case(key: &str) -> String { + let mut snake = String::with_capacity(key.len()); + for character in key.chars() { + if character.is_ascii_uppercase() { + snake.push('_'); + snake.push(character.to_ascii_lowercase()); + } else { + snake.push(character); + } + } + snake +} + +fn camel_case(field: &str) -> String { + let mut camel = String::with_capacity(field.len()); + let mut upper = false; + for character in field.chars() { + if character == '_' { + upper = true; + } else if upper { + camel.push(character.to_ascii_uppercase()); + upper = false; + } else { + camel.push(character); + } + } + camel +} diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index b3a753ff..33432cda 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "Add smart material", [], None, - "{material: id or label, above?: layer id, inside?: bool, index?: n} — above the selection by default; `above` (+ `inside` for a folder) or `index` in the top-level stack (0 = bottom) place it", + "{material: id or label, above?: layer id, inside?: bool, below?: layer id, top?: true, index?: n} — above the selection by default; `above` (+ `inside` for a folder), `below`, `top` or `index` in the top-level stack (0 = bottom) place it", always, material ), @@ -82,7 +82,7 @@ pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result // Paint above the smart material so new strokes remain visible for set_index in (0..session.set_count()).rev() { session.active_set = set_index; - session.selected.remove(&set_index); + session.select_none(set_index); crate::execute(&mut session, "layer.add.paint", &Value::Null)?; } session.undo.clear(); diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 8fe1fe5a..97d0bd9a 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use texturecraft_compose::ImageRes; use texturecraft_core::{Channel, Fill, Layer, LayerKind, Source}; +use texturecraft_formats::{MAX_RESOURCE_NAME_LEN, sanitize_resource_name}; use crate::commands::{CommandSpec, always, bad, channel_param, strp}; use crate::{EngineError, Result, Session, cmd}; @@ -66,17 +67,28 @@ impl Session { let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); - let mut base = texturecraft_formats::sanitize_resource_name(leaf); - if !prefix.trim().is_empty() { - // Names stay within the sanitized length; the file name keeps its room - let room = 120usize.saturating_sub(base.chars().count()); - let prefix: String = texturecraft_formats::sanitize_resource_name(prefix.trim()).chars().take(room).collect(); - base = format!("{prefix}{base}"); + let mut base = sanitize_resource_name(leaf); + + // The file name has priority over the optional prefix + let prefix_room = MAX_RESOURCE_NAME_LEN - base.len(); + let prefix = prefix.trim(); + if !prefix.is_empty() && prefix_room > 0 { + let mut prefix = sanitize_resource_name(prefix); + prefix.truncate(prefix_room); + base.insert_str(0, &prefix); } + + let (stem, extension) = base.rfind('.').map_or((base.as_str(), ""), |extension_start| base.split_at(extension_start)); let mut name = base.clone(); let mut duplicate_index = 2; while self.doc.resources.contains_key(&name) { - name = format!("{duplicate_index}_{base}"); + let discriminator = format!("{duplicate_index}_"); + let available = MAX_RESOURCE_NAME_LEN - discriminator.len(); + + // Leave room for a stem even for names that end in an unusually long extension + let (stem, extension) = if extension.len() < available { (stem, extension) } else { (base.as_str(), "") }; + let stem = stem.get(..stem.len().min(available - extension.len())).unwrap_or(stem); + name = format!("{discriminator}{stem}{extension}"); duplicate_index += 1; } @@ -137,10 +149,12 @@ pub(crate) fn read_image_file(cmd: &str, path: &str, max_bytes: u64) -> Result max_bytes { return Err(too_large()); } @@ -179,8 +193,7 @@ fn remove(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } -/// Drop resources no layer, mask effect, the projection stencil or the environment uses (one undo -/// step). +/// Drop resources unused by layers, mask effects, the brush alpha, the stencil or the environment. fn remove_unused(s: &mut Session, _: &Value) -> Result { let mut used = Vec::new(); for set in &s.doc.project.texture_sets { @@ -189,6 +202,7 @@ fn remove_unused(s: &mut Session, _: &Value) -> Result { } } used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone())); + used.extend(s.tool.brush.alpha_image.clone()); used.extend(s.doc.project.display.environment_resource().map(str::to_string)); let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); if !unused.is_empty() { @@ -263,4 +277,43 @@ mod tests { fn devices_are_rejected_before_reading() { assert!(read_image_file("test", "/dev/null", 16).unwrap_err().to_string().contains("not a regular file")); } + + #[test] + fn duplicate_prefixed_image_names_survive_saving_and_reopening() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let file_name = format!("{}.png", "x".repeat(108)); + let prefix = "material"; + let mut names = Vec::new(); + + for _ in 0..10 { + let name = session.import_resource_bytes_prefixed(prefix, &file_name, png.clone()).unwrap(); + crate::execute(&mut session, "layer.add.image", &json!({"name": name})).unwrap(); + names.push(name); + } + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + + assert_eq!(reopened.images.len(), names.len()); + for name in names { + assert!(reopened.images.contains_key(&name), "missing image after reload: {name}"); + assert!(name.ends_with(".png")); + } + } + + #[test] + fn removing_unused_resources_keeps_the_active_brush_alpha() { + let mut session = crate::sample_session(128, 32).unwrap(); + let png = texturecraft_formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let alpha = session.import_resource_bytes("brush.png", png.clone()).unwrap(); + let unused = session.import_resource_bytes("unused.png", png).unwrap(); + crate::execute(&mut session, "tool.brush", &json!({"alpha": {"image": alpha}})).unwrap(); + + let result = crate::execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(result["removed"], json!([unused])); + assert_eq!(session.tool.brush.alpha_image.as_deref(), Some(alpha.as_str())); + assert!(session.images.contains_key(&alpha)); + assert!(!session.images.contains_key(&unused)); + } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 54aa49bf..f8ce6c32 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -14,6 +14,7 @@ use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; use texturecraft_texel::DilationMap; use crate::fill_mode::FillMode; +pub use crate::stencil_look::StencilLook; use crate::{EngineError, Result}; /// Padding (texels) applied to composites for display. @@ -182,7 +183,24 @@ pub struct StencilState { impl StencilState { pub fn new(image: &str) -> StencilState { - StencilState { image: image.to_string(), center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 } + StencilState::with_look(image, StencilLook::default()) + } + + /// A stencil of `image` placed as `look` says. + pub fn with_look(image: &str, look: StencilLook) -> StencilState { + StencilState { image: image.to_string(), center: look.center, scale: look.scale, rotation: look.rotation, tile: look.tile, opacity: look.opacity } + } + + pub fn look(&self) -> StencilLook { + StencilLook { center: self.center, scale: self.scale, rotation: self.rotation, tile: self.tile, opacity: self.opacity } + } + + /// Back to the placement a new stencil starts with (center, scale and rotation); the image, tiling and opacity stay. + pub fn reset_placement(&mut self) { + let start = StencilState::new(&self.image); + self.center = start.center; + self.scale = start.scale; + self.rotation = start.rotation; } /// Placement for a viewport aspect (width / height): center, half extents in NDC, radians. @@ -201,6 +219,10 @@ pub struct ToolState { /// Material painted per channel (linear values) and whether each channel is painted. pub values: BTreeMap, pub enabled: BTreeSet, + /// The simple material (shelf id) the brush paints the pattern of, with `values` as its plain + /// stand-in; `None` for plain values (any edit of a value clears it). + #[serde(default)] + pub material: Option, /// Gray painted into masks. pub mask_value: f32, pub fill_mode: FillMode, @@ -213,12 +235,21 @@ pub struct ToolState { /// Stencil used by the Projection tool. #[serde(default)] pub stencil: Option, + /// Placement the next stencil starts with: the last stencil's, kept when the stencil is + /// cleared or the project changes (its image belongs to the project, the placement does not). + #[serde(default)] + pub stencil_look: StencilLook, /// Smudge tool: how much of the picked-up values each stamp deposits (0..1). #[serde(default = "default_smudge_strength")] pub smudge_strength: f32, - /// Clone tool source (V + click). + /// Clone tool source (V + click). It belongs to the active texture set: switching the set + /// (`textureSet.select`, `layer.select` into another set) clears it. #[serde(default)] pub clone_source: Option, + /// Clone tool: keep the offset of the first stroke for the following strokes (aligned, the + /// default). Off, every stroke starts sampling at the source point. + #[serde(default = "default_clone_aligned")] + pub clone_aligned: bool, /// What the Clone tool copies: the composite or the selected layer alone. #[serde(default)] pub clone_from: CloneFrom, @@ -227,10 +258,14 @@ pub struct ToolState { pub path: crate::path_tool::PathState, } -fn default_smudge_strength() -> f32 { +pub(crate) fn default_smudge_strength() -> f32 { 0.5 } +fn default_clone_aligned() -> bool { + true +} + fn default_fill_visible_only() -> bool { true } @@ -250,7 +285,7 @@ pub enum CloneFrom { pub struct CloneSource { pub uv: [f32; 2], /// Source minus destination, fixed by the first stroke after the source was set and kept - /// for the following strokes (aligned cloning). + /// for the following strokes (aligned cloning; never set when the tool is not aligned). pub offset: Option<[f32; 2]>, } @@ -262,13 +297,16 @@ impl Default for ToolState { brush: BrushSettings::default(), values, enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(), + material: None, mask_value: 1.0, fill_mode: FillMode::Triangle, fill_hit_test: Default::default(), fill_visible_only: default_fill_visible_only(), stencil: None, + stencil_look: StencilLook::default(), smudge_strength: default_smudge_strength(), clone_source: None, + clone_aligned: true, clone_from: CloneFrom::Composite, path: Default::default(), }; @@ -315,6 +353,48 @@ pub(crate) struct ActiveStroke { /// A stroke visibility buffer and what it was rendered for: camera, size, mesh id. pub(crate) type DepthCache = (OrbitCamera, (u32, u32), u64, Arc); +/// History labels that name a layer, a path number or a smart mask: the UI translates the +/// template and fills the value in (the control channel and `edit.history` keep the English label). +/// `{layer}` is a layer name, `{n}` a path number, `{name}` a smart mask name. +pub const HISTORY_TEMPLATES: &[&str] = &[ + "Paint on {layer}", + "Erase on {layer}", + "Clone on {layer}", + "Smudge on {layer}", + "Projection on {layer}", + "Paint mask of {layer}", + "Erase mask of {layer}", + "Projection mask of {layer}", + EDIT_PATH_TEMPLATE, + APPLY_SMART_MASK_TEMPLATE, +]; + +pub(crate) const EDIT_PATH_TEMPLATE: &str = "Edit path {n}"; +pub(crate) const APPLY_SMART_MASK_TEMPLATE: &str = "Apply smart mask {name}"; +pub(crate) const QUICK_MASK_STROKE_LABEL: &str = "Quick mask stroke"; + +/// `template` with its one `{...}` placeholder replaced by `value` +pub fn history_label(template: &str, value: &str) -> String { + match (template.find('{'), template.find('}')) { + (Some(open), Some(close)) if open < close => format!("{}{}{}", &template[..open], value, &template[close + 1..]), + _ => template.to_string(), + } +} + +/// The history template of a stroke by `tool`, on a layer or (`on_mask`) on its mask +pub fn stroke_template(tool: Tool, on_mask: bool) -> &'static str { + match (tool, on_mask) { + (Tool::Eraser, false) => "Erase on {layer}", + (Tool::Eraser, true) => "Erase mask of {layer}", + (Tool::Clone, _) => "Clone on {layer}", + (Tool::Smudge, _) => "Smudge on {layer}", + (Tool::Projection, false) => "Projection on {layer}", + (Tool::Projection, true) => "Projection mask of {layer}", + (_, false) => "Paint on {layer}", + (_, true) => "Paint mask of {layer}", + } +} + pub struct Session { pub doc: Document, pub mesh: Arc, @@ -340,9 +420,14 @@ pub struct Session { pub active_set: usize, /// Selected layer per texture set. pub selected: BTreeMap, + /// Layers selected together with the selected one (Shift+click, Ctrl+click), per texture set. + /// Counts only while the selected layer is the one they were picked with (see [`Session::selected_layers`]). + pub(crate) multi: BTreeMap, pub target: StackTarget, pub camera: OrbitCamera, pub view: ViewMode, + /// The layer shown alone in the viewport (not saved, not in the history; see [`crate::solo`]). + pub solo: Option, /// The live bake preview while the app bakes (see [`crate::bake_preview`]). pub bake_preview: Option, /// Viewport size (pixels) used by scripted strokes. @@ -363,6 +448,10 @@ pub struct Session { /// Point changes of the path being edited: (earlier states for undo, undone states for redo) pub(crate) path_steps: (Vec, Vec), pub path: Option, + /// False in the empty state (the app at start, or after File > Close): the document is a + /// tiny placeholder that panels do not show. Project-independent commands remain available + /// (see [`crate::commands::check_enabled`]). + pub project_open: bool, pub modified: bool, /// Bumps on every document change. pub revision: u64, @@ -411,9 +500,11 @@ impl Session { tool: ToolState::default(), active_set: 0, selected, + multi: BTreeMap::new(), target: StackTarget::Content, camera, view: ViewMode::Material, + solo: None, bake_preview: None, viewport: Vec2::new(1280.0, 800.0), stroke: None, @@ -425,6 +516,7 @@ impl Session { path_draft: None, path_steps: Default::default(), path: None, + project_open: true, modified: false, revision: 1, log: Vec::new(), @@ -436,8 +528,18 @@ impl Session { }) } - /// Replace this session with `next` (another project), keeping the viewport size and the - /// user's brush presets, export presets and project templates. + /// The empty state: no project is open. Holds a tiny placeholder document that the UI never + /// shows; project-dependent commands are refused. + pub fn closed() -> Result { + // The hidden placeholder uses the minimum supported texture resolution + let mut session = Session::new_project("", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, texturecraft_core::MIN_RESOLUTION)?; + session.project_open = false; + + Ok(session) + } + + /// Replace this session with `next` (another project), keeping the viewport size, the + /// user's brush presets, export presets and project templates and the tool settings. pub fn switch_to(&mut self, mut next: Session) { // Invalidate caches even when both projects were loaded with the same revision next.revision = self.revision.wrapping_add(1); @@ -446,6 +548,7 @@ impl Session { next.export_presets = std::mem::take(&mut self.export_presets); next.brush_presets = std::mem::take(&mut self.brush_presets); next.templates = std::mem::take(&mut self.templates); + crate::tool_settings::ToolSettings::of(&self.tool).apply(&mut next.tool); *self = next; } @@ -521,21 +624,35 @@ impl Session { /// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes). pub fn edit_merging(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result) -> Result { + self.edit_if_changed(label, merge, |s| change(s).map(|value| (value, true))) + } + + /// A conditional edit shares the usual rollback and history snapshot with layer reorders. + pub(crate) fn edit_if_changed(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<(T, bool)>) -> Result { // A box fill under way becomes its own step first, so this edit isn't written over or folded into it self.end_polygon_fill_box(); let before = self.doc.clone(); - let result = change(self).and_then(|value| match self.doc.project.instance_cycle() { - Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))), - None => Ok(value), + let result = change(self).and_then(|(value, changed)| { + if changed && let Some(id) = self.doc.project.instance_cycle() { + return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))); + } + + Ok((value, changed)) }); match result { - Ok(value) => { - self.record(label, before, merge); + Ok((value, changed)) => { + if changed { + self.record(label, before, merge); + } + Ok(value) } Err(error) => { self.doc = before; + + // A failed repaint may have cached tiles from the discarded document + self.path_cache = None; Err(error) } } @@ -588,6 +705,11 @@ impl Session { self.follow_uv_layouts(&previous_document.project); self.sync_caches(); + // Removed path effects must release their cached painted tiles + if self.path_cache.as_ref().is_some_and(|cache| self.paths(cache.eid).is_none()) { + self.path_cache = None; + } + // Removed or replaced resources may change any set's rendered content let removed_or_replaced_resource = previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current))); @@ -595,7 +717,7 @@ impl Session { let uses_added_resource = |texture_set_index: usize| { use texturecraft_core::{EffectKind, Fill, Source}; - let uses_source = |source: &Source| matches!(source, Source::Image { name, .. } if added_resource_names.contains(name)); + let uses_source = |source: &Source| source.images().into_iter().any(|name| added_resource_names.iter().any(|added| added.as_str() == name)); let uses_fill = |fill: &Fill| fill.sources.values().any(uses_source) || fill.link.as_ref().is_some_and(|link| added_resource_names.contains(&link.package)); let project = &self.doc.project; @@ -801,6 +923,9 @@ impl Session { fn after_history(&mut self, other: &Document) { self.modified = true; + + // Layers picked together belong to the stack they were picked in + self.multi.clear(); self.revision = self.revision.wrapping_add(1); self.invalidate_changed(other); @@ -849,10 +974,16 @@ impl Session { values: stroke.values.clone(), mask_value: self.tool.mask_value, stencil: stroke.stencil.clone(), + carried_mask: stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()).cloned(), carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(), }) }); + // A soloed layer's view of the project; a removed layer ends the solo + if self.solo.is_some_and(|solo| self.doc.project.locate(solo.layer).is_none()) { + self.set_solo(None); + } + let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None }; let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; @@ -883,7 +1014,7 @@ impl Session { let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { - project: &self.doc.project, + project: solo_view.as_ref().unwrap_or(&self.doc.project), ts, mesh: &self.mesh, gbuf: &cache.gbuf, diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index a0bf6b6d..59a8f8d5 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -90,6 +90,9 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { // Paths paint into the active set if ts != s.ts() { s.finish_path()?; + + // The clone source is a point of the set it was picked in + s.tool.clone_source = None; } s.active_set = ts; diff --git a/crates/engine/src/smart_masks.rs b/crates/engine/src/smart_masks.rs index dd0111f3..0529b0b8 100644 --- a/crates/engine/src/smart_masks.rs +++ b/crates/engine/src/smart_masks.rs @@ -1,10 +1,15 @@ //! Smart masks: procedural mask presets (generators and patterns driven by the baked mesh maps) //! that replace a layer's mask in one step. Smart materials build their masks from the same -//! presets. +//! presets. A user smart mask is a layer's mask saved to a `.tcmask` file (the `.tcraft` +//! container holding one layer that carries the mask) and applied back like a preset. + +use std::collections::BTreeMap; +use std::sync::Arc; use serde_json::{Value, json}; use texturecraft_core::{ - BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source, + BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, + Projection, Source, }; use crate::commands::{CommandSpec, always, bad, has_layer, layer_param, strp}; @@ -13,13 +18,25 @@ use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { vec![ - cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?}", has_layer, apply_cmd), + cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?} or {path: .tcmask file, layer?}", has_layer, apply_cmd), + cmd!( + "mask.smart.create", + "Create smart mask", + [], + None, + "{layer?, path: .tcmask file, name?} — saves the layer's mask (all effects, parameters, painted pixels and images) as a user smart mask", + has_layer, + create_cmd + ), cmd!("mask.smart.list", "List smart masks", [], None, "{}", always, |_, _| Ok(json!( SMART_MASKS.iter().map(|m| json!({"id": m.id, "label": m.label})).collect::>() ))), ] } +/// Smart mask file extension. +pub const SMART_MASK_EXT: &str = "tcmask"; + pub struct SmartMask { pub id: &'static str, pub label: &'static str, @@ -72,10 +89,10 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) }) } -/// A triplanar grayscale pattern fill. +/// A triplanar grayscale pattern fill pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind { EffectKind::Fill { - source: Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low: [0.0; 3], high: [1.0; 3] }, + source: Source::Procedural { pattern: Procedural { scale, seed, contrast, ..Procedural::new(kind) }, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, } } @@ -162,7 +179,7 @@ pub(crate) fn mask(p: &mut Project, id: &str, invert: bool) -> Result { /// Replace layer `layer`'s mask with smart mask `name` (one undo step). pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> { let sm = find(name).ok_or_else(|| EngineError::Other(format!("unknown smart mask `{name}`")))?; - s.edit(&format!("Apply smart mask {}", sm.label), |s| { + s.edit(&crate::session::history_label(crate::session::APPLY_SMART_MASK_TEMPLATE, sm.label), |s| { let m = mask(&mut s.doc.project, sm.id, false)?; let old = s.doc.project.layer_mut(layer)?.mask.replace(m); for e in old.map(|m| m.effects).unwrap_or_default() { @@ -173,13 +190,162 @@ pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> { }) } +impl Session { + /// Serialize layer `layer`'s mask (an instance without its own mask has its source's) as a user smart mask file named `name`. + pub fn smart_mask_bytes(&self, layer: LayerId, name: &str) -> Result> { + let owner = self.doc.project.mask_owner(layer); + let mask = self.doc.project.layer(owner)?.mask.clone().ok_or_else(|| EngineError::Other("the layer has no mask".into()))?; + let (ts, _, _) = self.doc.project.locate(owner).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; + let set = self.doc.project.texture_set(ts)?; + let mut mini = crate::material_lib::one_set_document(set, name); + let id = mini.project.alloc_id(); + let mut holder = Layer::new(id, name, LayerKind::Paint, &set.channel_list()); + + // The mask comes back switched on whatever state it was saved in + holder.mask = Some(Mask { enabled: true, ..copy_mask(&self.doc, &mask, &mut mini, set.size())? }); + mini.project.insert_layer(0, holder, None, false)?; + self.file_bytes(mini, id) + } + + /// Replace layer `layer`'s mask with the one in a user smart mask file (one undo step). + pub fn apply_smart_mask_bytes(&mut self, layer: LayerId, bytes: &[u8]) -> Result<()> { + let pf = texturecraft_formats::load_project_bytes(bytes).map_err(|e| EngineError::Other(e.to_string()))?; + self.apply_smart_mask_file(layer, pf) + } + + fn apply_smart_mask_file(&mut self, layer: LayerId, pf: texturecraft_formats::ProjectFile) -> Result<()> { + let mask = pf + .project + .texture_sets + .first() + .and_then(|t| t.stack.last().copied()) + .and_then(|root| pf.project.layers.get(&root)) + .and_then(|l| l.mask.clone()) + .ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?; + let resources: BTreeMap>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect(); + let src = crate::session::Document { + bake_paint: BTreeMap::new(), + project: pf.project, + pixels: pf.pixels, + baked: BTreeMap::new(), + resources: BTreeMap::new(), + }; + let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default(); + self.edit(&format!("Apply smart mask {label}"), |s| { + let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; + let size = s.doc.project.texture_set(ts)?.size(); + + // An image whose name the project already uses for other bytes comes in under a new name + let mut renames = BTreeMap::new(); + for (name, bytes) in &resources { + let mut taken = name.clone(); + let mut number = 2; + while s.doc.resources.get(&taken).is_some_and(|have| have != bytes) { + let (stem, ext) = name.rsplit_once('.').map_or((name.as_str(), String::new()), |(stem, ext)| (stem, format!(".{ext}"))); + taken = format!("{stem}_{number}{ext}"); + number += 1; + } + s.doc.resources.entry(taken.clone()).or_insert_with(|| bytes.clone()); + if taken != *name { + renames.insert(name.clone(), taken); + } + } + let mut new = copy_mask(&src, &mask, &mut s.doc, size)?; + for source in new.effects.iter_mut().flat_map(|effect| sources_mut(&mut effect.kind)) { + if let Source::Image { name, .. } = source + && let Some(renamed) = renames.get(name.as_str()) + { + *name = renamed.clone(); + } + } + let old = s.doc.project.layer_mut(layer)?.mask.replace(new); + for e in old.map(|m| m.effects).unwrap_or_default() { + s.doc.pixels.masks.remove(&e.id); + } + s.target = StackTarget::Mask; + Ok(()) + })?; + self.sync_images(); + Ok(()) + } +} + +/// The sources an effect reads. +fn sources_mut(kind: &mut EffectKind) -> Vec<&mut Source> { + match kind { + EffectKind::Fill { source, .. } => vec![source], + EffectKind::Material(fill) => fill.sources.values_mut().collect(), + EffectKind::Generator(generator) => generator.inputs.values_mut().collect(), + _ => Vec::new(), + } +} + +/// `mask` of document `src` with fresh effect ids from `dst` (anchor sources follow), its painted pixels moved to `dst` at `size`. +fn copy_mask(src: &crate::session::Document, mask: &Mask, dst: &mut crate::session::Document, size: (u32, u32)) -> Result { + let mut copy = mask.clone(); + let mut moved = BTreeMap::new(); + for e in &mut copy.effects { + let old = e.id; + e.id = dst.project.alloc_id(); + if matches!(e.kind, EffectKind::Anchor) { + moved.insert(old, e.id); + } + if let Some(img) = src.pixels.masks.get(&old) { + dst.pixels.masks.insert(e.id, crate::layer_ops::fit(img, size, &[0, 0])); + } + } + + // Sources that read an anchor effect of this mask follow it to its new id + for source in copy.effects.iter_mut().flat_map(|effect| sources_mut(&mut effect.kind)) { + if let Source::Anchor { anchor, .. } = source { + *anchor = *moved.get(anchor).ok_or_else(|| EngineError::Other(format!("smart mask refers to anchor {} outside this mask", anchor.0)))?; + } + } + Ok(copy) +} + fn apply_cmd(s: &mut Session, p: &Value) -> Result { - let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` is required"))?; let layer = layer_param(s, "mask.smart.apply", p)?; - apply(s, layer, name)?; + if let Some(path) = strp(p, "path") { + apply_file(s, layer, path)?; + } else { + let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` or `path` is required"))?; + apply(s, layer, name)?; + } Ok(json!({ "layer": layer.0 })) } +#[cfg(not(target_arch = "wasm32"))] +fn apply_file(s: &mut Session, layer: LayerId, path: &str) -> Result<()> { + let file = texturecraft_formats::load_project(std::path::Path::new(path)).map_err(|e| bad("mask.smart.apply", format!("cannot read {path}: {e}")))?; + s.apply_smart_mask_file(layer, file) +} + +#[cfg(target_arch = "wasm32")] +fn apply_file(_: &mut Session, _: LayerId, _: &str) -> Result<()> { + Err(EngineError::Other("file paths are not available in the browser".into())) +} + +#[cfg(not(target_arch = "wasm32"))] +fn create_cmd(s: &mut Session, p: &Value) -> Result { + let layer = layer_param(s, "mask.smart.create", p)?; + let path = strp(p, "path").ok_or_else(|| bad("mask.smart.create", "`path` is required"))?; + let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.layer(layer).map(|l| l.name.clone()).unwrap_or_default()); + let bytes = s.smart_mask_bytes(layer, &name)?; + let path = if path.ends_with(&format!(".{SMART_MASK_EXT}")) { path.to_string() } else { format!("{path}.{SMART_MASK_EXT}") }; + if let Some(dir) = std::path::Path::new(&path).parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir).map_err(|e| bad("mask.smart.create", format!("cannot create {}: {e}", dir.display())))?; + } + + texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad("mask.smart.create", format!("cannot write {path}: {e}")))?; + Ok(json!({ "path": path })) +} + +#[cfg(target_arch = "wasm32")] +fn create_cmd(_: &mut Session, _: &Value) -> Result { + Err(EngineError::Other("file paths are not available in the browser".into())) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/solo.rs b/crates/engine/src/solo.rs new file mode 100644 index 00000000..454a8817 --- /dev/null +++ b/crates/engine/src/solo.rs @@ -0,0 +1,88 @@ +//! Solo: a view-only preview of one layer on its own. The compositor draws a copy of the project +//! in which the other layers of the soloed layer's texture set are hidden (see +//! [`texturecraft_compose::solo_project`]); the document, the undo history, saving, exporting and +//! baking never see it. + +use serde_json::{Value, json}; +use texturecraft_core::{LayerId, Project}; + +use crate::commands::{CommandSpec, always, bad, boolp, layer_param}; +use crate::{Result, Session, cmd}; + +/// The layer shown alone and whether its mask is ignored (full coverage). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Solo { + pub layer: LayerId, + pub ignore_mask: bool, +} + +pub(crate) fn specs() -> Vec { + vec![cmd!( + "view.solo", + "Solo layer", + [], + None, + "{layer?: id | null (default: the selected layer; null ends the solo), ignoreMask?: bool (show the layer at full coverage, default false)} → {layer: id | null, ignoreMask}. View only: nothing is saved, exported, baked or put in the undo history", + always, + solo + )] +} + +fn solo(s: &mut Session, p: &Value) -> Result { + let next = match p.get("layer") { + Some(Value::Null) => None, + _ => { + let layer = layer_param(s, "view.solo", p)?; + if s.doc.project.locate(layer).is_none() { + return Err(bad("view.solo", "the layer is not in a stack")); + } + + Some(Solo { layer, ignore_mask: boolp(p, "ignoreMask").unwrap_or(false) }) + } + }; + s.set_solo(next); + Ok(json!({ "layer": s.solo.map(|solo| solo.layer.0), "ignoreMask": s.solo.is_some_and(|solo| solo.ignore_mask) })) +} + +impl Session { + /// Show `solo` alone (None: the whole stack again). Changes only the view: every covered + /// tile of every set is composited again, and the next frame draws it. + pub fn set_solo(&mut self, solo: Option) { + if self.solo == solo { + return; + } + + self.solo = solo; + for cache in &mut self.caches { + // What the cache holds was composited from the other stack + cache.below = Default::default(); + cache.invalidate_all(); + } + self.revision = self.revision.wrapping_add(1); + } + + /// The project as the compositor draws it: the soloed layer's, or None for the document's own. + pub(crate) fn solo_view(&self) -> Option { + let solo = self.solo?; + texturecraft_compose::solo_project(&self.doc.project, solo.layer, solo.ignore_mask) + } + + /// Sample document pixels while solo keeps its own composite in the viewport cache. + pub(crate) fn document_composite(&self, ts: usize, tiles: &[(u32, u32)]) -> Option> { + use std::borrow::Cow; + use texturecraft_compose::{Composite, composite_tiles, pad_tiles}; + + let cache = self.caches.get(ts)?; + if self.solo.is_none() { + return Some(Cow::Borrowed(&cache.composite)); + } + + self.with_inputs(ts, |inputs| { + let set = inputs.project.texture_sets.get(ts)?; + let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) }; + composite_tiles(inputs, &mut output, tiles); + pad_tiles(&mut output, &cache.dilation, tiles); + Some(Cow::Owned(output)) + }) + } +} diff --git a/crates/engine/src/stencil_look.rs b/crates/engine/src/stencil_look.rs new file mode 100644 index 00000000..46ddf6a0 --- /dev/null +++ b/crates/engine/src/stencil_look.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; + +/// How a stencil sits on screen, without the image (which is a project resource) +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct StencilLook { + pub center: [f32; 2], + pub scale: f32, + pub rotation: f32, + pub tile: bool, + pub opacity: f32, +} + +impl Default for StencilLook { + fn default() -> Self { + StencilLook { center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 } + } +} + +impl StencilLook { + pub(crate) const MAX_CENTER_OFFSET: f32 = 4.0; + pub(crate) const MIN_SCALE: f32 = 0.01; + pub(crate) const MAX_SCALE: f32 = 10.0; + + pub(crate) fn sanitized(mut self) -> Self { + let defaults = Self::default(); + let finite = |value: f32, fallback| if value.is_finite() { value } else { fallback }; + self.center = self.center.map(|v| finite(v, 0.0).clamp(-Self::MAX_CENTER_OFFSET, Self::MAX_CENTER_OFFSET)); + self.scale = finite(self.scale, defaults.scale).clamp(Self::MIN_SCALE, Self::MAX_SCALE); + self.rotation = finite(self.rotation, defaults.rotation).rem_euclid(360.0); + self.opacity = finite(self.opacity, defaults.opacity).clamp(0.0, 1.0); + self + } +} diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index 5964813f..5718f207 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -15,7 +15,7 @@ pub fn specs() -> Vec { "Add text", [], None, - "{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)", + "{text (lines split at \\n), font?: family (text.fonts; default a common sans-serif), style?: e.g. Bold (default Regular), size?: 8..1024 texels per em (default 256), color?: [r,g,b] linear or \"#rrggbb\" sRGB (default white), name?} — draws the text as an image resource with an alpha (white for tool.brush {alpha: {image}}, colored for layer.add.decal)", always, add_text ), diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index 6cd6e2a2..811a742f 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -293,7 +293,14 @@ impl ThumbService { self.tick = self.tick.wrapping_add(1); let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); let checked = self.checked(session); - if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) { + + // A target the document no longer has would render for nothing, again each frame + if !fresh + && checked + && !self.in_flight.contains(&(self.generation, target)) + && !self.queue.contains(&target) + && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(target)) + { self.queue.push_back(target); } @@ -475,6 +482,19 @@ mod tests { eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed()); } + #[test] + fn a_target_the_document_lacks_is_not_rendered() { + let session = test_session().unwrap(); + let removed_anchor = ThumbTarget::Stage { effect: texturecraft_core::LayerId(u64::MAX), channel: Channel::Height }; + let (mut service, jobs, _results) = held_worker(); + service.begin_frame(&session, 0.0); + + assert!(service.get(&session, removed_anchor).image.is_none()); + + assert!(!service.poll(&session), "nothing is rendered, so no frame is asked for"); + assert!(jobs.try_recv().is_err()); + } + #[test] fn collecting_the_last_result_requests_a_frame_to_display_it() { let session = test_session().unwrap(); diff --git a/crates/engine/src/tool_availability.rs b/crates/engine/src/tool_availability.rs index 392388e3..9dd93859 100644 --- a/crates/engine/src/tool_availability.rs +++ b/crates/engine/src/tool_availability.rs @@ -7,6 +7,10 @@ use crate::{Session, StackTarget, Tool}; impl Session { /// Whether `tool` can act on the selection (or on the quick mask while it is being edited) pub fn tool_usable(&self, tool: Tool) -> bool { + if !self.project_open { + return false; + } + match tool { // The picker reads the composite under the cursor, whatever is selected Tool::ColorPicker => return true, @@ -22,11 +26,9 @@ impl Session { let project = &self.doc.project; let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false }; - // Smudge and Clone read layer content, so they can't yet paint mask values - let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); match self.target { StackTarget::Content => matches!(layer.kind, LayerKind::Paint), - StackTarget::Mask => !reads_content, + StackTarget::Mask => true, StackTarget::Effect(effect) => { let Some((owner, found)) = project.effect(effect) else { return false }; let Some(owner_layer) = project.layers.get(&owner) else { return false }; @@ -37,7 +39,7 @@ impl Session { // Paths saved in a fill layer before paths there were removed stay editable EffectKind::Path(_) => tool == Tool::Path, EffectKind::Paint if tool == Tool::Path => !in_fill_content, - EffectKind::Paint => in_content || !reads_content, + EffectKind::Paint => true, _ => false, } } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index cecc8495..9ca84090 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Brush settings", [], None, - "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Tool material", [], None, - "{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1}", + "{channel, color?: ([r,g,b] linear or \"#rrggbb\" sRGB)|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)", always, material ), @@ -199,6 +199,19 @@ fn brush(session: &mut Session, params: &Value) -> Result { (settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone())); } + let alpha_params = &mut settings.alpha_params; + for (key, slot) in [("alphaSizeX", &mut alpha_params.size_x), ("alphaSizeY", &mut alpha_params.size_y), ("alphaRoundness", &mut alpha_params.roundness)] { + if let Some(value) = percent(key) { + *slot = value; + } + } + if let Some(value) = f32p(params, "alphaContrast") { + alpha_params.contrast = value; + } + if let Some(value) = boolp(params, "alphaInvert") { + alpha_params.invert = value; + } + if let Some(value) = boolp(params, "backfaceCulling") { settings.backface_culling = value; } @@ -258,6 +271,16 @@ fn brush(session: &mut Session, params: &Value) -> Result { session.tool.brush = settings.sanitized(); session.tool.clone_from = clone_from; + if let Some(aligned) = boolp(params, "cloneAligned") + && aligned != session.tool.clone_aligned + { + session.tool.clone_aligned = aligned; + + // A new mode starts without the offset of an earlier stroke + if let Some(source) = session.tool.clone_source.as_mut() { + source.offset = None; + } + } if let Some(value) = f32p(params, "smudgeStrength") { session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0); } @@ -277,11 +300,14 @@ pub(crate) fn brush_json(session: &Session) -> Value { (None, Some(id)) => json!({ "library": id }), (None, None) => json!(settings.alpha.label()), }, + "alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0, + "alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, "backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], "radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) }, "symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span, - "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles, + "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles, "cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, + "cloneAligned": session.tool.clone_aligned, }) } @@ -289,6 +315,23 @@ fn material(s: &mut Session, p: &Value) -> Result { let channel = channel_param("tool.material", p, "channel")?; let color = color_param("tool.material", p, "color")?; let value = color_param("tool.material", p, "value")?; + if let Some(id) = strp(p, "material") { + let values = crate::materials::brush_values(id).ok_or_else(|| { + bad("tool.material", format!("`{id}` is not a simple material (a brush paints plain values; add smart materials with material.apply)")) + })?; + + // Reset omitted channels so values from the previous brush material do not persist + // Normal maps remain flat + for channel in Channel::ALL { + if channel.kind() == texturecraft_core::ChannelKind::NormalMap { + continue; + } + + let value = values.iter().find(|(set, _)| *set == channel).map_or(channel.default_value(), |(_, value)| *value); + s.tool.values.insert(channel, value); + } + s.tool.material = Some(crate::materials::find(id).map_or_else(|| id.to_string(), |m| m.id.to_string())); + } if let Some(v) = f32p(p, "maskValue") { s.tool.mask_value = v.clamp(0.0, 1.0); } @@ -297,6 +340,7 @@ fn material(s: &mut Session, p: &Value) -> Result { let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) }; s.tool.values.insert(c, v); s.tool.enabled.insert(c); + s.tool.material = None; } match boolp(p, "enabled") { Some(true) => { @@ -313,6 +357,7 @@ fn material(s: &mut Session, p: &Value) -> Result { } s.revision = s.revision.wrapping_add(1); Ok(json!({ + "material": s.tool.material, "values": s.tool.values.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::>(), "enabled": s.tool.enabled.iter().map(|c| c.id()).collect::>(), "maskValue": s.tool.mask_value, @@ -345,7 +390,9 @@ fn swap_mask_value(session: &mut Session, _: &Value) -> Result { fn stencil(session: &mut Session, params: &Value) -> Result { if boolp(params, "clear") == Some(true) { - session.tool.stencil = None; + if let Some(cleared) = session.tool.stencil.take() { + session.tool.stencil_look = cleared.look(); + } return Ok(Value::Null); } @@ -355,19 +402,20 @@ fn stencil(session: &mut Session, params: &Value) -> Result { } let previous_stencil = session.tool.stencil.take(); - let mut stencil_state = crate::session::StencilState::new(name); + let mut stencil_state = crate::session::StencilState::with_look(name, session.tool.stencil_look); if let Some(previous_stencil) = previous_stencil { stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil }; } session.tool.stencil = Some(stencil_state); } + use crate::session::StencilLook; let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?; if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) { - stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0)); + stencil_state.center = center.map(|value| value.clamp(-StencilLook::MAX_CENTER_OFFSET, StencilLook::MAX_CENTER_OFFSET)); } if let Some(scale) = f32p(params, "scale") { - stencil_state.scale = scale.clamp(0.01, 10.0); + stencil_state.scale = scale.clamp(StencilLook::MIN_SCALE, StencilLook::MAX_SCALE); } if let Some(rotation) = f32p(params, "rotation") { stencil_state.rotation = rotation.rem_euclid(360.0); diff --git a/crates/engine/src/tool_settings.rs b/crates/engine/src/tool_settings.rs new file mode 100644 index 00000000..d8d3087f --- /dev/null +++ b/crates/engine/src/tool_settings.rs @@ -0,0 +1,65 @@ +//! The tool settings that outlive a project: they are kept when another project opens and are +//! saved with the UI state, so the next session starts with the same brush. + +use serde::{Deserialize, Serialize}; + +use crate::session::{CloneFrom, StencilLook, ToolState}; +use texturecraft_paint::BrushSettings; + +/// Brush, symmetry, stencil placement, smudge strength, clone mode and alignment and path switches. Left out +/// because they belong to one project: the clone source point, the stencil image, the points of +/// the path being drawn and the brush's image alpha (an image resource of that project). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ToolSettings { + pub brush: BrushSettings, + pub stencil: StencilLook, + pub smudge_strength: f32, + pub clone_from: CloneFrom, + /// Settings saved before the Aligned switch existed keep its default (on) + #[serde(default = "aligned_by_default")] + pub clone_aligned: bool, + pub path_closed: bool, + pub path_fill: bool, +} + +fn aligned_by_default() -> bool { + true +} + +impl Default for ToolSettings { + fn default() -> Self { + ToolSettings::of(&ToolState::default()) + } +} + +impl ToolSettings { + /// The settings `tool` has now. + pub fn of(tool: &ToolState) -> ToolSettings { + let mut brush = tool.brush.clone(); + brush.alpha_image = None; + ToolSettings { + brush, + stencil: tool.stencil.as_ref().map_or(tool.stencil_look, |stencil| stencil.look()), + smudge_strength: tool.smudge_strength, + clone_from: tool.clone_from, + clone_aligned: tool.clone_aligned, + path_closed: tool.path.closed, + path_fill: tool.path.fill, + } + } + + /// Make `tool` use these settings, leaving what belongs to its project alone. + pub fn apply(&self, tool: &mut ToolState) { + let alpha_image = tool.brush.alpha_image.take(); + tool.brush = self.brush.clone().sanitized(); + + // An image alpha names a resource of the project that was open; the library alpha is global + tool.brush.alpha_image = alpha_image; + tool.stencil_look = self.stencil.sanitized(); + tool.smudge_strength = if self.smudge_strength.is_finite() { self.smudge_strength.clamp(0.0, 1.0) } else { crate::session::default_smudge_strength() }; + tool.clone_from = self.clone_from; + tool.clone_aligned = self.clone_aligned; + tool.path.closed = self.path_closed; + tool.path.fill = self.path_fill; + } +} diff --git a/crates/engine/src/uv_symmetry.rs b/crates/engine/src/uv_symmetry.rs new file mode 100644 index 00000000..d777599a --- /dev/null +++ b/crates/engine/src/uv_symmetry.rs @@ -0,0 +1,6 @@ +//! Symmetry for strokes painted in the 2D view: a dab's copies land where the 3D view's copies would + +mod frame; +mod uv_mirror; + +pub(crate) use uv_mirror::UvMirror; diff --git a/crates/engine/src/uv_symmetry/frame.rs b/crates/engine/src/uv_symmetry/frame.rs new file mode 100644 index 00000000..0a35afb2 --- /dev/null +++ b/crates/engine/src/uv_symmetry/frame.rs @@ -0,0 +1,10 @@ +use texturecraft_geom::glam::Vec3; + +/// A point on a triangle with the 3D directions of one UV unit along U and along V +pub(super) struct Frame { + pub(super) pos: Vec3, + pub(super) along_u: Vec3, + pub(super) along_v: Vec3, + /// Surface length of one UV unit, for the distance a copy may be from the mirrored point + pub(super) scale: f32, +} diff --git a/crates/engine/src/uv_symmetry/uv_mirror.rs b/crates/engine/src/uv_symmetry/uv_mirror.rs new file mode 100644 index 00000000..383e5ceb --- /dev/null +++ b/crates/engine/src/uv_symmetry/uv_mirror.rs @@ -0,0 +1,141 @@ +use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; +use texturecraft_geom::{Bvh, Mesh, NO_TRI, UvGBuffer, surface_at}; +use texturecraft_paint::{StampSource, Symmetry, UvStamp}; + +use super::frame::Frame; + +/// The mirror and radial maps of one stroke, applied to dabs through the mesh surface +pub(crate) struct UvMirror<'a> { + mesh: &'a Mesh, + bvh: &'a Bvh, + gbuf: &'a UvGBuffer, + /// The texture set's material: copies land on its triangles only, the ones the texture covers + material: usize, + origin: Vec3, + /// Linear maps of the copies as `origin + map * (p - origin)`, without the identity + maps: Vec, +} + +impl<'a> UvMirror<'a> { + /// The copies' maps for `symmetry` about a mesh centered at `center`, `None` when it paints no copies + pub(crate) fn new(symmetry: &Symmetry, center: Vec3, mesh: &'a Mesh, bvh: &'a Bvh, gbuf: &'a UvGBuffer, material: usize) -> Option { + if !symmetry.any() { + return None; + } + + // The identity comes first: it is the dab itself + let maps: Vec = symmetry.transforms().into_iter().skip(1).collect(); + (!maps.is_empty()).then(|| UvMirror { mesh, bvh, gbuf, material, origin: symmetry.origin(center), maps }) + } + + /// Add the copies of `stamp` to `out` + pub(crate) fn add_copies(&self, stamp: &UvStamp, out: &mut Vec) { + let Some(frame) = self.frame_at(stamp.center) else { return }; + + // The stamp's x axis (turned by its angle, y up on screen) on the surface; v grows down, so an angle turns towards -V + let (sin, cos) = stamp.angle.to_radians().sin_cos(); + let x_axis = frame.along_u * cos - frame.along_v * sin; + let reach = stamp.radius * frame.scale; + for map in &self.maps { + let target = self.origin + *map * (frame.pos - self.origin); + let Some(hit) = self.bvh.nearest(target, reach, &|triangle| self.mesh.material_of(triangle as usize) == Some(self.material)) else { continue }; + let Some(surface) = surface_at(self.mesh, hit.tri, hit.u, hit.v) else { continue }; + let Some(landing) = self.frame_of(hit.tri, hit.u, hit.v) else { continue }; + + // Keep the dab's orientation as the 3D view does: its direction is mapped, its shape is not mirrored + let angle = turn_towards(&landing, *map * x_axis).map_or(stamp.angle, f32::to_degrees); + let source = Some(StampSource { origin: self.origin, to_source: map.transpose() }); + out.push(UvStamp { center: surface.uv, angle, source, ..*stamp }); + } + } + + /// The surface under texture coordinate `uv`, `None` off the texture or where no triangle covers it + fn frame_at(&self, uv: Vec2) -> Option { + let (width, height) = (self.gbuf.width as f32, self.gbuf.height as f32); + if !(0.0..1.0).contains(&uv.x) || !(0.0..1.0).contains(&uv.y) { + return None; + } + + let texel = (uv.y * height) as usize * self.gbuf.width as usize + (uv.x * width) as usize; + let triangle = *self.gbuf.tri.get(texel).filter(|triangle| **triangle != NO_TRI)?; + let [a, b, c] = self.mesh.tri(triangle as usize)?; + let (ua, ub, uc) = (*self.mesh.uvs.get(a)?, *self.mesh.uvs.get(b)?, *self.mesh.uvs.get(c)?); + + // Exact barycentrics of the dab's center, not the texel center's the G-buffer holds + let (to_b, to_c, to_point) = (ub - ua, uc - ua, uv - ua); + let double_area = to_b.x * to_c.y - to_c.x * to_b.y; + if double_area.abs() < f32::EPSILON { + return None; + } + + let b1 = (to_point.x * to_c.y - to_c.x * to_point.y) / double_area; + let b2 = (to_b.x * to_point.y - to_point.x * to_b.y) / double_area; + self.frame_of(triangle, b1, b2) + } + + /// The point of `triangle` with barycentrics `b1` and `b2` of its second and third corners, with its UV directions + fn frame_of(&self, triangle: u32, b1: f32, b2: f32) -> Option { + let [a, b, c] = self.mesh.tri(triangle as usize)?; + let (pa, pb, pc) = (*self.mesh.positions.get(a)?, *self.mesh.positions.get(b)?, *self.mesh.positions.get(c)?); + let (ua, ub, uc) = (*self.mesh.uvs.get(a)?, *self.mesh.uvs.get(b)?, *self.mesh.uvs.get(c)?); + let (edge_b, edge_c, to_b, to_c) = (pb - pa, pc - pa, ub - ua, uc - ua); + let double_area = to_b.x * to_c.y - to_c.x * to_b.y; + if double_area.abs() < f32::EPSILON { + return None; + } + + let along_u = (edge_b * to_c.y - edge_c * to_b.y) / double_area; + let along_v = (edge_c * to_b.x - edge_b * to_c.x) / double_area; + let scale = (edge_b.cross(edge_c).length() / double_area.abs()).sqrt(); + let pos = pa + edge_b * b1 + edge_c * b2; + (pos.is_finite() && along_u.is_finite() && along_v.is_finite() && scale.is_finite()).then_some(Frame { pos, along_u, along_v, scale }) + } +} + +/// The angle (radians) a stamp's x axis needs in the UV frame of `landing` to point along `direction` on the surface +fn turn_towards(landing: &Frame, direction: Vec3) -> Option { + // Least squares for direction = along_u * cos - along_v * sin, with (cos, -sin) the unknowns + let (uu, uv, vv) = (landing.along_u.dot(landing.along_u), landing.along_u.dot(landing.along_v), landing.along_v.dot(landing.along_v)); + let (u_dot, v_dot) = (landing.along_u.dot(direction), landing.along_v.dot(direction)); + let det = uu * vv - uv * uv; + if det.abs() < f32::EPSILON { + return None; + } + + let (cos, minus_sin) = ((u_dot * vv - v_dot * uv) / det, (v_dot * uu - u_dot * uv) / det); + let sin = -minus_sin; + (cos != 0.0 || sin != 0.0).then(|| sin.atan2(cos)).filter(|angle| angle.is_finite()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used)] +mod tests { + use super::*; + + #[test] + fn a_quarter_turn_copy_turns_the_dab_angle_the_same_way() { + // A square in the XY plane: U along +X, V down along -Y + let positions = vec![Vec3::new(-1.0, -1.0, 0.0), Vec3::new(1.0, -1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(-1.0, 1.0, 0.0)]; + let uvs = vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)]; + let mesh = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2, 0, 2, 3], "square").unwrap(); + let (bvh, gbuf) = (Bvh::new(&mesh), UvGBuffer::new(&mesh, 0, 64, 64)); + let symmetry = Symmetry { radial: 4, axis: 2, ..Symmetry::default() }; + let mirror = UvMirror::new(&symmetry, Vec3::ZERO, &mesh, &bvh, &gbuf, 0).unwrap(); + + // The dab at world (0.5, 0) points 30 degrees up from +X + let stamp = UvStamp { center: Vec2::new(0.75, 0.5), radius: 0.05, angle: 30.0, flow: 1.0, hardness: 1.0, seed: 0, source: None }; + let mut copies = Vec::new(); + mirror.add_copies(&stamp, &mut copies); + + assert_eq!(copies.len(), 3); + + // A quarter turn about +Z puts the copy at world (0, 0.5), pointing 120 degrees from +X + let quarter = copies.iter().find(|copy| (copy.center - Vec2::new(0.5, 0.25)).length() < 0.01).unwrap(); + assert!((quarter.angle - 120.0).abs() < 0.1, "angle {}", quarter.angle); + + // Each copy is told apart from the stroke and the other copies (a smudge gives each its own trail) + let sources: Vec<_> = copies.iter().map(|copy| copy.source).collect(); + assert!(sources.iter().all(Option::is_some), "copies carry their source"); + assert!(sources.iter().enumerate().all(|(i, a)| sources.iter().skip(i + 1).all(|b| a != b)), "every copy has its own source"); + } +} diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index db03435c..36e9a642 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -6,12 +6,30 @@ use texturecraft_core::{BakedMap, Channel, ToneMapping}; use texturecraft_geom::glam::Vec3; use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p}; +use crate::frame_target::FrameTarget; use crate::session::ViewMode; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { vec![ - cmd!("viewport.frame", "Show entire mesh", ["Viewport"], Some("F"), "{}", always, frame), + cmd!( + "viewport.frame", + "Show entire mesh", + ["Viewport"], + Some("F"), + "{target?: \"all\" (default: the whole mesh, helper geometry included) | \"selection\" (the active texture set's geometry)} → the camera; the orbit turns around the framed center", + always, + frame + ), + cmd!( + "viewport.frameSelection", + "Frame texture set", + ["Viewport"], + Some("Shift+F"), + "{} → the camera, framing the active texture set's geometry", + always, + |s, _| frame_target(s, FrameTarget::Selection) + ), cmd!("viewport.displayMaterial", "Display material", ["Viewport"], Some("M"), "{}", always, |s, _| set_view(s, ViewMode::Material)), cmd!("viewport.nextChannel", "Display next channel", ["Viewport"], Some("C"), "{}", always, |s, _| cycle_channel(s, 1)), cmd!("viewport.previousChannel", "Display previous channel", ["Viewport"], Some("Shift+C"), "{}", always, |s, _| cycle_channel(s, -1)), @@ -26,7 +44,7 @@ pub fn specs() -> Vec { "Display settings", [], None, - "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] (linear) | \"#rrggbb\", scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}", + "{environment?: |resource:, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?, displacement? (the viewport moves the surface by the height channel), scatterColor?: [r,g,b] linear or \"#rrggbb\" sRGB, scatterRadius? (0..1 of the mesh radius), ior? (1..3, transmission), dof?: {enabled?, focusDistance? (view depth, world units; 0 = the orbit target), aperture? (lens radius, 0..1 of the mesh radius)}}", always, display ), @@ -80,8 +98,24 @@ fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result) Ok((last, n)) } -fn frame(s: &mut Session, _: &Value) -> Result { - let (lo, hi) = s.mesh.bounds(); +fn frame(s: &mut Session, p: &Value) -> Result { + let target = match strp(p, "target") { + None | Some("all") => FrameTarget::All, + Some("selection") => FrameTarget::Selection, + Some(other) => return Err(bad("viewport.frame", format!("unknown target `{other}` (all or selection)"))), + }; + + frame_target(s, target) +} + +/// Frame the whole mesh, or only the triangles of the active texture set's material (the thing +/// being painted, without a floor plane or other helper geometry), and orbit around that center. +fn frame_target(s: &mut Session, target: FrameTarget) -> Result { + let selection = match target { + FrameTarget::Selection => s.doc.project.texture_sets.get(s.ts()).and_then(|set| s.mesh.bounds_of_material(set.material)), + FrameTarget::All => None, + }; + let (lo, hi) = selection.unwrap_or_else(|| s.mesh.bounds()); s.camera.frame(lo, hi); s.revision = s.revision.wrapping_add(1); Ok(camera_json(s)) diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index acf54274..4c5314ad 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -637,6 +637,21 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() { assert_eq!(session.history_labels(), history); } +#[test] +fn obj_submesh_id_separates_objects_with_the_same_name_and_material() { + use texturecraft_engine::{core::IdColorSource, formats::import_mesh_bytes}; + let file = b"o Part\nusemtl Shared\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 0.45 0\nvt 0 1\nf 1/1 2/2 3/3\no Part\nusemtl Shared\nv 2 0 0\nv 3 0 0\nv 2 1 0\nvt 0.5 0\nvt 0.95 0\nvt 0.5 1\nf 4/4 5/5 6/6"; + let mesh = import_mesh_bytes("parts.obj", file).unwrap().mesh; + assert_eq!(mesh.materials.len(), 1); + assert_eq!(mesh.submeshes.len(), 2); + let mut session = Session::new_project("parts", mesh, "parts.obj", None, 128).unwrap(); + session.doc.project.texture_sets[0].bake.maps.id.parameters.source = IdColorSource::Submesh; + execute(&mut session, "bake.run", &json!({"resolution":128,"maps":["id"],"dilation":0})).unwrap(); + let map = &session.doc.baked[&0].maps[&BakedMap::Id]; + let pixel = |x: usize| &map[(100 * 128 + x) * 3..(100 * 128 + x) * 3 + 3]; + assert_ne!(pixel(10), pixel(74)); +} + /// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay, /// the project counts as changed, and image resources are decoded in the new session. #[test] diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index 620de675..6ea63f2f 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -113,6 +113,7 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })], + inverted: Vec::new(), }], }); let files = session.export_files(&[0], &options).unwrap(); diff --git a/crates/engine/tests/it/brush_material.rs b/crates/engine/tests/it/brush_material.rs new file mode 100644 index 00000000..98cb9327 --- /dev/null +++ b/crates/engine/tests/it/brush_material.rs @@ -0,0 +1,195 @@ +//! A simple shelf material can be the brush's material (`tool.material {material}`): no layer, and the +//! next stroke paints it. Shelf drops place new layers with `below` and `top`. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::materials::{MATERIALS, brush_values}; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +fn stack(s: &Session) -> Vec { + s.doc.project.texture_set(0).unwrap().stack.clone() +} + +#[test] +fn every_simple_material_has_brush_values_and_no_smart_material_has() { + for material in MATERIALS { + let values = brush_values(material.id); + assert_eq!(values.is_some(), !material.smart, "{}", material.id); + if let Some(values) = values { + let channels: Vec = values.iter().map(|(channel, _)| *channel).collect(); + for channel in [Channel::BaseColor, Channel::Metallic, Channel::Roughness] { + assert!(channels.contains(&channel), "{} has no {channel:?}", material.id); + } + } + } + assert!(brush_values("nope").is_none()); +} + +#[test] +fn a_material_set_on_the_brush_adds_no_layer_and_no_history() { + let mut s = session(); + let (layers, history) = (stack(&s), s.history_labels()); + + execute(&mut s, "tool.material", &json!({"material": "copper_hammered"})).unwrap(); + + assert_eq!(stack(&s), layers); + assert_eq!(s.history_labels(), history); + for (channel, value) in brush_values("copper_hammered").unwrap() { + assert_eq!(s.tool.values[&channel], value, "{channel:?}"); + } + assert!(s.tool.values[&Channel::Height][0] < 0.0, "the material's height comes along"); + assert!(s.tool.enabled.contains(&Channel::Roughness), "the channel toggles stay as they were"); +} + +#[test] +fn a_material_without_height_resets_the_height_of_the_previous_one() { + let mut s = session(); + execute(&mut s, "tool.material", &json!({"material": "copper_hammered"})).unwrap(); + assert!(s.tool.values[&Channel::Height][0] < 0.0); + + execute(&mut s, "tool.material", &json!({"material": "copper"})).unwrap(); + + assert_eq!(s.tool.values[&Channel::Height], Channel::Height.default_value()); +} + +#[test] +fn a_smart_material_or_an_unknown_one_cannot_be_the_brush_material() { + let mut s = session(); + let before = s.tool.values.clone(); + + for id in ["iron_rusted", "nope"] { + assert!(execute(&mut s, "tool.material", &json!({"material": id})).is_err(), "{id}"); + } + assert_eq!(s.tool.values, before); +} + +/// Texel of the sphere point under screen position `(x, y)` +fn texel(s: &Session, x: f32, y: f32) -> (u32, u32) { + let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap(); + ((hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32) +} + +/// A session with `material` as the brush material, brush `size` (0..100), the stroke along y = 200 over `xs` +fn painted(material: &str, size: u32, xs: [f32; 2]) -> Session { + let mut s = session(); + paint(&mut s, material, size, xs); + s +} + +fn paint(s: &mut Session, material: &str, size: u32, xs: [f32; 2]) { + execute(s, "tool.material", &json!({"material": material})).unwrap(); + execute(s, "tool.brush", &json!({"size": size, "hardness": 100})).unwrap(); + execute(s, "tool.stroke", &json!({"points": [[xs[0], 200], [xs[1], 200]]})).unwrap(); + s.update(); +} + +/// What a fill layer of `material` (projection scale `scale`) shows over the sphere +fn fill_of(material: &str, scale: f32) -> Session { + let mut s = session(); + let layer = LayerId(execute(&mut s, "material.apply", &json!({"material": material})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "projection": "triplanar", "scale": scale})).unwrap(); + s.update(); + s +} + +fn at(s: &Session, channel: Channel, (x, y): (u32, u32)) -> f32 { + s.caches[0].composite.value(channel, x, y)[0] +} + +#[test] +fn a_stroke_after_picking_a_material_paints_its_pattern_like_a_fill_of_it() { + // Brush size 40 is the pattern's natural size: the same as a fill layer with the material + let (stroke, fill) = (painted("cobblestone", 40, [150.0, 250.0]), fill_of("cobblestone", 1.0)); + let samples: Vec = (0..24).map(|i| 170.0 + 3.0 * i as f32).collect(); + + let mut colours = Vec::new(); + for x in samples { + let texel = texel(&stroke, x, 200.0); + for channel in [Channel::BaseColor, Channel::Roughness, Channel::Height] { + let (painted, expected) = (at(&stroke, channel, texel), at(&fill, channel, texel)); + assert!((painted - expected).abs() < 0.02, "{channel:?} at x = {x}: {painted} vs {expected}"); + } + colours.push(at(&stroke, Channel::BaseColor, texel)); + } + let (low, high) = colours.iter().fold((f32::MAX, f32::MIN), |(low, high), v| (low.min(*v), high.max(*v))); + assert!(high - low > 0.05, "the colour varies along the stroke: {colours:?}"); +} + +#[test] +fn overlapping_strokes_agree_where_they_overlap() { + let mut s = painted("cobblestone", 40, [150.0, 215.0]); + let samples: Vec<(u32, u32)> = (0..8).map(|i| texel(&s, 190.0 + 3.0 * i as f32, 200.0)).collect(); + let first: Vec = samples.iter().map(|t| at(&s, Channel::BaseColor, *t)).collect(); + + paint(&mut s, "cobblestone", 40, [185.0, 250.0]); + + for (i, t) in samples.iter().enumerate() { + assert!((at(&s, Channel::BaseColor, *t) - first[i]).abs() < 0.005, "sample {i}"); + } +} + +#[test] +fn the_pattern_follows_the_brush_size() { + // A quarter of the natural brush size is a pattern four times as fine + let (stroke, fill) = (painted("cobblestone", 10, [194.0, 206.0]), fill_of("cobblestone", 4.0)); + let natural = fill_of("cobblestone", 1.0); + let (mut fine, mut coarse) = (0.0_f32, 0.0_f32); + for x in [197.0, 199.0, 201.0, 203.0] { + let texel = texel(&stroke, x, 200.0); + let painted = at(&stroke, Channel::BaseColor, texel); + fine = fine.max((painted - at(&fill, Channel::BaseColor, texel)).abs()); + coarse = coarse.max((painted - at(&natural, Channel::BaseColor, texel)).abs()); + } + assert!(fine < 0.02, "matches the pattern at 4x: {fine}"); + assert!(coarse > 0.02, "differs from the natural size: {coarse}"); +} + +#[test] +fn editing_a_brush_value_ends_the_pattern() { + let mut s = session(); + execute(&mut s, "tool.material", &json!({"material": "cobblestone"})).unwrap(); + assert_eq!(s.tool.material.as_deref(), Some("cobblestone")); + + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + + assert_eq!(s.tool.material, None); +} + +/// Add copper with `place` params (above, below, top, index) +fn apply(s: &mut Session, place: Value) -> LayerId { + let mut params = json!({"material": "copper"}); + params.as_object_mut().unwrap().extend(place.as_object().unwrap().clone()); + LayerId(execute(s, "material.apply", ¶ms).unwrap()["layer"].as_u64().unwrap()) +} + +#[test] +fn a_material_dropped_on_a_row_goes_directly_below_it_and_one_dropped_on_the_view_goes_on_top() { + let mut s = session(); + let paint = stack(&s)[0]; + let upper = apply(&mut s, json!({})); + let lower = apply(&mut s, json!({"index": 0})); + assert_eq!(stack(&s), vec![lower, paint, upper]); + + let below_paint = apply(&mut s, json!({"below": paint.0})); + assert_eq!(stack(&s), vec![lower, below_paint, paint, upper]); + + let below_bottom = apply(&mut s, json!({"below": lower.0})); + assert_eq!(stack(&s)[0], below_bottom, "below the bottom row is the bottom"); + + s.selected.insert(0, lower); + let top = apply(&mut s, json!({"top": true})); + assert_eq!(stack(&s).last(), Some(&top), "the top, wherever the selection is"); + assert_eq!(s.selected_layer(), Some(top)); + s.doc.project.validate().unwrap(); +} diff --git a/crates/engine/tests/it/closed_session.rs b/crates/engine/tests/it/closed_session.rs new file mode 100644 index 00000000..2c19e089 --- /dev/null +++ b/crates/engine/tests/it/closed_session.rs @@ -0,0 +1,79 @@ +//! The empty state (no project open): project-dependent commands are refused, and +//! File > Close returns to it. + +use serde_json::json; +use texturecraft_engine::{EngineError, Session, Tool, check_enabled, command_specs, execute, find}; + +fn open_project() -> Session { + Session::new_project("Open", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap() +} + +#[test] +fn a_closed_session_refuses_commands_that_need_a_project() { + let mut session = Session::closed().unwrap(); + + assert!(!session.project_open); + for id in ["layer.add.paint", "file.save", "file.close", "edit.undo", "tool.paint", "bake.run", "file.exportTextures", "viewport.view", "camera.add"] { + let error = execute(&mut session, id, &json!({})).unwrap_err(); + + assert!(matches!(error, EngineError::Disabled { .. }), "{id}: {error}"); + } + assert!(!session.can_undo(), "nothing was changed"); + assert!(!session.tool_usable(Tool::Paint), "no tool can act without a project"); +} + +#[test] +fn a_closed_session_lists_project_independent_commands_as_enabled() { + let session = Session::closed().unwrap(); + for id in ["file.open", "file.new", "project.new", "project.sample"] { + assert!(check_enabled(find(id).unwrap(), &session).is_ok(), "{id} runs with no project"); + } + let enabled: Vec<&str> = command_specs().iter().filter(|spec| check_enabled(spec, &session).is_ok()).map(|spec| spec.id).collect(); + + assert!(!enabled.iter().any(|id| id.starts_with("layer.") || id.starts_with("tool.") || id.starts_with("bake.")), "{enabled:?}"); +} + +#[test] +fn creating_a_project_from_the_closed_state_opens_it() { + let mut session = Session::closed().unwrap(); + + execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + + assert!(session.project_open); + + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); +} + +#[test] +fn close_returns_to_the_empty_state_and_allows_reopening() { + let mut session = open_project(); + session.modified = true; + + execute(&mut session, "file.close", &json!({})).unwrap(); + + assert!(!session.project_open && !session.modified && session.path.is_none()); + assert!(execute(&mut session, "file.close", &json!({})).is_err(), "closing again has nothing to close"); + + execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + + assert!(session.project_open, "a project can be created again"); +} + +#[test] +fn the_libraries_and_presets_still_answer_without_a_project() { + let mut session = Session::closed().unwrap(); + for id in [ + "export.presets", + "brush.preset.list", + "alpha.list", + "filter.list", + "material.list", + "mask.smart.list", + "text.fonts", + "project.templates", + "project.inspect", + ] { + execute(&mut session, id, &json!({})).unwrap_or_else(|error| panic!("{id}: {error}")); + } + assert_eq!(texturecraft_engine::inspect::session(&session)["projectOpen"], json!(false)); +} diff --git a/crates/engine/tests/it/frame_selection.rs b/crates/engine/tests/it/frame_selection.rs new file mode 100644 index 00000000..8d6aca91 --- /dev/null +++ b/crates/engine/tests/it/frame_selection.rs @@ -0,0 +1,110 @@ +//! Frame texture set (Shift+F) and Show entire mesh (F): a floor plane must not decide the camera + +use serde_json::{Value, json}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::{Session, execute}; + +/// A small "Hydrant" (set 0) near the origin and a huge "Floor" (set 1) below and around it +const SCENE_OBJ: &str = "o Hydrant\nusemtl Hydrant\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ +o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + +fn scene() -> Session { + let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap(); + let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| session.mesh.materials[set.material].as_str()).collect(); + assert_eq!(sets, ["Hydrant", "Floor"], "the sets follow the parts"); + session +} + +fn target(session: &Session) -> Vec3 { + session.camera.target +} + +fn near(a: Vec3, b: Vec3) -> bool { + (a - b).length() < 1e-4 +} + +#[test] +fn frame_texture_set_frames_only_the_active_set() { + let mut session = scene(); + let all = session.camera.distance; + + execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap(); + + assert!(near(target(&session), Vec3::new(0.5, 0.5, 0.0)), "the camera looks at the hydrant, not the floor: {:?}", target(&session)); + assert!(session.camera.distance < all * 0.05, "the hydrant is about 1 unit across, the whole scene about 280: {} vs {all}", session.camera.distance); +} + +#[test] +fn frame_texture_set_follows_the_selected_set() { + let mut session = scene(); + + execute(&mut session, "textureSet.select", &json!({"ts": 1})).unwrap(); + execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap(); + + assert!(near(target(&session), Vec3::new(0.0, -1.0, 0.0)), "{:?}", target(&session)); + assert!(session.camera.distance > 100.0, "the floor is wide: {}", session.camera.distance); +} + +#[test] +fn orbit_turns_around_the_framed_center() { + let mut session = scene(); + execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap(); + let (center, distance) = (target(&session), session.camera.distance); + + for (dx, dy) in [(90.0, 0.0), (0.0, 30.0), (-45.0, -10.0)] { + execute(&mut session, "camera.orbit", &json!({"dx": dx, "dy": dy})).unwrap(); + assert!(near(target(&session), center), "orbiting keeps the pivot"); + assert!(((session.camera.eye() - center).length() - distance).abs() < 1e-3, "and the eye stays that far from the framed center"); + } +} + +#[test] +fn show_entire_mesh_restores_the_whole_scene() { + let mut session = scene(); + let whole = (target(&session), session.camera.distance); + execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap(); + assert!(!near(target(&session), whole.0)); + + execute(&mut session, "viewport.frame", &Value::Null).unwrap(); + + assert!(near(target(&session), whole.0), "{:?}", target(&session)); + assert!((session.camera.distance - whole.1).abs() < 1e-3); +} + +#[test] +fn viewport_frame_takes_a_target() { + let mut session = scene(); + let whole = session.camera.distance; + + let selection = execute(&mut session, "viewport.frame", &json!({"target": "selection"})).unwrap(); + assert!(session.camera.distance < whole * 0.05); + assert_eq!(selection["target"], json!([0.5, 0.5, 0.0])); + + execute(&mut session, "viewport.frame", &json!({"target": "all"})).unwrap(); + assert!((session.camera.distance - whole).abs() < 1e-3); + + assert!(execute(&mut session, "viewport.frame", &json!({"target": "floor"})).is_err()); +} + +#[test] +fn a_set_without_triangles_frames_the_whole_mesh() { + let mut session = scene(); + let whole = (target(&session), session.camera.distance); + session.doc.project.texture_sets[0].material = 7; + + execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap(); + + assert!(near(target(&session), whole.0) && (session.camera.distance - whole.1).abs() < 1e-3); +} + +#[test] +fn a_saved_overview_camera_is_restored_after_framing_a_set() { + let mut session = scene(); + execute(&mut session, "camera.add", &json!({"name": "Overview"})).unwrap(); + let overview = session.camera.distance; + execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap(); + + execute(&mut session, "camera.select", &json!({"name": "Overview"})).unwrap(); + + assert!((session.camera.distance - overview).abs() < 1e-3, "{} vs {overview}", session.camera.distance); +} diff --git a/crates/engine/tests/it/gradient_map.rs b/crates/engine/tests/it/gradient_map.rs new file mode 100644 index 00000000..84ff10f8 --- /dev/null +++ b/crates/engine/tests/it/gradient_map.rs @@ -0,0 +1,223 @@ +//! Gradient maps on a fill's base color: color stops for a procedural or an anchor point, +//! through `layer.fill.set {colors}`, undo, inspect and a project round trip. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +/// Composited value of `c` under the viewport center. +fn center(s: &mut Session, c: Channel) -> [f32; 3] { + s.update(); + let hit = s.pick(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap(); + s.caches[0].composite.value(c, (hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32) +} + +fn close(a: [f32; 3], b: [f32; 3]) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < 2e-3) +} + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// The stops on `layer`'s base color source. +fn ramp(s: &Session, layer: u64) -> Vec<[f32; 3]> { + match &s.doc.project.layer(LayerId(layer)).unwrap().kind { + LayerKind::Fill(fill) => fill.source(Channel::BaseColor).ramp().to_vec(), + _ => panic!("not a fill layer"), + } +} + +const RGB: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]; + +#[test] +fn an_anchor_gradient_map_recolors_the_gray_below_and_undoes() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({})).unwrap(), "effect"); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.3, "metallic": 0.6})).unwrap(), "layer"); + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]), "{:?}", center(&mut s, Channel::BaseColor)); + + // Mid gray picks the middle stop; the other channels keep their values + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": RGB})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); + assert!(close(center(&mut s, Channel::Roughness), [0.3; 3])); + assert!(close(center(&mut s, Channel::Metallic), [0.6; 3])); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap(); + let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == top).unwrap().clone(); + assert_eq!(row["fill"]["sources"]["baseColor"]["colors"], json!(RGB), "{row}"); + + // One undo step each way + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(ramp(&s, top).is_empty()); + assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3])); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + assert_eq!(ramp(&s, top), RGB.to_vec()); + assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0])); + + // Picking the anchor again keeps the stops; hex colors work; an empty list removes them + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": ["#000000", "#ff0000"]})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap(); + assert!(close(center(&mut s, Channel::BaseColor), [0.5, 0.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor)); + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": []})).unwrap(); + assert!(ramp(&s, top).is_empty()); + assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3])); +} + +#[test] +fn a_procedural_gradient_map_saves_and_loads() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.4})).unwrap(), "layer"); + execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "procedural": "Checker", "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], "colors": [[1, 0, 0], [0, 0, 1]]})).unwrap(); + let value = center(&mut s, Channel::BaseColor); + assert!(close(value, [1.0, 0.0, 0.0]) || close(value, [0.0, 0.0, 1.0]), "a stop, not low or high: {value:?}"); + assert!(close(center(&mut s, Channel::Roughness), [0.4; 3])); + + // Changing the pattern's settings without `colors` (as its sliders do) keeps the stops + execute( + &mut s, + "layer.fill.set", + &json!({"layer": layer, "channel": "baseColor", "procedural": "Checker", "scale": 8.0, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8]}), + ) + .unwrap(); + assert_eq!(ramp(&s, layer), vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]); + + let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(back.doc.project, s.doc.project); + assert_eq!(ramp(&back, layer), vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]); + match &back.doc.project.layer(LayerId(layer)).unwrap().kind { + LayerKind::Fill(fill) => assert!(matches!(fill.source(Channel::BaseColor), Source::Procedural { .. })), + _ => panic!("not a fill layer"), + } +} + +#[test] +fn gradient_map_colors_are_refused_where_they_cannot_apply() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.4})).unwrap(), "layer"); + let set = |s: &mut Session, extra: Value| { + let mut p = json!({"layer": layer}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + execute(s, "layer.fill.set", &p) + }; + assert!(set(&mut s, json!({"channel": "baseColor", "colors": RGB})).is_err(), "a uniform color has no gray to map"); + assert!(set(&mut s, json!({"channel": "roughness", "procedural": "Clouds", "colors": RGB})).is_err(), "only color channels"); + assert!(set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": vec![[0.5; 3]; 17]})).is_err(), "at most 16 stops"); + assert!(set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": ["red"]})).is_err()); + assert!(ramp(&s, layer).is_empty(), "a refused edit changes nothing"); + + // Removing stops where there are none (a uniform color) changes nothing either + let before = s.doc.project.clone(); + set(&mut s, json!({"channel": "baseColor", "colors": []})).unwrap(); + assert_eq!(s.doc.project, before); + set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": [[2.0, -1.0, 0.5]]})).unwrap(); + assert_eq!(ramp(&s, layer), vec![[1.0, 0.0, 0.5]], "stops clamp to 0..1"); +} + +#[test] +fn a_scalar_channel_drops_stuck_stops_when_its_source_is_set() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.4})).unwrap(), "layer"); + + // Replacing a scalar source must discard color stops hidden by the panel + let stuck = |s: &mut Session| { + let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(LayerId(layer)).unwrap().kind else { panic!("not a fill layer") }; + let pattern = texturecraft_engine::core::Procedural::new(texturecraft_engine::core::ProceduralKind::Clouds); + fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: RGB.to_vec() }); + }; + let roughness_ramp = |s: &Session| match &s.doc.project.layer(LayerId(layer)).unwrap().kind { + LayerKind::Fill(fill) => fill.source(Channel::Roughness).ramp().to_vec(), + _ => panic!("not a fill layer"), + }; + stuck(&mut s); + execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "roughness", "procedural": "Clouds", "scale": 8.0})).unwrap(); + assert!(roughness_ramp(&s).is_empty(), "a new pattern on roughness keeps no stops"); + stuck(&mut s); + execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "roughness", "colors": []})).unwrap(); + assert!(roughness_ramp(&s).is_empty(), "`colors: []` removes them"); +} + +#[test] +fn removing_stops_from_an_absent_channel_adds_no_channel() { + let mut s = session(); + + // A content fill effect that supplies only roughness: a default gray base color would cover the layer + let effect = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect"); + let before = s.doc.project.clone(); + execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "colors": []})).unwrap(); + assert_eq!(s.doc.project, before, "no base color source appears on the effect"); + + // The same on a fill layer that has no base color channel + let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.4})).unwrap(), "layer"); + let before = s.doc.project.clone(); + execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "colors": []})).unwrap(); + assert_eq!(s.doc.project, before, "no base color channel appears on the layer"); + + // Turning the channel on still adds it + execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "enabled": true})).unwrap(); + let (_, x) = s.doc.project.effect(texturecraft_engine::core::LayerId(effect)).unwrap(); + match &x.kind { + texturecraft_engine::core::EffectKind::Material(f) => assert!(f.sources.contains_key(&Channel::BaseColor), "enabled adds the channel"), + _ => panic!("not a content fill effect"), + } +} + +#[test] +fn gradient_map_true_starts_the_stops_from_the_current_source() { + let mut s = session(); + let layer = id(execute(&mut s, "layer.add.fill", &json!({})).unwrap(), "layer"); + let set = |s: &mut Session, p: Value| { + let mut p = p; + p["layer"] = json!(layer); + p["channel"] = json!("baseColor"); + execute(s, "layer.fill.set", &p) + }; + + // A uniform color has nothing to start from + assert!(set(&mut s, json!({"gradientMap": true})).is_err()); + + // A procedural starts at low, halfway and high, so its look holds + set(&mut s, json!({"procedural": "Clouds", "low": [0.0, 0.25, 0.5], "high": [1.0, 0.75, 0.5]})).unwrap(); + set(&mut s, json!({"gradientMap": true})).unwrap(); + assert_eq!(ramp(&s, layer), vec![[0.0, 0.25, 0.5], [0.5; 3], [1.0, 0.75, 0.5]]); + + // Stops already there stay + set(&mut s, json!({"colors": RGB})).unwrap(); + set(&mut s, json!({"gradientMap": true})).unwrap(); + assert_eq!(ramp(&s, layer), RGB.to_vec()); + + // Set together with a new pattern, the stops stay + set(&mut s, json!({"procedural": "Voronoi", "gradientMap": true})).unwrap(); + assert_eq!(ramp(&s, layer), RGB.to_vec()); + + // It cannot go with `colors`, and it undoes in one step + assert!(set(&mut s, json!({"gradientMap": true, "colors": RGB})).is_err()); + set(&mut s, json!({"colors": []})).unwrap(); + set(&mut s, json!({"gradientMap": true})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(ramp(&s, layer).is_empty()); + + // An anchor starts at black, gray and white + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + let anchor = id(execute(&mut s, "effect.add.anchor", &json!({})).unwrap(), "effect"); + let top = id(execute(&mut s, "layer.add.fill", &json!({})).unwrap(), "layer"); + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "gradientMap": true})).unwrap(); + assert_eq!(ramp(&s, top), vec![[0.0; 3], [0.5; 3], [1.0; 3]]); + + // A scalar channel has no stops + assert!(execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "roughness", "gradientMap": true})).is_err()); +} diff --git a/crates/engine/tests/it/layer_multi_select.rs b/crates/engine/tests/it/layer_multi_select.rs new file mode 100644 index 00000000..14c375d8 --- /dev/null +++ b/crates/engine/tests/it/layer_multi_select.rs @@ -0,0 +1,525 @@ +//! Several selected layers, as in the reference app: Shift+click selects a range of rows, +//! Ctrl/Cmd+click adds or takes out one layer, and remove, duplicate, group, visibility and move +//! act on every selected layer in one undo step. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::layer_selection::stack_rows; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap() +} + +fn id(v: Value, key: &str) -> LayerId { + LayerId(v[key].as_u64().unwrap()) +} + +fn add(s: &mut Session, name: &str) -> LayerId { + id(execute(s, "layer.add.paint", &json!({ "name": name })).unwrap(), "layer") +} + +/// Paint layers A (bottom) to D (top) on texture set 0, D selected. +fn four(s: &mut Session) -> [LayerId; 4] { + execute(s, "textureSet.select", &json!({"ts": 0})).unwrap(); + [add(s, "A"), add(s, "B"), add(s, "C"), add(s, "D")] +} + +/// The names of set 0's rows from the top (folder contents included). +fn rows(s: &Session) -> Vec { + stack_rows(&s.doc.project, 0, false).iter().map(|id| s.doc.project.layer(*id).unwrap().name.clone()).collect() +} + +fn names(s: &Session, ids: &[LayerId]) -> Vec { + ids.iter().map(|id| s.doc.project.layer(*id).unwrap().name.clone()).collect() +} + +fn selected(s: &Session) -> Vec { + names(s, &s.selected_layers()) +} + +fn click(s: &mut Session, layer: LayerId, how: &str) { + let params = match how { + "shift" => json!({"layer": layer.0, "range": true}), + "ctrl" => json!({"layer": layer.0, "toggle": true}), + _ => json!({"layer": layer.0}), + }; + execute(s, "layer.select", ¶ms).unwrap(); +} + +#[test] +fn shift_click_selects_the_rows_from_the_last_clicked_layer() { + let mut s = session(); + let [a, b, _, d] = four(&mut s); + click(&mut s, b, "plain"); + click(&mut s, d, "shift"); + assert_eq!(selected(&s), ["D", "C", "B"]); + assert_eq!(s.selected_layer(), Some(d), "the clicked layer is the active one"); + + // The range still starts at B, not at the active D + click(&mut s, a, "shift"); + assert_eq!(selected(&s), ["B", "A"]); + assert_eq!(s.selected_layer(), Some(a)); + assert_eq!(texturecraft_engine::inspect::session(&s)["selectedLayers"], json!([b.0, a.0])); + + // A plain click selects one layer again + click(&mut s, d, "plain"); + assert_eq!(selected(&s), ["D"]); +} + +#[test] +fn ctrl_click_adds_and_takes_out_one_layer() { + let mut s = session(); + let [a, _, c, _] = four(&mut s); + click(&mut s, a, "plain"); + click(&mut s, c, "ctrl"); + assert_eq!(selected(&s), ["C", "A"]); + assert_eq!(s.selected_layer(), Some(c)); + click(&mut s, c, "ctrl"); + assert_eq!(selected(&s), ["A"], "a second Ctrl+click takes the layer out"); + assert_eq!(s.selected_layer(), Some(a), "the remaining layer becomes the active one"); + click(&mut s, a, "ctrl"); + assert!(selected(&s).is_empty(), "Ctrl+click on the only selected layer leaves an empty selection"); + assert_eq!(s.selected_layer(), None); + + // The next Shift+click has no anchor and starts over at the clicked layer + click(&mut s, c, "shift"); + assert_eq!(selected(&s), ["C"]); + click(&mut s, a, "ctrl"); + assert_eq!(selected(&s), ["C", "A"]); +} + +#[test] +fn ctrl_click_on_another_selected_layer_keeps_the_active_one_and_the_range_start() { + let mut s = session(); + let [a, b, c, d] = four(&mut s); + click(&mut s, b, "plain"); + click(&mut s, d, "shift"); + click(&mut s, c, "ctrl"); + assert_eq!(selected(&s), ["D", "B"]); + assert_eq!(s.selected_layer(), Some(d), "D stays the active layer"); + click(&mut s, a, "shift"); + assert_eq!(selected(&s), ["B", "A"], "the range still starts at B"); +} + +#[test] +fn a_range_covers_the_shown_rows_only() { + let mut s = session(); + let [a, b, c, d] = four(&mut s); + execute(&mut s, "layer.select", &json!({"layers": [b.0, c.0]})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer"); + assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "B", "A"]); + + click(&mut s, d, "plain"); + click(&mut s, a, "shift"); + assert_eq!(selected(&s), ["D", "Folder 1", "C", "B", "A"], "an open folder's layers are in the range"); + + if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind { + *collapsed = true; + } + click(&mut s, d, "plain"); + click(&mut s, a, "shift"); + assert_eq!(selected(&s), ["D", "Folder 1", "A"], "a collapsed folder's layers are not"); +} + +#[test] +fn another_selected_layer_ends_the_multiple_selection() { + let mut s = session(); + let [a, _, c, _] = four(&mut s); + click(&mut s, a, "plain"); + click(&mut s, c, "ctrl"); + add(&mut s, "E"); + assert_eq!(selected(&s), ["E"], "a new layer is selected alone"); +} + +#[test] +fn delete_removes_every_selected_layer_in_one_undo_step() { + let mut s = session(); + let [a, b, _, d] = four(&mut s); + execute(&mut s, "layer.select", &json!({"layers": [b.0, d.0]})).unwrap(); + let depth = s.history_labels().len(); + let r = execute(&mut s, "layer.remove", &Value::Null).unwrap(); + assert_eq!(r["removed"], json!([d.0, b.0])); + assert_eq!(rows(&s)[..2], ["C", "A"]); + assert_eq!(selected(&s), ["A"], "the layer under the lowest removed one is selected"); + assert_eq!(s.selected_layer(), Some(a)); + assert_eq!(s.history_labels().len(), depth + 1, "one undo step"); + s.undo().unwrap(); + assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]); +} + +#[test] +fn a_folder_and_its_own_layer_selected_remove_together() { + let mut s = session(); + let [a, b, _, _] = four(&mut s); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer"); + execute(&mut s, "layer.select", &json!({"layers": [folder.0, b.0, a.0]})).unwrap(); + execute(&mut s, "layer.remove", &Value::Null).unwrap(); + assert_eq!(rows(&s)[..2], ["D", "C"]); + assert!(s.doc.project.layer(b).is_err() && s.doc.project.layer(a).is_err()); +} + +#[test] +fn duplicate_puts_the_copies_in_one_block_above_the_topmost_selected_layer() { + let mut s = session(); + let [_, b, _, d] = four(&mut s); + execute(&mut s, "layer.select", &json!({"layers": [d.0, b.0], "layer": b.0})).unwrap(); + execute(&mut s, "layer.duplicate", &Value::Null).unwrap(); + assert_eq!(rows(&s)[..6], ["D copy", "B copy", "D", "C", "B", "A"], "the block sits directly above D, in stack order"); + assert_eq!(selected(&s), ["D copy", "B copy"], "the copies are selected"); + assert_eq!(names(&s, &[s.selected_layer().unwrap()]), ["B copy"], "the active layer's copy is the active one"); + s.undo().unwrap(); + assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]); +} + +#[test] +fn duplicate_block_lands_at_the_topmost_layers_level_also_for_a_layer_from_a_folder() { + let mut s = session(); + let [a, _, c, _] = four(&mut s); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [a.0], "above": folder.0, "inside": true})).unwrap(); + assert_eq!(rows(&s)[..5], ["Folder 1", "A", "D", "C", "B"]); + + // The topmost selected row is A, inside the folder, so the block goes there + execute(&mut s, "layer.select", &json!({"layers": [c.0, a.0]})).unwrap(); + execute(&mut s, "layer.duplicate", &Value::Null).unwrap(); + assert_eq!(rows(&s)[..7], ["Folder 1", "A copy", "C copy", "A", "D", "C", "B"]); + assert_eq!(selected(&s), ["A copy", "C copy"], "the copies are the selection"); +} + +#[test] +fn duplicate_of_a_root_layer_and_a_folder_layer_with_the_root_one_higher() { + let mut s = session(); + let [a, b, _, d] = four(&mut s); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [a.0], "above": folder.0, "inside": true})).unwrap(); + execute(&mut s, "layer.move", &json!({"layers": [folder.0], "above": b.0})).unwrap(); + + // Rows from the top: D, C, Folder 1 (A), B... select D (root, topmost) and A (in the folder) + assert_eq!(rows(&s)[..5], ["D", "C", "Folder 1", "A", "B"]); + execute(&mut s, "layer.select", &json!({"layers": [d.0, a.0]})).unwrap(); + execute(&mut s, "layer.duplicate", &Value::Null).unwrap(); + assert_eq!(rows(&s)[..4], ["D copy", "A copy", "D", "C"], "the block is at the root, above D"); +} + +#[test] +fn group_puts_the_selected_layers_into_one_folder_in_their_order() { + let mut s = session(); + let [a, _, c, _] = four(&mut s); + execute(&mut s, "layer.select", &json!({"layers": [a.0, c.0]})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer"); + assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "A", "B"], "the folder takes the top layer's place"); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [a, c], "bottom to top inside the folder"); + assert_eq!(s.selected_layers(), [folder]); + s.undo().unwrap(); + assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]); +} + +#[test] +fn group_puts_the_folder_at_the_topmost_selected_layer_with_gaps_between() { + let mut s = session(); + execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); + let [l1, l2, l3, l4, l5] = ["L1", "L2", "L3", "L4", "L5"].map(|n| add(&mut s, n)); + execute(&mut s, "layer.select", &json!({"layers": [l2.0, l4.0]})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer"); + assert_eq!(rows(&s)[..6], ["L5", "Folder 1", "L4", "L2", "L3", "L1"], "the folder sits where L4 was, L3 stays below it"); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [l2, l4], "L2 stays below L4 inside"); + let stack = &s.doc.project.texture_sets[0].stack; + assert_eq!(stack[stack.len() - 4..], [l1, l3, folder, l5], "L5 stays above the folder"); + + // Same result when the layers are picked in the other order + s.undo().unwrap(); + execute(&mut s, "layer.select", &json!({"layers": [l4.0, l2.0]})).unwrap(); + execute(&mut s, "layer.group", &Value::Null).unwrap(); + assert_eq!(rows(&s)[..6], ["L5", "Folder 1", "L4", "L2", "L3", "L1"]); +} + +#[test] +fn group_of_a_layer_inside_a_folder_and_one_outside_keeps_the_topmost_place() { + let mut s = session(); + execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); + let [x, y, z] = ["X", "Y", "Z"].map(|n| add(&mut s, n)); + let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [y.0, z.0], "above": outer.0, "inside": true})).unwrap(); + + // Rows from the top: Folder 1 (Z, Y), X + assert_eq!(rows(&s)[..4], ["Folder 1", "Z", "Y", "X"]); + + // The topmost selected layer Z is inside the folder: the new folder replaces it there + execute(&mut s, "layer.select", &json!({"layers": [z.0, x.0]})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer"); + assert_eq!(rows(&s)[..5], ["Folder 1", "Folder 2", "Z", "X", "Y"]); + assert_eq!(s.doc.project.layer(outer).unwrap().children(), [y, folder], "Z's place in the outer folder"); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [x, z], "X keeps its place below Z"); + s.undo().unwrap(); + assert_eq!(rows(&s)[..4], ["Folder 1", "Z", "Y", "X"]); + + // X is outside and Y inside: Y is the topmost, so the folder appears inside the outer folder + execute(&mut s, "layer.select", &json!({"layers": [x.0, y.0]})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer"); + assert_eq!(rows(&s)[..5], ["Folder 1", "Z", "Folder 2", "Y", "X"]); + assert_eq!(s.doc.project.texture_sets[0].stack.last(), Some(&outer), "the outer folder stays on top"); + assert_eq!(s.doc.project.layer(outer).unwrap().children(), [folder, z]); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [x, y]); +} + +#[test] +fn group_with_the_topmost_layer_at_the_root_takes_the_folder_layer_out_of_its_folder() { + let mut s = session(); + execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); + let [_x, fa, fb] = ["X", "Fill A", "Fill B"].map(|n| add(&mut s, n)); + let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [fa.0, fb.0], "above": outer.0, "inside": true})).unwrap(); + + // Folder 1 (Fill B, Fill A) at the root above X; add Fill 3 above the folder + let f3 = add(&mut s, "Fill 3"); + execute(&mut s, "layer.move", &json!({"layers": [f3.0], "above": outer.0})).unwrap(); + assert_eq!(rows(&s)[..5], ["Fill 3", "Folder 1", "Fill B", "Fill A", "X"]); + execute(&mut s, "layer.select", &json!({"layers": [f3.0, fa.0]})).unwrap(); + let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer"); + assert_eq!(rows(&s)[..6], ["Folder 2", "Fill 3", "Fill A", "Folder 1", "Fill B", "X"], "the new folder is at the root slot of Fill 3"); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [fa, f3], "stack order inside: the folder's own layer is lower"); + assert_eq!(s.doc.project.layer(outer).unwrap().children(), [fb], "Fill A left its folder"); +} + +#[test] +fn shift_range_counts_the_folder_row_and_skips_the_layers_of_a_collapsed_folder() { + let mut s = session(); + let [a, b, c, d] = four(&mut s); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [b.0, c.0], "above": folder.0, "inside": true})).unwrap(); + + // Rows from the top: Folder 1 (C, B), D, A... move the folder between D and A + execute(&mut s, "layer.move", &json!({"layers": [folder.0], "above": a.0})).unwrap(); + assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "B", "A"]); + + click(&mut s, d, "plain"); + click(&mut s, a, "shift"); + assert_eq!(selected(&s), ["D", "Folder 1", "C", "B", "A"], "an open folder: the row and its layers"); + + if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind { + *collapsed = true; + } + click(&mut s, d, "plain"); + click(&mut s, a, "shift"); + assert_eq!(selected(&s), ["D", "Folder 1", "A"], "a collapsed folder: the row, not its layers"); +} + +#[test] +fn select_all_takes_the_folder_rows_and_the_layers_of_open_folders_only() { + let mut s = session(); + let [a, b, c, d] = four(&mut s); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [a.0, b.0], "above": folder.0, "inside": true})).unwrap(); + click(&mut s, c, "plain"); + let depth = s.history_labels().len(); + + // Open folder: the folder row and its layers + let r = execute(&mut s, "layer.select", &json!({"all": true})).unwrap(); + let shown = stack_rows(&s.doc.project, 0, true); + assert_eq!(selected(&s)[..5], ["Folder 1", "B", "A", "D", "C"]); + assert_eq!(s.selected_layers(), shown, "every row of the set"); + assert_eq!(r["layers"].as_array().unwrap().len(), shown.len()); + assert_eq!(s.selected_layer(), Some(c), "the active layer stays"); + assert_eq!(s.history_labels().len(), depth, "selecting is no undo step"); + + // Collapsed folder: the folder row, not its layers + if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind { + *collapsed = true; + } + execute(&mut s, "layer.select", &json!({"layer": d.0})).unwrap(); + execute(&mut s, "layer.select", &json!({"all": true})).unwrap(); + assert_eq!(selected(&s)[..3], ["Folder 1", "D", "C"]); + assert!(!s.is_layer_selected(a) && !s.is_layer_selected(b), "the collapsed folder's layers stay unselected"); + assert_eq!(s.selected_layer(), Some(d), "the active layer stays when it is picked again"); +} + +#[test] +fn the_visibility_of_one_layer_leaves_the_other_selected_layers_alone() { + let mut s = session(); + let [a, _, c, _] = four(&mut s); + execute(&mut s, "layer.select", &json!({"layers": [a.0, c.0]})).unwrap(); + execute(&mut s, "layer.visible", &json!({"layer": c.0})).unwrap(); + assert!(!s.doc.project.layer(c).unwrap().visible && s.doc.project.layer(a).unwrap().visible, "only C is hidden"); + assert_eq!(s.selected_layers().len(), 2, "the selection stays"); +} + +#[test] +fn visibility_of_several_layers_follows_the_layer_given_as_lead() { + let mut s = session(); + let [a, b, c, _] = four(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap(); + + // The active layer is C (shown), but the eye of A (hidden) was clicked: all are shown + execute(&mut s, "layer.select", &json!({"layers": [a.0, b.0, c.0], "layer": c.0})).unwrap(); + execute(&mut s, "layer.visible", &json!({"layers": [a.0, b.0, c.0], "layer": a.0})).unwrap(); + let shown = |s: &Session| [a, b, c].map(|l| s.doc.project.layer(l).unwrap().visible); + assert_eq!(shown(&s), [true; 3], "A was hidden, so all are shown"); +} + +#[test] +fn visibility_toggles_every_selected_layer_the_way_of_the_active_one() { + let mut s = session(); + let [a, b, c, _] = four(&mut s); + execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap(); + execute(&mut s, "layer.select", &json!({"layers": [a.0, b.0, c.0], "layer": c.0})).unwrap(); + let depth = s.history_labels().len(); + execute(&mut s, "layer.visible", &Value::Null).unwrap(); + let shown = |s: &Session| [a, b, c].map(|l| s.doc.project.layer(l).unwrap().visible); + assert_eq!(shown(&s), [false; 3], "C was shown, so all are hidden"); + assert_eq!(s.history_labels().len(), depth + 1, "one undo step"); + execute(&mut s, "layer.visible", &json!({"layers": [a.0, b.0], "visible": true})).unwrap(); + assert_eq!(shown(&s), [true, true, false]); + s.undo().unwrap(); + s.undo().unwrap(); + assert_eq!(shown(&s), [false, true, true]); +} + +#[test] +fn selected_layers_move_together_keeping_their_order() { + let mut s = session(); + let [a, b, c, d] = four(&mut s); + execute(&mut s, "layer.move", &json!({"layers": [a.0, c.0], "above": d.0})).unwrap(); + assert_eq!(rows(&s)[..4], ["C", "A", "D", "B"]); + s.undo().unwrap(); + assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]); + + // Into a folder + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [d.0, b.0], "above": folder.0, "inside": true})).unwrap(); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [b, d]); + assert!(execute(&mut s, "layer.move", &json!({"layers": [a.0, c.0], "above": c.0})).is_err(), "not above one of themselves"); +} + +#[test] +fn selected_layers_moved_to_an_index_keep_their_order() { + for (pair, expected) in [("B", ["C", "D", "B", "A", "Layer 1"]), ("A", ["C", "D", "A", "B", "Layer 1"])] { + let mut s = session(); + let [a, b, _, d] = four(&mut s); + let lower = if pair == "A" { a } else { b }; + execute(&mut s, "layer.move", &json!({"layers": [d.0, lower.0], "index": 2})).unwrap(); + assert_eq!(rows(&s)[..5], expected, "D and {pair} to index 2"); + } +} + +#[test] +fn extreme_move_deltas_clamp_to_the_stack_ends() { + let mut session = session(); + let [_, layer, ..] = four(&mut session); + + execute(&mut session, "layer.move", &json!({"layer": layer.0, "delta": i64::MAX})).unwrap(); + assert_eq!(rows(&session)[0], "B", "a large positive delta moves to the top"); + + execute(&mut session, "layer.move", &json!({"layer": layer.0, "delta": i64::MIN})).unwrap(); + assert_eq!(rows(&session).last().map(String::as_str), Some("B"), "a large negative delta moves to the bottom"); +} + +#[test] +fn layers_in_and_out_of_a_folder_dropped_below_the_stack_stay_together_at_its_bottom() { + let mut s = session(); + let [_, b, _, d] = four(&mut s); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer"); + execute(&mut s, "layer.move", &json!({"layers": [d.0, b.0], "index": 0})).unwrap(); + assert_eq!(s.doc.project.texture_sets[0].stack[..2], [b, d], "B at the bottom, D right above it"); + assert!(s.doc.project.layer(folder).unwrap().children().is_empty(), "B left its folder"); +} + +#[test] +fn a_move_that_changes_nothing_is_not_an_undo_step() { + let mut s = session(); + let [a, b, c, _] = four(&mut s); + let depth = s.history_labels().len(); + execute(&mut s, "layer.move", &json!({"layer": b.0, "above": a.0})).unwrap(); + execute(&mut s, "layer.move", &json!({"layers": [c.0, b.0], "above": a.0})).unwrap(); + assert_eq!(s.history_labels().len(), depth, "B already sits above A, and C above B"); + execute(&mut s, "layer.move", &json!({"layer": a.0, "above": c.0})).unwrap(); + assert_eq!(s.history_labels().len(), depth + 1); +} + +#[test] +fn an_explicit_layer_acts_on_that_layer_only_while_several_are_selected() { + let select = |s: &mut Session, b: LayerId, d: LayerId| execute(s, "layer.select", &json!({"layers": [b.0, d.0]})).unwrap(); + + let mut s = session(); + let [_, b, _, d] = four(&mut s); + select(&mut s, b, d); + execute(&mut s, "layer.remove", &json!({"layer": b.0})).unwrap(); + assert_eq!(rows(&s)[..3], ["D", "C", "A"], "remove"); + + let mut s = session(); + let [_, b, _, d] = four(&mut s); + select(&mut s, b, d); + execute(&mut s, "layer.duplicate", &json!({"layer": b.0})).unwrap(); + assert_eq!(rows(&s)[..5], ["D", "C", "B copy", "B", "A"], "duplicate"); + + let mut s = session(); + let [_, b, _, d] = four(&mut s); + select(&mut s, b, d); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(folder).unwrap().children(), [b], "group"); + + let mut s = session(); + let [_, b, _, d] = four(&mut s); + select(&mut s, b, d); + execute(&mut s, "layer.visible", &json!({"layer": b.0})).unwrap(); + assert!(!s.doc.project.layer(b).unwrap().visible && s.doc.project.layer(d).unwrap().visible, "visible"); +} + +#[test] +fn undo_and_redo_end_the_multiple_selection() { + let mut s = session(); + let [_, b, ..] = four(&mut s); + let e = add(&mut s, "E"); + execute(&mut s, "layer.select", &json!({"layers": [b.0, e.0]})).unwrap(); + s.undo().unwrap(); + s.redo().unwrap(); + assert_eq!(selected(&s), ["E"], "E is back alone, B is not picked again"); + add(&mut s, "F"); + assert_eq!(s.selected_layers().len(), 1); + assert!(!s.is_layer_selected(b)); +} + +#[test] +fn reselecting_an_earlier_active_layer_does_not_bring_back_its_multiple_selection() { + let mut s = session(); + let [_, b, c, d] = four(&mut s); + click(&mut s, c, "plain"); + let effect = execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "effect.copy", &json!({ "effect": effect })).unwrap(); + execute(&mut s, "layer.select", &json!({"layers": [b.0, d.0], "layer": d.0})).unwrap(); + add(&mut s, "E"); + + // Pasting the effect onto D selects D again, alone + execute(&mut s, "effect.paste", &json!({"layer": d.0})).unwrap(); + assert_eq!(selected(&s), ["D"]); +} + +#[test] +fn bad_layer_lists_are_errors() { + let mut s = session(); + let [a, ..] = four(&mut s); + let other = id(execute(&mut s, "textureSet.select", &json!({"ts": 1})).and_then(|_| execute(&mut s, "layer.add.paint", &Value::Null)).unwrap(), "layer"); + for command in ["layer.select", "layer.remove", "layer.duplicate", "layer.group", "layer.visible", "layer.move"] { + for layers in [json!("x"), json!([]), json!([u64::MAX]), json!([a.0, other.0]), json!([a.0, "x"])] { + assert!(execute(&mut s, command, &json!({"layers": layers, "above": null})).is_err(), "{command} {layers}"); + } + } + assert!(execute(&mut s, "layer.select", &json!({"layers": [a.0], "layer": other.0})).is_err(), "the active layer must be listed"); +} + +#[test] +fn moving_layers_into_a_folder_in_another_set_preserves_the_document() { + let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + let source = s.doc.project.texture_sets[0].stack[0]; + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &json!({})).unwrap(), "layer"); + let before = s.doc.project.clone(); + let history = s.history_labels(); + + for params in [json!({"layer": source.0, "above": folder.0, "inside": true}), json!({"layers": [source.0], "above": folder.0, "inside": true})] { + assert!(execute(&mut s, "layer.move", ¶ms).is_err()); + assert_eq!(s.doc.project, before); + assert_eq!(s.history_labels(), history); + } +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 7c61e03b..17e217b4 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -6,14 +6,21 @@ mod bake_checks; mod bake_resolution; mod bake_settings; mod bake_tiles; +mod brush_material; +mod closed_session; mod color_selection; mod content_effects; mod export_colour_space; mod filter_swap; mod filters; +mod frame_selection; mod generator_inputs; +mod gradient_map; mod high_poly_missed; mod instances; +mod layer_multi_select; +mod mask_clone_smudge; +mod mask_export; mod materialcraft_link; mod materialx; mod materialx_import; @@ -26,10 +33,14 @@ mod perf; mod polygon_fill; mod project_recovery; mod sample; +mod solo; mod thumbs; +mod tile_generator; mod tool_availability; +mod tool_settings; mod tools; mod udim; +mod user_smart_mask; mod uv_strokes; mod symmetry; diff --git a/crates/engine/tests/it/mask_clone_smudge.rs b/crates/engine/tests/it/mask_clone_smudge.rs new file mode 100644 index 00000000..0035ca29 --- /dev/null +++ b/crates/engine/tests/it/mask_clone_smudge.rs @@ -0,0 +1,158 @@ +//! Clone and Smudge strokes on a layer mask read and write the mask's own values + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +const SIZE: u32 = 256; + +/// A paint layer with a black mask selected, a 2D-view brush of about 13 texels radius +fn session_on_mask() -> (Session, u64) { + let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap(); + session.update(); + let layer = execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10})).unwrap(); + execute(&mut session, "tool.material", &json!({"maskValue": 1.0})).unwrap(); + (session, layer) +} + +fn paint_white_blob(session: &mut Session, uv: [f32; 2]) { + execute(session, "tool.paint", &serde_json::Value::Null).unwrap(); + execute(session, "tool.strokeUv", &json!({"points": [uv, uv]})).unwrap(); +} + +fn mask_at(session: &Session, layer: u64, uv: [f32; 2]) -> f32 { + let texel = ((uv[0] * SIZE as f32) as u32, (uv[1] * SIZE as f32) as u32); + session.mask_at(texturecraft_engine::core::LayerId(layer), &[texel]).unwrap()[0] +} + +/// A stroke of `tool` that changes the mask next to the white blob at u = 0.25: clone copies the +/// blob to u = 0.75, smudge drags it to the right +fn stroke_with(session: &mut Session, tool: &str) { + execute(session, tool, &serde_json::Value::Null).unwrap(); + execute(session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap(); + let points = if tool == "tool.clone" { json!([[0.75, 0.5], [0.75, 0.5]]) } else { json!([[0.25, 0.5], [0.3, 0.5], [0.35, 0.5], [0.4, 0.5], [0.45, 0.5]]) }; + execute(session, "tool.strokeUv", &json!({"points": points})).unwrap(); +} + +/// Mask values at probes inside the blob, where smudge drags it and where clone copies it +const PROBES: [[f32; 2]; 3] = [[0.25, 0.5], [0.4, 0.5], [0.75, 0.5]]; + +#[test] +fn clone_on_a_mask_copies_the_mask_values_from_the_source() { + let (mut session, layer) = session_on_mask(); + paint_white_blob(&mut session, [0.25, 0.5]); + assert!(mask_at(&session, layer, [0.25, 0.5]) > 0.95); + assert!(mask_at(&session, layer, [0.75, 0.5]) < 0.05); + + execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap(); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap(); + + assert!(mask_at(&session, layer, [0.75, 0.5]) > 0.95, "the white blob is cloned"); + assert!(mask_at(&session, layer, [0.75, 0.8]) < 0.05, "only the stroke is painted"); + assert!(mask_at(&session, layer, [0.25, 0.5]) > 0.95, "the source stays"); +} + +#[test] +fn clone_on_a_mask_copies_black_over_white_too() { + let (mut session, layer) = session_on_mask(); + paint_white_blob(&mut session, [0.75, 0.5]); + + execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap(); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap(); + + assert!(mask_at(&session, layer, [0.75, 0.5]) < 0.05, "the black source erases the white blob"); +} + +#[test] +fn smudge_on_a_mask_drags_values_along_the_stroke() { + let (mut session, layer) = session_on_mask(); + paint_white_blob(&mut session, [0.25, 0.5]); + assert!(mask_at(&session, layer, [0.4, 0.5]) < 0.05); + + execute(&mut session, "tool.smudge", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.3, 0.5], [0.35, 0.5], [0.4, 0.5], [0.45, 0.5]]})).unwrap(); + + assert!(mask_at(&session, layer, [0.4, 0.5]) > 0.3, "white is dragged to the right"); + assert!(mask_at(&session, layer, [0.4, 0.8]) < 0.05, "nothing beside the stroke"); +} + +#[test] +fn a_clone_or_smudge_stroke_on_a_mask_leaves_the_channels_alone() { + for tool in ["tool.clone", "tool.smudge"] { + let (mut session, _) = session_on_mask(); + paint_white_blob(&mut session, [0.25, 0.5]); + let channels_before = session.doc.pixels.layers.clone(); + let colour_before = session.caches[0].composite.value(Channel::BaseColor, 192, 128); + + stroke_with(&mut session, tool); + session.update(); + + assert_eq!(session.doc.pixels.layers.len(), channels_before.len(), "{tool}: no channel image is created"); + assert!(session.doc.pixels.layers.keys().all(|key| channels_before.contains_key(key)), "{tool}"); + assert_eq!(session.caches[0].composite.value(Channel::BaseColor, 192, 128), colour_before, "{tool}: the composite colour is unchanged"); + } +} + +#[test] +fn one_undo_restores_the_mask_after_a_clone_or_smudge_stroke() { + for tool in ["tool.clone", "tool.smudge"] { + let (mut session, layer) = session_on_mask(); + paint_white_blob(&mut session, [0.25, 0.5]); + let steps = session.history_labels().len(); + let before: Vec = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect(); + + stroke_with(&mut session, tool); + + assert_eq!(session.history_labels().len(), steps + 1, "{tool}: one undo step per stroke"); + let after: Vec = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect(); + assert_ne!(before, after, "{tool}: the stroke changed the mask"); + + session.undo().unwrap(); + + let restored: Vec = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect(); + assert_eq!(restored, before, "{tool}"); + } +} + +#[test] +fn clone_works_on_a_folder_mask() { + let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap(); + session.update(); + let folder = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": folder})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": folder, "target": "mask"})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10})).unwrap(); + paint_white_blob(&mut session, [0.25, 0.5]); + + execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap(); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap(); + + assert!(mask_at(&session, folder, [0.75, 0.5]) > 0.95, "a folder mask clones too"); +} + +#[test] +fn clone_from_the_layer_reads_the_mask_on_a_folder_mask_and_a_paint_layer_mask() { + for group in [true, false] { + let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap(); + session.update(); + let command = if group { "layer.add.group" } else { "layer.add.paint" }; + let layer = execute(&mut session, command, &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10, "cloneSource": "layer"})).unwrap(); + paint_white_blob(&mut session, [0.25, 0.5]); + + execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap(); + execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap(); + + assert!(mask_at(&session, layer, [0.75, 0.5]) > 0.95, "group {group}"); + } +} diff --git a/crates/engine/tests/it/mask_export.rs b/crates/engine/tests/it/mask_export.rs new file mode 100644 index 00000000..2af45d56 --- /dev/null +++ b/crates/engine/tests/it/mask_export.rs @@ -0,0 +1,146 @@ +//! `mask.export` and `Session::mask_bitmaps`: the evaluated mask as a bitmap at the texture +//! set's resolution, oriented like the exported textures. + +use std::path::PathBuf; + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::{NO_TRI, primitives}; +use texturecraft_engine::{Session, execute}; + +/// A new folder for one test's files. +fn temp_dir(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-mask-export-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A session of `mesh` with a fill layer whose mask is `value` wherever the mesh covers the texture. +fn session_with_mask(mesh: texturecraft_engine::geom::Mesh, name: &str, resolution: u32, value: f32) -> (Session, LayerId) { + let mut s = Session::new_project("t", mesh, name, None, resolution).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"value": value})).unwrap(); + s.update(); + (s, layer) +} + +fn covered(s: &Session, x: u32, y: u32) -> bool { + let g = &s.caches[0].gbuf; + g.tri[(y * g.width + x) as usize] != NO_TRI +} + +#[test] +fn the_bitmap_is_the_mask_the_composite_is_drawn_with_in_the_same_orientation() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap()); + + // A white layer gives output = base + (1 - base) * mask, so its mask can be recovered + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap(); + s.update(); + let base: Vec = (0..256 * 256).map(|i| s.caches[0].composite.value(Channel::BaseColor, i % 256, i / 256)[0]).collect(); + execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"procedural": "clouds", "seed": 3})).unwrap(); + s.update(); + + let bitmaps = s.mask_bitmaps(layer, true).unwrap(); + assert_eq!(bitmaps.len(), 1, "a classic set gives one bitmap"); + let bitmap = &bitmaps[0]; + assert_eq!((bitmap.tile, bitmap.width, bitmap.height), (None, 256, 256)); + assert_eq!(bitmap.values.len(), 256 * 256); + + let (mut covered_texels, mut distinct) = (0, std::collections::BTreeSet::new()); + for y in 0..256u32 { + for x in 0..256u32 { + let value = bitmap.values[(y * 256 + x) as usize]; + if !covered(&s, x, y) { + assert_eq!(value, 0.0, "uncovered texel ({x}, {y}) is black"); + continue; + } + + covered_texels += 1; + distinct.insert((value * 100.0) as u32); + let base = base[(y * 256 + x) as usize]; + let shown = s.caches[0].composite.value(Channel::BaseColor, x, y)[0]; + assert!((base + (1.0 - base) * value - shown).abs() < 3e-3, "texel ({x}, {y}): mask {value} does not give the composite {shown} over {base}"); + } + } + assert!(covered_texels > 1000, "the mesh covers part of the texture"); + assert!(distinct.len() > 20, "the mask varies across the texture, so a mirrored bitmap would not match the composite"); +} + +#[test] +fn inverting_changes_the_bitmap_and_a_switched_off_or_missing_mask_is_an_error() { + let (mut s, layer) = session_with_mask(primitives::material_ball(), "builtin:material_ball", 128, 0.25); + execute(&mut s, "mask.invert", &json!({"layer": layer.0})).unwrap(); + let bitmap = s.mask_bitmaps(layer, false).unwrap().remove(0); + let (x, y) = (0..128 * 128).map(|i| (i % 128, i / 128)).find(|&(x, y)| covered(&s, x, y)).unwrap(); + assert!((bitmap.values[(y * 128 + x) as usize] - 0.75).abs() < 1e-3, "inverting 0.25 gives 0.75"); + execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": false})).unwrap(); + assert!(s.mask_bitmaps(layer, false).is_err(), "a switched-off mask has nothing to export"); + execute(&mut s, "mask.remove", &json!({"layer": layer.0})).unwrap(); + assert!(s.mask_bitmaps(layer, false).is_err(), "so has a layer without a mask"); +} + +#[test] +fn mask_export_writes_a_16_bit_gray_png() { + let (mut s, layer) = session_with_mask(primitives::material_ball(), "builtin:material_ball", 128, 0.5); + let dir = temp_dir("png"); + let path = dir.join("ball_mask.png"); + let done = execute(&mut s, "mask.export", &json!({"layer": layer.0, "path": path.display().to_string()})).unwrap(); + assert_eq!(done["files"], json!([path.display().to_string()])); + + let image = image::open(&path).unwrap(); + assert!(matches!(image, image::DynamicImage::ImageLuma16(_)), "16-bit grayscale, got {:?}", image.color()); + let gray = image.into_luma16(); + assert_eq!(gray.dimensions(), (128, 128)); + let expected = s.mask_bitmaps(layer, true).unwrap().remove(0).gray16(); + assert_eq!(gray.as_raw(), &expected, "the file holds the bitmap, top row first"); + + // 0.5 is a level 8-bit files cannot hold exactly + assert!(gray.pixels().any(|p| p.0[0] == 32768), "the 16-bit level of 0.5"); + + // The extension is added, and the layer defaults to the selected one + let done = execute(&mut s, "mask.export", &json!({"path": dir.join("other").display().to_string()})).unwrap(); + assert_eq!(done["files"], json!([dir.join("other.png").display().to_string()])); + assert!(dir.join("other.png").exists()); + assert!(execute(&mut s, "mask.export", &json!({"layer": layer.0})).is_err(), "a path is required"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_tiled_set_exports_one_file_per_tile_at_each_tiles_size() { + let (mut s, layer) = session_with_mask(primitives::udim_plane(), "builtin:udim_plane", 256, 0.5); + execute(&mut s, "textureSet.tile.resolution", &json!({"ts": 0, "tile": 1002, "resolution": 128})).unwrap(); + s.update(); + let (width, height) = s.caches[0].size; + assert_eq!((width, height), (512, 256), "two blocks of the larger tile's size"); + + let bitmaps = s.mask_bitmaps(layer, true).unwrap(); + assert_eq!(bitmaps.iter().map(|b| (b.tile, b.width, b.height)).collect::>(), [(Some(1001), 256, 256), (Some(1002), 128, 128)]); + + // The smaller tile fills the top-left corner of its block + for (bitmap, block_x) in bitmaps.iter().zip([0, 256]) { + for y in 0..bitmap.height { + for x in 0..bitmap.width { + let expected = if covered(&s, block_x + x, y) { 0.5 } else { 0.0 }; + let value = bitmap.values[(y * bitmap.width + x) as usize]; + assert!((value - expected).abs() < 1e-3, "tile {:?} texel ({x}, {y}): {value}", bitmap.tile); + } + } + } + assert!(bitmaps.iter().all(|b| b.values.iter().any(|v| *v > 0.4)), "both tiles have mask"); + + let atlas = s.mask_bitmaps(layer, false).unwrap(); + assert_eq!(atlas.len(), 1); + assert_eq!((atlas[0].tile, atlas[0].width, atlas[0].height), (None, 512, 256), "the clipboard copy is the whole atlas"); + + let dir = temp_dir("tiles"); + let path = dir.join("plane_mask.png"); + let done = execute(&mut s, "mask.export", &json!({"layer": layer.0, "path": path.display().to_string()})).unwrap(); + assert_eq!(done["files"], json!([dir.join("plane_mask.1001.png").display().to_string(), dir.join("plane_mask.1002.png").display().to_string()])); + assert_eq!(image::open(dir.join("plane_mask.1001.png")).unwrap().into_luma16().dimensions(), (256, 256)); + assert_eq!(image::open(dir.join("plane_mask.1002.png")).unwrap().into_luma16().dimensions(), (128, 128)); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/tests/it/painter_gaps.rs b/crates/engine/tests/it/painter_gaps.rs index b1b7859d..37b8e601 100644 --- a/crates/engine/tests/it/painter_gaps.rs +++ b/crates/engine/tests/it/painter_gaps.rs @@ -3,7 +3,7 @@ //! maps from images and fill projection transforms, through engine commands. use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection}; +use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Source}; use texturecraft_engine::geom::NO_TRI; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; @@ -171,7 +171,8 @@ fn solo_keeps_one_material_channel() { #[test] fn decals_project_an_image_from_a_frame_placed_on_the_surface() { let mut s = session(); - // A red disc on a transparent background. + + // A red disc on a transparent background let name = s .import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] })) .unwrap(); @@ -184,9 +185,11 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert!(matches!(f.projection, Projection::Decal(_))); assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed"); assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there"); - // The image's transparent corners leave the surface as it was. + + // The image's transparent corners leave the surface as it was assert!(!red(at(&mut s, Channel::BaseColor, 200.0 + 30.0, 200.0 - 30.0))); - // Bigger, then moved along its plane, then re-placed with a click. + + // Bigger, then moved along its plane, then re-placed with a click execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap(); assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0))); execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap(); @@ -196,7 +199,8 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal"); - // Not a decal; one undo step per edit. + + // Not a decal; one undo step per edit let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err()); execute(&mut s, "edit.undo", &Value::Null).unwrap(); @@ -204,6 +208,106 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() { assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0))); } +/// The decal of mask fill effect `effect` +fn effect_decal(s: &Session, effect: LayerId) -> Decal { + let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &s.doc.project.effect(effect).unwrap().1.kind else { panic!("a decal fill effect") }; + *decal +} + +#[test] +fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let added = execute(&mut s, "layer.add.decal", &json!({"image": name, "channel": "mask", "x": 200, "y": 200, "size": 0.5})).unwrap(); + let (layer, effect) = (id(added.clone(), "layer"), id(added, "maskEffect")); + let layer_decal = id(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(), "layer"); + let before = effect_decal(&s, effect); + let steps = s.history_labels().len(); + + // Only the effect id, with no layer selected + s.selected.clear(); + assert!(s.selected_layer().is_none()); + let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap(); + assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported"); + let after = effect_decal(&s, effect); + assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0)); + assert_eq!(after.center, before.center, "the other fields stay"); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step per edit"); + + // Re-placing with a click + execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap(); + assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal"); + + // The layer decal is untouched by all of it + let LayerKind::Fill(f) = &s.doc.project.layer(layer_decal).unwrap().kind else { panic!("a fill layer") }; + assert!(matches!(&f.projection, Projection::Decal(d) if d.size[1] == 0.5 && d.rotation == 0.0)); + + // Errors: unknown effect, an effect that is not a decal, an effect of another layer + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err()); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); + let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect"); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err()); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err()); + assert_eq!(effect_decal(&s, effect), before); + + // A new image replaces the effect's source, not a layer channel + let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap(); + execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap(); + assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other)); +} + +#[test] +fn decals_keep_the_image_aspect_and_flip_their_image() { + let mut s = session(); + + // Twice as wide as tall, left half red and right half blue + let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap(); + let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(); + let layer = id(r.clone(), "layer"); + assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image"); + assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra"); + let size = |s: &mut Session| { + let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; + let Projection::Decal(d) = &f.projection else { panic!("a decal") }; + (d.size, d.flip) + }; + + // A pair of sides is taken as given, unless the proportions are kept: then the width wins + execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.6]); + execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect"); + execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width"); + execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap(); + execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step"); + + // Flip U and V each on their own, kept by later edits, undone one step at a time + execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0))); + let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap(); + assert_eq!(r["decal"]["flip"], json!([true, false])); + assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame"); + execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap(); + assert_eq!(size(&mut s).1, [true, true]); + execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap(); + assert_eq!(size(&mut s).1, [false, true], "the other flip stays"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(size(&mut s).1, [true, true]); + + // A new image in the same call sets the aspect: a tall one (1:2) + let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap(); + execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap(); + assert_eq!(size(&mut s).0, [0.2, 0.4]); +} + #[test] fn a_decal_takes_its_up_from_the_params_or_a_rule_that_never_degenerates() { let mut s = session(); @@ -616,7 +720,8 @@ fn directx_normal_images_flip_green() { assert!(fill(&mut s, json!({"normalFormat": "sideways"})).is_err()); assert!(fill(&mut s, json!({"image": name, "normalFormat": 1})).is_err(), "not a string"); assert!(fill(&mut s, json!({"value": [0.5, 0.5, 1.0], "normalFormat": "directX"})).is_err(), "not an image"); - // Marking an image on a channel that is off leaves it off. + + // Marking an image on a channel that is off leaves it off fill(&mut s, json!({"enabled": false})).unwrap(); fill(&mut s, json!({"normalFormat": "directX"})).unwrap(); assert!(!s.doc.project.layer(layer).unwrap().channels.contains_key(&Channel::Normal)); @@ -626,3 +731,189 @@ fn directx_normal_images_flip_green() { let old: texturecraft_engine::core::Source = serde_json::from_value(json!({"Image": {"name": "n"}})).unwrap(); assert_eq!(old, texturecraft_engine::core::Source::image("n")); } + +/// Red texels of the cube's -X face (turned away from where the decals are placed) whose position satisfies `inside` +fn red_on_minus_x(s: &mut Session, inside: impl Fn(f32, f32) -> bool) -> usize { + s.update(); + let cache = &s.caches[0]; + let (w, h) = cache.size; + (0..w * h) + .filter(|&i| { + let Some(surface) = cache.gbuf.surface(&s.mesh, i as usize) else { return false }; + surface.nrm.x < -0.99 && inside(surface.pos.y, surface.pos.z) && red(cache.composite.value(Channel::BaseColor, i % w, i / w)) + }) + .count() +} + +fn decal_of(s: &Session, layer: LayerId) -> texturecraft_engine::core::Decal { + let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; + let Projection::Decal(decal) = fill.projection else { panic!("a decal") }; + decal +} + +#[test] +fn a_decal_with_symmetry_also_covers_the_mirrored_side_and_follows_its_edits() { + use texturecraft_engine::core::{DecalFlip, DecalSymmetry}; + let mut s = Session::new_project("t", primitives::cube(2.0), "builtin:cube", None, 256).unwrap(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap(); + let place = json!({"image": name, "position": [1.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0], "up": [0.0, 1.0, 0.0], "size": 0.6}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + assert_eq!(decal_of(&s, layer).symmetry, None, "no copy unless asked for"); + assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0); + + assert!(execute(&mut s, "layer.decal.set", &json!({"symmetry": "w"})).is_err()); + assert!(execute(&mut s, "layer.decal.set", &json!({"symmetryFlip": "up"})).is_err()); + let depth = s.history_labels().len(); + let r = execute(&mut s, "layer.decal.set", &json!({"symmetry": "x", "symmetryFlip": "u"})).unwrap(); + assert_eq!(r["decal"]["symmetry"], json!({"axis": 0, "flip": "u"})); + assert_eq!(s.history_labels().len(), depth + 1, "one undo step"); + let centered = red_on_minus_x(&mut s, |y, z| y.abs() < 0.2 && z.abs() < 0.2); + assert!(centered > 20, "the mirrored copy shows opposite the decal: {centered}"); + + // The copy follows the decal when it moves (offset along its up) and when it grows + execute(&mut s, "layer.decal.set", &json!({"offset": [0.0, 0.5]})).unwrap(); + assert!(red_on_minus_x(&mut s, |y, _| y > 0.3) > 20, "moved up with the decal"); + assert_eq!(red_on_minus_x(&mut s, |y, _| y.abs() < 0.1), 0, "and left the middle"); + execute(&mut s, "layer.decal.set", &json!({"size": 1.6})).unwrap(); + assert!(red_on_minus_x(&mut s, |y, _| y.abs() < 0.1) > 20, "bigger with the decal"); + execute(&mut s, "layer.decal.set", &json!({"size": 0.6})).unwrap(); + + // A flip alone keeps the axis; off removes the copy + execute(&mut s, "layer.decal.set", &json!({"symmetryFlip": "v"})).unwrap(); + assert_eq!(decal_of(&s, layer).symmetry, Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.0 })); + execute(&mut s, "layer.decal.set", &json!({"symmetry": "z"})).unwrap(); + assert_eq!(decal_of(&s, layer).symmetry, Some(DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: 0.0 }), "a new axis keeps the flip"); + execute(&mut s, "layer.decal.set", &json!({"symmetry": "x"})).unwrap(); + + // The mirror plane's position is kept across axis changes, stays within the mesh and is saved + let r = execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 0.5})).unwrap(); + assert_eq!(r["decal"]["symmetry"]["offset"], json!(0.5)); + assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0, "a plane at x = 0.5 puts the copy out of reach of the -X face"); + let r = execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 9.0})).unwrap(); + assert_eq!(r["decal"]["symmetry"]["offset"], json!(1.0), "the cube is 2 wide: at most 1 from its center"); + assert_eq!(r["decal"]["symmetry"]["axis"], json!(0), "the axis is kept"); + execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 0.5})).unwrap(); + + // Saved with the project + let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project, s.doc.project); + assert_eq!(decal_of(&reopened, layer).symmetry, Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.5 })); + + // Ten edits since the copy was asked for: undoing them all leaves the decal as placed + for _ in 0..10 { + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + } + assert_eq!(decal_of(&s, layer).symmetry, None); + assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + assert!(red_on_minus_x(&mut s, |_, _| true) > 20, "redo brings the copy back"); + execute(&mut s, "layer.decal.set", &json!({"symmetry": "off"})).unwrap(); + assert_eq!(decal_of(&s, layer).symmetry, None); + assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0, "off: the other side is bare again"); + + // A decal can be added with a copy right away + let both = execute(&mut s, "layer.add.decal", &json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "symmetry": "y"})).unwrap(); + assert_eq!(both["decal"]["symmetry"], json!({"axis": 1, "flip": "none"}), "no offset is written while it is 0"); + let shifted = execute( + &mut s, + "layer.add.decal", + &json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "symmetry": "y", "symmetryOffset": -0.4}), + ) + .unwrap(); + assert!((shifted["decal"]["symmetry"]["offset"].as_f64().unwrap() + 0.4).abs() < 1e-6); +} + +/// A decal's up as the projection shows it: the stored up inside the surface plane. +fn plane_up(decal: &Value) -> texturecraft_engine::geom::glam::Vec3 { + use texturecraft_engine::geom::glam::Vec3; + let v = |key: &str| Vec3::new(decal[key][0].as_f64().unwrap() as f32, decal[key][1].as_f64().unwrap() as f32, decal[key][2].as_f64().unwrap() as f32); + let normal = v("normal").normalize(); + (v("up") - normal * normal.dot(v("up"))).normalize_or_zero() +} + +#[test] +fn a_decal_moved_onto_another_facing_surface_keeps_a_valid_frame_with_the_carried_up() { + use texturecraft_engine::geom::glam::Vec3; + let mut s = Session::new_project("t", primitives::cube(2.0), "builtin:cube", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + let name = s.import_resource_bytes("logo.png", png(8, 4, |_, _| [255, 0, 0, 255])).unwrap(); + + // On the +Z face, its up turned halfway between world X and Y, size and turn set by the user + let place = json!({"image": name, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [1.0, 1.0, 0.0], "size": [0.6, 0.3], "rotation": 25}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + + // Onto the +Y face: the up turns with the surface and follows the old up's direction in it + let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.2, 1.0, 0.1], "normal": [0.0, 1.0, 0.0]})).unwrap(); + let up = plane_up(&r["decal"]); + assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(Vec3::Y).abs() < 1e-4, "an up inside the +Y face: {up}"); + assert!(up.x > 0.5, "the old up's X side stays on the X side: {up}"); + assert_eq!(r["decal"]["rotation"], json!(25.0), "the user's turn stays"); + assert_eq!(r["decal"]["size"], json!([0.6_f32, 0.3_f32]), "and the size"); + + // Straight up the face with the old up along the new normal: no degenerate frame, nothing arbitrary + let r = + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0]})).unwrap(); + assert_eq!(plane_up(&r["decal"]), Vec3::Y); + let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0]})).unwrap(); + assert!((plane_up(&r["decal"]) - Vec3::NEG_Z).length() < 1e-4, "the up that pointed up the +Z face points away over the edge: {:?}", r["decal"]["up"]); + + // Onto the opposite face there is no smallest turn: the frame is still valid and follows the camera rule + let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, -1.0, 0.0], "normal": [0.0, -1.0, 0.0]})).unwrap(); + let up = plane_up(&r["decal"]); + assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(Vec3::Y).abs() < 1e-4, "{up}"); + + // An explicit up still wins + let r = + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [1.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0], "up": [0.0, 0.0, 1.0]})).unwrap(); + assert_eq!(plane_up(&r["decal"]), Vec3::Z); + let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "up": [0.0, 1.0, 0.0]})).unwrap(); + assert_eq!(plane_up(&r["decal"]), Vec3::Y, "an up without a move too"); +} + +#[test] +fn a_decal_dragged_over_the_sphere_never_flips_its_up_between_steps() { + use texturecraft_engine::geom::glam::Vec3; + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap(); + let place = json!({"image": name, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "size": 0.3}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + + // Over the pole (the old up lies along the normal there) and down the far side, in 5 degree steps + let mut last = Vec3::Y; + for step in 0..=72 { + let angle = (step as f32 * 5.0).to_radians(); + let normal = [0.0, angle.sin(), angle.cos()]; + let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": normal, "normal": normal, "merge": step > 0})).unwrap(); + let up = plane_up(&r["decal"]); + assert!((up.length() - 1.0).abs() < 1e-4, "step {step}: no frame at {normal:?}"); + assert!(up.dot(last) > 0.0, "step {step}: up turned from {last} to {up}"); + last = up; + } + + // The same drag through viewport points (what the 3D view sends), from the middle to the edge + for step in 0..25 { + let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "x": 200.0 + step as f32 * 2.0, "y": 200.0 - step as f32 * 2.0, "merge": true})) + .unwrap(); + let up = plane_up(&r["decal"]); + assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(last) > 0.0, "viewport step {step}: {last} to {up}"); + last = up; + } +} + +#[test] +fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited() { + let mut session = session(); + let image = session.import_resource_bytes("decal.png", png(4, 4, |_, _| [255; 4])).unwrap(); + let layer = id(execute(&mut session, "layer.add.decal", &json!({"image": image, "symmetry": "x"})).unwrap(), "layer"); + let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind else { panic!("expected fill") }; + let Projection::Decal(decal) = &mut fill.projection else { panic!("expected decal") }; + decal.symmetry.as_mut().unwrap().axis = u8::MAX; + let bytes = session.to_project_bytes().unwrap(); + + let mut loaded = Session::from_project_bytes(&bytes).unwrap(); + assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2); + + execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap(); + + assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2); +} diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs index bb4ea764..a17442bd 100644 --- a/crates/engine/tests/it/path_tool.rs +++ b/crates/engine/tests/it/path_tool.rs @@ -709,3 +709,124 @@ fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() { assert_eq!(session.doc.project, before.project); assert_eq!(session.doc.pixels.layers, before.pixels.layers); } + +const SQUARE_UV: [[f32; 2]; 4] = [[0.2, 0.2], [0.8, 0.2], [0.8, 0.8], [0.2, 0.8]]; + +/// A closed path of corner points runs straight along its edges; the smooth one bulges past them +#[test] +fn corner_points_make_a_path_with_straight_edges() { + let mut s = session(wall()); + execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "closed": true, "commit": true})).unwrap(); + assert!(red_uv(&s, 0.5, 0.125), "a smooth closed path bulges outside the square's edge"); + assert!(!red_uv(&s, 0.5, 0.2)); + + let mut s = session(wall()); + execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, true, true, true], "closed": true, "commit": true})).unwrap(); + assert!(red_uv(&s, 0.5, 0.2) && red_uv(&s, 0.8, 0.5) && red_uv(&s, 0.5, 0.8) && red_uv(&s, 0.2, 0.5), "the edges are straight"); + assert!(!red_uv(&s, 0.5, 0.125) && !red_uv(&s, 0.875, 0.5), "no bulge past the edges"); + + // The fill of a corner path is the quadrilateral too + let mut s = session(wall()); + execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, true, true, true], "closed": true, "fill": true, "commit": true})).unwrap(); + assert!(red_uv(&s, 0.5, 0.21) && !red_uv(&s, 0.5, 0.15)); + + assert!(execute(&mut s, "tool.path", &json!({"corners": [true, 3]})).is_err()); +} + +#[test] +fn invalid_corner_flags_leave_the_current_curve_unchanged() { + let mut session = session(wall()); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "corners": [true, false, true]})).unwrap(); + let before = session.tool.path.clone(); + + assert!(execute(&mut session, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, 3]})).is_err()); + assert_eq!(session.tool.path, before, "malformed flags leave the curve intact"); + + assert!(execute(&mut session, "tool.path", &json!({"corners": [true, true, true, true]})).is_err()); + assert_eq!(session.tool.path, before, "extra flags cannot outlive their points"); +} + +/// Toggling a corner repaints the edited path, is one undo step that also restores the pixels, and is saved with the project +#[test] +fn toggling_a_corner_is_one_undo_step_and_is_saved() { + let mut s = session(wall()); + let report = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut s, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let smooth_pixels = s.doc.pixels.clone(); + let history = s.history_labels().len(); + assert!(s.paths(effect).unwrap()[0].corners.is_empty()); + assert!(execute(&mut s, "path.corner", &json!({"index": 3})).is_err(), "no such point"); + assert!(execute(&mut s, "path.corner", &json!({})).is_err(), "no point selected"); + + let report = execute(&mut s, "path.corner", &json!({"index": 1})).unwrap(); + assert_eq!(report["corner"], true); + assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]); + assert_ne!(s.doc.pixels.layers, smooth_pixels.layers, "the sharp turn repaints the path"); + let corner_pixels = s.doc.pixels.clone(); + assert_eq!(s.history_labels().len(), history + 1); + + // Saved: the flags survive a project round trip + let saved = serde_json::to_string(&s.doc.project).unwrap(); + let loaded: texturecraft_engine::core::Project = serde_json::from_str(&saved).unwrap(); + s.doc.project = loaded; + assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]); + + // One undo returns to the smooth curve and its pixels, one redo to the corner + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.tool.path.corners.is_empty() && !s.tool.path.is_corner(1)); + assert!(s.paths(effect).unwrap()[0].corners.is_empty()); + assert_eq!(s.doc.pixels.layers, smooth_pixels.layers); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]); + assert_eq!(s.doc.pixels.layers, corner_pixels.layers); + + // The selected point toggles back to smooth; the stored flags are empty again + s.select_path_point(1); + let report = execute(&mut s, "path.corner", &json!({})).unwrap(); + assert_eq!(report["corner"], false); + assert!(s.paths(effect).unwrap()[0].corners.is_empty(), "an all-smooth path is stored like an old one"); + assert_eq!(s.doc.pixels.layers, smooth_pixels.layers); +} + +/// Inserting and removing points keeps the corner flags on their points +#[test] +fn corner_flags_follow_their_points_when_points_are_inserted_or_removed() { + let mut s = session(wall()); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "corners": [false, true, false]})).unwrap(); + s.insert_path_corner(1, Vec3::new(0.35, 0.5, 0.0)).unwrap(); + assert_eq!(s.tool.path.corner_flags(), vec![false, true, true, false]); + s.insert_path_point(0, Vec3::new(0.1, 0.1, 0.0)).unwrap(); + assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, true, false]); + s.select_path_point(2); + s.remove_selected_path_point(); + assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false]); + s.append_path_point(Vec3::new(0.9, 0.9, 0.0), true).unwrap(); + assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, false]); + assert!(s.toggle_selected_path_corner(), "the appended point is selected"); + assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, true]); + + // Undo steps through each change with its flags + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, false]); +} + +/// A path saved before corner points existed has no `corners` key: it loads smooth and unchanged +#[test] +fn paths_saved_without_corner_flags_load_smooth() { + let mut s = session(wall()); + let report = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + let stored = s.paths(effect).unwrap()[0].clone(); + let mut json = serde_json::to_value(&stored).unwrap(); + assert!(json.get("corners").is_none(), "a smooth path writes the same JSON as before"); + json.as_object_mut().unwrap().remove("corners"); + let old: texturecraft_engine::core::PathShape = serde_json::from_value(json).unwrap(); + assert_eq!(old, stored); + + let pixels = s.doc.pixels.clone(); + execute(&mut s, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + assert!(s.tool.path.corners.is_empty()); + assert!(!s.path_live().unwrap(), "a loaded smooth path matches what is stored"); + assert_eq!(s.doc.pixels.layers, pixels.layers); +} diff --git a/crates/engine/tests/it/solo.rs b/crates/engine/tests/it/solo.rs new file mode 100644 index 00000000..202df7aa --- /dev/null +++ b/crates/engine/tests/it/solo.rs @@ -0,0 +1,152 @@ +//! Solo: a view-only preview of one layer. The composite shows that layer alone (optionally at +//! full coverage); saving, exporting and the history never see it. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, Solo, execute}; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap(); + s.update(); + s +} + +fn add_fill(s: &mut Session, color: [f32; 3], roughness: f32) -> LayerId { + let r = execute(s, "layer.add.fill", &json!({"color": color, "roughness": roughness})).unwrap(); + LayerId(r["layer"].as_u64().unwrap()) +} + +/// A red fill below a green fill that a black mask hides everywhere, and the green one. +fn masked_stack() -> (Session, LayerId, LayerId) { + let mut s = session(); + let red = add_fill(&mut s, [1.0, 0.0, 0.0], 0.2); + let green = add_fill(&mut s, [0.0, 1.0, 0.0], 0.8); + execute(&mut s, "mask.add.black", &json!({"layer": green.0})).unwrap(); + s.update(); + (s, red, green) +} + +/// A texel the mesh covers. +fn covered(s: &Session) -> (u32, u32) { + let g = &s.caches[0].gbuf; + let i = g.tri.iter().position(|t| *t != texturecraft_engine::geom::NO_TRI).unwrap(); + (i as u32 % g.width, i as u32 / g.width) +} + +fn base(s: &mut Session) -> [f32; 3] { + s.update(); + let (x, y) = covered(s); + s.caches[0].composite.value(Channel::BaseColor, x, y) +} + +fn close(a: [f32; 3], b: [f32; 3]) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < 2e-3) +} + +#[test] +fn solo_shows_only_that_layer_and_ignoring_the_mask_shows_it_everywhere() { + let (mut s, red, green) = masked_stack(); + assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the black mask hides the green layer"); + + s.set_solo(Some(Solo { layer: green, ignore_mask: false })); + assert!(close(base(&mut s), Channel::BaseColor.default_value()), "alone and masked away: nothing is left"); + s.set_solo(Some(Solo { layer: green, ignore_mask: true })); + assert!(close(base(&mut s), [0.0, 1.0, 0.0]), "the mask is ignored: the whole material shows"); + s.set_solo(Some(Solo { layer: red, ignore_mask: true })); + assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the other layer alone"); +} + +#[test] +fn the_solo_composite_equals_the_layer_alone_without_its_mask() { + let (mut s, _, green) = masked_stack(); + s.set_solo(Some(Solo { layer: green, ignore_mask: true })); + s.update(); + + // The same layer in a project of its own, without mask and without the layer below + let mut alone = session(); + add_fill(&mut alone, [0.0, 1.0, 0.0], 0.8); + alone.update(); + assert!(s.caches[0].composite == alone.caches[0].composite, "every channel, every texel"); +} + +#[test] +fn the_solo_changes_neither_the_document_nor_the_history_nor_the_saved_file() { + let (mut s, _, green) = masked_stack(); + let (project, labels, saved) = + (s.doc.project.clone(), s.history_labels(), Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.project); + s.set_solo(Some(Solo { layer: green, ignore_mask: true })); + s.update(); + assert_eq!(s.doc.project, project); + assert_eq!(s.history_labels(), labels); + assert_eq!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.project, saved, "the file holds every layer and the mask"); +} + +#[test] +fn exports_hold_the_whole_stack_while_a_layer_is_soloed_and_the_solo_stays() { + let (mut s, _, green) = masked_stack(); + let opts = texturecraft_engine::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap(); + let whole = s.export_files(&[0], &opts).unwrap(); + s.set_solo(Some(Solo { layer: green, ignore_mask: true })); + s.update(); + let revision = s.caches[0].revision; + let soloed = s.export_files(&[0], &opts).unwrap(); + assert_eq!(s.pending_tiles(), 0, "export leaves the viewport cache ready to draw"); + assert_eq!(s.caches[0].revision, revision); + assert_eq!(soloed.len(), whole.len()); + assert!(soloed.iter().zip(&whole).all(|(a, b)| a.name == b.name && a.bytes == b.bytes), "the files are the whole stack's"); + assert_eq!(s.solo, Some(Solo { layer: green, ignore_mask: true }), "the view keeps showing the solo"); + assert!(close(base(&mut s), [0.0, 1.0, 0.0]), "and the viewport composite is the solo again"); +} + +#[test] +fn turning_the_solo_off_restores_the_original_composite() { + let (mut s, _, green) = masked_stack(); + let before = s.caches[0].composite.clone(); + s.set_solo(Some(Solo { layer: green, ignore_mask: true })); + s.update(); + assert!(s.caches[0].composite != before); + s.set_solo(None); + s.update(); + assert!(s.caches[0].composite == before); +} + +#[test] +fn edits_while_soloed_show_in_the_solo_and_in_the_whole_stack_afterwards() { + let (mut s, red, _) = masked_stack(); + s.set_solo(Some(Solo { layer: red, ignore_mask: false })); + s.update(); + execute(&mut s, "layer.fill.set", &json!({"layer": red.0, "channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + assert!(close(base(&mut s), [0.0, 0.0, 1.0]), "the edited layer, alone"); + s.set_solo(None); + assert!(close(base(&mut s), [0.0, 0.0, 1.0]), "the stack still hides the green layer behind its mask: blue shows"); +} + +#[test] +fn removing_the_soloed_layer_ends_the_solo() { + let (mut s, _, green) = masked_stack(); + s.set_solo(Some(Solo { layer: green, ignore_mask: true })); + execute(&mut s, "layer.remove", &json!({"layer": green.0})).unwrap(); + s.update(); + assert_eq!(s.solo, None); + assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the whole stack again"); +} + +#[test] +fn the_view_solo_command_sets_reports_and_ends_the_solo() { + let (mut s, _, green) = masked_stack(); + let r = execute(&mut s, "view.solo", &json!({"layer": green.0, "ignoreMask": true})).unwrap(); + assert_eq!(r, json!({"layer": green.0, "ignoreMask": true})); + assert_eq!(texturecraft_engine::inspect::session(&s)["solo"], json!({"layer": green.0, "ignoreMask": true})); + + // The selected layer is the default + execute(&mut s, "view.solo", &json!({"layer": null})).unwrap(); + assert_eq!(s.solo, None); + execute(&mut s, "layer.select", &json!({"layer": green.0})).unwrap(); + let r = execute(&mut s, "view.solo", &json!({})).unwrap(); + assert_eq!(r, json!({"layer": green.0, "ignoreMask": false})); + assert!(execute(&mut s, "view.solo", &json!({"layer": 999_999})).is_err()); + assert_eq!(texturecraft_engine::inspect::session(&s)["solo"]["layer"], json!(green.0)); + execute(&mut s, "view.solo", &json!({"layer": null})).unwrap(); + assert_eq!(texturecraft_engine::inspect::session(&s)["solo"], Value::Null); +} diff --git a/crates/engine/tests/it/symmetry.rs b/crates/engine/tests/it/symmetry.rs index 6beb03cc..b5ae6c36 100644 --- a/crates/engine/tests/it/symmetry.rs +++ b/crates/engine/tests/it/symmetry.rs @@ -1,6 +1,6 @@ //! Symmetry around a moved plane or axis, driven through engine commands the way agents paint -use serde_json::json; +use serde_json::{Value, json}; use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; use texturecraft_engine::geom::{Mesh, primitives}; @@ -281,3 +281,174 @@ fn disabling_symmetry_paints_only_the_source_and_keeps_the_settings() { assert_eq!(session.tool.brush.symmetry, settings); } } + +/// Base color of the composite at the surface point under world `point` +fn color_at(session: &Session, point: Vec3) -> [f32; 3] { + let hit = session.pick(screen(session, point), session.viewport).unwrap(); + session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32) +} + +/// A red dab at `x` (and its mirror image with symmetry on), then a smudge stroke from `x` along `step` pixels per sample. Returns the strokes' surface points +fn smudge_a_red_dab(session: &mut Session, symmetry: bool, x: f32, step: f32) -> (Vec3, Vec3) { + execute(session, "tool.brush", &json!({"size": 12, "hardness": 90, "symmetryX": symmetry})).unwrap(); + execute(session, "tool.stroke", &json!({"points": [[x, 200.0]]})).unwrap(); + session.update(); + let (dragged_to, mirrored_to) = (surface(session, x + 35.0 * step, 200.0), surface(session, 400.0 - x - 35.0 * step, 200.0)); + execute(session, "tool.smudge", &Value::Null).unwrap(); + execute(session, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap(); + let points: Vec<[f32; 2]> = (0..=40).map(|i| [x + i as f32 * step, 200.0]).collect(); + execute(session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + (dragged_to, mirrored_to) +} + +#[test] +fn smudge_drags_the_mirrored_spot_equally() { + let mut session = session(primitives::cube(2.0)); + let (right, left) = smudge_a_red_dab(&mut session, true, 240.0, 1.0); + assert!(right.x > 0.0 && left.x < 0.0 && (right.x + left.x).abs() < 1e-3, "{right:?} {left:?}"); + let (on_source, on_copy) = (color_at(&session, right), color_at(&session, left)); + assert!(on_source[0] - on_source[1] > 0.2, "the stroke drags red along +X: {on_source:?}"); + for channel in 0..3 { + assert!((on_source[channel] - on_copy[channel]).abs() < 0.1, "the copy drags the same on -X: {on_source:?} vs {on_copy:?}"); + } +} + +#[test] +fn smudge_without_symmetry_leaves_the_mirrored_spot_alone() { + let mut session = session(primitives::cube(2.0)); + let (right, left) = smudge_a_red_dab(&mut session, false, 240.0, 1.0); + let (on_source, on_far_side) = (color_at(&session, right), color_at(&session, left)); + assert!(on_source[0] - on_source[1] > 0.2, "the stroke drags red along +X: {on_source:?}"); + assert!(on_far_side[0] - on_far_side[1] < 0.05, "nothing on the mirrored spot: {on_far_side:?}"); +} + +/// Is the composite red at texture coordinate `uv`? +fn red_at_uv(session: &Session, uv: Vec2) -> bool { + let color = session.caches[0].composite.value(Channel::BaseColor, (uv.x * TEXTURE_SIZE) as u32, (uv.y * TEXTURE_SIZE) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +/// Texture coordinate of the surface a ray from `from` along `direction` hits first +fn uv_hit(session: &Session, from: Vec3, direction: Vec3) -> Vec2 { + let hit = session.bvh.closest(from, direction, f32::MAX).unwrap(); + texturecraft_engine::geom::surface_at(&session.mesh, hit.tri, hit.u, hit.v).unwrap().uv +} + +/// A stroke of one dab in the 2D view at `uv` +fn dab_uv(session: &mut Session, uv: Vec2) { + execute(session, "tool.strokeUv", &json!({"points": [[uv.x, uv.y]]})).unwrap(); + session.update(); +} + +#[test] +fn a_2d_dab_paints_its_copy_where_the_3d_stroke_paints_it() { + let brush = json!({"size": 1, "symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]}); + + // Paint one surface point in the 3D view + let mut in_3d = session(wall()); + execute(&mut in_3d, "tool.brush", &brush).unwrap(); + let hit = in_3d.pick(Vec2::new(300.0, 200.0), in_3d.viewport).unwrap(); + execute(&mut in_3d, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap(); + in_3d.update(); + + // Paint its UV in the 2D view + let mut in_2d = session(wall()); + execute(&mut in_2d, "tool.brush", &brush).unwrap(); + dab_uv(&mut in_2d, hit.uv); + + let mirrored = Vec3::new(0.5 - hit.pos.x, hit.pos.y, hit.pos.z); + for (name, session) in [("3D", &in_3d), ("2D", &in_2d)] { + assert!(red_at(session, hit.pos), "the dab in {name}"); + assert!(red_at(session, mirrored), "its copy across x = 0.25 in {name}"); + assert!(!red_at(session, Vec3::new(-hit.pos.x, hit.pos.y, hit.pos.z)), "nothing across the mesh center in {name}"); + } +} + +#[test] +fn a_2d_dab_on_the_cube_paints_the_opposite_face() { + let mut session = session(primitives::cube(2.0)); + execute(&mut session, "tool.brush", &json!({"size": 1, "symmetryX": true})).unwrap(); + + let right = uv_hit(&session, Vec3::new(5.0, 0.3, 0.2), Vec3::NEG_X); + dab_uv(&mut session, right); + + assert!(red_at_uv(&session, right), "the dab"); + assert!(red_at_uv(&session, uv_hit(&session, Vec3::new(-5.0, 0.3, 0.2), Vec3::X)), "its copy on the left face, at the mirrored point"); + assert!(!red_at_uv(&session, uv_hit(&session, Vec3::new(-5.0, -0.3, 0.2), Vec3::X)), "not elsewhere on the left face"); + assert!(!red_at_uv(&session, uv_hit(&session, Vec3::new(0.3, 5.0, 0.2), Vec3::NEG_Y)), "not on the top face"); +} + +#[test] +fn a_2d_dab_with_four_radial_copies_paints_three_more() { + let mut session = session(wall()); + execute(&mut session, "tool.brush", &json!({"size": 1, "symmetryRadial": 4, "symmetryAxis": "z"})).unwrap(); + let hit = session.pick(Vec2::new(290.0, 160.0), session.viewport).unwrap(); + + dab_uv(&mut session, hit.uv); + + let at = hit.pos; + assert!(red_at(&session, at), "the dab"); + for (name, point) in + [("a quarter turn", Vec3::new(-at.y, at.x, 0.0)), ("a half turn", Vec3::new(-at.x, -at.y, 0.0)), ("three quarters", Vec3::new(at.y, -at.x, 0.0))] + { + assert!(red_at(&session, point), "the copy {name} around Z"); + } + assert!(!red_at(&session, Vec3::new(at.x, -at.y, 0.0)), "no mirrored copy"); + let painted = (0..TEXTURE_SIZE as u32).flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }); + let mut blobs: Vec<(u32, u32)> = Vec::new(); + for (x, y) in painted { + if !blobs.iter().any(|&(bx, by)| bx.abs_diff(x) < 16 && by.abs_diff(y) < 16) { + blobs.push((x, y)); + } + } + assert_eq!(blobs.len(), 4, "the dab and three copies, no more"); +} + +#[test] +fn a_2d_dab_paints_no_copy_with_symmetry_off() { + let mut session = session(wall()); + let hit = session.pick(Vec2::new(300.0, 200.0), session.viewport).unwrap(); + let mirrored = Vec3::new(-hit.pos.x, hit.pos.y, hit.pos.z); + + execute(&mut session, "tool.brush", &json!({"size": 1})).unwrap(); + dab_uv(&mut session, hit.uv); + assert!(red_at(&session, hit.pos), "the dab"); + assert!(!red_at(&session, mirrored), "no copy without symmetry"); + + // The toolbar toggle off keeps the settings but paints no copies + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOn": false})).unwrap(); + dab_uv(&mut session, hit.uv); + assert!(!red_at(&session, mirrored), "no copy with the toggle off"); +} + +#[test] +fn a_2d_smudge_with_symmetry_drags_both_sides_alike_at_the_mirror_plane() { + let mut session = session(wall()); + let uv = |session: &Session, x: f32| uv_hit(session, Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z); + let color = |session: &Session, uv: Vec2| session.caches[0].composite.value(Channel::BaseColor, (uv.x * TEXTURE_SIZE) as u32, (uv.y * TEXTURE_SIZE) as u32); + + // A red dab next to the mirror plane (and its copy on the other side), then a smudge away from the plane + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90, "symmetryX": true})).unwrap(); + let start = uv(&session, 0.05); + dab_uv(&mut session, start); + execute(&mut session, "tool.smudge", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "smudgeStrength": 100, "spacing": 5})).unwrap(); + let end = uv(&session, 0.4); + let points: Vec<[f32; 2]> = (0..=40).map(|i| start + (end - start) * (i as f32 / 40.0)).map(|p| [p.x, p.y]).collect(); + execute(&mut session, "tool.strokeUv", &json!({"points": points})).unwrap(); + session.update(); + + // The copies overlap at the plane; each drags its own trail, so both sides end up mirror images + let dragged = color(&session, uv(&session, 0.2)); + assert!(dragged[0] - dragged[1] > 0.1, "the smudge drags red away from the plane: {dragged:?}"); + for x in [0.01, 0.03, 0.05, 0.08, 0.12, 0.2, 0.3] { + let (right, left) = (color(&session, uv(&session, x)), color(&session, uv(&session, -x))); + for channel in 0..3 { + assert!((right[channel] - left[channel]).abs() < 0.03, "x = ±{x}: {right:?} vs {left:?}"); + } + } +} diff --git a/crates/engine/tests/it/tile_generator.rs b/crates/engine/tests/it/tile_generator.rs new file mode 100644 index 00000000..fc62ca2a --- /dev/null +++ b/crates/engine/tests/it/tile_generator.rs @@ -0,0 +1,320 @@ +//! The Tile Generator pattern and pattern resolutions through engine commands + +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + Channel, EffectKind, LayerId, LayerKind, Procedural, ProceduralKind, Projection, ResolutionMode, Source, TileGenerator, TileShape, +}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap() +} + +/// A fill layer whose base color reads the Tile Generator, and its id +fn tile_fill(session: &mut Session) -> u64 { + let layer = execute(session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + execute(session, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "Tile Generator"})).unwrap(); + layer +} + +fn base_color_pattern(session: &Session, layer: u64) -> Procedural { + let LayerKind::Fill(fill) = &session.doc.project.layer(LayerId(layer)).unwrap().kind else { panic!("not a fill layer") }; + let Source::Procedural { pattern, .. } = fill.source(Channel::BaseColor) else { panic!("the base color is not a pattern") }; + pattern +} + +fn tile(pattern: &Procedural) -> TileGenerator { + pattern.tile.as_deref().cloned().unwrap() +} + +/// A mask fill effect reading a uniform value, on a fresh fill layer's black mask +fn mask_fill(session: &mut Session) -> u64 { + execute(session, "layer.add.fill", &Value::Null).unwrap(); + execute(session, "mask.add.black", &Value::Null).unwrap(); + execute(session, "effect.add.fill", &json!({"value": 1.0})).unwrap()["effect"].as_u64().unwrap() +} + +fn mask_pattern(session: &Session, effect: u64) -> Procedural { + let Some((_, effect)) = session.doc.project.effect(LayerId(effect)) else { panic!("no effect {effect}") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, .. } = &effect.kind else { panic!("the mask fill reads no pattern") }; + pattern.clone() +} + +#[test] +fn a_new_tile_generator_starts_from_the_reference_defaults() { + let mut session = session(); + let layer = tile_fill(&mut session); + + let pattern = base_color_pattern(&session, layer); + assert_eq!(pattern.kind, ProceduralKind::TileGenerator); + assert_eq!(tile(&pattern), TileGenerator::default()); + assert_eq!(pattern.scale, 1.0, "the tile counts set its frequency: the grid covers one repeat of the projection"); +} + +#[test] +fn tile_settings_alone_edit_the_channels_pattern() { + let mut session = session(); + let layer = tile_fill(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [4, 2], "shape": "Half bell", "offset": 0.5}})).unwrap(); + + let tile = tile(&base_color_pattern(&session, layer)); + assert_eq!(tile.amount, [4, 2]); + assert_eq!(tile.shape, TileShape::HalfBell, "a menu choice is taken by its label"); + assert_eq!(tile.offset, 0.5); + assert_eq!(tile.specific, TileGenerator::default().specific, "settings not named keep their value"); +} + +#[test] +fn tile_settings_with_a_seed_edit_both() { + let mut session = session(); + let layer = tile_fill(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [3, 3]}, "seed": 9, "invert": true})).unwrap(); + + let pattern = base_color_pattern(&session, layer); + assert_eq!(tile(&pattern).amount, [3, 3]); + assert_eq!((pattern.seed, pattern.invert), (9, true), "the seed and invert beside a tile setting are applied, not dropped"); +} + +#[test] +fn picking_the_tile_generator_again_keeps_its_settings() { + let mut session = session(); + let layer = tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [3, 3]}, "resolution": "custom", "customResolution": 128})) + .unwrap(); + + // The panel's scale and seed edits send the pattern again with its kind + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "Tile Generator", "seed": 9})).unwrap(); + + let pattern = base_color_pattern(&session, layer); + assert_eq!(pattern.seed, 9); + assert_eq!(tile(&pattern).amount, [3, 3]); + assert_eq!((pattern.resolution.mode, pattern.resolution.custom), (ResolutionMode::Custom, 128)); +} + +#[test] +fn hostile_tile_settings_are_brought_into_range() { + let mut session = session(); + let layer = tile_fill(&mut session); + + execute( + &mut session, + "layer.fill.set", + &json!({"channel": "baseColor", "tile": {"amount": [0, 999], "specific": -5.0, "shapeTiling": 400, "rotation": 450.0, "shapeResolution": [3, 100000]}}), + ) + .unwrap(); + + let tile = tile(&base_color_pattern(&session, layer)); + assert_eq!(tile.amount, [1, 64]); + assert_eq!(tile.specific, 0.0); + assert_eq!(tile.shape_tiling, 16); + assert_eq!(tile.rotation, 90.0, "angles wrap around the turn"); + assert_eq!(tile.shape_resolution, [256, 4096]); +} + +#[test] +fn unknown_or_misplaced_tile_settings_are_errors() { + let mut session = session(); + tile_fill(&mut session); + + let unknown = execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"colour": 0.5}})); + assert!(unknown.unwrap_err().to_string().contains("colour"), "the unknown setting is named"); + let bad_shape = execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Hexagon"}})); + assert!(bad_shape.is_err()); + + execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "procedural": "Clouds"})).unwrap(); + let on_clouds = execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "tile": {"offset": 0.5}})); + assert!(on_clouds.is_err(), "tile settings go with the Tile Generator only"); + let no_pattern = execute(&mut session, "layer.fill.set", &json!({"channel": "metallic", "tile": {"offset": 0.5}})); + assert!(no_pattern.is_err(), "a uniform channel has no pattern to edit"); +} + +#[test] +fn a_mask_fill_picks_and_edits_a_pattern_with_effect_set() { + let mut session = session(); + let effect = mask_fill(&mut session); + + execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap(); + execute(&mut session, "effect.set", &json!({"effect": effect, "tile": {"checkerMask": true}, "seed": 4})).unwrap(); + + let pattern = mask_pattern(&session, effect); + assert!(tile(&pattern).checker_mask); + assert_eq!(pattern.seed, 4); + + execute(&mut session, "effect.set", &json!({"effect": effect, "tileDefaults": true})).unwrap(); + assert_eq!(tile(&mask_pattern(&session, effect)), TileGenerator::default(), "Restore defaults puts every tile setting back"); + + // Only an explicit uniform pick replaces an active pattern + execute(&mut session, "effect.set", &json!({"effect": effect, "value": 0.3})).unwrap(); + assert_eq!(mask_pattern(&session, effect).kind, ProceduralKind::TileGenerator); + + execute(&mut session, "effect.set", &json!({"effect": effect, "uniform": 0.3})).unwrap(); + let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; + assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "a uniform pick reads the value again"); +} + +#[test] +fn a_uniform_pick_outranks_pattern_edits_on_a_mask_fill() { + let mut session = session(); + let effect = mask_fill(&mut session); + execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "uniform": 0.3, "seed": 4})).unwrap(); + + let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; + assert!(matches!(&edited.kind, EffectKind::Fill { source: Source::Uniform(value), .. } if *value == [0.3; 3]), "the fill reads the value, not the pattern"); +} + +/// A fill effect's `scale` is also its projection's: while it reads a pattern, the pattern takes it +#[test] +fn a_pattern_scale_edit_leaves_the_mask_fills_projection_alone() { + let mut session = session(); + let effect = mask_fill(&mut session); + execute(&mut session, "effect.set", &json!({"effect": effect, "procedural": "Tile Generator"})).unwrap(); + + execute(&mut session, "effect.set", &json!({"effect": effect, "scale": 3.0})).unwrap(); + + let Some((_, edited)) = session.doc.project.effect(LayerId(effect)) else { panic!("the mask fill is gone") }; + let EffectKind::Fill { source: Source::Procedural { pattern, .. }, projection } = &edited.kind else { panic!("the fill reads a pattern") }; + assert_eq!(pattern.scale, 3.0); + assert_eq!(*projection, Projection::default(), "the projection keeps its scale"); +} + +#[test] +fn a_mask_fill_added_with_tile_settings_keeps_them() { + let mut session = session(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + + let added = execute(&mut session, "effect.add.fill", &json!({"procedural": "Tile Generator", "tile": {"amount": [6, 6]}, "resolutionFactor": -2})).unwrap(); + + let pattern = mask_pattern(&session, added["effect"].as_u64().unwrap()); + assert_eq!(tile(&pattern).amount, [6, 6]); + assert_eq!(pattern.resolution.factor, -2); +} + +#[test] +fn inspect_reports_the_tile_settings_and_a_patterns_resolution() { + let mut session = session(); + tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"amount": [5, 7]}, "resolution": "textureSet"})).unwrap(); + + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspected.contains("\"amount\":[5,7]"), "the settings are reported: {inspected}"); + assert!(inspected.contains("\"randomMask\""), "under the camelCase names the commands take"); + assert!(inspected.contains("\"mode\":\"TextureSet\""), "the pattern's resolution is reported"); +} + +/// Imports a small gray PNG as resource `name` and returns its resource name +fn import_gray(session: &mut Session, name: &str) -> String { + let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255])); + let mut bytes = Vec::new(); + image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes(name, bytes).unwrap() +} + +#[test] +fn removing_unused_resources_keeps_the_images_a_tile_generator_reads() { + let mut session = session(); + let input = import_gray(&mut session, "vent.png"); + let background = import_gray(&mut session, "plate.png"); + let unused = import_gray(&mut session, "unused.png"); + tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "backgroundImage": background}})) + .unwrap(); + + execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + assert!(session.doc.resources.contains_key(&input), "the pattern input is still read"); + assert!(session.doc.resources.contains_key(&background), "the background image is still read"); + assert!(!session.doc.resources.contains_key(&unused)); +} + +/// The composited base color of every texel of the texture set +fn base_colors(session: &mut Session) -> Vec { + session.update(); + let composite = &session.caches[0].composite; + let size = composite.resolution; + (0..size * size).map(|texel| composite.value(Channel::BaseColor, texel % size, texel / size)[0]).collect() +} + +#[test] +fn the_compositor_draws_a_tile_generators_image_input() { + let mut session = session(); + let input = import_gray(&mut session, "plate.png"); + tile_fill(&mut session); + + // One tile with no gap: the image covers the whole texture + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "amount": [1, 1]}})).unwrap(); + + let colors = base_colors(&mut session); + let mid_gray = colors.iter().filter(|value| (**value - 0.5).abs() < 0.05).count(); + assert!(mid_gray > colors.len() / 2, "the image's gray reaches the texture, not an empty shape: {mid_gray} of {}", colors.len()); +} + +#[test] +fn importing_the_image_a_tile_generator_names_redraws_it() { + let mut session = session(); + tile_fill(&mut session); + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": ["plate.png"], "amount": [1, 1]}})).unwrap(); + let before = base_colors(&mut session); + + assert_eq!(import_gray(&mut session, "plate.png"), "plate.png"); + let after = base_colors(&mut session); + + assert_ne!(before, after, "the image that arrived later reaches the texture"); +} + +#[test] +fn a_coarser_pattern_resolution_changes_the_composite() { + let mut session = session(); + tile_fill(&mut session); + let exact = base_colors(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "resolutionFactor": -3})).unwrap(); + let coarse = base_colors(&mut session); + let changed = exact.iter().zip(&coarse).filter(|(exact, coarse)| (**exact - **coarse).abs() > 0.05).count(); + assert!(changed > 0, "an eighth of the resolution blurs the bricks' bevels"); +} + +#[test] +fn a_tile_generator_gradient_map_reads_the_image_input() { + let mut session = session(); + let input = import_gray(&mut session, "plate.png"); + tile_fill(&mut session); + let colors = [[0.0; 3], [1.0, 0.0, 0.0]]; + execute( + &mut session, + "layer.fill.set", + &json!({"channel": "baseColor", "tile": {"shape": "Image", "inputs": [input], "amount": [1, 1]}, "colors": colors}), + ) + .unwrap(); + + let red = base_colors(&mut session); + + let mid_red = red.iter().filter(|value| (**value - 0.5).abs() < 0.05).count(); + assert!(mid_red > red.len() / 2, "the gradient map recolors the input image's gray: {mid_red} of {}", red.len()); + assert_eq!(session.caches[0].composite.value(Channel::BaseColor, 64, 64)[1], 0.0); +} + +#[test] +fn a_tile_generator_gradient_map_keeps_the_selected_resolution() { + let mut session = session(); + let layer = tile_fill(&mut session); + let colors = [[0.0; 3], [1.0, 0.0, 0.0]]; + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "colors": colors})).unwrap(); + let exact = base_colors(&mut session); + + execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "resolution": "uvTile", "resolutionFactor": -3})).unwrap(); + let coarse = base_colors(&mut session); + let inspected = execute(&mut session, "project.inspect", &Value::Null).unwrap(); + let row = inspected["layers"].as_array().unwrap().iter().find(|row| row["id"] == layer).unwrap(); + let source = &row["fill"]["sources"]["baseColor"]; + + assert_ne!(exact, coarse, "the gradient map samples the coarser pattern"); + assert_eq!(source["colors"], json!(colors)); + assert_eq!(source["resolution"]["mode"], "UvTile"); + assert_eq!(source["resolution"]["factor"], -3); + assert_eq!(source["tile"]["amount"], json!(TileGenerator::default().amount)); +} diff --git a/crates/engine/tests/it/tool_availability/selection.rs b/crates/engine/tests/it/tool_availability/selection.rs index aaca56a8..537edbd1 100644 --- a/crates/engine/tests/it/tool_availability/selection.rs +++ b/crates/engine/tests/it/tool_availability/selection.rs @@ -56,16 +56,13 @@ impl Selection { /// Whether the shelf offers `tool` for this selection pub(super) fn offers(self, tool: Tool) -> bool { - let reads_content = matches!(tool, Tool::Smudge | Tool::Clone); match tool { Tool::ColorPicker => true, Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing), _ => match self { Selection::PaintContent | Selection::PaintSublayer => true, Selection::PaintSublayerInFill => tool != Tool::Path, - Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => { - !reads_content - } + Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => true, Selection::PathSublayer => tool == Tool::Path, Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path, _ => false, diff --git a/crates/engine/tests/it/tool_settings.rs b/crates/engine/tests/it/tool_settings.rs new file mode 100644 index 00000000..281e28a0 --- /dev/null +++ b/crates/engine/tests/it/tool_settings.rs @@ -0,0 +1,150 @@ +//! Brush, symmetry and other tool settings outlive the project; what belongs to a project does not + +use serde_json::json; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::paint::BrushAlpha; +use texturecraft_engine::{CloneFrom, CloneSource, Session, ToolSettings, execute, sample_session}; + +fn another_project() -> Session { + sample_session(128, 64).unwrap() +} + +fn import_image(session: &mut Session, file: &str) -> String { + let mut png_bytes = Vec::new(); + let image = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([200, 100, 50, 255])); + image.write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes(file, png_bytes).unwrap() +} + +/// A session with every kind of tool setting changed from its default +fn tuned() -> Session { + let mut session = another_project(); + execute( + &mut session, + "tool.brush", + &json!({ + "size": 33, "hardness": 80, "flow": 40, "angle": 15, "spacing": 30, "alpha": "star", + "symmetryOn": true, "symmetryX": true, "symmetryY": false, "symmetryZ": true, + "symmetryRadial": 8, "symmetryAxis": "x", "symmetryOffset": [0.1, 0.0, 0.2], + "smudgeStrength": 80, "cloneSource": "layer", "cloneAligned": false, + }), + ) + .unwrap(); + session.tool.path.closed = true; + session.tool.path.fill = true; + session +} + +#[test] +fn opening_another_project_keeps_the_brush_symmetry_and_tool_settings() { + let mut session = tuned(); + let before = session.tool.clone(); + + session.switch_to(another_project()); + + assert_eq!(session.tool.brush, before.brush); + assert_eq!(session.tool.brush.alpha, BrushAlpha::Star); + assert!(session.tool.brush.symmetry.x && session.tool.brush.symmetry.z && !session.tool.brush.symmetry.y); + assert_eq!(session.tool.smudge_strength, 0.8); + assert_eq!(session.tool.clone_from, CloneFrom::Layer); + assert!(!session.tool.clone_aligned, "the Clone tool's Aligned switch is kept too"); + assert!(session.tool.path.closed && session.tool.path.fill); +} + +#[test] +fn a_project_loaded_from_a_file_gets_the_tool_settings_too() { + let mut session = tuned(); + let before_size = session.tool.brush.size; + let bytes = another_project().to_project_bytes().unwrap(); + + session.switch_to(Session::from_project_bytes(&bytes).unwrap()); + + assert_ne!(session.tool.brush.size, another_project().tool.brush.size); + assert_eq!(session.tool.brush.size, before_size); + assert_eq!(session.tool.smudge_strength, 0.8); +} + +#[test] +fn what_belongs_to_the_old_project_is_reset() { + let mut session = tuned(); + let before_size = session.tool.brush.size; + let image = import_image(&mut session, "stamp.png"); + execute(&mut session, "tool.brush", &json!({"alpha": {"image": image.clone()}})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": image, "scale": 2.0, "rotation": 30, "tile": true, "opacity": 0.9})).unwrap(); + session.tool.clone_source = Some(CloneSource { uv: [0.3, 0.4], offset: Some([0.1, 0.1]) }); + session.tool.path.push(Vec3::new(1.0, 2.0, 3.0), false); + + session.switch_to(another_project()); + + assert_eq!(session.tool.clone_source, None); + assert_eq!(session.tool.stencil, None); + assert_eq!(session.tool.brush.alpha_image, None); + assert!(session.tool.path.points.is_empty()); + + // The rest of the brush came along + assert_ne!(session.tool.brush.size, another_project().tool.brush.size); + assert_eq!(session.tool.brush.size, before_size); +} + +#[test] +fn the_stencil_placement_carries_over_to_the_next_stencil() { + let mut session = another_project(); + let image = import_image(&mut session, "stamp.png"); + execute(&mut session, "tool.stencil", &json!({"image": image, "scale": 2.0, "rotation": 30, "tile": true, "opacity": 0.9})).unwrap(); + + session.switch_to(another_project()); + let image = import_image(&mut session, "other.png"); + execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap(); + + let stencil = session.tool.stencil.as_ref().unwrap(); + assert_eq!((stencil.scale, stencil.rotation, stencil.tile, stencil.opacity), (2.0, 30.0, true, 0.9)); +} + +#[test] +fn clearing_the_stencil_keeps_its_placement_for_the_next_one() { + let mut session = another_project(); + let image = import_image(&mut session, "stamp.png"); + execute(&mut session, "tool.stencil", &json!({"image": image.clone(), "scale": 2.0})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"clear": true})).unwrap(); + + execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap(); + + assert_eq!(session.tool.stencil.as_ref().unwrap().scale, 2.0); +} + +#[test] +fn settings_survive_json_and_apply_to_a_fresh_tool() { + let session = tuned(); + let saved = ToolSettings::of(&session.tool); + let loaded: ToolSettings = serde_json::from_str(&serde_json::to_string(&saved).unwrap()).unwrap(); + + let mut fresh = another_project(); + loaded.apply(&mut fresh.tool); + + assert_eq!(ToolSettings::of(&fresh.tool), saved); + assert_eq!(fresh.tool.brush.size, session.tool.brush.size); +} + +#[test] +fn settings_saved_before_the_clone_aligned_switch_load_with_it_on() { + let mut saved = serde_json::to_value(ToolSettings::of(&tuned().tool)).unwrap(); + saved.as_object_mut().unwrap().remove("clone_aligned"); + let loaded: ToolSettings = serde_json::from_value(saved).unwrap(); + assert!(loaded.clone_aligned); +} + +#[test] +fn restored_stencil_and_smudge_settings_use_the_tool_limits() { + let mut session = another_project(); + let mut settings = ToolSettings::default(); + settings.smudge_strength = 2.0; + settings.stencil.center = [-20.0, 30.0]; + settings.stencil.opacity = -1.0; + settings.stencil.scale = 0.0; + settings.stencil.rotation = -15.0; + settings.apply(&mut session.tool); + + assert_eq!(session.tool.smudge_strength, 1.0); + let look = session.tool.stencil_look; + assert_eq!((look.center, look.scale, look.opacity, look.rotation), ([-4.0, 4.0], 0.01, 0.0, 345.0)); +} diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs index 0e217d88..7dcf78c1 100644 --- a/crates/engine/tests/it/tools.rs +++ b/crates/engine/tests/it/tools.rs @@ -53,15 +53,93 @@ fn clone_copies_values_from_the_source_offset() { dab(&mut s, 240.0, 200.0); let v = color_at(&s, 240.0, 200.0); assert!(red(v), "cloned red: {v:?}"); - // The offset stays for the next strokes: the source moved along with the destination. + + // The offset stays for the next strokes: the source moved along with the destination let off = s.tool.clone_source.unwrap().offset.unwrap(); assert!(off[0].abs() > 0.01, "{off:?}"); - // One undo step per clone stroke. + + // One undo step per clone stroke execute(&mut s, "edit.undo", &Value::Null).unwrap(); s.update(); assert!(!red(color_at(&s, 240.0, 200.0))); } +/// A red dab at (160, 200) as the clone source, the Clone tool selected with a small brush. +fn clone_ready() -> Session { + let mut s = session(); + paint_red(&mut s, 20.0); + dab(&mut s, 160.0, 200.0); + execute(&mut s, "tool.clone", &Value::Null).unwrap(); + execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + s +} + +#[test] +fn aligned_clone_keeps_the_first_offset_for_later_strokes() { + let mut s = clone_ready(); + assert_eq!(execute(&mut s, "tool.brush", &Value::Null).unwrap()["cloneAligned"], true, "aligned by default"); + dab(&mut s, 240.0, 200.0); + assert!(red(color_at(&s, 240.0, 200.0))); + + // The second stroke reads at the same offset, 40 points left of the first source: nothing red there + dab(&mut s, 200.0, 200.0); + assert!(!red(color_at(&s, 200.0, 200.0)), "aligned: the source moved along"); + assert!(s.tool.clone_source.unwrap().offset.is_some()); +} + +#[test] +fn not_aligned_clone_starts_every_stroke_at_the_source() { + let mut s = clone_ready(); + let r = execute(&mut s, "tool.brush", &json!({"cloneAligned": false})).unwrap(); + assert_eq!(r["cloneAligned"], false); + dab(&mut s, 240.0, 200.0); + assert!(red(color_at(&s, 240.0, 200.0)), "first stroke copies the source"); + assert!(s.tool.clone_source.unwrap().offset.is_none(), "no offset is kept"); + dab(&mut s, 200.0, 200.0); + assert!(red(color_at(&s, 200.0, 200.0)), "the second stroke starts at the source again"); +} + +#[test] +fn switching_the_clone_mode_forgets_the_offset_of_earlier_strokes() { + let mut s = clone_ready(); + dab(&mut s, 240.0, 200.0); + assert!(s.tool.clone_source.unwrap().offset.is_some()); + execute(&mut s, "tool.brush", &json!({"cloneAligned": false})).unwrap(); + execute(&mut s, "tool.brush", &json!({"cloneAligned": true})).unwrap(); + assert!(s.tool.clone_source.unwrap().offset.is_none(), "the next aligned stroke fixes a fresh offset"); +} + +#[test] +fn the_clone_source_is_forgotten_when_another_texture_set_becomes_active() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "tool.clone", &Value::Null).unwrap(); + execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap(); + + // Selecting the active set again keeps it + let active = s.ts(); + execute(&mut s, "textureSet.select", &json!({"ts": active})).unwrap(); + assert!(s.tool.clone_source.is_some()); + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + assert!(s.tool.clone_source.is_none(), "a point of set 0 means nothing in set 1"); + assert!(execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).is_err(), "asks for a source again"); + + // The same through selecting a layer that lives in another set + let other = s.doc.project.texture_sets[0].stack.last().copied().expect("set 0 has a layer"); + execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": other.0})).unwrap(); + assert_eq!(s.ts(), 0); + assert!(s.tool.clone_source.is_none()); + + execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap(); + execute(&mut s, "layer.select", &json!({"layers": [other.0]})).unwrap(); + assert!(s.tool.clone_source.is_some()); + let layers = s.doc.project.texture_sets[1].stack.clone(); + execute(&mut s, "layer.select", &json!({"layers": layers})).unwrap(); + assert_eq!(s.ts(), 1); + assert!(s.tool.clone_source.is_none()); +} + #[test] fn smudge_drags_color_along_the_stroke() { let mut s = session(); @@ -77,6 +155,21 @@ fn smudge_drags_color_along_the_stroke() { assert!(after[0] - before[0] > 0.2 && after[1] < before[1], "red dragged right: {before:?} -> {after:?}"); } +#[test] +fn smudge_leaves_a_channel_alone_that_the_material_has_off() { + let mut s = session(); + paint_red(&mut s, 12.0); + dab(&mut s, 170.0, 200.0); + let before = color_at(&s, 205.0, 200.0); + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "enabled": false})).unwrap(); + execute(&mut s, "tool.smudge", &Value::Null).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap(); + let pts: Vec<[f32; 2]> = (0..=40).map(|i| [170.0 + i as f32, 200.0]).collect(); + execute(&mut s, "tool.stroke", &json!({"points": pts})).unwrap(); + let after = color_at(&s, 205.0, 200.0); + assert!((after[0] - before[0]).abs() < 0.02 && (after[1] - before[1]).abs() < 0.02, "base color not dragged: {before:?} -> {after:?}"); +} + #[test] fn image_alpha_shapes_the_stamp() { let mut s = session(); @@ -273,7 +366,8 @@ fn stroke_after_undoing_mask_is_paint_stroke() { s.update(); let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]); + let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone(); + assert_eq!(undone["undone"], format!("Paint on {layer}"), "the stroke after undoing the mask was recorded as {}", undone["undone"]); execute(&mut s, "edit.redo", &Value::Null).unwrap(); s.update(); @@ -300,5 +394,121 @@ fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() { execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap(); let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap(); - assert_eq!(undone["undone"], "Mask stroke"); + let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone(); + assert_eq!(undone["undone"], format!("Paint mask of {layer}")); +} + +/// The name of the selected layer +fn selected_name(s: &Session) -> String { + s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone() +} + +/// The label of the newest history step +fn last_label(s: &Session) -> String { + s.history_labels().pop().unwrap() +} + +#[test] +fn strokes_are_named_by_tool_and_layer() { + let mut s = session(); + execute(&mut s, "layer.rename", &json!({"name": "Rust"})).unwrap(); + paint_red(&mut s, 20.0); + dab(&mut s, 160.0, 200.0); + assert_eq!(last_label(&s), "Paint on Rust"); + + execute(&mut s, "tool.clone", &Value::Null).unwrap(); + execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap(); + dab(&mut s, 240.0, 200.0); + assert_eq!(last_label(&s), "Clone on Rust"); + + execute(&mut s, "tool.smudge", &Value::Null).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[150, 200], [200, 200], [250, 200]]})).unwrap(); + assert_eq!(last_label(&s), "Smudge on Rust"); + + execute(&mut s, "tool.eraser", &Value::Null).unwrap(); + dab(&mut s, 160.0, 200.0); + assert_eq!(last_label(&s), "Erase on Rust"); + + // Another layer gives another name + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "layer.rename", &json!({"name": "Dust"})).unwrap(); + execute(&mut s, "tool.paint", &Value::Null).unwrap(); + dab(&mut s, 160.0, 200.0); + assert_eq!(last_label(&s), format!("Paint on {}", selected_name(&s))); + assert_eq!(selected_name(&s), "Dust"); +} + +#[test] +fn the_label_template_of_every_tool_is_listed_for_translation() { + use texturecraft_engine::{HISTORY_TEMPLATES, Tool, history_label, stroke_template}; + for tool in Tool::ALL { + for on_mask in [false, true] { + let template = stroke_template(tool, on_mask); + assert!(HISTORY_TEMPLATES.contains(&template), "{template} is not in HISTORY_TEMPLATES"); + assert!(history_label(template, "Rust").contains("Rust")); + } + } + assert_eq!(history_label("Paint on {layer}", "A {b}"), "Paint on A {b}"); +} + +/// Texels of base color red along a viewport row +fn red_width(s: &Session, y: f32) -> usize { + (100..300).filter(|x| s.pick(Vec2::new(*x as f32, y), s.viewport).is_some() && red(color_at(s, *x as f32, y))).count() +} + +#[test] +fn brush_alpha_parameters_are_set_read_back_and_narrow_the_stamp() { + let mut full_session = session(); + paint_red(&mut full_session, 30.0); + dab(&mut full_session, 200.0, 200.0); + let full = red_width(&full_session, 200.0); + assert!(full > 20, "{full}"); + + let mut s = session(); + paint_red(&mut s, 30.0); + + let brush = execute(&mut s, "tool.brush", &json!({"alphaSizeX": 50, "alphaRoundness": 0, "alphaContrast": 2.5, "alphaInvert": false})).unwrap(); + assert_eq!((brush["alphaSizeX"].as_f64(), brush["alphaSizeY"].as_f64(), brush["alphaRoundness"].as_f64()), (Some(50.0), Some(100.0), Some(0.0))); + assert_eq!((brush["alphaContrast"].as_f64(), brush["alphaInvert"].as_bool()), (Some(2.5), Some(false))); + execute(&mut s, "tool.brush", &json!({"alphaRoundness": 100, "alphaContrast": 1})).unwrap(); + dab(&mut s, 200.0, 200.0); + let narrow = red_width(&s, 200.0); + assert!(narrow > 5 && narrow * 10 < full * 7, "half the stamp width: {narrow} of {full}"); + + // Out-of-range values are clamped, not rejected + let brush = execute(&mut s, "tool.brush", &json!({"alphaSizeX": 0, "alphaContrast": 99})).unwrap(); + assert_eq!((brush["alphaSizeX"].as_f64(), brush["alphaContrast"].as_f64()), (Some(5.0), Some(8.0))); +} + +#[test] +fn brushes_saved_without_alpha_parameters_load_unchanged() { + use texturecraft_engine::paint::{AlphaParams, BrushSettings}; + + let mut saved = serde_json::to_value(BrushSettings::default()).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("alpha_params").is_some()); + let loaded: BrushSettings = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(loaded, BrushSettings::default()); + + saved["alpha_params"] = json!({"size_x": 0.5, "invert": true}); + let partial: BrushSettings = serde_json::from_value(saved).unwrap(); + assert_eq!(partial.alpha_params, AlphaParams { size_x: 0.5, invert: true, ..AlphaParams::default() }); +} + +#[test] +fn solo_keeps_the_document_source_for_clone_and_the_material_picker() { + let mut s = clone_ready(); + let layer = s.selected_layer().unwrap(); + let empty = execute(&mut s, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut s, "view.solo", &json!({"layer": empty})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); + s.update(); + assert!(!red(color_at(&s, 160.0, 200.0))); + + let picked = s.color_pick(Vec2::new(160.0, 200.0), s.viewport).unwrap(); + assert!(red(picked[&Channel::BaseColor])); + dab(&mut s, 240.0, 200.0); + execute(&mut s, "view.solo", &json!({"layer": null})).unwrap(); + s.update(); + assert!(red(color_at(&s, 240.0, 200.0))); } diff --git a/crates/engine/tests/it/user_smart_mask.rs b/crates/engine/tests/it/user_smart_mask.rs new file mode 100644 index 00000000..04fce3a6 --- /dev/null +++ b/crates/engine/tests/it/user_smart_mask.rs @@ -0,0 +1,210 @@ +//! A layer's mask saved as a user smart mask (`.tcmask`) and applied to other layers and projects. + +use serde_json::{Value, json}; +use texturecraft_engine::core::{Effect, EffectKind, LayerId, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::smart_masks::SMART_MASK_EXT; +use texturecraft_engine::{Session, execute}; +use texturecraft_texel::TileImage; + +fn session(resolution: u32) -> Session { + Session::new_project("t", primitives::sphere(1.0, 24, 12), "builtin:sphere", None, resolution).unwrap() +} + +fn layer(s: &mut Session) -> LayerId { + LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()) +} + +/// A mask with a generator, a filter, an image fill and painted pixels. Returns the layer and the image's name. +fn multi_effect_mask(s: &mut Session) -> (LayerId, String) { + let mut png = Vec::new(); + image::RgbaImage::from_fn(8, 8, |x, y| image::Rgba([(x * 30) as u8, (y * 30) as u8, 90, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let name = s.import_resource_bytes("stencil.png", png).unwrap(); + + let id = layer(s); + execute(s, "mask.add.black", &json!({"layer": id.0})).unwrap(); + execute(s, "effect.add.generator", &json!({"layer": id.0, "generator": "edgeWear"})).unwrap(); + execute(s, "effect.add.filter", &json!({"layer": id.0, "target": "mask", "filter": "invert"})).unwrap(); + let fill = execute(s, "effect.add.fill", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + let paint = execute(s, "effect.add.paint", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + + let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap(); + for effect in &mut mask.effects { + if effect.id.0 == fill { + effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default() }; + } + } + let size = s.doc.project.texture_set(0).unwrap().resolution; + let mut pixels = TileImage::new(size, size, 2); + pixels.set(10, 12, &[40000, 65535]); + s.doc.pixels.masks.insert(LayerId(paint), pixels); + (id, name) +} + +/// The mask's effects without their ids (those are new in every project). +fn effects(s: &Session, layer: LayerId) -> Vec { + s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| Effect { id: LayerId(0), ..effect.clone() }).collect() +} + +fn painted(s: &Session, layer: LayerId) -> Vec<[u16; 4]> { + let mask = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap(); + mask.effects.iter().filter(|effect| matches!(effect.kind, EffectKind::Paint)).map(|effect| s.doc.pixels.masks[&effect.id].get(10, 12)).collect() +} + +#[test] +fn a_saved_mask_applies_to_another_layer_with_parameters_pixels_and_images() { + let mut s = session(256); + let (source, image) = multi_effect_mask(&mut s); + let bytes = s.smart_mask_bytes(source, "Worn stencil").unwrap(); + + let other = layer(&mut s); + execute(&mut s, "mask.add.white", &json!({"layer": other.0})).unwrap(); + let before = s.doc.project.layers.len(); + s.apply_smart_mask_bytes(other, &bytes).unwrap(); + + assert_eq!(effects(&s, other), effects(&s, source), "every effect keeps its type and parameters"); + assert_eq!(painted(&s, other), painted(&s, source), "and the painted pixels"); + assert_eq!(s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().background, s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().background); + assert_eq!(s.doc.project.layers.len(), before, "no layer is added"); + let ids: Vec<_> = s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert!(ids.iter().all(|id| !s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().any(|e| e.id == *id)), "the effects are new ones"); + assert!(s.doc.resources.contains_key(&image)); + s.doc.project.validate().unwrap(); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().effects.len(), 0, "one undo step restores the old mask"); +} + +#[test] +fn a_saved_mask_applies_in_a_fresh_project_of_another_size() { + let mut s = session(256); + let (source, image) = multi_effect_mask(&mut s); + let bytes = s.smart_mask_bytes(source, "Worn stencil").unwrap(); + let expected = effects(&s, source); + + let mut fresh = session(128); + let target = layer(&mut fresh); + assert!(fresh.doc.resources.is_empty()); + fresh.apply_smart_mask_bytes(target, &bytes).unwrap(); + + assert_eq!(effects(&fresh, target), expected); + assert_eq!(fresh.doc.resources.get(&image), s.doc.resources.get(&image), "the image arrives byte for byte"); + assert!(fresh.images.contains_key(&image), "and is decoded for the mask to read"); + let mask = fresh.doc.project.layer(target).unwrap().mask.as_ref().unwrap(); + let paint = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::Paint)).unwrap(); + assert_eq!(fresh.doc.pixels.masks[&paint.id].width(), 128, "painted pixels are fitted to the project's size"); + fresh.doc.project.validate().unwrap(); +} + +#[test] +fn the_commands_write_a_file_and_apply_it_by_path() { + let mut s = session(128); + let (source, _) = multi_effect_mask(&mut s); + let dir = std::env::temp_dir().join(format!("tc_user_smart_mask_{}", std::process::id())); + let path = dir.join("lib").join("worn"); + + let saved = execute(&mut s, "mask.smart.create", &json!({"layer": source.0, "path": path.display().to_string(), "name": "Worn"})).unwrap(); + let file = dir.join("lib").join(format!("worn.{SMART_MASK_EXT}")); + assert_eq!(saved["path"], file.display().to_string(), "the extension is added and the folder made"); + + let other = layer(&mut s); + execute(&mut s, "mask.smart.apply", &json!({"layer": other.0, "path": file.display().to_string()})).unwrap(); + assert_eq!(effects(&s, other), effects(&s, source)); + std::fs::remove_dir_all(&dir).ok(); + + let plain = layer(&mut s); + assert!(execute(&mut s, "mask.smart.create", &json!({"layer": plain.0, "path": "unused"})).is_err(), "a layer without a mask has nothing to save"); + assert!(execute(&mut s, "mask.smart.apply", &json!({"layer": plain.0, "path": file.display().to_string()})).is_err(), "a missing file changes nothing"); + assert!(s.doc.project.layer(plain).unwrap().mask.is_none()); +} + +#[test] +fn a_file_without_a_mask_is_refused_and_a_disabled_mask_comes_back_on() { + let mut s = session(128); + let plain = layer(&mut s); + let material = s.smart_material_bytes(plain, "Plain").unwrap(); + assert!(s.apply_smart_mask_bytes(plain, &material).is_err(), "a smart material file has no mask to take"); + assert!(s.apply_smart_mask_bytes(plain, b"junk").is_err()); + + let (source, _) = multi_effect_mask(&mut s); + s.doc.project.layer_mut(source).unwrap().mask.as_mut().unwrap().enabled = false; + let bytes = s.smart_mask_bytes(source, "Off").unwrap(); + s.apply_smart_mask_bytes(plain, &bytes).unwrap(); + assert!(s.doc.project.layer(plain).unwrap().mask.as_ref().unwrap().enabled); +} + +#[test] +fn an_image_name_the_project_uses_for_other_bytes_gets_a_new_name() { + let mut s = session(128); + let (source, image) = multi_effect_mask(&mut s); + let bytes = s.smart_mask_bytes(source, "Stencil").unwrap(); + + let mut other = session(128); + let mut png = Vec::new(); + image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + assert_eq!(other.import_resource_bytes("stencil.png", png).unwrap(), image); + let own = other.doc.resources[&image].clone(); + let target = layer(&mut other); + other.apply_smart_mask_bytes(target, &bytes).unwrap(); + + assert_eq!(other.doc.resources[&image], own, "the project's own image is untouched"); + let mask = other.doc.project.layer(target).unwrap().mask.as_ref().unwrap(); + let read: Vec<&str> = mask.effects.iter().flat_map(|effect| effect.kind.images_read()).collect(); + assert_eq!(read.len(), 1); + assert_ne!(read[0], image, "the mask reads its own image under another name"); + assert_eq!(other.doc.resources[read[0]], s.doc.resources[&image]); +} + +#[test] +fn effects_reading_an_anchor_of_the_mask_follow_it() { + let mut s = session(128); + let id = layer(&mut s); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + let fill = execute(&mut s, "effect.add.fill", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap(); + for effect in &mut mask.effects { + if effect.id.0 == fill { + effect.kind = EffectKind::Fill { + source: Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() }, + projection: Default::default(), + }; + } + } + let bytes = s.smart_mask_bytes(id, "Anchored").unwrap(); + + let target = layer(&mut s); + s.apply_smart_mask_bytes(target, &bytes).unwrap(); + let mask = s.doc.project.layer(target).unwrap().mask.as_ref().unwrap(); + let new_anchor = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::Anchor)).unwrap().id; + let reads = mask.effects.iter().find_map(|effect| match &effect.kind { + EffectKind::Fill { source: Source::Anchor { anchor, .. }, .. } => Some(*anchor), + _ => None, + }); + assert_eq!(reads, Some(new_anchor), "the fill reads the copied anchor, not the old one"); +} + +#[test] +fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() { + let mut s = session(128); + let (source, _) = multi_effect_mask(&mut s); + let external = layer(&mut s); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": external.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + let source_ref = Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() }; + let mut file = texturecraft_engine::formats::load_project_bytes(&s.smart_mask_bytes(source, "Preset").unwrap()).unwrap(); + let holder = file.project.texture_sets[0].stack[0]; + for (project, id) in [(&mut file.project, holder), (&mut s.doc.project, source)] { + let mask = project.layer_mut(id).unwrap().mask.as_mut().unwrap(); + let fill = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Fill { .. })).unwrap(); + fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default() }; + } + + assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask")); + let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap(); + let before = s.doc.project.clone(); + let history = s.history_labels(); + assert!(s.apply_smart_mask_bytes(external, &bytes).unwrap_err().to_string().contains("outside this mask")); + assert_eq!(s.doc.project, before); + assert_eq!(s.history_labels(), history); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 554a712a..f776f46a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -247,6 +247,37 @@ fn panic_hunt() { } } +/// A colour param is `[r, g, b]` in linear 0..1 or `"#rrggbb"` in sRGB, and the same digits differ +/// between the two, so every command that takes a colour says which form is which. +#[test] +fn colour_params_name_their_colour_space() { + for spec in command_specs() { + if ["color?", "colors?", "Color?"].iter().any(|k| spec.params.contains(k)) { + assert!(spec.params.contains("linear"), "{}: {}", spec.id, spec.params); + let hex = spec.params.matches("\"#rrggbb\"").count(); + assert_eq!(hex, spec.params.matches("\"#rrggbb\" sRGB").count(), "{}: {}", spec.id, spec.params); + } + } + // These read their colours through `color_param`, which takes both forms. + for id in + ["layer.add.fill", "layer.fill.set", "effect.add.fill", "effect.add.filter", "tool.material", "mask.add.colorSelection", "resource.text", "display.set"] + { + let spec = command_specs().iter().find(|c| c.id == id).unwrap(); + assert!(spec.params.contains("[r,g,b] linear or \"#rrggbb\" sRGB"), "{id}: {}", spec.params); + } + let base_color = |color: Value| { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({ "color": color })).unwrap(); + s.update(); + s.caches[0].composite.value(Channel::BaseColor, 128, 128) + }; + let hex = base_color(json!("#c8102e")); + let linear = base_color(json!([0.5776, 0.0052, 0.0273])); + assert!(hex.iter().zip(&linear).all(|(a, b)| (a - b).abs() < 2e-3), "{hex:?} {linear:?}"); + let digits = base_color(json!([0.7843, 0.0627, 0.1804])); + assert!(digits[0] - hex[0] > 0.1, "{digits:?} {hex:?}"); +} + #[test] fn copy_paste_flatten_and_resize_keep_the_look() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); @@ -747,43 +778,43 @@ fn changing_generator_kind_keeps_the_effect_identity_and_settings() { fn unparseable_color_param_returns_error() { let mut s = session(); let err = execute(&mut s, "layer.add.fill", &json!({"color": "#fff"})).unwrap_err(); - assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "color": "#123"})).unwrap_err(); - assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); let err = execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": "invalid"})).unwrap_err(); - assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); let err = execute(&mut s, "mask.add.colorSelection", &json!({"color": "#xyz"})).unwrap_err(); - assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`mask.add.colorSelection`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); let err = execute(&mut s, "display.set", &json!({"scatterColor": "#12345"})).unwrap_err(); - assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); let rev_before = s.revision; let exposure_before = s.doc.project.display.env_exposure; let err = execute(&mut s, "display.set", &json!({"exposure": 2.0, "scatterColor": "invalid"})).unwrap_err(); - assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`display.set`: `scatterColor` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); assert_eq!(s.doc.project.display.env_exposure, exposure_before); assert_eq!(s.revision, rev_before); let mask_before = s.tool.mask_value; let err = execute(&mut s, "tool.material", &json!({"maskValue": 0.25, "channel": "baseColor", "color": "invalid"})).unwrap_err(); - assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); assert_eq!(s.tool.mask_value, mask_before); assert_eq!(s.revision, rev_before); let err = execute(&mut s, "tool.material", &json!({"color": "invalid"})).unwrap_err(); - assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`tool.material`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); assert_eq!(s.revision, rev_before); let err = execute(&mut s, "layer.add.fill", &json!({"color": [1e40, 0.0, 0.0]})).unwrap_err(); - assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`layer.add.fill`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); assert_eq!(s.revision, rev_before); let err = execute(&mut s, "layer.fill.set", &json!({"channel": "baseColor", "procedural": "noise", "color": "red"})).unwrap_err(); - assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\")"); + assert_eq!(err.to_string(), "`layer.fill.set`: `color` must be a color ([r, g, b] linear or \"#rrggbb\" sRGB)"); assert_eq!(s.revision, rev_before); assert!(execute(&mut s, "tool.cloneSource", &json!({"uv": [0.2, 0.8, 0.4]})).is_err()); @@ -791,3 +822,53 @@ fn unparseable_color_param_returns_error() { let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err(); assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]"); } + +#[test] +fn resetting_a_stencil_puts_back_its_placement_only() { + let mut stencil = texturecraft_engine::StencilState::new("logo.png"); + stencil.center = [0.4, -0.2]; + stencil.scale = 2.0; + stencil.rotation = 30.0; + stencil.opacity = 0.9; + stencil.tile = true; + stencil.reset_placement(); + assert_eq!((stencil.center, stencil.scale, stencil.rotation, stencil.opacity, stencil.tile), ([0.0, 0.0], 0.8, 0.0, 0.9, true)); +} + +#[test] +fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() { + let mut s = session(); + let layer = execute(&mut s, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap(); + let read = |s: &Session| s.doc.project.layers[&texturecraft_engine::core::LayerId(layer)].channels.clone(); + let before = read(&s); + execute( + &mut s, + "layer.blending.set", + &json!({"layer": layer, "channels": {"baseColor": {"mode": "Multiply", "opacity": 0.25}, "roughness": {"opacity": 0.5}}}), + ) + .unwrap(); + let after = read(&s); + assert_eq!((after[&Channel::BaseColor].mode, after[&Channel::BaseColor].opacity), (texturecraft_engine::core::BlendMode::Multiply, 0.25)); + assert_eq!((after[&Channel::Roughness].mode, after[&Channel::Roughness].opacity), (before[&Channel::Roughness].mode, 0.5)); + assert_eq!(after[&Channel::Metallic], before[&Channel::Metallic], "channels not listed stay as they were"); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(read(&s), before, "one undo step restores every listed channel"); + execute(&mut s, "edit.redo", &Value::Null).unwrap(); + + // A channel the layer has disabled stays disabled + execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "metallic", "enabled": false})).unwrap(); + execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"metallic": {"opacity": 0.1}}})).unwrap(); + assert!(!read(&s).contains_key(&Channel::Metallic)); + let stable = read(&s); + for bad in [ + json!({"layer": layer}), + json!({"layer": layer, "channels": {"nope": {}}}), + json!({"layer": layer, "channels": {"baseColor": {"mode": "Multiply"}, "nope": {}}}), + json!({"layer": layer, "channels": {"baseColor": {"mode": "???"}}}), + ] { + assert!(execute(&mut s, "layer.blending.set", &bad).is_err(), "{bad}"); + assert_eq!(read(&s), stable, "an error changes nothing"); + } + execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"baseColor": {"opacity": 2.0}, "roughness": {"opacity": -1.0}}})).unwrap(); + assert_eq!((read(&s)[&Channel::BaseColor].opacity, read(&s)[&Channel::Roughness].opacity), (1.0, 0.0), "opacity is clamped"); +} diff --git a/crates/formats/README.md b/crates/formats/README.md index b11c8087..5b70b777 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -78,7 +78,7 @@ pub fn preset_from_json(json: &str) -> Result; pub fn preset_to_json(preset: &ExportPreset) -> Result; ``` -- `ExportPreset { name, maps: Vec }`, `MapSpec { file, format, bit_depth, channels: Vec<(Dest, SourceRef)> }` +- `ExportPreset { name, maps: Vec }`, `MapSpec { file, format, bit_depth, channels: Vec<(Dest, SourceRef)>, inverted: Vec }` (serde JSON, so presets can be user files). - `Dest`: `R G B A` or `L` (gray; `L` + `A` = gray + alpha). - `SourceRef`: `Channel { channel, component }` (`Normal` = the **final** normal in the export diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 811a60bc..dba74423 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -253,6 +253,10 @@ pub struct MapSpec { pub format: FileFormat, pub bit_depth: u8, pub channels: Vec<(Dest, SourceRef)>, + /// Destination channels written as `1 - value` (absent in old files: none). The source value + /// is inverted before the colour-space encoding, so a colour map is inverted in linear light. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub inverted: Vec, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -268,26 +272,38 @@ impl ExportPreset { if self.name.trim().is_empty() || self.name.chars().count() > MAX_PRESET_NAME || self.name.chars().any(char::is_control) { return bad(format!("the name must be 1 to {MAX_PRESET_NAME} characters without control characters")); } + if self.maps.len() > MAX_MAPS { return bad(format!("more than {MAX_MAPS} maps")); } + for m in &self.maps { if let Some(e) = template_error(&m.file) { return bad(e); } + if !matches!(m.bit_depth, 8 | 16 | 32) { return bad(format!("map \"{}\" has bit depth {} (8, 16 or 32)", m.file, m.bit_depth)); } + if m.channels.iter().any(|(_, s)| s.component() != s.raw_component()) { return bad(format!("map \"{}\" picks a component other than 0, 1 or 2", m.file)); } + let dests: BTreeSet = m.channels.iter().map(|(d, _)| *d).collect(); if dests.len() != m.channels.len() || m.channels.is_empty() { return bad(format!("map \"{}\" needs distinct destination channels", m.file)); } + if dests.contains(&Dest::L) && dests.iter().any(|d| matches!(d, Dest::R | Dest::G | Dest::B)) { return bad(format!("map \"{}\" mixes L with R/G/B", m.file)); } + + let inv: BTreeSet = m.inverted.iter().copied().collect(); + if inv.len() != m.inverted.len() || !inv.is_subset(&dests) { + return bad(format!("map \"{}\" inverts a channel it does not write, or one twice", m.file)); + } + if m.channels.iter().any(|(_, s)| matches!(s, SourceRef::Constant(v) if !v.is_finite())) { return bad(format!("map \"{}\" has a non-finite constant", m.file)); } @@ -389,7 +405,7 @@ pub struct PlannedFile { } // --------------------------------------------------------------------------------------------- -// Planning: which maps exist for a texture set and what their files are called. +// Planning: which maps exist for a texture set and what their files are called fn normal_present(set: &TextureSet) -> bool { set.has_channel(Channel::Normal) || set.has_channel(Channel::Height) || set.baked.contains(&BakedMap::Normal) @@ -476,6 +492,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export { return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); } + let mut used = BTreeSet::new(); let mut out = Vec::new(); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; @@ -483,6 +500,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export if !map.channels.iter().any(|(_, s)| source_present(set, s)) { continue; } + let format = opts.format_override.unwrap_or(map.format); let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth)); let space = opts.space_for(format); @@ -491,9 +509,11 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export (true, ColorSpace::Srgb) => "sRGB", (true, other) => other.name(), }; - // Integer files clamp to 0-1, which wide-gamut linear colour can leave. + + // Integer files clamp wide-gamut linear color to 0–1 let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); - // One file per UV tile: names without `$udim` get it appended. + + // Append `$udim` to names for separate UV tiles let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; for &tile in &tiles { let stem = template @@ -503,7 +523,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export .replace("$textureSet", &set.name) .replace("$channel", channel_label(map)) .replace("$colorSpace", color_space); - // The same name with the tile number as a placeholder, to write it as `` after. + + // Replace the tile number with `` in the shared name let token_stem = tile.map(|_| { let t = template .replace("$udim", "UDIMTOKEN") @@ -525,7 +546,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export format.extension().to_uppercase() )); } - // Case-insensitive: Windows and macOS file systems are. + + // Compare names case-insensitively for Windows and macOS let mut k = 2; while used.contains(&name.to_ascii_lowercase()) { name = format!("{stem}_{k}.{ext}"); @@ -535,8 +557,9 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } used.insert(name.to_ascii_lowercase()); - // Only when putting the tile number back gives this file's name: the length limit cuts the - // longer placeholder elsewhere (or off), and a name may hold the placeholder text itself. + + // Use a UDIM name only when substituting its tile recovers the output name + // Truncation or literal placeholder text can make that substitution ambiguous let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| { let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() }; format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "") @@ -548,7 +571,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } // --------------------------------------------------------------------------------------------- -// Sampling. +// Sampling /// Which texel a value is taken from. #[derive(Clone, Copy, PartialEq)] @@ -702,10 +725,12 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { return Err(FormatError::Invalid(format!("composite size {res}×{height} does not fit texture set \"{}\"", set.name))); } + if input.coverage.len() != res as usize * height as usize { return Err(FormatError::Invalid(format!("coverage has {} texels, expected {res}×{height}", input.coverage.len()))); } - // Padding stays inside each UV tile. + + // Padding stays inside each UV tile let dmap = match opts.padding { Padding::None => None, Padding::Dilation(d) | Padding::DilationDefault(d) => Some(DilationMap::in_blocks(input.coverage, res, height, Some(d), tile_res)), @@ -729,11 +754,14 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result = lay.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + + // The texels written: one tile, or the whole set let (x0, y0, w, h) = match (p.tile, grid) { (Some(t), Some(g)) => { let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; - // A tile smaller than its block fills the block's top-left corner. + + // A tile smaller than its block fills the block's top-left corner let side = ((tile_res as f32 * set.tile_scale(t)).round() as u32).clamp(1, tile_res); (bx * tile_res, by * tile_res, side, side) } @@ -755,17 +783,19 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]); let mut data = data; @@ -781,7 +811,8 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect(); - // A colour space the user chose is written into the colour maps (data maps have none). + + // A colour space the user chose is written into the colour maps (data maps have none) let embed = (opts.color_space.is_some() && is_color(map) && rgb).then_some(space); let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, embed, &mut warnings)?; Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings }) @@ -839,8 +870,8 @@ fn encode( warnings: &mut Vec, ) -> Result> { let failed = |e: &dyn std::fmt::Display| FormatError::Invalid(format!("{} encoding failed: {e}", format.extension())); - // Where the colour space goes: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities - // attribute in EXR. The other formats have no place for it. + + // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr) { @@ -858,7 +889,8 @@ fn encode( } _ => {} } - // Integer formats: transfer function and quantization first, then fit the channel layout. + + // Integer formats: transfer function and quantization first, then fit the channel layout let encoded: Vec = data.iter().enumerate().map(|(i, v)| if srgb.get(i % n).copied().unwrap_or(false) { linear_to_srgb(*v) } else { v.clamp(0.0, 1.0) }).collect(); let (encoded, n) = match (format, n) { @@ -890,7 +922,8 @@ fn remap(data: &[f32], n: usize, pick: &[usize]) -> Vec { fn write_image(format: FileFormat, bytes: &[u8], (w, h): (u32, u32), color: image::ExtendedColorType, icc: Option>) -> image::ImageResult> { use image::ImageEncoder; let mut out = Cursor::new(Vec::new()); - // `set_icc_profile` says no (an error to ignore) for an encoder without a place for it. + + // `set_icc_profile` says no (an error to ignore) for an encoder without a place for it let fmt = match format { FileFormat::Jpeg => { let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY); @@ -957,13 +990,15 @@ fn write_exr((w, h): (u32, u32), n: usize, data: &[f32], half: bool, space: Opti let layer = Layer::new((w as usize, h as usize), LayerAttributes::default(), Encoding::SMALL_LOSSLESS, AnyChannels::sort(channels)); let mut out = Cursor::new(Vec::new()); let mut image = Image::from_layer(layer); - // The primaries and white point of the values, in the attribute OpenEXR readers look for. + + // Store primaries and white point in the OpenEXR attribute if let Some(space) = space { let [r, g, b, white] = space.chromaticities().map(|xy| Vec2(xy[0] as f32, xy[1] as f32)); image.attributes.chromaticities = Some(exr::meta::attribute::Chromaticities { red: r, green: g, blue: b, white }); } let writer = image.write(); - // No worker threads on the web. + + // The web build has no worker threads #[cfg(target_arch = "wasm32")] let writer = writer.non_parallel(); writer.to_buffered(&mut out)?; @@ -978,11 +1013,12 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result.`; the stem alone is capped at MAX_STEM. + // Cap the sanitized stem before adding the extension let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, "")); if f.name.is_empty() || stem != sanitize_file_stem(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() { return Err(FormatError::Invalid(format!("\"{}\" is not a plain file name", f.name))); } + let path = dir.join(&f.name); crate::write_atomic(&path, &f.bytes)?; Ok(path) diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index bf8c5a44..d61bf124 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -242,6 +242,7 @@ fn templates_are_sanitized_and_collisions_suffixed() { format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 })], + inverted: Vec::new(), }; let preset = ExportPreset { name: "t".into(), @@ -316,6 +317,7 @@ fn every_format_encodes_and_decodes() { format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 }), (Dest::A, SourceRef::Constant(0.5))], + inverted: Vec::new(), }; let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); preset.maps.push(gray_alpha); @@ -331,9 +333,11 @@ fn every_format_encodes_and_decodes() { if format == FileFormat::Exr && f.name.starts_with("la") { continue; // Y/A EXR: covered by `exr_values_are_linear`. } + assert_eq!(decode(f).dimensions(), (RES, RES), "{}", f.name); } - // Roughness 0.25 everywhere survives every format (JPEG within its loss). + + // Roughness 0.25 everywhere survives every format (JPEG within its loss) let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}"); let base = find(&files, "_BaseColor."); @@ -407,7 +411,7 @@ fn write_files_accepts_planned_name_with_max_length_stem() { } fn gray_map(file: &str, src: SourceRef) -> MapSpec { - MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)] } + MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() } } #[test] @@ -449,6 +453,7 @@ fn converted_maps_invert_and_derive_normals() { format: FileFormat::Png, bit_depth: 8, channels: [Dest::R, Dest::G, Dest::B].into_iter().zip(0u8..).map(|(d, k)| (d, SourceRef::Virtual { map, component: k })).collect(), + inverted: Vec::new(), }; let preset = ExportPreset { name: "converted".into(), @@ -467,7 +472,8 @@ fn converted_maps_invert_and_derive_normals() { assert_eq!(hn.get_pixel(30, 30), full.get_pixel(30, 30), "without a normal channel the final normal is the height normal"); let (a, b) = (hn.get_pixel(30, 30), decode(find(&files, "dx")).to_rgb8().get_pixel(30, 30).to_owned()); assert!(a[1] > 136 && (a[1] as i32 + b[1] as i32 - 255).abs() <= 1, "DirectX flips green: {a:?} vs {b:?}"); - // Converted maps only exist when their source channel does. + + // Converted maps only exist when their source channel does let fx = Fx::new(&default_channels()); let only = ExportPreset { name: "c".into(), maps: vec![gray_map("rough", virt(VirtualMap::Roughness)), rgb("hn", VirtualMap::HeightNormal)] }; let names: Vec = list_outputs(&fx.project, 0, "m", &ExportOptions::new(only)).unwrap().into_iter().map(|p| p.name).collect(); @@ -476,7 +482,7 @@ fn converted_maps_invert_and_derive_normals() { #[test] fn uv_tiles_export_one_file_per_tile_without_padding_across() { - // Tiles 1001 (left block: red, only x < 16 covered) and 1002 (right block: blue). + // Tiles 1001 (left block: red, only x < 16 covered) and 1002 (right block: blue) let mut project = Project::new("My Project", "builtin:udim_plane"); let mut ts = TextureSet::new("Body Set", 0, RES); ts.uv_tiles = vec![1001, 1002]; @@ -505,6 +511,7 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() { (Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }), (Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }), ], + inverted: Vec::new(), }], }; let files = render_maps(&input, &ExportOptions::new(preset.clone())).unwrap(); @@ -512,10 +519,12 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() { assert_eq!(names, ["Body_Set_color.1001.png", "Body_Set_color.1002.png"]); let (left, right) = (decode(&files[0]).to_rgb8(), decode(&files[1]).to_rgb8()); assert_eq!((left.width(), left.height(), right.width()), (RES, RES, RES)); - // Infinite padding fills tile 1001 from its own island only. + + // Infinite padding fills tile 1001 from its own island only assert!(left.pixels().all(|p| p.0 == [255, 0, 0]), "tile 1001 is red"); assert!(right.pixels().all(|p| p.0 == [0, 0, 255]), "tile 1002 is blue"); - // `$udim` placed by the template; a size applies per tile; the atlas is one image. + + // `$udim` placed by the template; a size applies per tile; the atlas is one image let mut named = preset.clone(); named.maps[0].file = "$udim_$textureSet".into(); let opts = ExportOptions { size: Some(32), ..ExportOptions::new(named) }; @@ -534,12 +543,13 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { project.texture_sets.push(ts); let udim_names = |file: String| { let channels = vec![(Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 })]; - let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { file, format: FileFormat::Png, bit_depth: 8, channels }] }; + let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { file, format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() }] }; list_outputs(&project, 0, "m", &ExportOptions::new(preset)).unwrap().into_iter().map(|f| f.udim_name).collect::>() }; let placeholder = Some("Body_.png".to_string()); assert_eq!(udim_names("$textureSet_$udim".into()), [placeholder.clone(), placeholder]); - // The length limit cuts the longer placeholder where it doesn't cut the tile number: none then. + + // The length limit cuts the longer placeholder where it doesn't cut the tile number: none then assert_eq!(udim_names(format!("{}_$udim_$textureSet", "a".repeat(MAX_STEM - 10))), [None, None]); } @@ -635,6 +645,7 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { (Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }), (Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }), ], + inverted: Vec::new(), }], }; let plan = |space: Option, format: Option| { @@ -648,7 +659,8 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() { assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings); assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values"); assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty()); - // The planned names are the rendered names. + + // The planned names are the rendered names let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) }; let names: Vec = fx.render(&opts).into_iter().map(|f| f.name).collect(); assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::>()); @@ -685,13 +697,15 @@ fn a_chosen_colour_space_is_embedded_as_an_icc_profile() { if depth == 16 && matches!(format, FileFormat::Jpeg | FileFormat::Webp) { continue; } + for space in ColorSpace::ALL { let mut warnings = Vec::new(); let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], Some(space), &mut warnings).unwrap(); assert_eq!(embedded_icc(format, &bytes), crate::icc::profile(space), "{format:?} {depth}-bit {space:?}"); assert!(warnings.is_empty(), "{warnings:?}"); } - // No colour space chosen (a data map, or the default): nothing is embedded. + + // No colour space chosen (a data map, or the default): nothing is embedded let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap(); assert_eq!(embedded_icc(format, &bytes), None, "{format:?} {depth}-bit"); } @@ -727,3 +741,116 @@ fn formats_without_a_place_for_a_colour_space_say_so() { assert!(quiet.is_empty(), "{format:?}: nothing to say without a chosen space: {quiet:?}"); } } + +/// R packs roughness (0.25) and B metallic (0.75); G and A are constants. +fn invert_map(depth: u8, inverted: Vec) -> MapSpec { + let ch = |channel| SourceRef::Channel { channel, component: 0 }; + MapSpec { + file: "packed".into(), + format: FileFormat::Png, + bit_depth: depth, + channels: vec![ + (Dest::R, ch(Channel::Roughness)), + (Dest::G, SourceRef::Constant(0.5)), + (Dest::B, ch(Channel::Metallic)), + (Dest::A, SourceRef::Constant(1.0)), + ], + inverted, + } +} + +#[test] +fn inverted_channels_write_one_minus_the_source() { + let fx = Fx::new(&default_channels()); + for depth in [8u8, 16] { + let preset = |inverted| ExportPreset { name: "inv".into(), maps: vec![invert_map(depth, inverted)] }; + let px = |p: ExportPreset| { + let files = fx.render(&ExportOptions::new(p)); + let img = decode(find(&files, "packed")).to_rgba16(); + let p = img.get_pixel(9, 9).0; + + // Compare 16-bit values for both depths: an 8-bit file widens to value * 257 + p.map(i32::from) + }; + let plain = px(preset(Vec::new())); + let inv = px(preset(vec![Dest::R, Dest::A])); + let tol = if depth == 8 { 257 } else { 2 }; + + // Roughness 0.25 inverts to 0.75, constant alpha 1 to 0; G and B stay + assert!((inv[0] - (65535 - plain[0])).abs() <= tol, "depth {depth}: R {} vs {}", inv[0], 65535 - plain[0]); + assert!((inv[0] - 49151).abs() <= tol, "depth {depth}: R {}", inv[0]); + assert!(inv[3] <= tol, "depth {depth}: A {}", inv[3]); + assert_eq!((inv[1], inv[2]), (plain[1], plain[2]), "depth {depth}: channels not listed stay as they are"); + assert!((plain[0] - 16384).abs() <= tol && plain[3] == 65535, "depth {depth}: un-inverted {plain:?}"); + } + + // Gray maps and float files too + let gray = gray_map("g", SourceRef::Channel { channel: Channel::Metallic, component: 0 }); + let gray = MapSpec { inverted: vec![Dest::L], ..gray }; + let files = fx.render(&ExportOptions::new(ExportPreset { name: "inv".into(), maps: vec![gray] })); + assert_eq!(decode(find(&files, "g.png")).to_luma8().get_pixel(4, 4)[0], 64, "1 - metallic 0.75"); + let mut float = invert_map(32, vec![Dest::B]); + float.format = FileFormat::Exr; + let files = fx.render(&ExportOptions::new(ExportPreset { name: "inv".into(), maps: vec![float] })); + let v = decode(find(&files, "packed.exr")).to_rgba32f().get_pixel(4, 4).0; + assert!((v[2] - 0.25).abs() < 1e-3 && (v[0] - 0.25).abs() < 1e-3, "metallic 0.75 inverted, roughness 0.25 not: {v:?}"); +} + +#[test] +fn inverted_flag_round_trips_and_old_json_loads() { + let mut map = invert_map(8, vec![Dest::B]); + let preset = ExportPreset { name: "Mine".into(), maps: vec![map.clone()] }; + let json = preset_to_json(&preset).unwrap(); + assert_eq!(preset_from_json(&json).unwrap(), preset); + + // A file written before the flag existed has no `inverted` and keeps none on save + map.inverted.clear(); + let old = ExportPreset { name: "Old".into(), maps: vec![map] }; + let json = preset_to_json(&old).unwrap(); + assert!(!json.contains("inverted"), "{json}"); + assert_eq!(preset_from_json(&json).unwrap(), old); + assert!(preset_from_json(&json).unwrap().maps[0].inverted.is_empty()); +} + +#[test] +fn validation_rejects_inverting_a_channel_the_map_lacks() { + let ok = ExportPreset { name: "Mine".into(), maps: vec![invert_map(8, vec![Dest::R])] }; + ok.validate().unwrap(); + let mut bad = ok.clone(); + bad.maps[0].inverted = vec![Dest::L]; + assert!(bad.validate().is_err()); + bad.maps[0].inverted = vec![Dest::R, Dest::R]; + assert!(bad.validate().is_err()); +} + +#[test] +fn inverting_a_colour_channel_inverts_the_linear_value_before_encoding() { + let fx = Fx::new(&default_channels()); + let base = |inverted: Vec, size: Option| { + let map = MapSpec { + file: "col".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: [Dest::R, Dest::G, Dest::B] + .into_iter() + .zip(0u8..) + .map(|(d, k)| (d, SourceRef::Channel { channel: Channel::BaseColor, component: k })) + .collect(), + inverted, + }; + let mut opts = ExportOptions::new(ExportPreset { name: "c".into(), maps: vec![map] }); + opts.size = size; + decode(find(&fx.render(&opts), "col")).to_rgb8() + }; + let (plain, inv) = (base(Vec::new(), None), base(vec![Dest::R], None)); + + // Texel (9, 9): linear red 9/63, written as sRGB + let want = linear_to_srgb(1.0 - 9.0 / 63.0) * 255.0; + assert!((inv.get_pixel(9, 9)[0] as f32 - want).abs() <= 1.0, "{} vs {want}", inv.get_pixel(9, 9)[0]); + assert_eq!(inv.get_pixel(9, 9).0[1..], plain.get_pixel(9, 9).0[1..], "G and B stay"); + + // A size override goes through the resize path: the left-most texels are 1 - 0 -> white red + let half = base(vec![Dest::R], Some(RES / 2)); + assert_eq!(half.width(), RES / 2); + assert!(half.get_pixel(0, 5)[0] >= 250, "{}", half.get_pixel(0, 5)[0]); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 17820459..73b6a055 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -51,8 +51,8 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ - BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, - set_project_open_limit_gib, + BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, + save_project_bytes, set_project_open_limit_gib, }; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 9c737f16..0b02f3c3 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -72,7 +72,7 @@ pub fn usd_export_options() -> ExportOptions { "ClearcoatRoughness" => gray(ch(Channel::CoatRoughness, 0)), _ => gray(ch(Channel::Opacity, 0)), }; - MapSpec { file: stem.into(), format: FileFormat::Png, bit_depth: 8, channels } + MapSpec { file: stem.into(), format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() } }) .collect(); super::png8_options(ExportPreset { name: "USD preview surface".into(), maps }, NormalFormat::OpenGl) diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 92e52f72..379a71d3 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -292,21 +292,23 @@ fn check_buffer_uris(doc: &gltf::Document) -> Result<()> { } pub(crate) fn percent_decode(s: &str) -> Option { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while let Some(&c) = b.get(i) { - let hex = |k: usize| b.get(k).and_then(|h| (*h as char).to_digit(16)); - match (c, hex(i + 1), hex(i + 2)) { - (b'%', Some(h), Some(l)) => { - out.push((h * 16 + l) as u8); - i += 3; - } - _ => { - out.push(c); - i += 1; - } + craft_mesh::gltf::uri_decode_strict(s) +} + +#[cfg(test)] +mod uri_decode_tests { + use super::percent_decode; + + #[test] + fn strict_shared_uri_decoder_preserves_reference_policy() { + assert_eq!(percent_decode("texture%20é%2B.png"), Some("texture é+.png".into())); + assert_eq!(percent_decode("a+b%GG%2"), Some("a+b%GG%2".into())); + assert_eq!(percent_decode("%252e%252e"), Some("%2e%2e".into())); + // Decoding does not replace the external-reference confinement checks. + assert_eq!(percent_decode("%2e%2e%2fsecret"), Some("../secret".into())); + assert_eq!(percent_decode("%00"), Some("\0".into())); + for uri in ["%FF", "%C0%AF", "%ED%A0%80", "%E2%82"] { + assert_eq!(percent_decode(uri), None, "{uri}"); } } - String::from_utf8(out).ok() } diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index f0231d11..5b4a0c7c 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -130,6 +130,9 @@ pub(crate) struct RawMesh { pub colors: Option>, /// Triangles (vertex indices) per (material, part name); an empty part is unnamed. pub groups: Vec<(String, String, Vec)>, + // Build-time index; group names are restored only after polygon collection ends + // Nested maps allow borrowed lookups without allocating keys for every polygon + group_index: HashMap>, pub warnings: Vec, pub cameras: Vec, /// Materials whose base color is not plain white (glTF). @@ -148,11 +151,13 @@ pub(crate) struct RawBaseColor { impl RawMesh { /// Triangle list of `material` in `part`, created on first use. pub fn group(&mut self, material: &str, part: &str) -> &mut Vec { - let i = match self.groups.iter().position(|(m, p, _)| m == material && p == part) { + let i = match self.group_index.get(material).and_then(|parts| parts.get(part)).copied() { Some(i) => i, None => { - self.groups.push((material.to_string(), part.to_string(), Vec::new())); - self.groups.len() - 1 + let i = self.groups.len(); + self.groups.push((material.to_owned(), part.to_owned(), Vec::new())); + self.group_index.entry(material.to_owned()).or_default().insert(part.to_owned(), i); + i } }; &mut self.groups[i].2 diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 267aa8ea..e2d1fb52 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -31,10 +31,11 @@ fn read_inner(bytes: &[u8]) -> Result { let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Vec::new(), Vec::new(), Vec::new()); let (mut missing_normals, mut missing_uvs) = (false, false); - for mesh in &scene.meshes { + for (mesh_id, mesh) in scene.meshes.iter().enumerate() { + // The shared reader preserves declarations as meshes, even when their names match + let declaration = mesh_id.to_string(); for part in &mesh.parts { let material = part.material.and_then(|i| scene.materials.get(i)).map_or("Default", |m| m.name.as_str()); - let name = if part.name.is_empty() { mesh.name.as_str() } else { part.name.as_str() }; // OBJ model/material runs have independent v/vt/vn deduplication. let mut ids = HashMap::new(); for face in part.faces() { @@ -73,10 +74,16 @@ fn read_inner(bytes: &[u8]) -> Result { }; polygon.push(id); } - raw.polygon(material, name, &polygon); + raw.polygon(material, &declaration, &polygon); } } } + // Restore display names only after grouping by declaration and material + for (_, name, _) in &mut raw.groups { + if let Some(mesh) = name.parse::().ok().and_then(|id| scene.meshes.get(id)) { + *name = mesh.name.clone(); + } + } if missing_uvs { raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } @@ -85,3 +92,23 @@ fn read_inner(bytes: &[u8]) -> Result { raw.colors = any_colors.then_some(colors); Ok(raw) } + +#[cfg(test)] +mod tests { + #[test] + #[ignore = "release benchmark for declaration-heavy OBJ input"] + fn declaration_import_benchmark() { + for count in [10_000, 50_000] { + let mut source = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n"); + for _ in 0..count { + source.push_str("o repeated\nf 1 2 3\n"); + } + let start = std::time::Instant::now(); + let raw = super::read(source.as_bytes()).unwrap(); + println!("{count} declarations: {:?}", start.elapsed()); + assert_eq!(raw.groups.len(), count); + assert_eq!(raw.triangle_count(), count); + assert!(raw.groups.iter().all(|(_, name, tris)| name == "repeated" && tris.len() == 3)); + } + } +} diff --git a/crates/formats/src/mesh_import/stl.rs b/crates/formats/src/mesh_import/stl.rs index e087b711..95eeee6b 100644 --- a/crates/formats/src/mesh_import/stl.rs +++ b/crates/formats/src/mesh_import/stl.rs @@ -55,7 +55,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { if has_colors { raw.colors = Some(vertex_colors); } - raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect())); + let vertex_count = raw.positions.len() as u32; + raw.group("Default", "").extend(0..vertex_count); Ok(raw) } diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index 88509a05..99f9173c 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -610,3 +610,22 @@ fn ply_face_element_before_vertex_element() { let bad = format!("{head}3 0 1 5\n0 0 0\n1 0 0\n0 1 0\n"); assert!(import_mesh_bytes("a.ply", bad.as_bytes()).is_err()); } + +#[test] +fn group_index_preserves_order_and_reuses_nonadjacent_material_parts() { + let mut raw = super::RawMesh::default(); + for i in 0..1000 { + raw.group("shared", &i.to_string()).extend_from_slice(&[0, 1, 2]); + } + for i in (0..1000).rev() { + raw.group("shared", &i.to_string()).extend_from_slice(&[3, 4, 5]); + } + raw.group("other", "0").extend_from_slice(&[6, 7, 8]); + assert_eq!(raw.groups.len(), 1001); + for (i, (material, part, indices)) in raw.groups.iter().take(1000).enumerate() { + assert_eq!(material, "shared"); + assert_eq!(part, &i.to_string()); + assert_eq!(indices, &[0, 1, 2, 3, 4, 5]); + } + assert_eq!(raw.groups[1000], ("other".into(), "0".into(), vec![6, 7, 8])); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index c77e665a..06c9ac11 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -19,7 +19,7 @@ pub(crate) fn virt(map: VirtualMap, component: u8) -> SourceRef { /// `$mesh_$textureSet_` PNG. fn map(suffix: &str, bit_depth: u8, channels: Vec<(Dest, SourceRef)>) -> MapSpec { - MapSpec { file: format!("$mesh_$textureSet_{suffix}"), format: FileFormat::Png, bit_depth, channels } + MapSpec { file: format!("$mesh_$textureSet_{suffix}"), format: FileFormat::Png, bit_depth, channels, inverted: Vec::new() } } pub(crate) fn rgb(f: impl Fn(u8) -> SourceRef) -> Vec<(Dest, SourceRef)> { @@ -68,7 +68,7 @@ pub(crate) const GLTF_SHEEN: &str = "Sheen"; /// glTF metallic-roughness maps (8-bit PNG), plus the clear coat and sheen extension maps where /// the texture set has those channels; `file` turns a stem above into a file template. pub(crate) fn gltf_pbr_maps(file: impl Fn(&str) -> String) -> Vec { - let spec = |stem: &str, channels| MapSpec { file: file(stem), format: FileFormat::Png, bit_depth: 8, channels }; + let spec = |stem: &str, channels| MapSpec { file: file(stem), format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() }; let mut sheen = rgb(|k| virt(VirtualMap::SheenTint, k)); sheen.push((Dest::A, ch(Channel::SheenRoughness, 0))); vec![ diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index fd13bec2..9f2053fc 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -81,9 +81,12 @@ pub struct ProjectFile { pub warnings: Vec, } +/// Maximum length of a resource name after sanitization. +pub const MAX_RESOURCE_NAME_LEN: usize = 120; + /// A resource name safe as a zip entry and a file name: `[A-Za-z0-9_.-]`, at most 120 chars. pub fn sanitize_resource_name(name: &str) -> String { - let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).take(120).collect(); + let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-') { c } else { '_' }).take(MAX_RESOURCE_NAME_LEN).collect(); let s = s.trim_start_matches('.').to_string(); if s.is_empty() { "resource".into() } else { s } } diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index b0d311df..0d1d54d5 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -71,6 +71,19 @@ impl Mesh { self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p))) } + /// Axis-aligned bounds of the triangles drawn with `material` (None when none are). + pub fn bounds_of_material(&self, material: usize) -> Option<(Vec3, Vec3)> { + let mut bounds: Option<(Vec3, Vec3)> = None; + for triangle in self.triangles_of(material) { + let Some(corners) = self.tri(triangle) else { continue }; + for corner in corners { + let Some(position) = self.positions.get(corner) else { continue }; + bounds = Some(bounds.map_or((*position, *position), |(lo, hi)| (lo.min(*position), hi.max(*position)))); + } + } + bounds + } + /// Bounding-sphere radius around the bounds center (at least a small epsilon). pub fn radius(&self) -> f32 { let (lo, hi) = self.bounds(); @@ -480,6 +493,13 @@ mod tests { assert_eq!(m.triangles_of(0).collect::>(), vec![0, 1]); } + #[test] + fn bounds_of_a_material_cover_only_its_triangles() { + let m = quad(); + assert_eq!(m.bounds_of_material(0), Some((Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)))); + assert_eq!(m.bounds_of_material(1), None); + } + #[test] fn wire_edges_leave_out_polygon_diagonals() { let mut m = quad(); diff --git a/crates/paint/src/alpha_params.rs b/crates/paint/src/alpha_params.rs new file mode 100644 index 00000000..217db8c9 --- /dev/null +++ b/crates/paint/src/alpha_params.rs @@ -0,0 +1,63 @@ +//! Parameters shared by every brush alpha: extent inside the stamp, roundness, contrast, invert. +//! The defaults leave a stamp exactly as it was before the parameters existed. + +use serde::{Deserialize, Serialize}; + +/// Smallest extent a stamp's alpha can be shrunk to along one axis +pub const MIN_ALPHA_SIZE: f32 = 0.05; + +/// Highest contrast; 1 leaves the alpha's values as they are +pub const MAX_ALPHA_CONTRAST: f32 = 8.0; + +/// How the alpha is placed and graded inside the stamp square (see [`crate::Shape::sample`]). +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct AlphaParams { + /// Width of the alpha as a fraction of the stamp (1 = the whole stamp) + pub size_x: f32, + /// Height of the alpha as a fraction of the stamp + pub size_y: f32, + /// Round procedural shape only: 1 = circle, 0 = square + pub roundness: f32, + /// Steepness of the values around 0.5 (1 = unchanged, more = harder edges) + pub contrast: f32, + /// Swap paint and no paint inside the stamp square + pub invert: bool, +} + +impl Default for AlphaParams { + fn default() -> Self { + AlphaParams { size_x: 1.0, size_y: 1.0, roundness: 1.0, contrast: 1.0, invert: false } + } +} + +impl AlphaParams { + /// Every value into its valid range (input from the UI, a file or an agent) + pub fn sanitized(self) -> AlphaParams { + let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default }; + AlphaParams { + size_x: clamp_finite(self.size_x, MIN_ALPHA_SIZE, 1.0, 1.0), + size_y: clamp_finite(self.size_y, MIN_ALPHA_SIZE, 1.0, 1.0), + roundness: clamp_finite(self.roundness, 0.0, 1.0, 1.0), + contrast: clamp_finite(self.contrast, 1.0, MAX_ALPHA_CONTRAST, 1.0), + invert: self.invert, + } + } + + /// The local coordinates the alpha is sampled at: the stamp's, stretched so the alpha fills + /// only its extent + pub fn place(&self, lx: f32, ly: f32) -> (f32, f32) { + (lx / self.size_x, ly / self.size_y) + } + + /// Contrast, then invert, on a sampled value `v` at stamp coordinates (`lx`, `ly`). Invert + /// stays inside the stamp square, so the area around a shape isn't flooded with paint. + pub fn grade(&self, v: f32, lx: f32, ly: f32) -> f32 { + let v = if self.contrast == 1.0 { v } else { ((v - 0.5) * self.contrast + 0.5).clamp(0.0, 1.0) }; + match self.invert { + true if lx.abs() <= 1.0 && ly.abs() <= 1.0 => 1.0 - v, + true => 0.0, + false => v, + } + } +} diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 2cde78c8..dd55d182 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -5,6 +5,7 @@ use texturecraft_compose::ImageRes; use texturecraft_geom::glam::{Mat3, Vec3}; use texturecraft_texel::noise; +use crate::alpha_params::AlphaParams; use crate::alphas::AlphaImage; /// How the stamp plane is oriented. @@ -93,23 +94,35 @@ pub struct Shape<'a> { pub alpha: BrushAlpha, pub image: Option<&'a ImageRes>, pub library: Option<&'a AlphaImage>, + /// Extent, roundness, contrast and invert shared by every kind of alpha + pub params: AlphaParams, /// Mip level of `library` to sample (set per stamp by [`Shape::at_radius`]). pub level: usize, } impl Shape<'_> { - /// Shape value at local stamp coordinates (see [`BrushAlpha::sample`]). + /// Shape value at local stamp coordinates (see [`BrushAlpha::sample`]), placed and graded by + /// the [`AlphaParams`]: the same for image, library and procedural alphas. pub fn sample(&self, lx: f32, ly: f32, hardness: f32, seed: u32) -> f32 { - match (self.image, self.library) { - (Some(img), _) => image_alpha(img, lx, ly), - (None, Some(lib)) => lib.sample(self.level, lx, ly), - (None, None) => self.alpha.sample(lx, ly, hardness, seed), - } + let (x, y) = self.params.place(lx, ly); + let value = match (self.image, self.library) { + (Some(img), _) => image_alpha(img, x, y), + (None, Some(lib)) => lib.sample(self.level, x, y), + (None, None) if self.alpha == BrushAlpha::Round && self.params.roundness < 1.0 => { + // Between the square's edge distance (0) and the circle's (1) + let (square, circle) = (x.abs().max(y.abs()), (x * x + y * y).sqrt()); + 1.0 - smoothstep(hardness.min(0.999), 1.0, square + (circle - square) * self.params.roundness) + } + (None, None) => self.alpha.sample(x, y, hardness, seed), + }; + self.params.grade(value, lx, ly) } /// This shape for a stamp `radius` texels wide (picks the library alpha's mip level). pub fn at_radius(self, radius: f32) -> Self { - Shape { level: self.library.map_or(0, |l| l.level_for(radius)), ..self } + // A shrunk alpha covers fewer texels, so it wants a finer mip level + let covered = radius * self.params.size_x.min(self.params.size_y); + Shape { level: self.library.map_or(0, |l| l.level_for(covered)), ..self } } } @@ -311,6 +324,9 @@ pub struct BrushSettings { /// Built-in library alpha id used as the stamp shape (see [`crate::alphas`]). #[serde(default)] pub alpha_library: Option, + /// Extent, roundness, contrast and invert of whichever alpha is used. + #[serde(default)] + pub alpha_params: AlphaParams, /// Only paint surfaces facing the camera. pub backface_culling: bool, /// Half-depth of the stamp volume relative to the radius (thinner = less bleed into folds). @@ -343,6 +359,7 @@ impl Default for BrushSettings { alpha: BrushAlpha::Round, alpha_image: None, alpha_library: None, + alpha_params: AlphaParams::default(), backface_culling: true, depth: 1.0, symmetry: Symmetry::default(), @@ -379,6 +396,7 @@ impl BrushSettings { jitter_flow: clamp_finite(self.jitter_flow, 0.0, 1.0, 0.0), jitter_position: clamp_finite(self.jitter_position, 0.0, 4.0, 0.0), depth: clamp_finite(self.depth, 0.05, 4.0, 1.0), + alpha_params: self.alpha_params.sanitized(), symmetry: Symmetry { radial: self.symmetry.radial.min(MAX_RADIAL_COPIES), axis: self.symmetry.axis.min(LAST_AXIS), @@ -426,9 +444,9 @@ mod tests { #[test] fn image_alpha_follows_the_image_and_is_zero_outside() { - // Left half white, right half black (2×1 image, sampled at texel centers). + // Left half white, right half black (2×1 image, sampled at texel centers) let img = ImageRes { width: 2, height: 1, rgba: vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], srgb: true }; - let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, level: 0 }; + let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 }; assert!(shape.sample(-0.5, 0.0, 0.5, 0) > 0.99); assert!(shape.sample(0.5, 0.0, 0.5, 0) < 0.01); assert_eq!(shape.sample(1.5, 0.0, 0.5, 0), 0.0); @@ -443,4 +461,120 @@ mod tests { assert!(b.hardness < 1.0); assert!(b.spacing > 0.0); } + + /// A grid over the stamp square and beyond it + fn grid() -> impl Iterator { + (-30..=30).flat_map(|i| (-30..=30).map(move |j| (i as f32 / 20.0, j as f32 / 20.0))) + } + + /// Width and height (in grid steps) of the area where `shape` is above zero + fn extent(shape: &Shape, hardness: f32) -> (usize, usize) { + let (mut xs, mut ys) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); + for (x, y) in grid().filter(|&(x, y)| shape.sample(x, y, hardness, 1) > 0.0) { + xs.insert((x * 20.0) as i32); + ys.insert((y * 20.0) as i32); + } + (xs.len(), ys.len()) + } + + fn procedural(alpha: BrushAlpha, params: AlphaParams) -> Shape<'static> { + Shape { alpha, image: None, library: None, params, level: 0 } + } + + #[test] + fn default_parameters_reproduce_every_alpha_exactly() { + let img = ImageRes { + width: 3, + height: 2, + rgba: vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]], + srgb: true, + }; + let library = crate::alphas::library().first().map(|alpha| alpha.image()); + let kinds = BrushAlpha::ALL.map(|alpha| Shape { alpha, image: None, library: None, params: AlphaParams::default(), level: 0 }); + for shape in kinds.into_iter().chain([ + Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 }, + Shape { alpha: BrushAlpha::Round, image: None, library, params: AlphaParams::default(), level: 0 }, + ]) { + for (x, y) in grid() { + let before = match (shape.image, shape.library) { + (Some(img), _) => image_alpha(img, x, y), + (None, Some(lib)) => lib.sample(shape.level, x, y), + (None, None) => shape.alpha.sample(x, y, 0.4, 7), + }; + assert_eq!(shape.sample(x, y, 0.4, 7).to_bits(), before.to_bits(), "{:?} at ({x}, {y})", shape.alpha); + } + } + } + + #[test] + fn size_x_half_halves_the_width_and_keeps_the_height() { + for alpha in [BrushAlpha::Round, BrushAlpha::Square] { + let (width, height) = extent(&procedural(alpha, AlphaParams::default()), 0.5); + let (narrow_width, narrow_height) = extent(&procedural(alpha, AlphaParams { size_x: 0.5, ..AlphaParams::default() }), 0.5); + assert_eq!(narrow_height, height, "{alpha:?}"); + assert!((narrow_width as f32 - width as f32 / 2.0).abs() <= 2.0, "{alpha:?}: {narrow_width} of {width}"); + + let (flat_width, flat_height) = extent(&procedural(alpha, AlphaParams { size_y: 0.25, ..AlphaParams::default() }), 0.5); + assert_eq!(flat_width, width, "{alpha:?}"); + assert!((flat_height as f32 - height as f32 / 4.0).abs() <= 2.0, "{alpha:?}: {flat_height} of {height}"); + } + } + + #[test] + fn sizes_apply_to_image_and_library_alphas_too() { + let img = ImageRes { width: 1, height: 1, rgba: vec![[1.0; 4]], srgb: true }; + let params = AlphaParams { size_x: 0.5, ..AlphaParams::default() }; + let image = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params, level: 0 }; + assert_eq!((image.sample(0.4, 0.0, 0.5, 0) > 0.99, image.sample(0.6, 0.0, 0.5, 0)), (true, 0.0)); + + let library = crate::alphas::find("square").map(|alpha| alpha.image()); + let shape = |params| Shape { alpha: BrushAlpha::Round, image: None, library, params, level: 0 }; + assert!(shape(AlphaParams::default()).sample(0.7, 0.0, 0.5, 0) > 0.5, "a library square is wide open"); + assert_eq!(shape(params).sample(0.7, 0.0, 0.5, 0), 0.0); + } + + #[test] + fn invert_flips_values_inside_the_stamp_square_only() { + let invert = AlphaParams { invert: true, ..AlphaParams::default() }; + for alpha in BrushAlpha::ALL { + for (x, y) in grid() { + let (plain, inverted) = (procedural(alpha, AlphaParams::default()).sample(x, y, 0.5, 3), procedural(alpha, invert).sample(x, y, 0.5, 3)); + let expected = if x.abs() <= 1.0 && y.abs() <= 1.0 { 1.0 - plain } else { 0.0 }; + assert!((inverted - expected).abs() < 1e-6, "{alpha:?} at ({x}, {y})"); + } + } + } + + #[test] + fn roundness_zero_turns_the_round_shape_into_a_square_footprint() { + let square = AlphaParams { roundness: 0.0, ..AlphaParams::default() }; + assert_eq!(procedural(BrushAlpha::Round, AlphaParams::default()).sample(0.9, 0.9, 0.5, 0), 0.0, "a circle leaves the corner empty"); + assert!(procedural(BrushAlpha::Round, square).sample(0.9, 0.9, 0.5, 0) > 0.0); + assert_eq!(extent(&procedural(BrushAlpha::Round, square), 0.99), extent(&procedural(BrushAlpha::Square, AlphaParams::default()), 0.99)); + + let half = AlphaParams { roundness: 0.5, ..AlphaParams::default() }; + let (round, rounded) = (procedural(BrushAlpha::Round, AlphaParams::default()), procedural(BrushAlpha::Round, half)); + assert!(rounded.sample(0.75, 0.75, 0.5, 0) > round.sample(0.75, 0.75, 0.5, 0), "between circle and square"); + + // Other shapes have no roundness + let star = |params| procedural(BrushAlpha::Star, params).sample(0.3, 0.2, 0.5, 0); + assert_eq!(star(square), star(AlphaParams::default())); + } + + #[test] + fn contrast_steepens_the_values_around_one_half() { + let sharp = AlphaParams { contrast: 4.0, ..AlphaParams::default() }; + let (soft, hard) = (procedural(BrushAlpha::Round, AlphaParams::default()), procedural(BrushAlpha::Round, sharp)); + let [low, high] = [0.8, 0.3].map(|x| (soft.sample(x, 0.0, 0.0, 0), hard.sample(x, 0.0, 0.0, 0))); + assert!(low.0 < 0.5 && low.1 < low.0, "dark values get darker: {low:?}"); + assert!(high.0 > 0.5 && high.1 > high.0, "light values get lighter: {high:?}"); + assert_eq!(hard.sample(1.2, 0.0, 0.0, 0), 0.0, "outside the shape stays empty"); + } + + #[test] + fn sanitize_clamps_alpha_parameters() { + let wild = AlphaParams { size_x: 0.0, size_y: f32::NAN, roundness: 3.0, contrast: -2.0, invert: true }; + let clean = BrushSettings { alpha_params: wild, ..BrushSettings::default() }.sanitized().alpha_params; + assert_eq!(clean, AlphaParams { size_x: crate::alpha_params::MIN_ALPHA_SIZE, size_y: 1.0, roundness: 1.0, contrast: 1.0, invert: true }); + } } diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index a41285c3..8351ca8f 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -244,7 +244,7 @@ impl Staging { /// the same arguments will write. pub fn stage_mask(&mut self, pixels: &PixelStore, effect: LayerId, value: f32, src: &CommitSource) { let value = [value.clamp(0.0, 1.0)]; - let b = Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: None }; + let b = Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }; self.images.entry(None).or_default().stage(pixels.masks.get(&effect), 2, &b, src); } @@ -290,6 +290,8 @@ pub struct CommitSource<'a> { pub per_texel: Option>, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). pub carried: Option<&'a BTreeMap>, + /// Scalar values sampled from a mask by clone or smudge. + pub carried_mask: Option<&'a TileImage>, } /// Commit a stroke into paint layer `layer` (channels in `values`; erase clears every painted @@ -300,7 +302,8 @@ pub fn commit_layer(pixels: &mut PixelStore, layer: LayerId, size: (u32, u32), v for &c in &channels { pixels.layer_mut(layer, c, size); } - // The channels blend in parallel too: an 8K stroke touches hundreds of tiles per channel. + + // The channels blend in parallel too: an 8K stroke touches hundreds of tiles per channel let images: Vec<(Channel, &mut TileImage, Option)> = pixels.layers.iter_mut().filter(|((id, c), _)| *id == layer && channels.contains(c)).map(|((_, c), img)| (*c, img, staging.take(Some(*c)))).collect(); images.into_par_iter().for_each(|(c, img, staged)| over(img, &layer_blend(c, values, &src), &src, staged)); @@ -310,7 +313,7 @@ pub fn commit_layer(pixels: &mut PixelStore, layer: LayerId, size: (u32, u32), v pub fn commit_mask(pixels: &mut PixelStore, effect: LayerId, size: (u32, u32), value: f32, src: CommitSource, staging: &mut Staging) { let img = pixels.mask_mut(effect, size); let value = [value.clamp(0.0, 1.0)]; - over(img, &Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: None }, &src, staging.take(None)); + over(img, &Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }, &src, staging.take(None)); } /// Commit a stroke into a coverage-only image (1 component), e.g. the quick mask. @@ -323,7 +326,7 @@ mod tests { use super::*; fn src<'a>(alpha: &'a TileImage, tiles: &'a BTreeSet<(u32, u32)>, opacity: f32, erase: bool) -> CommitSource<'a> { - CommitSource { alpha, tiles, opacity, erase, per_texel: None, carried: None } + CommitSource { alpha, tiles, opacity, erase, per_texel: None, carried: None, carried_mask: None } } fn alpha(v: f32) -> (TileImage, BTreeSet<(u32, u32)>) { @@ -394,6 +397,20 @@ mod tests { CommitSource { carried, ..src(a, tiles, 0.8, erase) } } + #[test] + fn layer_roughness_does_not_override_mask_coverage() { + let (alpha, tiles) = alpha(1.0); + let mut roughness = TileImage::new(64, 64, 1); + roughness.set(5, 5, &[to_u16(0.25)]); + let carried = [(Channel::Roughness, roughness)].into(); + let source = CommitSource { carried: Some(&carried), ..src(&alpha, &tiles, 1.0, false) }; + let mut pixels = PixelStore::default(); + + commit_mask(&mut pixels, LayerId(1), (64, 64), 1.0, source, &mut Staging::default()); + + assert_eq!(pixels.masks[&LayerId(1)].get(5, 5)[0], u16::MAX); + } + #[test] fn staged_commits_match_and_stale_copies_are_ignored() { let vals: BTreeMap = [(Channel::BaseColor, [0.2, 0.4, 0.6]), (Channel::Height, [-0.5; 3])].into_iter().collect(); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 88e68e1d..31fcf547 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -11,6 +11,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod alpha_params; pub mod alphas; pub mod brush; pub mod commit; @@ -24,9 +25,10 @@ pub mod stroke; pub mod text; pub mod visibility; +pub use alpha_params::AlphaParams; pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Particles, Shape, Symmetry, image_alpha}; pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask}; -pub use path::{Lasso, spline, spline_segments}; +pub use path::{Lasso, spline, spline_segments, spline_segments_with_corners, spline_with_corners}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; pub use stamp_source::StampSource; diff --git a/crates/paint/src/path.rs b/crates/paint/src/path.rs index 6614857b..108d80c3 100644 --- a/crates/paint/src/path.rs +++ b/crates/paint/src/path.rs @@ -8,8 +8,14 @@ const MAX_SEGMENT_SAMPLES: f32 = 1024.0; /// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too) pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { + spline_with_corners(points, &[], closed, step) +} + +/// [`spline`] with corner points: the curve turns sharply at a point whose entry in `corners` is true (a missing entry is smooth). +/// Each run between corners is its own Catmull-Rom spline ending on the corners, so two adjacent corners give a straight segment. +pub fn spline_with_corners(points: &[Vec2], corners: &[bool], closed: bool, step: f32) -> Vec { let mut out: Vec = points.first().copied().into_iter().collect(); - for segment in segment_samples(points, closed, step) { + for segment in segment_samples(points, corners, closed, step) { out.extend(segment); } out @@ -17,16 +23,20 @@ pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { /// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec> { - segment_samples(points, closed, step).map(Iterator::collect).collect() + spline_segments_with_corners(points, &[], closed, step) +} + +/// [`spline_segments`] with corner points as in [`spline_with_corners`] +pub fn spline_segments_with_corners(points: &[Vec2], corners: &[bool], closed: bool, step: f32) -> Vec> { + segment_samples(points, corners, closed, step).map(Iterator::collect).collect() } /// Stream samples so a flat curve does not allocate and retain every segment alongside its output -fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator> + '_ { +fn segment_samples<'a>(points: &'a [Vec2], corners: &'a [bool], closed: bool, step: f32) -> impl Iterator + 'a> + 'a { let n = points.len(); - let at = move |i: isize| { - let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) }; - points.get(i as usize).copied().unwrap_or_default() - }; + let wrap = move |i: isize| if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) }; + let at = move |i: isize| points.get(wrap(i) as usize).copied().unwrap_or_default(); + let corner = move |i: isize| corners.get(wrap(i) as usize).copied().unwrap_or(false); let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 }; let segments = if n < 2 { 0 @@ -36,7 +46,11 @@ fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator [Vec2; 4] { + [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)] + } + + /// Distance from `p` to the closed polygon `poly` + fn edge_distance(poly: &[Vec2], p: Vec2) -> f32 { + poly.iter() + .zip(poly.iter().cycle().skip(1)) + .map(|(a, b)| { + let e = *b - *a; + (*a + e * ((p - *a).dot(e) / e.length_squared()).clamp(0.0, 1.0)).distance(p) + }) + .fold(f32::MAX, f32::min) + } + + #[test] + fn all_corner_closed_path_is_the_straight_edged_quadrilateral() { + let pts = square(); + let curve = spline_with_corners(&pts, &[true; 4], true, 0.5); + assert!(curve.len() > 40); + for p in &curve { + assert!(edge_distance(&pts, *p) < 1e-3, "{p} left the edges"); + } + for corner in pts { + assert!(curve.iter().any(|q| q.distance(corner) < 1e-4), "{corner}"); + } + let smooth = spline(&pts, true, 0.5); + assert!(smooth.iter().any(|q| edge_distance(&pts, *q) > 0.5), "the smooth curve bulges off the edges"); + } + + #[test] + fn mixed_corners_split_the_spline_into_runs() { + let pts = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 8.0), Vec2::new(20.0, 0.0), Vec2::new(30.0, 8.0), Vec2::new(40.0, 0.0)]; + let corners = [false, false, true, false, false]; + let mixed = spline_segments_with_corners(&pts, &corners, false, 0.5); + let smooth = spline_segments(&pts, false, 0.5); + + // The segments next to the corner differ; the corner point itself is still reached + assert_ne!(mixed[1], smooth[1]); + assert_ne!(mixed[2], smooth[2]); + assert_eq!(mixed[1].last().copied(), Some(pts[2])); + + // Neither side of the corner overshoots past it: the turn is a cusp, not a loop + let before = mixed[1][mixed[1].len() - 2]; + let after = mixed[2][0]; + assert!(before.x < 20.0 && after.x > 20.0); + + // Pure smooth input is unchanged, and a short or missing flag list means smooth + assert_eq!(spline_segments_with_corners(&pts, &[], false, 0.5), smooth); + assert_eq!(spline_segments_with_corners(&pts, &[false; 5], false, 0.5), smooth); + assert_eq!(spline_with_corners(&pts, &[false, false], false, 0.5), spline(&pts, false, 0.5)); + } + #[test] fn lasso_covers_the_inside_with_a_soft_edge() { let sq = Lasso::new(vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)]); diff --git a/crates/paint/src/pickup.rs b/crates/paint/src/pickup.rs index cd45abc1..c70c1f92 100644 --- a/crates/paint/src/pickup.rs +++ b/crates/paint/src/pickup.rs @@ -2,17 +2,25 @@ //! painting the tool's material. The carried values are kept straight (not premultiplied) per //! channel next to the stroke alpha, so the live preview and the commit read them directly. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; -use texturecraft_compose::Composite; use texturecraft_compose::eval::FlatTile; +use texturecraft_compose::{Composite, MASK_CHANNEL, PaintTarget}; use texturecraft_core::Channel; use texturecraft_geom::{NO_TRI, UvGBuffer}; -use texturecraft_texel::{TILE_AREA, TileImage, from_u16, to_u16}; +use texturecraft_texel::{TILE, TILE_AREA, TileImage, from_u16, to_u16}; +use crate::StampSource; use crate::commit::{dec, enc}; +mod lane; +mod pickup_snapshot; + +pub use pickup_snapshot::PickupSnapshot; + +use lane::Lane; + /// How a pickup stroke finds the values it deposits. #[derive(Clone, Copy, Debug, PartialEq)] pub enum PickupMode { @@ -32,12 +40,18 @@ pub struct Pickup { /// How much of `source` there is to read per texel (a single layer's coverage); None reads /// everywhere. coverage: Option, + mask: bool, + snapshot: Option>, + loaded: BTreeSet<(u32, u32)>, /// Texels outside the texture set's UV islands are never read. gbuf: Arc, /// Straight values per painted channel; the stroke alpha lives in the stroke canvas. pub values: BTreeMap, /// Previous smudge stamp center (texels). prev: Option<[f32; 2]>, + /// Smudge with symmetry: each copy drags its own trail (see [`Pickup::isolate_copies`]). + isolated: bool, + lanes: Vec, /// Per-stamp scratch: texels that receive values, and the values read for them. reads: Vec<(u32, u32, f32)>, read_values: Vec<[f32; 3]>, @@ -56,7 +70,21 @@ impl Pickup { /// A pickup reading `source` (whose resolution is the stroke's) for `channels`. pub fn new(mode: PickupMode, source: Composite, gbuf: Arc, channels: impl IntoIterator) -> Pickup { let values = channels.into_iter().map(|c| (c, TileImage::new(source.resolution, source.height, c.components()))).collect(); - Pickup { mode, source, coverage: None, gbuf, values, prev: None, reads: Vec::new(), read_values: Vec::new() } + Pickup { + mode, + source, + coverage: None, + mask: false, + snapshot: None, + loaded: BTreeSet::new(), + gbuf, + values, + prev: None, + isolated: false, + lanes: Vec::new(), + reads: Vec::new(), + read_values: Vec::new(), + } } /// A pickup reading one layer alone, from its flattened tiles (premultiplied values plus @@ -64,10 +92,18 @@ impl Pickup { /// layer is empty the stroke deposits nothing. pub fn from_layer(mode: PickupMode, flat: &[FlatTile], size: (u32, u32), gbuf: Arc, channels: impl IntoIterator) -> Pickup { let channels: Vec = channels.into_iter().collect(); - let mut source = Composite::with_size(&channels, size.0, size.1); - let mut coverage = TileImage::new(size.0, size.1, 1); + let source = Composite::with_size(&channels, size.0, size.1); + let mut pickup = Self::new(mode, source, gbuf, channels); + pickup.coverage = Some(TileImage::new(size.0, size.1, 1)); + pickup.add_layer_tiles(flat); + pickup + } + + fn add_layer_tiles(&mut self, flat: &[FlatTile]) { + let Some(coverage) = self.coverage.as_mut() else { return }; + for (c, (tx, ty), data) in flat { - let Some(img) = source.channels.get_mut(c) else { continue }; + let Some(img) = self.source.channels.get_mut(c) else { continue }; let (n, kind) = (c.components(), c.kind()); let mut straight = vec![0u16; TILE_AREA * n]; let Some(cov) = coverage.tile_mut(*tx, *ty, &[0]) else { continue }; @@ -88,75 +124,192 @@ impl Pickup { } img.set_tile(*tx, *ty, Some(Arc::new(straight))); } - let mut p = Pickup::new(mode, source, gbuf, channels); - p.coverage = Some(coverage); - p } - fn covered(&self, x: u32, y: u32) -> bool { - let i = y as usize * self.gbuf.width as usize + x as usize; - x < self.gbuf.width && self.gbuf.tri.get(i).is_some_and(|t| *t != NO_TRI) + /// A pickup reading mask `values` (one component per texel, at the stroke's size): the stroke + /// carries mask values under [`MASK_CHANNEL`]. + pub fn from_mask(mode: PickupMode, values: TileImage, gbuf: Arc) -> Pickup { + let mut source = Composite::with_size(&[MASK_CHANNEL], values.width(), values.height()); + source.channels.insert(MASK_CHANNEL, values); + let mut pickup = Pickup::new(mode, source, gbuf, [MASK_CHANNEL]); + pickup.mask = true; + pickup } - /// Blend one stamp's texels `(x, y, alpha)` (stamp center `center` in texels) into the - /// stroke `alpha` and the carried values. False when nothing was deposited: the first smudge - /// stamp only picks up. - pub fn stamp(&mut self, alpha: &mut TileImage, texels: &[(u32, u32, f32)], center: [f32; 2]) -> bool { + /// Evaluate only the source tiles read by this stroke, sharing each tile across its stamps. + pub fn from_snapshot(mode: PickupMode, snapshot: PickupSnapshot, gbuf: Arc, channels: impl IntoIterator) -> Self { + let mask = matches!(snapshot.target, PaintTarget::Mask(_)); + let channels = if mask { vec![MASK_CHANNEL] } else { channels.into_iter().collect() }; + let source = Composite::with_size(&channels, gbuf.width, gbuf.height); + let coverage = (!mask).then(|| TileImage::new(gbuf.width, gbuf.height, 1)); + let mut pickup = Self::new(mode, source, gbuf, channels); + pickup.coverage = coverage; + pickup.mask = mask; + pickup.snapshot = Some(Arc::new(snapshot)); + pickup + } + + /// Only a mask pickup can supply coverage to a mask preview or commit. + pub fn mask_values(&self) -> Option<&TileImage> { + self.mask.then(|| self.values.get(&MASK_CHANNEL)).flatten() + } + + fn load_tiles(&mut self, texels: &[(u32, u32, f32)], shift: [i64; 2]) { + let Some(snapshot) = &self.snapshot else { return }; + let mut missing = Vec::new(); + let mut previous = None; + for &(x, y, alpha) in texels { + let Ok(x) = u32::try_from(i64::from(x).saturating_add(shift[0])) else { continue }; + let Ok(y) = u32::try_from(i64::from(y).saturating_add(shift[1])) else { continue }; + let tile = (x / TILE, y / TILE); + if previous == Some(tile) || alpha <= 0.0 || !covered(&self.gbuf, x, y) { + continue; + } + + previous = Some(tile); + if self.loaded.insert(tile) { + missing.push(tile); + } + } + if missing.is_empty() { + return; + } + + let Some(inputs) = snapshot.inputs(&self.gbuf) else { return }; + match snapshot.target { + PaintTarget::Layer(id) => { + if let Some(flat) = texturecraft_compose::flatten_layer(&inputs, id, &missing) { + self.add_layer_tiles(&flat); + } + } + PaintTarget::Mask(owner) => { + if let Some(output) = self.source.channels.get_mut(&MASK_CHANNEL) { + texturecraft_compose::eval::mask_values_into(&inputs, owner, &missing, output); + } + } + } + } + + /// Smudge with symmetry: every copy of the stamp (told apart by its [`StampSource`]) drags + /// its own trail. A copy reads the texture as it was when the stroke began plus what it + /// deposited itself, never what another copy deposited, so copies where they overlap (at the + /// mirror plane) do not smear each other. Their deposits still blend into the stroke, later + /// copies over earlier ones. + pub fn isolate_copies(&mut self) { + self.isolated = true; + } + + /// Blend one stamp's texels `(x, y, alpha)` (stamp center `center` in texels, `source` the + /// symmetry copy it belongs to, None for the stroke itself) into the stroke `alpha` and the + /// carried values. False when nothing was deposited: the first smudge stamp only picks up. + pub fn stamp(&mut self, alpha: &mut TileImage, texels: &[(u32, u32, f32)], center: [f32; 2], source: Option) -> bool { if texels.is_empty() { return false; } + + let mut lane = if self.isolated && matches!(self.mode, PickupMode::Smudge { .. }) { Some(self.take_lane(source, alpha)) } else { None }; let (shift, strength, smudge) = match self.mode { PickupMode::Clone { offset } => (offset, 1.0, false), PickupMode::Smudge { strength } => { - let Some(prev) = self.prev.replace(center) else { return false }; + let prev = match &mut lane { + Some(l) => l.prev.replace(center), + None => self.prev.replace(center), + }; + let Some(prev) = prev else { return self.put_back(lane, false) }; let d = [center[0] - prev[0], center[1] - prev[1]]; - // A jump (UV seam, lifted cursor) has nothing to drag along. + + // A jump across a UV seam or lifted cursor has nothing to drag along if d[0].hypot(d[1]) > extent(texels) { - return false; + return self.put_back(lane, false); } - // shortcut: nearest-texel pickup; bilinear would smooth sub-texel stamp spacing. + + // Nearest-texel pickup avoids smoothing sub-texel stamp spacing ([-(d[0].round() as i64), -(d[1].round() as i64)], strength.clamp(0.0, 1.0), true) } }; + self.load_tiles(texels, shift); let (w, h) = (i64::from(self.source.resolution), i64::from(self.source.height)); self.reads.clear(); self.read_values.clear(); for &(x, y, a) in texels { - let (sx, sy) = (i64::from(x) + shift[0], i64::from(y) + shift[1]); - if !(a > 0.0 && (0..w).contains(&sx) && (0..h).contains(&sy) && self.covered(sx as u32, sy as u32)) { + // Saturate hostile offsets so the bounds check rejects them without overflow + let (sx, sy) = (i64::from(x).saturating_add(shift[0]), i64::from(y).saturating_add(shift[1])); + if !(a > 0.0 && (0..w).contains(&sx) && (0..h).contains(&sy) && covered(&self.gbuf, sx as u32, sy as u32)) { continue; } + let (sx, sy) = (sx as u32, sy as u32); let a = a * strength * self.coverage.as_ref().map_or(1.0, |c| from_u16(c.get(sx, sy)[0])); if a <= 0.0 { continue; } - // Smudge reads what the stroke shows so far: carried values over the source. - let m = if smudge { from_u16(alpha.get(sx, sy)[0]) } else { 0.0 }; - for (c, img) in &self.values { + + // Each smudge copy reads its own deposits over the original source + let (seen_alpha, seen_values) = match &lane { + Some(l) => (&l.alpha, &l.values), + None => (&*alpha, &self.values), + }; + let m = if smudge { from_u16(seen_alpha.get(sx, sy)[0]) } else { 0.0 }; + for c in self.values.keys() { let base = self.source.value(*c, sx, sy); - let v = if m > 0.0 { - let carried = get(img, *c, sx, sy); - std::array::from_fn(|k| carried[k] * m + base[k] * (1.0 - m)) - } else { - base + let v = match seen_values.get(c) { + Some(img) if m > 0.0 => { + let carried = get(img, *c, sx, sy); + std::array::from_fn(|k| carried[k] * m + base[k] * (1.0 - m)) + } + _ => base, }; self.read_values.push(v); } self.reads.push((x, y, a)); } - let n = self.values.len(); - for (i, &(x, y, a)) in self.reads.iter().enumerate() { - let m = from_u16(alpha.get(x, y)[0]); - let m2 = a + m * (1.0 - a); - for (k, (c, img)) in self.values.iter_mut().enumerate() { - let Some(src) = self.read_values.get(i * n + k) else { continue }; - let old = get(img, *c, x, y); - put(img, *c, x, y, std::array::from_fn(|j| (src[j] * a + old[j] * m * (1.0 - a)) / m2.max(1e-6))); - } - alpha.set(x, y, &[to_u16(m2)]); + if let Some(l) = &mut lane { + deposit(&mut l.alpha, &mut l.values, &self.reads, &self.read_values); } - !self.reads.is_empty() + deposit(alpha, &mut self.values, &self.reads, &self.read_values); + let painted = !self.reads.is_empty(); + self.put_back(lane, painted) + } + + /// The lane of the copy `source`, started when the copy first stamps. + fn take_lane(&mut self, source: Option, alpha: &TileImage) -> Lane { + match self.lanes.iter().position(|l| l.source == source) { + Some(i) => self.lanes.swap_remove(i), + None => { + let values = self.values.iter().map(|(c, img)| (*c, TileImage::new(img.width(), img.height(), c.components()))).collect(); + Lane { source, prev: None, alpha: TileImage::new(alpha.width(), alpha.height(), 1), values } + } + } + } + + fn put_back(&mut self, lane: Option, painted: bool) -> bool { + self.lanes.extend(lane); + painted + } +} + +fn covered(gbuf: &UvGBuffer, x: u32, y: u32) -> bool { + if x >= gbuf.width || y >= gbuf.height { + return false; + } + + let i = u64::from(y) * u64::from(gbuf.width) + u64::from(x); + usize::try_from(i).ok().and_then(|i| gbuf.tri.get(i)).is_some_and(|t| *t != NO_TRI) +} + +/// Blend the texels `reads` `(x, y, alpha)` with their `read_values` (one entry per channel of +/// `values`, in order) into `alpha` and `values` ("over"). +fn deposit(alpha: &mut TileImage, values: &mut BTreeMap, reads: &[(u32, u32, f32)], read_values: &[[f32; 3]]) { + let n = values.len(); + for (i, &(x, y, a)) in reads.iter().enumerate() { + let m = from_u16(alpha.get(x, y)[0]); + let m2 = a + m * (1.0 - a); + for (k, (c, img)) in values.iter_mut().enumerate() { + let Some(src) = read_values.get(i * n + k) else { continue }; + let old = get(img, *c, x, y); + put(img, *c, x, y, std::array::from_fn(|j| (src[j] * a + old[j] * m * (1.0 - a)) / m2.max(1e-6))); + } + alpha.set(x, y, &[to_u16(m2)]); } } @@ -203,23 +356,82 @@ mod tests { v } + #[test] + fn layer_and_mask_pickups_only_evaluate_the_shifted_tiles_the_stroke_reads() { + use texturecraft_core::{Fill, Layer, LayerKind, Mask, MaskBackground, Project, Source, TextureSet}; + + let size = 4 * TILE; + let mesh = Arc::new(primitives::plane(2.0, 4)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, size, size)); + let mut project = Project::new("test", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Set", 0, size)); + let id = project.alloc_id(); + let fill = Fill { sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), projection: Default::default(), link: None }; + let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]); + layer.mask = Some(Mask::new(MaskBackground::White)); + project.insert_layer(0, layer, None, false).unwrap(); + + for (target, expected) in [(PaintTarget::Layer(id), 0.25), (PaintTarget::Mask(id), 1.0)] { + let snapshot = PickupSnapshot { + project: project.clone(), + ts: 0, + target, + mesh: mesh.clone(), + bounds: mesh.bounds(), + pixels: Default::default(), + baked: Default::default(), + images: Default::default(), + }; + let mut pickup = Pickup::from_snapshot(PickupMode::Clone { offset: [i64::from(TILE), 0] }, snapshot, gbuf.clone(), [Channel::Roughness]); + let mut alpha = TileImage::new(size, size, 1); + assert!(pickup.loaded.is_empty()); + + for x in [8, 12, TILE + 8] { + assert!(pickup.stamp(&mut alpha, &[(x, 8, 1.0)], [x as f32, 8.0], None)); + let image = &pickup.values[&Channel::Roughness]; + assert!((from_u16(image.get(x, 8)[0]) - expected).abs() < 1e-4); + assert_eq!(pickup.mask_values().is_some(), matches!(target, PaintTarget::Mask(_))); + } + + assert_eq!(pickup.loaded, [(1, 0), (2, 0)].into()); + assert_eq!(pickup.source.channels[&Channel::Roughness].allocated_count(), 2); + } + } + #[test] fn clone_copies_values_from_the_offset() { let (c, g) = setup(|x| if x < 32 { 0.9 } else { 0.1 }); let mut p = Pickup::new(PickupMode::Clone { offset: [-30, 0] }, c, g, [Channel::Roughness]); let mut alpha = TileImage::new(TILE, TILE, 1); - assert!(p.stamp(&mut alpha, &disc(45, 32, 4), [45.0, 32.0])); + assert!(p.stamp(&mut alpha, &disc(45, 32, 4), [45.0, 32.0], None)); let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 45, 32); assert!((v[0] - 0.9).abs() < 1e-3, "{v:?}"); assert!(from_u16(alpha.get(45, 32)[0]) > 0.99); - // Sources outside the image are skipped. - assert!(!p.stamp(&mut alpha, &disc(5, 5, 2), [5.0, 5.0])); + + // Sources outside the image are skipped + assert!(!p.stamp(&mut alpha, &disc(5, 5, 2), [5.0, 5.0], None)); + } + + #[test] + fn clone_skips_offsets_outside_the_coordinate_range() { + for offset in [[i64::MAX, 0], [0, i64::MAX], [i64::MIN, 0], [0, i64::MIN]] { + let (composite, gbuf) = setup(|_| 0.5); + let mut pickup = Pickup::new(PickupMode::Clone { offset }, composite, gbuf, [Channel::Roughness]); + let mut alpha = TileImage::new(TILE, TILE, 1); + + let painted = pickup.stamp(&mut alpha, &[(1, 1, 1.0)], [1.0, 1.0], None); + + assert!(!painted); + assert_eq!(alpha.allocated_count(), 0); + assert_eq!(pickup.values[&Channel::Roughness].allocated_count(), 0); + } } #[test] fn layer_clones_copy_only_where_the_layer_has_paint() { let (_, g) = setup(|_| 0.0); - // The layer: roughness 0.8 at half coverage on the left half (premultiplied). + + // The layer has roughness 0.8 at half coverage on its left half let mut data = vec![0u16; TILE_AREA * 2]; for y in 0..TILE { for x in 0..TILE / 2 { @@ -231,13 +443,14 @@ mod tests { let flat = vec![(Channel::Roughness, (0, 0), data)]; let mut p = Pickup::from_layer(PickupMode::Clone { offset: [-30, 0] }, &flat, (TILE, TILE), g.clone(), [Channel::Roughness]); let mut alpha = TileImage::new(TILE, TILE, 1); - assert!(p.stamp(&mut alpha, &disc(45, 32, 3), [45.0, 32.0])); + assert!(p.stamp(&mut alpha, &disc(45, 32, 3), [45.0, 32.0], None)); let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 45, 32)[0]; assert!((v - 0.8).abs() < 1e-3, "straight value: {v}"); assert!((from_u16(alpha.get(45, 32)[0]) - 0.5).abs() < 1e-3, "the layer's coverage scales the stroke"); - // Reading the layer's empty right half deposits nothing. + + // Reading the layer's empty right half deposits nothing let mut q = Pickup::from_layer(PickupMode::Clone { offset: [30, 0] }, &flat, (TILE, TILE), g, [Channel::Roughness]); - assert!(!q.stamp(&mut TileImage::new(TILE, TILE, 1), &disc(20, 32, 3), [20.0, 32.0]), "the source is the empty half"); + assert!(!q.stamp(&mut TileImage::new(TILE, TILE, 1), &disc(20, 32, 3), [20.0, 32.0], None), "the source is the empty half"); } #[test] @@ -245,13 +458,49 @@ mod tests { let (c, g) = setup(|x| if x < 20 { 1.0 } else { 0.0 }); let mut p = Pickup::new(PickupMode::Smudge { strength: 1.0 }, c, g, [Channel::Roughness]); let mut alpha = TileImage::new(TILE, TILE, 1); - assert!(!p.stamp(&mut alpha, &disc(18, 32, 5), [18.0, 32.0]), "the first stamp only picks up"); + assert!(!p.stamp(&mut alpha, &disc(18, 32, 5), [18.0, 32.0], None), "the first stamp only picks up"); for cx in 20..30 { - p.stamp(&mut alpha, &disc(cx, 32, 5), [cx as f32, 32.0]); + p.stamp(&mut alpha, &disc(cx, 32, 5), [cx as f32, 32.0], None); } let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 30, 32)[0]; assert!(v > 0.5 && from_u16(alpha.get(30, 32)[0]) > 0.99, "white dragged to the right: {v}"); - // A jump larger than the stamp deposits nothing. - assert!(!p.stamp(&mut alpha, &disc(50, 10, 3), [50.0, 10.0])); + + // A jump larger than the stamp deposits nothing + assert!(!p.stamp(&mut alpha, &disc(50, 10, 3), [50.0, 10.0], None)); + } + + /// Two copies smudging through the same texels: copy B drags exactly what it would alone. + #[test] + fn mirrored_smudge_copies_do_not_feed_each_other() { + use texturecraft_geom::glam::{Mat3, Vec3}; + let source = |x: f32| Some(StampSource { origin: Vec3::ZERO, to_source: Mat3::from_diagonal(Vec3::new(x, 1.0, 1.0)) }); + let (a, b) = (source(1.0), source(-1.0)); + let smudge = || { + let (c, g) = setup(|x| if x < 20 { 1.0 } else { 0.0 }); + Pickup::new(PickupMode::Smudge { strength: 1.0 }, c, g, [Channel::Roughness]) + }; + + // A drags white right along row 32 while B drags left through the same texels + let (mut alone, mut isolated) = (smudge(), smudge()); + isolated.isolate_copies(); + let (mut alpha_alone, mut alpha_isolated) = (TileImage::new(TILE, TILE, 1), TileImage::new(TILE, TILE, 1)); + for i in 0..24 { + let (xa, xb) = (18.0 + i as f32, 46.0 - i as f32); + for (pickup, alpha, copies) in [(&mut isolated, &mut alpha_isolated, true), (&mut alone, &mut alpha_alone, false)] { + if copies { + pickup.stamp(alpha, &disc(xa as u32, 32, 5), [xa, 32.0], a); + } + pickup.stamp(alpha, &disc(xb as u32, 32, 5), [xb, 32.0], b); + } + } + let lane_b = isolated.lanes.iter().find(|l| l.source == b).expect("copy B has its lane"); + let (mut stroke_differs, mut lane_differs) = (false, false); + for x in 14..52 { + let alone_value = get(&alone.values[&Channel::Roughness], Channel::Roughness, x, 32)[0]; + lane_differs |= (get(&lane_b.values[&Channel::Roughness], Channel::Roughness, x, 32)[0] - alone_value).abs() > 1e-4; + stroke_differs |= (get(&isolated.values[&Channel::Roughness], Channel::Roughness, x, 32)[0] - alone_value).abs() > 1e-4; + } + assert!(!lane_differs, "copy B drags what it would drag alone"); + assert!(stroke_differs, "the stroke shows both copies where they overlap"); } } diff --git a/crates/paint/src/pickup/lane.rs b/crates/paint/src/pickup/lane.rs new file mode 100644 index 00000000..edac39bb --- /dev/null +++ b/crates/paint/src/pickup/lane.rs @@ -0,0 +1,15 @@ +use std::collections::BTreeMap; + +use texturecraft_core::Channel; +use texturecraft_texel::TileImage; + +use crate::StampSource; + +/// What one symmetry copy of a smudge stroke carries: its own previous stamp and deposits +#[derive(Clone, Debug)] +pub(super) struct Lane { + pub(super) source: Option, + pub(super) prev: Option<[f32; 2]>, + pub(super) alpha: TileImage, + pub(super) values: BTreeMap, +} diff --git a/crates/paint/src/pickup/pickup_snapshot.rs b/crates/paint/src/pickup/pickup_snapshot.rs new file mode 100644 index 00000000..5fa4e7c9 --- /dev/null +++ b/crates/paint/src/pickup/pickup_snapshot.rs @@ -0,0 +1,36 @@ +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PaintTarget, PixelStore}; +use texturecraft_core::Project; +use texturecraft_geom::{Mesh, UvGBuffer}; + +/// Compositor inputs frozen at stroke start. A mask target identifies the layer that owns it. +#[derive(Clone, Debug)] +pub struct PickupSnapshot { + pub project: Project, + pub ts: usize, + pub target: PaintTarget, + pub mesh: Arc, + pub bounds: (texturecraft_geom::glam::Vec3, texturecraft_geom::glam::Vec3), + pub pixels: PixelStore, + pub baked: BakedMaps, + pub images: ImageStore, +} + +impl PickupSnapshot { + pub(super) fn inputs<'a>(&'a self, gbuf: &'a UvGBuffer) -> Option> { + let set = self.project.texture_sets.get(self.ts)?; + Some(Inputs { + project: &self.project, + ts: self.ts, + mesh: &self.mesh, + gbuf, + pixels: &self.pixels, + baked: &self.baked, + block_scales: set.block_scales(), + preview: None, + images: &self.images, + bounds: self.bounds, + }) + } +} diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rs index 72f537e6..e82bf3e9 100644 --- a/crates/paint/src/presets.rs +++ b/crates/paint/src/presets.rs @@ -22,7 +22,7 @@ impl BrushPreset { } /// `brush` with the stroke of `from` (shape, flow, opacity, spacing, hardness, angle, path -/// following, jitters and particles): what a preset sets. +/// following, jitters, particles and the alpha's parameters): what a preset sets. pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSettings { BrushSettings { flow: from.flow, @@ -38,6 +38,7 @@ pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSetti alpha: from.alpha, alpha_image: from.alpha_image.clone(), alpha_library: from.alpha_library.clone(), + alpha_params: from.alpha_params, particles: from.particles, ..brush.clone() } @@ -178,6 +179,15 @@ pub const PRESETS: [BrushPreset; 18] = [ #[cfg(test)] mod tests { use super::*; + use crate::alpha_params::AlphaParams; + + #[test] + fn a_saved_brush_brings_its_alpha_parameters_and_a_built_in_preset_resets_them() { + let params = AlphaParams { size_x: 0.5, invert: true, ..AlphaParams::default() }; + let saved = BrushSettings { alpha_params: params, ..BrushSettings::default() }; + assert_eq!(with_stroke_of(&BrushSettings::default(), &saved).alpha_params, params); + assert_eq!(PRESETS[0].applied(&saved).alpha_params, AlphaParams::default()); + } #[test] fn presets_are_unique_valid_and_keep_the_setup() { diff --git a/crates/paint/src/raster.rs b/crates/paint/src/raster.rs index 5d50a92f..68eafa83 100644 --- a/crates/paint/src/raster.rs +++ b/crates/paint/src/raster.rs @@ -11,6 +11,7 @@ use texturecraft_texel::{TILE, TileImage, from_u16, to_u16}; use crate::brush::Shape; use crate::pickup::Pickup; +use crate::stamp_source::StampSource; use crate::stroke::Stamp; use crate::visibility::EyeDepth; @@ -52,7 +53,7 @@ impl StrokeCanvas { /// Blend the gathered stamp texels (stamp center `center` in texels) into the stroke: the /// quick mask scales them, then the pickup deposits its values or the alpha accumulates /// ("over": `m = a + m·(1 − a)`). - fn add_stamp(&mut self, center: [f32; 2]) { + fn add_stamp(&mut self, center: [f32; 2], source: Option) { let mut texels = std::mem::take(&mut self.texels); if let Some((mask, invert)) = &self.limit { for t in &mut texels { @@ -61,7 +62,7 @@ impl StrokeCanvas { } } let painted = match &mut self.pickup { - Some(p) => p.stamp(&mut self.alpha, &texels, center), + Some(p) => p.stamp(&mut self.alpha, &texels, center, source), None => { for &(x, y, a) in &texels { let m = from_u16(self.alpha.get(x, y)[0]); @@ -216,7 +217,7 @@ pub fn rasterize(canvas: &mut StrokeCanvas, context: &RasterCtx, stamps: &[Stamp canvas.texels.extend(texels); } - canvas.add_stamp(center.0); + canvas.add_stamp(center.0, stamp.source); } } @@ -338,7 +339,7 @@ pub fn fill_coverage(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, coverage: impl (a > 0.0).then_some(((i as u32) % w, (i as u32) / w, a)) }) .collect(); - canvas.add_stamp([0.0; 2]); + canvas.add_stamp([0.0; 2], None); } #[cfg(test)] @@ -383,7 +384,7 @@ mod tests { eye: camera.eye(), backface_culling: false, angle_fade: (89.0, 90.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; let stamp = Stamp { center: Vec3::new(0.0, 0.03, 0.0), @@ -428,7 +429,7 @@ mod tests { eye: camera.eye(), backface_culling: true, angle_fade: (89.0, 90.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; let point = Vec3::ZERO; let to_eye = (camera.eye() - point).normalize(); @@ -459,7 +460,7 @@ mod tests { eye: camera.eye(), backface_culling: true, angle_fade: (89.0, 90.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; let point = Vec3::new(1.0, 0.0, 0.0); let to_eye = (camera.eye() - point).normalize(); @@ -485,7 +486,7 @@ mod tests { eye: camera.eye(), backface_culling: false, angle_fade: (89.0, 90.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; let to_eye = -camera.forward(); let behind = context.eye + to_eye; @@ -547,7 +548,7 @@ mod tests { eye: camera.eye(), backface_culling: culling, angle_fade: (89.0, 90.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; let stamp = Stamp { center, normal: Vec3::Y, tangent: Vec3::X, bitangent: Vec3::Z, radius, flow: 1.0, hardness: 0.9, depth: 1.0, seed: 0, source: None }; @@ -676,7 +677,7 @@ mod tests { eye: camera.eye(), backface_culling: false, angle_fade: (89.0, 90.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; // A silhouette normal is perpendicular to the direction from the surface to the eye @@ -746,7 +747,7 @@ mod tests { eye: Vec3::new(0.0, 5.0, 0.0), backface_culling: true, angle_fade: (70.0, 85.0), - shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 }, + shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 }, }; let stamp = Stamp { center: Vec3::ZERO, @@ -789,6 +790,9 @@ pub struct UvStamp { pub flow: f32, pub hardness: f32, pub seed: u32, + /// The symmetry copy this dab belongs to (None: the stroke itself), so a smudge's copies each + /// drag their own trail as in the 3D view + pub source: Option, } /// Accumulate UV-space stamps into `canvas` (only texels covered by the texture set). @@ -799,6 +803,7 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s if s.radius.is_nan() || s.radius <= 0.0 || !s.center.is_finite() { continue; } + let (cx, cy, r) = (s.center.x * w as f32, s.center.y * h as f32, s.radius * w as f32); let x0 = (cx - r * 1.42).floor().max(0.0) as u32; let x1 = ((cx + r * 1.42).ceil().max(0.0) as u32).min(w); @@ -811,7 +816,8 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s if gbuf.tri.get((y * w + x) as usize).copied().unwrap_or(NO_TRI) == NO_TRI { continue; } - // Local frame with y up on screen (texel rows grow downward), as in the 3D view. + + // Local frame with y up on screen (texel rows grow downward), as in the 3D view let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r); let (lx, ly) = (dx * cs + dy * sn, -dx * sn + dy * cs); let a = shape.sample(lx, ly, s.hardness, s.seed) * s.flow; @@ -820,6 +826,6 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s } } } - canvas.add_stamp([cx, cy]); + canvas.add_stamp([cx, cy], s.source); } } diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index 9cc3972b..fcca6427 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -265,6 +265,11 @@ impl Stroke { copies } + /// The center of the mesh the stroke paints, which the symmetry planes are measured from + pub fn center(&self) -> Vec3 { + self.center + } + pub fn last_hit(&self) -> Option { self.last } diff --git a/crates/ui-egui/src/angle_dial.rs b/crates/ui-egui/src/angle_dial.rs new file mode 100644 index 00000000..a2129841 --- /dev/null +++ b/crates/ui-egui/src/angle_dial.rs @@ -0,0 +1,52 @@ +//! An angle as a dial beside a slider, as the reference app shows angles: drag the dial to point it, or set the slider + +use egui::{Sense, Stroke, Ui, vec2}; + +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::slider_edit; + +const DIAL_SIZE: f32 = 36.0; +const DIAL_RIM_WIDTH: f32 = 1.5; +const POINTER_WIDTH: f32 = 2.0; +const HUB_RADIUS: f32 = 2.0; +/// Gap between the dial and its slider +const DIAL_GAP: f32 = 8.0; +const FULL_TURN: f32 = 360.0; + +/// `label` over a dial and an "Angle" slider for `degrees` (0 at the right, counterclockwise): `Some(merge)` on every frame that changes it, as [`slider_edit`] +pub(crate) fn angle_dial(ui: &mut Ui, label: &str, degrees: &mut f32) -> Option { + ui.label(label); + ui.horizontal(|ui| { + let dial_edit = dial(ui, degrees); + ui.add_space(DIAL_GAP); + let slider = ui.vertical(|ui| slider_edit(ui, tr("Angle"), degrees, 0.0..=FULL_TURN, 0)).inner; + dial_edit.or(slider) + }) + .inner +} + +/// The dial: a disc whose pointer follows a drag around its center +fn dial(ui: &mut Ui, degrees: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(DIAL_SIZE, DIAL_SIZE), Sense::click_and_drag()); + let center = rect.center(); + let mut edit = None; + if let Some(pointer) = response.interact_pointer_pos().filter(|_| response.dragged() || response.clicked()) { + let offset = pointer - center; + if offset.length() > HUB_RADIUS { + // Screen y grows downwards, angles grow counterclockwise + *degrees = (-offset.y).atan2(offset.x).to_degrees().rem_euclid(FULL_TURN); + edit = Some(response.dragged() && !response.drag_started()); + } + } + + let radius = DIAL_SIZE * 0.5 - DIAL_RIM_WIDTH; + let painter = ui.painter(); + let rim = if response.hovered() || response.dragged() { tokens.button_border } else { tokens.field_border }; + painter.circle(center, radius, tokens.field, Stroke::new(DIAL_RIM_WIDTH, rim)); + let (sin, cos) = degrees.to_radians().sin_cos(); + painter.line_segment([center, center + vec2(cos, -sin) * (radius - DIAL_RIM_WIDTH)], Stroke::new(POINTER_WIDTH, tokens.accent)); + painter.circle_filled(center, HUB_RADIUS, tokens.text); + edit +} diff --git a/crates/ui-egui/src/ask.rs b/crates/ui-egui/src/ask.rs new file mode 100644 index 00000000..32bcfad1 --- /dev/null +++ b/crates/ui-egui/src/ask.rs @@ -0,0 +1,10 @@ +use crate::list_action::ListAction; + +/// A question waiting for an answer in the Output templates tab +#[derive(Clone, Debug, PartialEq)] +pub enum Ask { + /// Delete this template (its file goes with it) + Delete(String), + /// Leave the selected template, whose last edit does not validate and is not saved, for this + Leave(ListAction), +} diff --git a/crates/ui-egui/src/color_management.rs b/crates/ui-egui/src/color_management.rs new file mode 100644 index 00000000..148acf55 --- /dev/null +++ b/crates/ui-egui/src/color_management.rs @@ -0,0 +1,19 @@ +use crate::i18n::n_; + +/// How a project manages colour. Only Legacy is implemented; OpenColorIO can be chosen to see its +/// settings, but they stay disabled and a project is always created and kept as Legacy. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ColorManagement { + #[default] + Legacy, + OpenColorIo, +} + +impl ColorManagement { + pub(crate) fn label(self) -> &'static str { + match self { + ColorManagement::Legacy => n_("Legacy"), + ColorManagement::OpenColorIo => "OpenColorIO", + } + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index bc44e107..c5dc53bf 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -7,7 +7,9 @@ //! - `session.inspect`: project, texture sets, layer stack, tool, camera, display, history. //! - `ui.inspect`: the UI state (panels, windows, mode, layout, viewport rect, who draws the title bar). //! - `ui.menu.list`: the menu catalog with ids, shortcuts and whether each is live. -//! - `ui.menu.invoke {id}`: behave like a menu click (may open a window). +//! - `ui.menu.invoke {id}`: behave like a menu click (may open a window; `ui.resetUi` asks first). +//! `{id: "ui.layout.apply", name}` switches to the saved panel layout `name` (an error when there is none). +//! - `ui.reset`: reset the panels and every view setting at once, without the question the menu asks. //! - `ui.set {...}`: merge fields into the UI state (e.g. `{"layout":"Only3D"}`). //! - `viewport.screenshot {view?: "3d"|"2d"}`: PNG of a viewport, base64. //! - `ui.screenshot`: PNG of the whole window (replies after the next frame). @@ -74,6 +76,12 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec) -> Option<(u32, u32, Vec pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Value { app.ui.prefs.apply_resource_limits(); + + // These direct control jobs bypass the engine command availability check + if !app.session.project_open && matches!(method, "ui.bake.start" | "debug.paintTest") { + return err("no project is open"); + } + match method { "ping" => ok(json!("pong")), "ui.resize" => { @@ -95,12 +103,28 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para "command.run" => { let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") }; let command_params = params.get("params").cloned().unwrap_or(Value::Null); + let before = app.session.camera; match texturecraft_engine::execute(&mut app.session, id, &command_params) { Ok(value) => { if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") { app.thumbs.forget_saved_files(); } + // Work from the old project must not reach its replacement + if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { + app.resize = None; + app.pbr_import = None; + app.layer_panel = Default::default(); + } + + // The Export dialog cannot operate after Close + if id == "file.close" { + app.ui.windows.export = false; + } + + // A command that moved the camera takes over from a glide in progress; a projection switch joins it + app.settle_camera_glide(id, before); + ok(value) } Err(error) => err(error), @@ -169,6 +193,11 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para )), "ui.menu.invoke" => { let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") }; + if id == "ui.layout.apply" { + let Some(name) = params.get("name").and_then(Value::as_str) else { return err("`name` is required") }; + return if app.ui.apply_named_layout(name) { ok(Value::Null) } else { err(format!("no saved layout named `{name}`")) }; + } + if !crate::menus::implemented(id) { return err(format!("menu item `{id}` is not implemented")); } @@ -176,6 +205,12 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para crate::menus::invoke(app, ctx, id); ok(Value::Null) } + + // What Window > Reset UI does once the question is answered with Reset + "ui.reset" => { + app.ui.adopt_layout(crate::UiState::default()); + ok(Value::Null) + } "ui.set" => { let mut current_state = serde_json::to_value(&app.ui).unwrap_or(Value::Null); if let (Some(object), Some(patch)) = (current_state.as_object_mut(), params.as_object()) { @@ -206,6 +241,10 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para /// Encode a rendered view as PNG. pub fn screenshot(app: &TextureCraftApp, view: u64) -> Option<(u32, u32, Vec)> { + if !app.session.project_open { + return None; + } + let rs = app.render_state.as_ref()?; let renderer = rs.renderer.read(); let gpu = renderer.callback_resources.get::()?; diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 24ac3f03..d831213d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -6,14 +6,16 @@ use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ - BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Projection, - Source, + BakedMap, BlendMode, Channel, ChannelBlend, ChannelKind, Decal, DecalFlip, Effect, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, LinkParam, + MaterialLink, Projection, Source, }; use texturecraft_engine::filter_lib::scalar_params; +use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; +use crate::filter_slot::SLOT_HEIGHT; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::shelf::{Asset, ShelfDrag}; @@ -41,6 +43,11 @@ const TAG_COLORS: [Color32; 8] = [ ]; pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { + // The empty state lists nothing + if !app.session.project_open { + return; + } + let tk = Tokens::get(ui.ctx()); let sets: Vec<(String, String, bool)> = app .session @@ -93,7 +100,8 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text); - // Narrow panels drop the shader label, then the resolution, before cutting the name. + + // Narrow panels drop the shader label, then the resolution, before cutting the name let cy = rect.center().y; let mut right = rect.right() - 6.0; if rect.width() >= 260.0 { @@ -140,42 +148,62 @@ fn add_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, row: Option) { } pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); // Wrap in a narrow column so rows stay within the panel - ui.horizontal_wrapped(|ui| { - // Keep menu buttons as compact as the adjacent icon buttons - ui.spacing_mut().button_padding.x = 4.0; - ui.spacing_mut().item_spacing.x = 4.0; - let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt("layer_channel").width(86.0).selected_text(tr(app.ui.layer_channel.label())).show_ui(ui, |ui| { - for c in chans { - ui.selectable_value(&mut app.ui.layer_channel, c, tr(c.label())); + let project_open = app.session.project_open; + ui.add_enabled_ui(project_open, |ui| { + ui.horizontal_wrapped(|ui| { + // Keep menu buttons as compact as the adjacent icon buttons + ui.spacing_mut().button_padding.x = 4.0; + ui.spacing_mut().item_spacing.x = TOOLBAR_SPACING; + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default(); + + // The channel box takes what the six buttons leave, so the toolbar stays on one row in a narrow column + let buttons = 2.0 * (MENU_BUTTON_WIDTH + TOOLBAR_SPACING) + 4.0 * (TOOLBAR_ICON_SIZE + TOOLBAR_SPACING); + let channel_width = (ui.available_width() - buttons).clamp(CHANNEL_BOX_MIN_WIDTH, CHANNEL_BOX_WIDTH); + ui.allocate_ui(vec2(channel_width, ICON_BUTTON_SIZE), |ui| { + egui::ComboBox::from_id_salt("layer_channel").width(channel_width).truncate().selected_text(tr(app.ui.layer_channel.label())).show_ui( + ui, + |ui| { + for channel in channels { + ui.selectable_value(&mut app.ui.layer_channel, channel, tr(channel.label())); + } + }, + ); + }); + ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| { + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); + match &selected { + Some(layer) => effect_menu(app, ui, layer), + None => { + ui.label(RichText::new(tr("Select a layer")).color(tokens.text_dim)); + } + } + }) + .response + .on_hover_text(tr("Add effect")); + ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); + if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.add.paint", Value::Null); } - }); - let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id)).cloned(); - ui.menu_button(RichText::new(ic::MAGIC_WAND).size(14.0), |ui| match &selected { - Some(l) => effect_menu(app, ui, l), - None => { - ui.label(RichText::new(tr("Select a layer")).color(tk.text_dim)); + if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.add.fill", Value::Null); + } + if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.add.group", Value::Null); + } + if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, TOOLBAR_ICON_SIZE).clicked() { + app.run("layer.remove", Value::Null); } }) - .response - .on_hover_text(tr("Add effect")); - ui.menu_button(RichText::new(ic::SELECTION_BACKGROUND).size(14.0), |ui| add_mask_menu(app, ui, None)).response.on_hover_text(tr("Add mask")); - if icon_button(ui, ic::PAINT_BRUSH, tr("Add paint layer"), false, 22.0).clicked() { - app.run("layer.add.paint", Value::Null); - } - if icon_button(ui, ic::PAINT_BUCKET, tr("Add fill layer"), false, 22.0).clicked() { - app.run("layer.add.fill", Value::Null); - } - if icon_button(ui, ic::FOLDER_SIMPLE, tr("Add folder"), false, 22.0).clicked() { - app.run("layer.add.group", Value::Null); - } - if icon_button(ui, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), false, 22.0).clicked() { - app.run("layer.remove", Value::Null); - } }); + + // The empty state has no layers: the toolbar stays, greyed + if !project_open { + return; + } + ui.add_space(2.0); let ts = app.session.ts(); let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); @@ -192,7 +220,9 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if free.is_finite() { free.max(24.0) } else { 24.0 }), Sense::hover()); if let Some(dragged) = dnd_release::(&resp) { let bottom = app.session.doc.project.texture_sets.get(ts).and_then(|t| t.stack.first().copied()); - if bottom.map(|b| b.0) != Some(*dragged) { + if let Some(layers) = selection_with(app, LayerId(*dragged)) { + app.run("layer.move", json!({"layers": layers, "index": 0})); + } else if bottom.map(|b| b.0) != Some(*dragged) { app.run("layer.move", json!({"layer": *dragged, "index": 0})); } } @@ -207,10 +237,48 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { } let material = resp.dnd_hover_payload::().is_some_and(|d| d.asset.is_material()); if resp.dnd_hover_payload::().is_some() || material { - ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); + ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tokens.accent)); } }); - app.layer_panel.end(ui.ctx(), &app.session); + select_all_layers(app, ui); +} + +/// Ctrl+A (Cmd+A on macOS) with the pointer over the Layers panel selects every row shown in the +/// active texture set (folder rows and the layers of open folders). A focused text field (a +/// rename, a number field) keeps the key for itself, and the key is left alone over other panels. +fn select_all_layers(app: &mut TextureCraftApp, ui: &Ui) { + let ctx = ui.ctx(); + if ctx.egui_wants_keyboard_input() || !ui.ui_contains_pointer() { + return; + } + + if ctx.input_mut(|input| input.consume_key(egui::Modifiers::COMMAND, egui::Key::A)) { + app.run("layer.select", json!({"all": true})); + } +} + +/// A click on a layer row or its content thumbnail, as in the reference app: Shift selects the +/// rows from the last clicked layer to this one, Ctrl/Cmd adds or takes out this layer, and a +/// plain click selects it alone (on `target`, when given). +fn click_layer(app: &mut TextureCraftApp, modifiers: egui::Modifiers, layer: u64, target: Option<&str>) { + let params = if modifiers.shift { + json!({"layer": layer, "range": true}) + } else if modifiers.command { + json!({"layer": layer, "toggle": true}) + } else { + match target { + Some(target) => json!({"layer": layer, "target": target}), + None => json!({"layer": layer}), + } + }; + app.run("layer.select", params); +} + +/// The selected layers when `layer` is one of several selected ones, so an action on its row +/// (drag and drop, the row menu) applies to all of them. +fn selection_with(app: &TextureCraftApp, layer: LayerId) -> Option> { + let selected = app.session.selected_layers(); + (selected.len() > 1 && selected.contains(&layer)).then(|| selected.iter().map(|id| id.0).collect()) } /// Whether the selection targets the layer content (the content or one of its effects) rather @@ -268,10 +336,30 @@ fn row_shade(tokens: &Tokens, index: usize) -> Color32 { if index.is_multiple_of(2) { tokens.row } else { tokens.row.lerp_to_gamma(tokens.row_hover, ALTERNATE_LAYER_SHADE) } } +/// Fill of the active layer's row: the panel tinted well towards the accent so the row stands out +/// from its neighbours at any scale, while the lettering on it keeps its contrast. +pub fn selected_layer_fill(tokens: &Tokens) -> Color32 { + tokens.row_selected.lerp_to_gamma(tokens.accent_dim, SELECTED_LAYER_TINT) +} + +/// Glyph colour of a layer's eye and the chip behind it: a visible layer shows a bright eye on an +/// accent chip, a hidden one only the dim crossed-out eye, so the two states differ by more than a glyph. +pub fn layer_eye_colors(tokens: &Tokens, visible: bool) -> (Color32, Option) { + if visible { (tokens.text_strong, Some(tokens.accent_dim)) } else { (tokens.text_dim, None) } +} + /// Width of the blend mode / opacity column at the right of a layer row. const RIGHT_COLUMN: f32 = 58.0; /// Indent per folder level, and per level of the effect tree. const INDENT: f32 = 14.0; +/// Width of the Layers toolbar's channel box when there is room, and the least it shrinks to. +const CHANNEL_BOX_WIDTH: f32 = 86.0; +const CHANNEL_BOX_MIN_WIDTH: f32 = 40.0; +/// Gap between the Layers toolbar's buttons. +const TOOLBAR_SPACING: f32 = 2.0; +/// Edge of the toolbar's icon buttons, and the width of its two menu buttons. +const TOOLBAR_ICON_SIZE: f32 = 20.0; +const MENU_BUTTON_WIDTH: f32 = 22.0; /// Edge of the small icon buttons in the properties panel. const ICON_BUTTON_SIZE: f32 = 22.0; /// Height of a blend mode menu or opacity field in a stack row, and the rounding of its hover fill. @@ -284,6 +372,13 @@ const ROW_LEFT_PADDING: f32 = 7.0; const ROW_RIGHT_PADDING: f32 = 6.0; /// Width of the selected row's accent edge. const SELECTED_EDGE_WIDTH: f32 = 3.0; +/// The same edge on a layer row, wide enough to read on a dense display. +const SELECTED_LAYER_EDGE_WIDTH: f32 = 4.0; +/// How far the active layer's fill moves from the plain selected shade to the accent tint. +const SELECTED_LAYER_TINT: f32 = 0.3; +/// The chip behind a visible layer's eye: its inset from the eye's hit area and its rounding. +const EYE_CHIP_INSET: f32 = 1.0; +const EYE_CHIP_ROUNDING: f32 = 4.0; /// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. const THUMBNAIL_ROUNDING: f32 = 2.0; const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; @@ -311,7 +406,9 @@ const ROW_FIELD_PADDING: f32 = 4.0; const OPACITY_DRAG_SPEED: f64 = 0.5; /// A layer row's eye: its hit area, its glyph size and the column it sits in. const LAYER_EYE_SIZE: f32 = 18.0; -const LAYER_EYE_FONT_SIZE: f32 = 13.0; +const LAYER_EYE_FONT_SIZE: f32 = 14.0; +/// The wand on a mask thumbnail that has effects. +const LAYER_WAND_FONT_SIZE: f32 = 13.0; const LAYER_EYE_COLUMN_WIDTH: f32 = 20.0; /// A folder's caret: its size (the space it takes before the thumbnail) and its center from where it starts. const FOLDER_CARET_SIZE: f32 = 14.0; @@ -380,6 +477,11 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { (Rect::from_min_max(pos2(left, rect.top() + 4.0), pos2(name_right.max(left), rect.bottom() - 4.0)), show_blend) } +/// Whether `text` at font `size` is wider than `width`, so a row shows it shortened. +fn text_is_cut(painter: &egui::Painter, text: &str, size: f32, width: f32) -> bool { + painter.layout_no_wrap(text.to_owned(), egui::FontId::proportional(size), Color32::WHITE).size().x > width +} + /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) @@ -449,15 +551,23 @@ fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { let tokens = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); + + // One of several selected layers (Shift/Ctrl+click) is highlighted like the active one + let highlighted = selected || app.session.is_layer_selected(layer.id); + let several = selection_with(app, layer.id); let content_target = selected && targets_content(app); let preferred_size = layer_preview_size(app); let row_height = layer_row_height(preferred_size); let (rect, row) = ui.allocate_exact_size(vec2(ui.available_width(), row_height), Sense::click_and_drag()); - row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); + row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); - // Background, folder lines, the selected row's accent edge and the colour tag + // Background, folder lines, the selected rows' accent edge and the colour tag let painter = ui.painter().clone(); + + // The active layer gets the strong tint; the other selected rows the plain selected shade let background = if selected { + selected_layer_fill(&tokens) + } else if highlighted { tokens.row_selected } else if row.hovered() { tokens.row_hover @@ -465,6 +575,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize row_shade(&tokens, index) }; painter.rect_filled(rect, 0.0, background); + let solo = app.session.solo.filter(|solo| solo.layer == layer.id); let (indent, thumbnail_size) = layer_thumbnail_layout(rect.width(), depth, layer.is_group(), preferred_size); // Folder contents hang off lines down the left without crossing compact row controls @@ -478,26 +589,45 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let x = rect.left() + FOLDER_BRANCH_OFFSET + indent - INDENT; painter.hline(x..=x + INDENT * 0.5, rect.center().y, line); } - if selected { - painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_EDGE_WIDTH, row_height)), 0.0, tokens.accent); + if highlighted { + painter.rect_filled(Rect::from_min_size(rect.min, vec2(SELECTED_LAYER_EDGE_WIDTH, row_height)), 0.0, tokens.accent); } if let Some(tag) = layer.color_tag.and_then(|tag| TAG_COLORS.get(tag as usize)) { - painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); + painter.rect_filled(Rect::from_min_size(rect.min + vec2(SELECTED_LAYER_EDGE_WIDTH, 0.0), vec2(TAG_WIDTH, row_height)), 0.0, *tag); + } + + // A soloed layer: an outline round the row and a lit eye + if solo.is_some() { + painter.rect_stroke(rect.shrink(SOLO_OUTLINE_WIDTH * 0.5), 0.0, Stroke::new(SOLO_OUTLINE_WIDTH, tokens.warning), egui::StrokeKind::Inside); } // The eye let content_left = rect.left() + ROW_LEFT_PADDING + indent; let eye = Rect::from_center_size(pos2(content_left + EYE_SIZE * 0.5, rect.center().y), vec2(LAYER_EYE_SIZE, LAYER_EYE_SIZE)); - let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); + let eye_response = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_ui(|ui| { + ui.label(tr("Show or hide the layer")); + ui.label(tr("Alt+click: show only this layer. Alt+Shift+click: without its mask.")); + }); + let (eye_color, eye_chip) = layer_eye_colors(&tokens, layer.visible); + if let Some(chip) = eye_chip { + painter.rect_filled(eye.shrink(EYE_CHIP_INSET), EYE_CHIP_ROUNDING, chip); + } painter.text( eye.center(), egui::Align2::CENTER_CENTER, - if layer.visible { ic::EYE } else { ic::EYE_SLASH }, + if layer.visible || solo.is_some() { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), - if layer.visible { tokens.text } else { tokens.text_dim }, + if solo.is_some() { tokens.warning } else { eye_color }, ); + + // The eye shows or hides its own layer only, even on one of several selected rows if eye_response.clicked() { - app.run("layer.visible", json!({"layer": layer.id.0})); + let modifiers = ui.input(|input| input.modifiers); + if modifiers.alt { + toggle_solo(app, layer.id, modifiers.shift); + } else { + app.run("layer.visible", json!({"layer": layer.id.0})); + } } // A folder's caret @@ -521,7 +651,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize x += FOLDER_CARET_SIZE; } - // Content thumbnail: the layer's own result in the displayed channel. + // Content thumbnail: the layer's own result in the displayed channel let channel = app.ui.layer_channel; let thumbnail = Rect::from_min_size(pos2(x, rect.center().y - thumbnail_size * 0.5), vec2(thumbnail_size, thumbnail_size)); if !thumb_box(ui, app, thumbnail, ThumbTarget::Content { layer: layer.id, channel }, !layer.visible) { @@ -530,11 +660,12 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.rect_stroke(thumbnail, THUMBNAIL_ROUNDING, target_stroke(&tokens, content_target), egui::StrokeKind::Outside); let content_response = ui.interact(thumbnail, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); if content_response.clicked() { - app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); + let modifiers = ui.input(|input| input.modifiers); + click_layer(app, modifiers, layer.id.0, Some("content")); } x = thumbnail.right() + THUMBNAIL_SPACING; - // An instance draws its source's content, blending and (unless it has its own) mask. + // An instance draws its source's content, blending and (unless it has its own) mask let project = &app.session.doc.project; let source = layer.instance_source().map(|source| { let set = project.locate(source).and_then(|(set, _, _)| project.texture_sets.get(set)).map(|set| set.name.as_str()).unwrap_or("?"); @@ -543,7 +674,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.clone()); let blend = project.content_layer(layer.id).and_then(|content| content.blend(channel)); - // Mask thumbnail, selectable on its own; or the slot that adds one. + // Mask thumbnail, selectable on its own; or the slot that adds one let mask_rect; if let Some(mask) = &mask { let mask_target = selected && !targets_content(app); @@ -552,7 +683,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let white = mask.background == texturecraft_engine::core::MaskBackground::White; painter.rect_filled(mask_rect, THUMBNAIL_ROUNDING, Color32::from_gray(if white { WHITE_MASK_GRAY } else { BLACK_MASK_GRAY })); if !mask.effects.is_empty() { - painter.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(LAYER_EYE_FONT_SIZE), tokens.text_dim); + painter.text( + mask_rect.center(), + egui::Align2::CENTER_CENTER, + ic::MAGIC_WAND, + egui::FontId::proportional(LAYER_WAND_FONT_SIZE), + tokens.text_dim, + ); } } painter.rect_stroke(mask_rect, THUMBNAIL_ROUNDING, target_stroke(&tokens, mask_target), egui::StrokeKind::Outside); @@ -579,7 +716,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize ); } } else { - // The empty slot adds a mask to this layer. + // The empty slot adds a mask to this layer let slot_size = thumbnail_size.min(MASK_SLOT_SIZE); mask_rect = Rect::from_min_size(pos2(x, rect.center().y - slot_size * 0.5), vec2(slot_size, slot_size)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); @@ -592,7 +729,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } x = mask_rect.right() + THUMBNAIL_GAP; - // Name (or rename editor) with the quieter subtitle under it. + // Name (or rename editor) with the quieter subtitle under it let (name_rect, show_blend) = layer_name_layout(rect, x); let show_name = name_rect.width() >= MIN_NAME_WIDTH; if !show_name { @@ -605,13 +742,13 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize if renaming { let mut editor_ui = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); if let Some((_, text)) = app.ui.rename.as_mut() { - // Escape reaches us instead of just unfocusing the field, so it can cancel. + // Escape reaches us instead of just unfocusing the field, so it can cancel let filter = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, escape: true, ..Default::default() }; let editor = editor_ui.add(egui::TextEdit::singleline(text).desired_width(name_rect.width()).event_filter(filter)); if ui.input(|input| input.key_pressed(egui::Key::Escape)) { app.ui.rename = None; } else if editor.lost_focus() { - // Enter or a click elsewhere. + // Enter or a click elsewhere let name = text.trim().to_string(); app.ui.rename = None; if !name.is_empty() && name != layer.name { @@ -639,11 +776,18 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize (None, 1) => format!("{kind} · {}", tr("1 effect")), (None, count) => format!("{kind} · {}", trf("{count} effects", &[("count", &count)])), }; + + // A name or subtitle cut short by a narrow panel is shown in full on hover + if text_is_cut(&painter, &layer.name, LAYER_NAME_FONT_SIZE, name_rect.width()) + || text_is_cut(&painter, &subtitle, LAYER_SUBTITLE_FONT_SIZE, name_rect.width()) + { + row.clone().on_hover_text(format!("{}\n{subtitle}", layer.name)); + } let subtitle = elided(&painter, subtitle, LAYER_SUBTITLE_FONT_SIZE, tokens.text_dim, name_rect.width()); painter.galley(pos2(name_rect.left(), rect.center().y + NAME_LINE_GAP), subtitle, tokens.text_dim); } - // Blend mode and opacity of the displayed channel, stacked at the right. + // Blend mode and opacity of the displayed channel, stacked at the right let mode_rect = Rect::from_min_size( pos2(rect.right() - RIGHT_COLUMN - ROW_CONTROL_GAP, rect.center().y - ROW_CONTROL_HEIGHT - ROW_STACK_GAP), vec2(RIGHT_COLUMN, ROW_CONTROL_HEIGHT), @@ -669,50 +813,65 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize painter.text(mode_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(ROW_SMALL_FONT_SIZE), tokens.text_dim); } - // Interaction: select, rename, drag & drop, context menu. + // Interaction: select, rename, drag & drop, context menu let on_control = eye_response.clicked() || content_response.clicked(); + + // Shift or Ctrl/Cmd clicks in quick succession pick layers; only a plain double click renames + let modifiers = ui.input(|input| input.modifiers); if row.clicked() && !on_control && !renaming { - app.run("layer.select", json!({"layer": layer.id.0})); + click_layer(app, modifiers, layer.id.0, None); } - if row.double_clicked() && !on_control && !renaming && show_name { + if row.double_clicked() && !on_control && !renaming && show_name && !modifiers.shift && !modifiers.command { app.ui.rename = Some((layer.id.0, layer.name.clone())); } if row.drag_started() && !renaming { row.dnd_set_drag_payload(layer.id.0); } - // Drops: a layer or a shelf material lands above this row (inside a folder on its middle); a shelf smart mask replaces the mask + // A folder midpoint accepts child drops; a smart mask replaces the current mask let inside = layer.is_group() && ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| (pointer.y - rect.center().y).abs() < row_height * FOLDER_DROP_ZONE); let shelf = row.dnd_hover_payload::().map(|drag| drag.asset.clone()); - let moving = row.dnd_hover_payload::().is_some_and(|dragged| *dragged != layer.id.0); + + // Several selected layers move together, so none of them is a place to drop them + let in_drag = |dragged: u64| dragged == layer.id.0 || several.as_ref().is_some_and(|layers| layers.contains(&dragged)); + let moving = row.dnd_hover_payload::().is_some_and(|dragged| !in_drag(*dragged)); let drop_stroke = Stroke::new(DROP_LINE_WIDTH, tokens.accent); - if moving || shelf.as_ref().is_some_and(Asset::is_material) { + let shelf_material = shelf.as_ref().is_some_and(Asset::is_material); + if moving || shelf_material { if inside { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); + } else if shelf_material { + painter.line_segment([rect.left_bottom(), rect.right_bottom()], drop_stroke); } else { painter.line_segment([rect.left_top(), rect.right_top()], drop_stroke); } - } else if matches!(shelf, Some(Asset::SmartMask(_))) { + } else if matches!(shelf, Some(Asset::SmartMask(_) | Asset::SavedMask(_))) { painter.rect_stroke(mask_rect.expand(HIGHLIGHT_OUTSET), THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Outside); } else if matches!(shelf, Some(Asset::Filter(_))) && !layer.is_group() { painter.rect_stroke(rect, THUMBNAIL_ROUNDING, drop_stroke, egui::StrokeKind::Inside); } if let Some(dragged) = dnd_release::(&row) - && *dragged != layer.id.0 + && !in_drag(*dragged) { - app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})); + match selection_with(app, LayerId(*dragged)) { + Some(layers) => app.run("layer.move", json!({"layers": layers, "above": layer.id.0, "inside": inside})), + None => app.run("layer.move", json!({"layer": *dragged, "above": layer.id.0, "inside": inside})), + }; } match dnd_release::(&row).map(|drag| drag.asset.clone()) { Some(Asset::Material(material)) => { - app.run("material.apply", json!({"material": material, "above": layer.id.0, "inside": inside})); + app.run("material.apply", shelf_drop_place(json!({"material": material}), layer.id, inside)); } Some(Asset::Library(path)) => { - app.run("material.load", json!({"path": path, "above": layer.id.0, "inside": inside})); + app.run("material.load", shelf_drop_place(json!({"path": path}), layer.id, inside)); } Some(Asset::SmartMask(smart_mask)) => { app.run("mask.smart.apply", json!({"name": smart_mask, "layer": layer.id.0})); } + Some(Asset::SavedMask(path)) => { + app.run("mask.smart.apply", json!({"path": path, "layer": layer.id.0})); + } Some(Asset::Filter(filter)) => { app.run("layer.select", json!({"layer": layer.id.0})); app.run("effect.add.filter", json!({"layer": layer.id.0, "filter": filter, "target": "content"})); @@ -722,6 +881,15 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize row.context_menu(|ui| layer_context_menu(app, ui, layer)); } +/// `params` of a shelf material dropped on the row of `layer`: inside a folder when dropped on its middle, else directly below the row +fn shelf_drop_place(mut params: serde_json::Value, layer: LayerId, inside: bool) -> serde_json::Value { + params[if inside { "above" } else { "below" }] = json!(layer.0); + if inside { + params["inside"] = json!(true); + } + params +} + /// The border of a content or mask thumbnail: the accent while it is the layer's target. fn target_stroke(tokens: &Tokens, target: bool) -> Stroke { if target { Stroke::new(TARGET_BORDER_WIDTH, tokens.accent) } else { Stroke::new(THUMBNAIL_BORDER_WIDTH, tokens.button_border) } @@ -958,7 +1126,11 @@ fn effect_row( let name_rect = Rect::from_min_max(pos2(name_left, rect.center().y - half_height), pos2(name_right, rect.center().y + half_height)); effect_rename_editor(app, ui, name_rect, effect); } else { - let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, (name_right - name_left).max(MIN_NAME_WIDTH)); + let name_width = (name_right - name_left).max(MIN_NAME_WIDTH); + if text_is_cut(&painter, &effect.name, EFFECT_NAME_FONT_SIZE, name_width) { + row.clone().on_hover_text(&effect.name); + } + let galley = elided(&painter, effect.name.clone(), EFFECT_NAME_FONT_SIZE, name_color, name_width); painter.galley(pos2(name_left, rect.center().y - galley.size().y * 0.5), galley, tokens.text); } if show_blend { @@ -1107,25 +1279,138 @@ fn geometry_mask_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { }); } +/// Ask for a file and write `layer`'s evaluated mask there as a 16-bit grayscale PNG (one file per +/// UV tile for a tiled set). +#[cfg(not(target_arch = "wasm32"))] +fn export_mask_file(app: &mut TextureCraftApp, layer: &Layer) { + use crate::file_dialogs::{Bound, FileDialog}; + let lid = layer.id.0; + let name = format!("{}_mask.png", texturecraft_engine::formats::export::sanitize_file_stem(&layer.name)); + app.ask_file(FileDialog::save().filter(tr("PNG image"), &["png"]).file_name(name), Bound::Project, move |app, paths| { + let Some(path) = paths.first() else { return }; + let Some(done) = app.run("mask.export", json!({"layer": lid, "path": path.display().to_string()})) else { return }; + let files = done.get("files").and_then(Value::as_array).map(|files| files.iter().filter_map(Value::as_str).collect::>().join(", ")); + app.toast(trf("Saved {path}", &[("path", &files.unwrap_or_default())]), false); + }); +} + +/// Put the evaluated mask of layer `id` on the system clipboard as an 8-bit grayscale image (the +/// whole texture set; a UV-tiled set copies its tile atlas). +fn copy_mask(app: &mut TextureCraftApp, ctx: &egui::Context, id: texturecraft_engine::core::LayerId) { + match app.session.mask_bitmaps(id, false) { + Ok(bitmaps) => { + let Some(bitmap) = bitmaps.first() else { return }; + ctx.copy_image(egui::ColorImage::from_gray([bitmap.width as usize, bitmap.height as usize], &bitmap.gray8())); + app.toast(tr("Mask copied to the clipboard"), false); + } + Err(e) => app.toast(e.to_string(), true), + } +} + +/// Width of the outline round a soloed layer's row +const SOLO_OUTLINE_WIDTH: f32 = 2.0; + +/// Show `layer` alone (its mask ignored with `ignore_mask`), or end the solo when it is the one shown. +fn toggle_solo(app: &mut TextureCraftApp, layer: texturecraft_engine::core::LayerId, ignore_mask: bool) { + if app.session.solo.is_some_and(|solo| solo.layer == layer) { + app.run("view.solo", json!({"layer": null})); + } else { + app.run("view.solo", json!({"layer": layer.0, "ignoreMask": ignore_mask})); + } +} + +/// The context menu's solo entries: a view-only preview, so they never select the layer or edit the document. +fn solo_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: texturecraft_engine::core::LayerId) { + let solo = app.session.solo.filter(|solo| solo.layer == layer); + if ui.add(egui::Button::new(tr("Solo layer")).selected(solo.is_some())).clicked() { + toggle_solo(app, layer, false); + ui.close(); + } + let ignoring = solo.is_some_and(|solo| solo.ignore_mask); + if ui.add(egui::Button::new(tr("Solo layer without its mask")).selected(ignoring)).clicked() { + app.run("view.solo", json!({"layer": layer.0, "ignoreMask": !ignoring})); + ui.close(); + } +} + +/// Layer menu ▸ Blending options: the displayed channel's mode and/or opacity for every channel of the layer, and copy / paste of all channels' blending. +fn blending_options_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { + let lid = layer.id.0; + let project = &app.session.doc.project; + let content = project.content_layer(layer.id).unwrap_or(layer); + let shown = content.blend(app.ui.layer_channel); + let copied: Vec<(Channel, ChannelBlend)> = content.channels.iter().map(|(c, b)| (*c, *b)).collect(); + let can_paste = app.ui.blend_clipboard.is_some() && !content.channels.is_empty(); + ui.menu_button(tr("Blending options"), |ui| { + let apply = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, mode: bool, opacity: bool| { + let Some(shown) = shown else { + ui.add_enabled(false, egui::Button::new(label)); + return; + }; + + if ui.button(label).clicked() { + let mut params = json!({"layer": lid, "channel": "all"}); + if mode { + params["mode"] = json!(format!("{:?}", shown.mode)); + } + if opacity { + params["opacity"] = json!(shown.opacity); + } + app.run("layer.blend", params); + ui.close(); + } + }; + apply(app, ui, tr("Apply blending mode to all channels"), true, false); + apply(app, ui, tr("Apply opacity to all channels"), false, true); + apply(app, ui, tr("Apply both to all channels"), true, true); + ui.separator(); + if ui.button(tr("Copy channel blending settings")).clicked() { + app.ui.blend_clipboard = Some(copied); + ui.close(); + } + if ui.add_enabled(can_paste, egui::Button::new(tr("Paste channel blending settings"))).clicked() { + if let Some(saved) = app.ui.blend_clipboard.clone() { + let channels: serde_json::Map = + saved.iter().map(|(c, b)| (c.id().to_string(), json!({"mode": format!("{:?}", b.mode), "opacity": b.opacity}))).collect(); + app.run("layer.blending.set", json!({"layer": lid, "channels": channels})); + } + ui.close(); + } + }); +} + fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { let tk = Tokens::get(ui.ctx()); ui.set_min_width(230.0); let lid = layer.id.0; let keymap = app.ui.keymap.clone(); + + // On one of several selected layers, remove, duplicate and group act on all of them + let several = selection_with(app, layer.id); let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, p: Value, enabled: bool| { let mut b = egui::Button::new(label); if let Some(sc) = crate::keymap::shortcut_of(&keymap, id) { b = b.shortcut_text(sc); } if ui.add_enabled(enabled, b).clicked() { - app.run("layer.select", json!({"layer": lid})); - app.run(id, p); + let batch = matches!(id, "layer.remove" | "layer.duplicate" | "layer.group"); + match several.as_ref().filter(|_| batch) { + Some(layers) => app.run(id, json!({"layers": layers})), + None => { + app.run("layer.select", json!({"layer": lid})); + app.run(id, p) + } + }; ui.close(); } }; + // An instance edits its source mask until it gets its own let project = &app.session.doc.project; let has_mask = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.is_some()); + + // A switched-off mask has no values to export + let mask_on = project.layers.get(&project.mask_owner(layer.id)).is_some_and(|l| l.mask.as_ref().is_some_and(|m| m.enabled)); run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": lid}), layer.mask.is_none()); run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": lid}), layer.mask.is_none()); run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": lid}), true); @@ -1135,8 +1420,19 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { run(app, ui, tr("Invert mask"), "mask.invert", json!({"layer": lid}), has_mask); run(app, ui, tr("Clear mask"), "mask.clear", json!({"layer": lid}), has_mask); run(app, ui, tr("Remove mask"), "mask.remove", json!({"layer": lid}), has_mask); + #[cfg(not(target_arch = "wasm32"))] + if ui.add_enabled(mask_on, egui::Button::new(tr("Export mask to file..."))).clicked() { + export_mask_file(app, layer); + ui.close(); + } + if ui.add_enabled(mask_on, egui::Button::new(tr("Copy mask to clipboard"))).clicked() { + copy_mask(app, ui.ctx(), layer.id); + ui.close(); + } geometry_mask_menu(app, ui, layer); ui.separator(); + solo_menu(app, ui, layer.id); + ui.separator(); run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": lid}), !layer.is_group()); #[cfg(not(target_arch = "wasm32"))] if ui.button(tr("Create smart material")).clicked() { @@ -1148,6 +1444,12 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { } ui.close(); } + #[cfg(not(target_arch = "wasm32"))] + if ui.add_enabled(has_mask, egui::Button::new(tr("Create smart mask"))).clicked() { + app.run("layer.select", json!({"layer": lid})); + crate::smart_mask_menu::save(app, layer, &crate::library_dir()); + ui.close(); + } ui.separator(); run(app, ui, tr("Cut layer(s)"), "layer.cut", json!({"layer": lid}), true); run(app, ui, tr("Copy layer(s)"), "layer.copy", json!({"layer": lid}), true); @@ -1162,6 +1464,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { run(app, ui, tr("Copy to all texture sets"), "layer.instantiateAll", json!({"layer": lid, "copy": true}), app.session.set_count() > 1); run(app, ui, tr("Remove layer(s)"), "layer.remove", json!({"layer": lid}), true); run(app, ui, tr("Group layer(s)"), "layer.group", json!({"layer": lid}), true); + blending_options_menu(app, ui, layer); ui.separator(); ui.horizontal(|ui| { let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); @@ -1400,7 +1703,9 @@ mod image_menu_tests { let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); let app = TextureCraftApp::new(&creation_context, session); - Ok(Harness::builder().with_size(egui::vec2(320.0, 400.0)).with_context_setup(crate::theme::install).build_ui_state( + + // Translated menu labels may need fonts this preview-cache test does not load + Ok(Harness::builder().with_size(egui::vec2(320.0, 400.0)).with_context_setup(crate::theme::install).allow_missing_glyphs().build_ui_state( |ui, (app, picked)| { if let Some(name) = image_menu(app, ui) { *picked = Some(name); @@ -1421,6 +1726,8 @@ mod image_menu_tests { #[test] fn image_menu_previews_only_visible_rows_and_keeps_later_images_selectable() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); const IMAGE_COUNT: usize = 128; let mut harness = image_menu_harness(IMAGE_COUNT).unwrap(); let (initial_previews, _) = preview_stats(&harness.ctx); @@ -1481,6 +1788,10 @@ pub(crate) fn mesh_map_color(map: BakedMap) -> Color32 { /// The Properties tab title: what the panel edits pub(crate) fn properties_title(app: &TextureCraftApp) -> String { + if !app.session.project_open { + return tr("Properties").to_string(); + } + let project = &app.session.doc.project; let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); @@ -1507,6 +1818,11 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { /// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder, instance or mask, else the tool (or a hint to select a layer when it can't act) pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); + if !app.session.project_open { + ui.label(RichText::new(tr("No properties found")).color(tokens.text_dim)); + return; + } + let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned()); let tool = app.session.tool.tool; let tool_usable = app.session.tool_usable(tool); @@ -1638,12 +1954,15 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) +const STENCIL_POSITION_RANGE: f32 = 2.0; + fn stencil_section(app: &mut TextureCraftApp, ui: &mut Ui) { let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Stencil"))); let names: Vec = app.session.doc.resources.keys().cloned().collect(); let current = app.session.tool.stencil.as_ref().map(|s| s.image.clone()).unwrap_or_else(|| tr("None").into()); - ui.horizontal(|ui| { + let row = ui.horizontal(|ui| { egui::ComboBox::from_id_salt("stencil_img").width(170.0).selected_text(current.clone()).show_ui(ui, |ui| { if ui.selectable_label(app.session.tool.stencil.is_none(), tr("None")).clicked() { app.run("tool.stencil", json!({"clear": true})); @@ -1656,16 +1975,32 @@ fn stencil_section(app: &mut TextureCraftApp, ui: &mut Ui) { }); import_button(app, ui); }); + + // An image from the Assets panel dropped on the row becomes the stencil + let row_response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as the stencil")); + if let Some(name) = image_drop(ui, &row_response) { + app.run("tool.stencil", json!({"image": name})); + } if names.is_empty() { ui.label(RichText::new(tr("Import an image (File > Import resources) to project it onto the mesh.")).color(tk.text_dim)); return; } + if let Some(st) = app.session.tool.stencil.as_mut() { slider(ui, tr("Scale"), &mut st.scale, 0.05..=4.0, 2); slider(ui, tr("Rotation"), &mut st.rotation, 0.0..=360.0, 0); + slider(ui, tr("Position X"), &mut st.center[0], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); + slider(ui, tr("Position Y"), &mut st.center[1], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); + if ui.button(tr("Reset stencil")).on_hover_text(tr("Put the stencil back in the middle of the view at its starting size and rotation")).clicked() { + st.reset_placement(); + } slider(ui, tr("Overlay opacity"), &mut st.opacity, 0.0..=1.0, 2); ui.checkbox(&mut st.tile, tr("Tile")); - ui.label(RichText::new(tr("Hold S: left-drag rotates, right-drag scales, middle-drag moves the stencil.")).size(10.5).color(tk.text_dim)); + ui.label( + RichText::new(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves; or use Position X / Y.")) + .size(10.5) + .color(tk.text_dim), + ); } } @@ -1690,17 +2025,28 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { } } }); + let mut aligned = app.session.tool.clone_aligned; + if ui + .checkbox(&mut aligned, tr("Aligned")) + .on_hover_text(tr("On: the offset from the first stroke is kept. Off: every stroke starts at the source point.")) + .changed() + { + app.run("tool.brush", json!({"cloneAligned": aligned})); + } let Some(src) = app.session.tool.clone_source else { ui.label(RichText::new(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")).color(tk.text_dim)); return; }; + ui.horizontal(|ui| { ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", src.uv[0])), ("v", &format!("{:.3}", src.uv[1]))])); if ui.small_button(tr("Clear")).clicked() { app.run("tool.cloneSource", json!({"clear": true})); } }); - let hint = if src.offset.is_some() { + let hint = if !app.session.tool.clone_aligned { + tr("Not aligned: every stroke starts at the source. V + click sets a new source.") + } else if src.offset.is_some() { tr("Aligned: the offset set by the first stroke is kept. V + click sets a new source.") } else { tr("The first stroke sets the offset from the source.") @@ -1716,6 +2062,10 @@ fn smudge_section(app: &mut TextureCraftApp, ui: &mut Ui) { app.session.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0); } ui.label(RichText::new(tr("Drags the layer stack's values along the stroke into the selected layer.")).size(10.5).color(tk.text_dim)); + ui.add_space(4.0); + ui.label(tr("Channels dragged")); + material_channel_chips(app, ui); + ui.label(RichText::new(tr("These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.")).size(10.5).color(tk.text_dim)); } fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { @@ -1869,6 +2219,7 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { let defaults = BrushSettings::default(); let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); + ui.label(RichText::new(tr("Ctrl+Shift+right-drag: size and hardness in fine steps.")).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); // Each section's reset puts back only the fields it shows let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); @@ -1888,7 +2239,7 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); } - let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing, settings.hardness); + let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing); if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { let mut flow_percent = brush.flow * 100.0; if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { @@ -1904,13 +2255,8 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { brush.spacing = spacing_percent / 100.0; } - - let mut hardness_percent = brush.hardness * 100.0; - if slider(ui, tr("Hardness"), &mut hardness_percent, 0.0..=99.9, 0).changed() { - brush.hardness = hardness_percent / 100.0; - } }) { - (brush.flow, brush.opacity, brush.spacing, brush.hardness) = flow_fields(&defaults); + (brush.flow, brush.opacity, brush.spacing) = flow_fields(&defaults); } let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); @@ -2018,7 +2364,8 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { pick = Some(json!(a.label())); } } - // The library alpha in use (picked from the shelf's Alphas tab). + + // The library alpha in use (picked from the shelf's Alphas tab) if let Some(a) = library { let tex = app.thumbs.alpha(ui.ctx(), a); alpha_tile(ui, true, &a.label, |p, r| { @@ -2027,7 +2374,8 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { } }); } - // Imported images, sampled as grayscale. + + // Imported images, sampled as grayscale for name in app.session.doc.resources.keys() { let Some(img) = app.session.images.get(name) else { continue }; let tex = app.thumbs.image(ui.ctx(), name, img); @@ -2046,9 +2394,38 @@ fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { } ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim)); crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush); + alpha_parameters(&mut app.session.tool.brush, ui); section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui)); } +/// Hardness and the parameters every alpha shares, under a header whose reset puts them back +fn alpha_parameters(brush: &mut BrushSettings, ui: &mut Ui) { + let defaults = BrushSettings::default(); + let at_defaults = brush.hardness == defaults.hardness && brush.alpha_params == defaults.alpha_params; + let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); + let percent_slider = |ui: &mut Ui, label: &str, value: &mut f32, min: f32, max: f32| { + let mut percent = *value * 100.0; + if slider(ui, label, &mut percent, min..=max, 0).changed() { + *value = percent / 100.0; + } + }; + + let reset = section_with_reset(ui, "sec_alpha_params", tr("Parameters"), true, at_defaults, |ui| { + percent_slider(ui, tr("Hardness"), &mut brush.hardness, 0.0, 99.9); + percent_slider(ui, tr("Size X"), &mut brush.alpha_params.size_x, 5.0, 100.0); + percent_slider(ui, tr("Size Y"), &mut brush.alpha_params.size_y, 5.0, 100.0); + + // Only the procedural Round shape has a roundness + ui.add_enabled_ui(round, |ui| percent_slider(ui, tr("Roundness"), &mut brush.alpha_params.roundness, 0.0, 100.0)); + slider(ui, tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); + ui.checkbox(&mut brush.alpha_params.invert, tr("Invert")); + }); + if reset { + (brush.hardness, brush.alpha_params) = (defaults.hardness, defaults.alpha_params); + } + *brush = brush.sanitized(); +} + /// Text drawn in a font, as the brush alpha or a decal (`resource.text`). fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { if app.ui.text.fonts.is_empty() @@ -2113,11 +2490,9 @@ fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { material_controls(app, ui); } -/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask) -fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { - use texturecraft_engine::core::ChannelKind; - - let tokens = Tokens::get(ui.ctx()); +/// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. +/// The Material tab and the Smudge panel both draw these, so they share one set of flags. +fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { for channel in &channels { @@ -2128,6 +2503,15 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { } } }); + channels +} + +/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask) +fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::core::ChannelKind; + + let tokens = Tokens::get(ui.ctx()); + let channels = material_channel_chips(app, ui); ui.add_space(4.0); if !targets_content(app) { @@ -2142,6 +2526,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { if !app.session.tool.enabled.contains(&channel) { continue; } + let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()); match channel.kind() { ChannelKind::Color => { @@ -2149,6 +2534,7 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(tr(channel.label())); if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) { app.session.tool.values.insert(channel, value); + app.session.tool.material = None; } }); } @@ -2158,11 +2544,13 @@ fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) { ChannelKind::Signed => { if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() { app.session.tool.values.insert(channel, [value[0]; 3]); + app.session.tool.material = None; } } ChannelKind::Scalar => { if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() { app.session.tool.values.insert(channel, [value[0]; 3]); + app.session.tool.material = None; } } } @@ -2302,13 +2690,13 @@ fn link_param_editor(ui: &mut Ui, layer: LayerId, p: &LinkParam) -> Option Value { - let mut v = base.clone(); - if let (Some(o), Value::Object(e)) = (v.as_object_mut(), extra) { - o.extend(e); +/// `base` with the fields of `extra` added +pub(crate) fn with(base: &Value, extra: Value) -> Value { + let mut params = base.clone(); + if let (Some(fields), Value::Object(extra)) = (params.as_object_mut(), extra) { + fields.extend(extra); } - v + params } /// Anchor points below layer `reader` in its texture set: (effect id, "layer / anchor" label). @@ -2351,7 +2739,7 @@ pub(crate) fn effect_anchors_below(app: &TextureCraftApp, layer: LayerId, effect } /// Whether anchor point `anchor` sits in a mask (it then records the mask's gray, whatever the channel). -fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { +pub(crate) fn anchor_in_mask(app: &TextureCraftApp, anchor: LayerId) -> bool { let project = &app.session.doc.project; project .effect(anchor) @@ -2401,7 +2789,7 @@ const FILL_CHANNELS_GAP: f32 = 4.0; fn fill_editor(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, enabled_channels: &[Channel], reader: LayerId) { let salt = base.to_string(); if let Projection::Decal(decal) = &fill.projection { - decal_editor(app, ui, decal, reader); + decal_editor(app, ui, decal, base, reader); } else { projection_editor(app, ui, &fill.projection, "layer.fill.projection", base, &salt); } @@ -2531,14 +2919,17 @@ fn axis_combo(ui: &mut Ui, axis: u8) -> Option { picked } -/// A decal's frame: place it with a click in the 3D view, then size, turn and shift it. -fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerId) { +/// A decal's frame: place it with a click in the 3D view, then size, turn and shift it. `base` is the +/// `{layer}` or `{effect}` holding it (a mask fill effect's decal edits like a layer's); `layer` is the reader. +fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, base: &Value, layer: LayerId) { + // What a placing click or the stack selection names: the effect when the decal is a mask effect's + let holder = base.get("effect").and_then(Value::as_u64).map_or(layer, LayerId); let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Decal"))); - let placing = app.placing_decal == Some(layer); + let placing = app.placing_decal == Some(holder); let label = format!("{} {}", ic::CROSSHAIR, if placing { tr("Click the mesh to place the decal") } else { tr("Place on the surface") }); if ui.selectable_label(placing, label).on_hover_text(tr("The next click in the 3D view moves the decal there")).clicked() { - app.placing_decal = if placing { None } else { Some(layer) }; + app.placing_decal = if placing { None } else { Some(holder) }; } let (lo, hi) = app.session.mesh.bounds(); let diag = (hi - lo).length().max(1e-3); @@ -2552,12 +2943,33 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerI (tr("Depth"), diag * 0.005..=diag), ]; let mut edit = None; - for ((label, range), x) in rows.into_iter().zip(v.iter_mut()) { - edit = edit.or(slider_edit(ui, label, x, range, 3)); + for (row, ((label, range), x)) in rows.into_iter().zip(v.iter_mut()).enumerate() { + edit = edit.or(slider_edit(ui, label, x, range, 3).map(|merge| (row, merge))); } - if let Some(merge) = edit { - app.run("layer.decal.set", json!({"layer": layer.0, "size": [v[0], v[1]], "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5], "merge": merge})); + + // The lock is a setting of the editor, not of the decal: every decal starts locked + let keep_id = ui.scope_id().with(("decal_keep_proportions", holder.0)); + let mut keep = ui.ctx().data(|data| data.get_temp::(keep_id)).unwrap_or(true); + if ui.checkbox(&mut keep, tr("Keep proportions")).on_hover_text(tr("Width and height follow each other by the image's aspect")).changed() { + ui.ctx().data_mut(|data| data.insert_temp(keep_id, keep)); + if keep { + app.run("layer.decal.set", with(base, json!({"keepProportions": true}))); + } } + let mut flip = d.flip; + let flipped = ui.horizontal(|ui| ui.checkbox(&mut flip[0], tr("Flip U")).changed() | ui.checkbox(&mut flip[1], tr("Flip V")).changed()).inner; + if flipped { + app.run("layer.decal.set", with(base, json!({"flipU": flip[0], "flipV": flip[1]}))); + } + if let Some((row, merge)) = edit { + // Locked: the edited side sets the other (a height sets the width, anything else the height) + let size = if keep && row == 1 { json!(v[1]) } else { json!([v[0], v[1]]) }; + app.run( + "layer.decal.set", + with(base, json!({"size": size, "keepProportions": keep && row < 2, "rotation": v[2], "offset": [v[3], v[4]], "depth": v[5], "merge": merge})), + ); + } + decal_symmetry_editor(app, ui, d, base); ui.label( RichText::new(tr("The image's alpha cuts the decal's shape; faces turned away and surfaces beyond its depth stay clear.")) .size(10.5) @@ -2565,120 +2977,184 @@ fn decal_editor(app: &mut TextureCraftApp, ui: &mut Ui, d: &Decal, layer: LayerI ); } -/// The source of one fill channel: uniform, procedural, image or anchor. -fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, c: Channel, anchors: &[(LayerId, String)], salt: &str) { - let tk = Tokens::get(ui.ctx()); - use texturecraft_engine::core::ChannelKind; - { - let set = |extra: Value| with(base, with(&json!({"channel": c.id()}), extra)); - let group = ui.group(|ui| { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(c.label())).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(13.0), |ui| { - if ui.button(tr("Uniform value")).clicked() { - app.run("layer.fill.set", set(json!({"value": c.default_value()}))); - ui.close(); - } - ui.separator(); - for k in ProceduralKind::ALL { - if ui.button(tr(k.label())).clicked() { - let (lo, hi) = match c { - Channel::BaseColor => ([0.15, 0.15, 0.15], [0.85, 0.85, 0.85]), - Channel::Height => ([-0.05; 3], [0.05; 3]), - _ => ([0.2; 3], [0.8; 3]), - }; - app.run("layer.fill.set", set(json!({"procedural": k.label(), "low": lo, "high": hi}))); - ui.close(); - } - } - ui.separator(); - if let Some(name) = image_menu(app, ui) { - app.run("layer.fill.set", set(json!({"image": name}))); - } - if let Some(a) = anchor_entries(ui, anchors, fill.source(c).anchor()) { - app.run("layer.fill.set", set(json!({"anchor": a.0}))); - ui.close(); - } - }) - .response - .on_hover_text(tr("Channel source: uniform value, procedural, image or anchor")); - }); - }); - match fill.source(c) { - Source::Uniform(mut v) => { - if c.kind() == ChannelKind::Color { - if color_swatch(ui, &format!("fill_{salt}_{}", c.id()), &mut v, ui.available_width() - 4.0) { - app.run("layer.fill.set", set(json!({"color": v}))); - } - } else { - let range = if c.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 }; - if let Some(merge) = slider_edit(ui, tr("Value"), &mut v[0], range, 2) { - app.run("layer.fill.set", set(json!({"value": v[0], "merge": merge}))); - } - } - } - Source::Procedural { pattern, low, high } => { - ui.label( - RichText::new(trf( - "{pattern} (scale {scale}, seed {seed})", - &[("pattern", &tr(pattern.kind.label())), ("scale", &format!("{:.1}", pattern.scale)), ("seed", &pattern.seed)], - )) - .color(tk.text_dim), - ); - let mut s = pattern.scale; - let mut con = pattern.contrast; - let r1 = slider_edit(ui, tr("Pattern scale"), &mut s, 0.1..=100.0, 1); - let r2 = slider_edit(ui, tr("Contrast"), &mut con, 0.0..=8.0, 2); - let mut seed = pattern.seed as f32; - let r3 = slider_edit(ui, tr("Seed"), &mut seed, 0.0..=999.0, 0); - if let Some(merge) = r1.or(r2).or(r3) { - app.run( - "layer.fill.set", - set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": seed as u64, "low": low, "high": high, "merge": merge})), - ); - } - if c.kind() == ChannelKind::Color { - let (mut lo, mut hi) = (low, high); - let mut changed = false; - ui.horizontal(|ui| { - ui.label(tr("Low")); - changed |= color_swatch(ui, &format!("lo_{salt}_{}", c.id()), &mut lo, 60.0); - ui.label(tr("High")); - changed |= color_swatch(ui, &format!("hi_{salt}_{}", c.id()), &mut hi, 60.0); - }); - if changed { - app.run( - "layer.fill.set", - set(json!({"procedural": pattern.kind.label(), "scale": s, "contrast": con, "seed": pattern.seed, "low": lo, "high": hi})), - ); - } - } - } - Source::Image { name, normal_format } => { - ui.label(trf("Image: {name}", &[("name", &name)])); - if c.kind() == ChannelKind::NormalMap { - let mut directx = normal_format == texturecraft_engine::core::NormalFormat::DirectX; - if ui - .checkbox(&mut directx, tr("DirectX normal map")) - .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")) - .changed() - { - app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); - } - } - } - Source::Anchor { anchor, channel } => { - ui.label(RichText::new(anchor_label(app, anchor, channel)).color(tk.text_dim)); +/// The decal's mirrored copy on the other side of the mesh: the axis it is mirrored across and how its image is flipped +fn decal_symmetry_editor(app: &mut TextureCraftApp, ui: &mut Ui, decal: &Decal, base: &Value) { + let axes = ["X", "Y", "Z"]; + let axis = decal.symmetry.map(|symmetry| usize::from(symmetry.axis)); + let mut picked = None; + combo(ui, tr("Mirror across"), axis.and_then(|axis| axes.get(axis).copied()).unwrap_or_else(|| tr("Off")), |ui| { + if ui.selectable_label(axis.is_none(), tr("Off")).clicked() && axis.is_some() { + picked = Some(json!({"symmetry": "off"})); + } + for (i, name) in axes.into_iter().enumerate() { + if ui.selectable_label(axis == Some(i), name).clicked() && axis != Some(i) { + picked = Some(json!({"symmetry": name.to_ascii_lowercase()})); + } + } + }); + + if let Some(symmetry) = decal.symmetry { + let flips = [(DecalFlip::None, tr("None"), "none"), (DecalFlip::U, "U", "u"), (DecalFlip::V, "V", "v")]; + let current = flips.iter().find(|flip| flip.0 == symmetry.flip).map_or("", |flip| flip.1); + combo(ui, tr("Flip the copy's image"), current, |ui| { + for (flip, name, id) in flips { + if ui.selectable_label(flip == symmetry.flip, name).clicked() && flip != symmetry.flip { + picked = Some(json!({"symmetryFlip": id})); } } }); + } - // A shelf image dropped on the channel becomes its source - if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { - app.run("layer.fill.set", set(json!({"image": name}))); + if let Some(symmetry) = decal.symmetry { + // The plane moves within the mesh, as the symmetry popup's axis position does + let (lo, hi) = app.session.mesh.bounds(); + let limit = ((hi - lo) * 0.5)[usize::from(symmetry.axis.min(2))]; + let mut offset = symmetry.offset; + if let Some(merge) = slider_edit(ui, tr("Axis position"), &mut offset, -limit..=limit, 2) { + picked = Some(json!({"symmetryOffset": offset, "merge": merge})); } } + + if let Some(change) = picked { + app.run("layer.decal.set", with(base, change)); + } +} + +/// Space a fill channel's color swatch leaves at the group's right edge +const CHANNEL_SWATCH_MARGIN: f32 = 4.0; +/// Width of a pattern's low and high swatches +const PATTERN_RANGE_SWATCH_WIDTH: f32 = 60.0; +/// Size of the gradient map menu icon beside the fill source slot +const FILL_CHANNEL_MENU_ICON_SIZE: f32 = 13.0; +const GRADIENT_MAP_HINT: &str = n_("Colors the procedural or anchor from dark to light through color stops"); + +/// The source slot, source settings and gradient map of one fill channel +fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Value, channel: Channel, anchors: &[(LayerId, String)], salt: &str) { + let tokens = Tokens::get(ui.ctx()); + let set = |extra: Value| with(base, with(&json!({"channel": channel.id()}), extra)); + let default_source = Source::uniform_of(channel); + let source = fill.sources.get(&channel).unwrap_or(&default_source); + let is_color = channel.kind() == ChannelKind::Color; + let group = ui.group(|ui| { + let slot = crate::fill_source_target::FillSourceTarget::Channel { base: base.clone(), channel }; + if is_color { + ui.allocate_ui_with_layout(vec2(ui.available_width(), SLOT_HEIGHT), egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.menu_button(RichText::new(ic::DOTS_THREE).size(FILL_CHANNEL_MENU_ICON_SIZE), |ui| gradient_map_item(app, ui, source, &set)) + .response + .on_hover_text(tr(GRADIENT_MAP_HINT)); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label()))); + }); + }); + } else { + crate::fill_source_slot::show(app, ui, &slot, source, (anchors, tr(channel.label()))); + } + + match source { + Source::Uniform(value) if is_color => { + let mut value = *value; + if color_swatch(ui, &format!("fill_{salt}_{}", channel.id()), &mut value, ui.available_width() - CHANNEL_SWATCH_MARGIN) { + app.run("layer.fill.set", set(json!({"color": value}))); + } + } + Source::Uniform(value) => { + let mut value = value[0]; + let range = if channel.kind() == ChannelKind::Signed { -1.0..=1.0 } else { 0.0..=1.0 }; + if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, range, 2) { + app.run("layer.fill.set", set(json!({"value": value, "merge": merge}))); + } + } + Source::Procedural { pattern, low, high, ramp } => { + let target = crate::pattern_target::PatternTarget { + command: "layer.fill.set", + base: with(base, json!({"channel": channel.id(), "low": low, "high": high})), + salt: format!("{salt}_{}", channel.id()), + }; + crate::pattern_panel::pattern_properties(app, ui, &target, pattern); + if is_color && ramp.is_empty() { + let (mut low, mut high) = (*low, *high); + let mut changed = false; + ui.horizontal(|ui| { + ui.label(tr("Low")); + changed |= color_swatch(ui, &format!("lo_{salt}_{}", channel.id()), &mut low, PATTERN_RANGE_SWATCH_WIDTH); + ui.label(tr("High")); + changed |= color_swatch(ui, &format!("hi_{salt}_{}", channel.id()), &mut high, PATTERN_RANGE_SWATCH_WIDTH); + }); + if changed { + crate::pattern_panel::send(app, &target, pattern, json!({"low": low, "high": high})); + } + } + } + Source::Image { name, normal_format } => { + ui.label(trf("Image: {name}", &[("name", name)])); + if channel.kind() == ChannelKind::NormalMap { + let mut directx = *normal_format == texturecraft_engine::core::NormalFormat::DirectX; + let toggle = ui + .checkbox(&mut directx, tr("DirectX normal map")) + .on_hover_text(tr("Flips the image's green channel, for normal maps made with Y pointing down")); + if toggle.changed() { + app.run("layer.fill.set", set(json!({"normalFormat": if directx { "directX" } else { "openGl" }}))); + } + } + } + Source::Anchor { anchor, channel: anchored, .. } => { + ui.label(RichText::new(anchor_label(app, *anchor, *anchored)).color(tokens.text_dim)); + } + } + + if is_color && !source.ramp().is_empty() { + ramp_editor(app, ui, source.ramp(), &format!("ramp_{salt}_{}", channel.id()), &set); + } + }); + + // A shelf image dropped on the channel becomes its source + if let Some(name) = image_drop(ui, &group.response.interact(Sense::hover())) { + app.run("layer.fill.set", set(json!({"image": name}))); + } +} + +/// The Gradient Map item beside a color channel's source slot: turns the color stops of its +/// procedural (starting from its low and high, so the look holds) or anchor on, or off. +fn gradient_map_item(app: &mut TextureCraftApp, ui: &mut Ui, source: &Source, set: &impl Fn(Value) -> Value) { + let can = matches!(source, Source::Procedural { .. } | Source::Anchor { .. }); + let on = !source.ramp().is_empty(); + let hint = tr(GRADIENT_MAP_HINT); + let item = ui.add_enabled_ui(can, |ui| ui.selectable_label(on, tr("Gradient Map"))).inner; + if item.on_hover_text(hint).on_disabled_hover_text(hint).clicked() { + let params = if on { json!({ "colors": [] }) } else { json!({ "gradientMap": true }) }; + app.run("layer.fill.set", set(params)); + ui.close(); + } +} + +/// The color stops of a fill channel's gradient map. +fn ramp_editor(app: &mut TextureCraftApp, ui: &mut Ui, ramp: &[[f32; 3]], salt: &str, set: &impl Fn(Value) -> Value) { + let mut stops = ramp.to_vec(); + if gradient_stops(ui, salt, &mut stops) { + app.run("layer.fill.set", set(json!({ "colors": stops }))); + } +} + +/// Swatches for gradient map stops (dark to light) with Add color and Remove last; true when +/// they changed. +fn gradient_stops(ui: &mut Ui, salt: &str, stops: &mut Vec<[f32; 3]>) -> bool { + let mut changed = false; + ui.horizontal_wrapped(|ui| { + for (i, stop) in stops.iter_mut().enumerate() { + changed |= color_swatch(ui, &format!("{salt}_{i}"), stop, FILTER_SWATCH_WIDTH); + } + }); + ui.horizontal(|ui| { + if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { + stops.push(stops.last().copied().unwrap_or([1.0; 3])); + changed = true; + } + if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { + stops.pop(); + changed = true; + } + }); + changed } /// The properties of effect `effect_id` of `layer`: each kind's own settings. @@ -2694,26 +3170,11 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe EffectKind::Fill { source, projection } => { ui.label(caption(tr("Fill"))); let anchors = effect_anchors_below(app, layer.id, effect_id); - let current = match source { - Source::Anchor { anchor, channel } => anchor_label(app, *anchor, *channel), - Source::Uniform(_) => tr("Uniform value").to_string(), - Source::Procedural { pattern, .. } => tr(pattern.kind.label()).to_string(), - Source::Image { name, .. } => trf("Image: {name}", &[("name", name)]), - }; - let source_response = combo(ui, tr("Source"), current, |ui| { - if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() { - app.run("effect.set", json!({"effect": id, "value": 1.0})); - } - if let Some(anchor) = anchor_entries(ui, &anchors, source.anchor()) { - app.run("effect.set", json!({"effect": id, "anchor": anchor.0})); - } - if let Some(name) = image_menu(app, ui) { - app.run("effect.set", json!({"effect": id, "image": name})); - } - }); + let target = crate::fill_source_target::FillSourceTarget::Mask { effect: id }; + let slot = ui.scope(|ui| crate::fill_source_slot::show(app, ui, &target, source, (&anchors, tr("Grayscale")))).response; - // The source selector accepts image drops from the Assets panel - if let Some(name) = image_drop(ui, &source_response.interact(Sense::hover())) { + // The slot accepts image drops from the Assets panel + if let Some(name) = image_drop(ui, &slot.interact(Sense::hover())) { app.run("effect.set", json!({"effect": id, "image": name})); } @@ -2724,6 +3185,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe app.run("effect.set", json!({"effect": id, "value": value, "merge": merge})); } } + Source::Procedural { pattern, .. } => { + let target = crate::pattern_target::PatternTarget { command: "effect.set", base: json!({"effect": id}), salt: format!("mask_fill_{id}") }; + crate::pattern_panel::pattern_properties(app, ui, &target, pattern); + } Source::Anchor { anchor, .. } if anchor_in_mask(app, *anchor) => { let note = if mask_anchor_enabled(app, *anchor) == Some(false) { tr("Off") } else { tr("A mask anchor reads as its mask's gray.") }; ui.label(RichText::new(note).color(tokens.text_dim)); @@ -2740,9 +3205,12 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effe ui.label(RichText::new(tr("Colors read as gray. Add a levels or blur effect above to shape the result.")).color(tokens.text_dim)); } Source::Image { .. } => { - projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); + if let Projection::Decal(decal) = projection { + decal_editor(app, ui, decal, &json!({"effect": id}), layer.id); + } else { + projection_editor(app, ui, projection, "effect.set", &json!({"effect": id}), &format!("maskfill{id}")); + } } - _ => {} } if anchors.is_empty() { ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tokens.text_dim)); @@ -2865,23 +3333,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &F } Filter::GradientMap { colors } => { let mut stops = colors.clone(); - let mut changed = false; - ui.horizontal_wrapped(|ui| { - for (i, stop) in stops.iter_mut().enumerate() { - changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH); - } - }); - ui.horizontal(|ui| { - if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() { - stops.push(stops.last().copied().unwrap_or([1.0; 3])); - changed = true; - } - if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() { - stops.pop(); - changed = true; - } - }); - if changed { + if gradient_stops(ui, &format!("gradient_{id}"), &mut stops) { set(app, "colors", json!(stops), false); } ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim)); diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 62bfa427..13d39465 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -480,6 +480,12 @@ 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); + if !app.session.project_open && !works_empty { + return; + } + egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), @@ -490,6 +496,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::Layers => crate::dock::layers(app, ui), 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, diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 5d5ddafc..8503541e 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -120,6 +120,14 @@ fn is_rgb(d: Dest) -> bool { fn set_layout(map: &mut MapSpec, layout: Layout) { let get = |d: Dest| map.channels.iter().find(|(x, _)| *x == d).map(|(_, s)| s.clone()); let color = get(Dest::R).or_else(|| get(Dest::L)).unwrap_or(SourceRef::Constant(0.0)); + + // A source that moves to a new channel keeps its inversion + let color_inverted = map.inverted.contains(if get(Dest::R).is_some() { &Dest::R } else { &Dest::L }); + let was_inverted = |d: Dest| match get(d) { + Some(_) => map.inverted.contains(&d), + None => !matches!(d, Dest::A) && color_inverted, + }; + let inverted: Vec = layout.dests().iter().copied().filter(|&d| was_inverted(d)).collect(); let channels = layout .dests() .iter() @@ -132,10 +140,11 @@ fn set_layout(map: &mut MapSpec, layout: Layout) { }) .collect(); map.channels = channels; + map.inverted = inverted; } fn new_map(layout: Layout) -> MapSpec { - let mut map = MapSpec { file: "$mesh_$textureSet_Output".into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new() }; + let mut map = MapSpec { file: "$mesh_$textureSet_Output".into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new(), inverted: Vec::new() }; set_layout(&mut map, layout); map } @@ -170,16 +179,8 @@ fn sync_draft(app: &mut TextureCraftApp) { } } -enum ListAction { - Select(String), - New, - Duplicate, - StartRename(String), - Rename(String), - Remove, - Import, - Export, -} +pub use crate::ask::Ask; +pub use crate::list_action::ListAction; enum MapAction { Add(Layout), @@ -200,7 +201,7 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { }); ui.separator(); ui.vertical(|ui| { - // Leave room for the input maps column and two separators. + // Leave room for the input maps column and two separators ui.set_width((ui.available_width() - INPUTS_WIDTH - 5.0 * ui.spacing().item_spacing.x - 4.0).max(200.0)); ui.set_height(height); outputs(app, ui); @@ -216,6 +217,16 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { } } +/// Select template `name` from outside the list (the Settings tab's dropdown); an unfinished +/// edit of the current one is asked about first. +pub fn select(app: &mut TextureCraftApp, name: String) { + if name != app.ui.export.preset && unfinished(app).is_some() { + app.ui.export.ask = Some(Ask::Leave(ListAction::Select(name))); + } else { + app.ui.export.preset = name; + } +} + fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) -> Option { let mut act = None; let sel = app.ui.export.preset.clone(); @@ -278,7 +289,28 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] act } +/// The error of the selected template's draft when it does not validate: that edit is not saved. +fn unfinished(app: &TextureCraftApp) -> Option { + app.ui.export.draft.as_ref().and_then(|d| d.validate().err()).map(|e| e.to_string()) +} + +/// Run `act`; deleting a template and leaving one with an unfinished edit ask first. fn apply(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { + let leaves = match &act { + ListAction::Select(name) | ListAction::StartRename(name) => *name != app.ui.export.preset, + ListAction::New | ListAction::Duplicate | ListAction::Imported(_) => true, + _ => false, + }; + if act == ListAction::Remove { + app.ui.export.ask = Some(Ask::Delete(app.ui.export.preset.clone())); + } else if leaves && unfinished(app).is_some() { + app.ui.export.ask = Some(Ask::Leave(act)); + } else { + perform(app, ctx, act); + } +} + +fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { app.ui.export.renaming = None; match act { ListAction::Select(name) => app.ui.export.preset = name, @@ -297,18 +329,76 @@ fn apply(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { ctx.memory_mut(|m| m.request_focus(egui::Id::unique(RENAME_ID))); } ListAction::Rename(name) => rename(app, name.trim()), - ListAction::Remove => { - let name = app.ui.export.preset.clone(); - if app.run("export.preset.remove", json!({ "name": name })).is_some() { - app.ui.export.preset = crate::state::ExportUi::default().preset; - app.toast(trf("Deleted template \"{name}\"", &[("name", &name)]), false); - } - } + ListAction::Remove => remove(app, app.ui.export.preset.clone()), ListAction::Import => import_file(app, ctx), + ListAction::Imported(p) => add_imported(app, &p), ListAction::Export => export_file(app), } } +fn remove(app: &mut TextureCraftApp, name: String) { + if app.run("export.preset.remove", json!({ "name": name })).is_some() { + if app.ui.export.preset == name { + app.ui.export.preset = crate::state::ExportUi::default().preset; + } + app.toast(trf("Deleted template \"{name}\"", &[("name", &name)]), false); + } +} + +/// The open question, if any: Escape or Cancel keeps things as they are. +pub(crate) fn ask(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(question) = app.ui.export.ask.clone() else { return }; + + // The edit was fixed while the question was open: nothing is dropped any more + if matches!(question, Ask::Leave(_)) && unfinished(app).is_none() { + app.ui.export.ask = None; + return; + } + + let mut cancel = false; + let mut yes = false; + let (title, text, yes_label, no_label) = match &question { + Ask::Delete(name) => ( + tr("Delete template"), + trf("Delete the template \"{name}\"? Its file is removed and this cannot be undone.", &[("name", name)]), + tr("Delete"), + tr("Cancel"), + ), + Ask::Leave(_) => ( + tr("Unfinished template edit"), + trf( + "The last edit of the template \"{name}\" is not saved: {error}. Switching away drops it.", + &[("name", &app.ui.export.preset), ("error", &unfinished(app).unwrap_or_default())], + ), + tr("Discard changes"), + tr("Keep editing"), + ), + }; + egui::Window::new(title) + .id(egui::Id::unique("export_template_ask")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .show(ctx, |ui| { + ui.set_max_width(360.0); + ui.label(text); + ui.add_space(8.0); + ui.horizontal(|ui| { + yes = ui.button(yes_label).clicked(); + cancel |= ui.button(no_label).clicked(); + }); + }); + if yes { + app.ui.export.ask = None; + match question { + Ask::Delete(name) => remove(app, name), + Ask::Leave(act) => perform(app, ctx, act), + } + } else if cancel { + app.ui.export.ask = None; + } +} + /// Save `preset` as a new user preset (renamed when its name is taken) and select it. fn save_new(app: &mut TextureCraftApp, preset: &ExportPreset) -> Option { let v = serde_json::to_value(preset).ok()?; @@ -334,6 +424,14 @@ fn rename(app: &mut TextureCraftApp, name: &str) { /// Add an imported preset (renamed when its name is taken) and select it. pub fn import(app: &mut TextureCraftApp, preset: &ExportPreset) { + if unfinished(app).is_some() { + app.ui.export.ask = Some(Ask::Leave(ListAction::Imported(preset.clone()))); + } else { + add_imported(app, preset); + } +} + +fn add_imported(app: &mut TextureCraftApp, preset: &ExportPreset) { if let Some(name) = save_new(app, preset) { app.toast(trf("Imported template \"{name}\"", &[("name", &name)]), false); } @@ -587,7 +685,8 @@ fn channel_slots(ui: &mut Ui, mi: usize, map: &mut MapSpec) -> bool { let tk = Tokens::get(ui.ctx()); let mut changed = false; let mut dropped = None; - for (k, (dest, src)) in map.channels.iter_mut().enumerate() { + let MapSpec { channels, inverted, .. } = map; + for (k, (dest, src)) in channels.iter_mut().enumerate() { ui.horizontal(|ui| { let dest_name = match *dest { Dest::L => tr("Gray"), @@ -628,6 +727,14 @@ fn channel_slots(ui: &mut Ui, mi: usize, map: &mut MapSpec) -> bool { } _ => {} } + let on = inverted.contains(dest); + if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() { + inverted.retain(|x| x != dest); + if !on { + inverted.push(*dest); + } + changed = true; + } }); } if let Some((dest, input)) = dropped { @@ -649,7 +756,8 @@ fn input_maps(ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for (k, (label, s)) in inputs.iter().enumerate() { let label = tr(label); - // Not `dnd_drag_source`: its scope doesn't wrap inside `horizontal_wrapped`. + + // `dnd_drag_source` cannot wrap inside `horizontal_wrapped` let r = chip(ui, label, false).interact(egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); r.dnd_set_drag_payload(s.clone()); if r.dragged() @@ -697,4 +805,24 @@ mod tests { assert!(same_source(&ch(Channel::Normal, 2), &ch(Channel::Normal, 0))); assert!(!same_source(&SourceRef::Constant(0.0), &SourceRef::Constant(1.0))); } + + #[test] + fn inversion_follows_its_source_through_layouts_and_drops() { + let mut map = new_map(Layout::Rgb); + map.inverted = vec![Dest::R]; + set_layout(&mut map, Layout::Gray); + assert_eq!(map.inverted, vec![Dest::L], "the colour source keeps its inversion on L"); + set_layout(&mut map, Layout::Rgb); + assert_eq!(map.inverted, vec![Dest::R, Dest::G, Dest::B], "and spreads it over R, G, B"); + set_layout(&mut map, Layout::Rgba); + assert_eq!(map.inverted, vec![Dest::R, Dest::G, Dest::B], "alpha stays un-inverted"); + map.inverted = vec![Dest::G]; + set_layout(&mut map, Layout::GrayAlpha); + assert!(map.inverted.is_empty(), "channels that leave take their inversion with them"); + let mut map = new_map(Layout::Rgb); + map.inverted = vec![Dest::B]; + drop_input(&mut map, Dest::B, &ch(Channel::Metallic, 0)); + assert_eq!(map.inverted, vec![Dest::B], "a dropped map keeps the channel's toggle, like picking from the list"); + ExportPreset { name: "t".into(), maps: vec![map] }.validate().unwrap(); + } } diff --git a/crates/ui-egui/src/fill_source_slot.rs b/crates/ui-egui/src/fill_source_slot.rs new file mode 100644 index 00000000..0e87dbf2 --- /dev/null +++ b/crates/ui-egui/src/fill_source_slot.rs @@ -0,0 +1,301 @@ +//! The source slot of a fill: a mask fill's grayscale or one channel of a fill. It shows what the fill reads and opens the source picker: the patterns, the project's images and a uniform value, or the anchor points below the layer + +use std::sync::{Arc, LazyLock}; + +use egui::{Sense, Ui, vec2}; +use serde_json::json; +use texturecraft_engine::compose::{ImageRes, ThumbTarget}; +use texturecraft_engine::core::{Channel, LayerId, ProceduralKind, Source}; + +use crate::TextureCraftApp; +use crate::dock::with; +use crate::fill_source_target::FillSourceTarget; +use crate::filter_slot::{SLOT_HEIGHT, paint}; +use crate::i18n::tr; +use crate::resource_picker; +use crate::resource_picker_anchor::ResourcePickerAnchor; +use crate::resource_picker_choice::ResourcePickerChoice; +use crate::resource_picker_tile::ResourcePickerTile; +use crate::shelf_preview::ShelfPreview; + +/// The key of the uniform value tile, and the prefixes of the pattern and image tiles' keys +const UNIFORM_KEY: &str = "uniform"; +const PATTERN_PREFIX: &str = "pattern:"; +const IMAGE_PREFIX: &str = "image:"; +/// The gray the uniform value tile shows +const UNIFORM_TILE_GRAY: f32 = 0.8; +/// The swatch's name among the image previews, prefixed like the stencil previews so it is not taken for a project image +const UNIFORM_SWATCH_NAME: &str = "swatch:uniform"; +/// One swatch for every frame, so its preview stays cached +static UNIFORM_SWATCH: LazyLock> = + LazyLock::new(|| Arc::new(ImageRes { width: 1, height: 1, rgba: vec![[UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, UNIFORM_TILE_GRAY, 1.0]], srgb: false })); + +/// The slot of `fill`, which reads `source`; `anchors` are the anchor points below its layer and `caption` names what it fills +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, fill: &FillSourceTarget, source: &Source, (anchors, caption): (&[(LayerId, String)], &str)) { + let ctx = ui.ctx().clone(); + let channel = match fill { + FillSourceTarget::Mask { .. } => source_channel(source), + FillSourceTarget::Channel { channel, .. } => *channel, + }; + let (name, picture) = shown(app, &ctx, source); + + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click()); + + // Read as a dropdown named for what it fills, its value the source + response.widget_info(|| egui::WidgetInfo { current_text_value: Some(name.clone()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, caption) }); + let popup = ui.make_persistent_id(("fill_source_picker", fill_key(fill))); + if response.clicked() { + resource_picker::toggle(&ctx, popup); + } + let highlighted = response.hovered() || resource_picker::is_open(&ctx, popup); + paint(ui, rect, (highlighted, response.has_focus()), picture, (caption, &name)); + if !resource_picker::is_open(&ctx, popup) { + return; + } + + let tiles = tiles(app, &ctx); + let anchors: Vec = anchors + .iter() + .map(|(anchor, name)| ResourcePickerAnchor { + anchor: *anchor, + name: name.clone(), + layer: layer_name(app, *anchor), + channel: read_label(app, *anchor, channel), + }) + .collect(); + let current = current_key(source); + let picked = resource_picker::show_sources(&response, popup, &mut app.thumbs, (current.as_deref(), source.anchor()), tiles, anchors, |ui, anchor| { + app.layer_panel.texture_outside(ui.ctx(), &app.session, ThumbTarget::Stage { effect: anchor, channel }) + }); + match picked { + Some(ResourcePickerChoice::Resource(key)) if Some(&key) != current.as_ref() => pick_resource(app, fill, &key), + Some(ResourcePickerChoice::Anchor(anchor)) if source.anchor() != Some(anchor) => pick_anchor(app, fill, anchor, channel), + _ => {} + } +} + +/// The name and picture of what `source` reads +fn shown(app: &mut TextureCraftApp, ctx: &egui::Context, source: &Source) -> (String, Option) { + match source { + Source::Uniform(_) => (tr("Uniform value").to_string(), None), + Source::Procedural { pattern, .. } => (tr(pattern.kind.label()).to_string(), app.thumbs.procedural(ctx, pattern.kind).map(|texture| texture.id())), + Source::Image { name, .. } => { + let picture = app.session.images.get(name).cloned().map(|image| app.thumbs.image(ctx, name, &image).id()); + (name.clone(), picture) + } + Source::Anchor { anchor, channel, .. } => { + let name = format!("{} · {}", layer_name(app, *anchor), tr(read_label(app, *anchor, *channel))); + (name, app.layer_panel.texture_outside(ctx, &app.session, ThumbTarget::Stage { effect: *anchor, channel: *channel })) + } + } +} + +/// What a fill reads at anchor point `anchor`: its mask's gray when it sits in a mask, else `channel` +fn read_label(app: &TextureCraftApp, anchor: LayerId, channel: Channel) -> &'static str { + if crate::dock::anchor_in_mask(app, anchor) { "Mask" } else { channel.label() } +} + +/// The name of the layer anchor point `anchor` sits on +fn layer_name(app: &TextureCraftApp, anchor: LayerId) -> String { + let project = &app.session.doc.project; + let layer = project.effect(anchor).and_then(|(owner, _)| project.layers.get(&owner)); + layer.map_or_else(|| tr("missing").to_string(), |layer| layer.name.clone()) +} + +/// The channel a mask fill's anchor is read in (height until one is picked) +fn source_channel(source: &Source) -> Channel { + match source { + Source::Anchor { channel, .. } => *channel, + _ => Channel::Height, + } +} + +/// Keeps the pickers of two slots shown at once apart +fn fill_key(fill: &FillSourceTarget) -> String { + match fill { + FillSourceTarget::Mask { effect } => format!("mask_{effect}"), + FillSourceTarget::Channel { base, channel } => format!("{base}_{}", channel.id()), + } +} + +/// The key of the tile `source` is, outlined in the picker +fn current_key(source: &Source) -> Option { + match source { + Source::Uniform(_) => Some(UNIFORM_KEY.to_string()), + Source::Procedural { pattern, .. } => Some(format!("{PATTERN_PREFIX}{}", pattern.kind.label())), + Source::Image { name, .. } => Some(format!("{IMAGE_PREFIX}{name}")), + Source::Anchor { .. } => None, + } +} + +/// The Resources tab: the patterns, the project's images and a uniform value +fn tiles(app: &mut TextureCraftApp, ctx: &egui::Context) -> Vec> { + let mut tiles: Vec> = ProceduralKind::ALL + .into_iter() + .map(|kind| ResourcePickerTile { + key: format!("{PATTERN_PREFIX}{}", kind.label()), + label: tr(kind.label()).to_string(), + group: tr("Patterns"), + thumbnail: app.thumbs.procedural(ctx, kind), + image: None, + preview: Box::new(move || ShelfPreview::Procedural(kind)), + }) + .collect(); + let mut names: Vec<(String, Arc)> = app.session.images.iter().map(|(name, image)| (name.clone(), image.clone())).collect(); + names.sort_by(|a, b| a.0.cmp(&b.0)); + for (name, image) in names { + let preview_name = name.clone(); + tiles.push(ResourcePickerTile { + key: format!("{IMAGE_PREFIX}{name}"), + label: name, + group: tr("Images"), + thumbnail: None, + image: Some(image.clone()), + preview: Box::new(move || ShelfPreview::Image(preview_name.clone(), image.clone())), + }); + } + tiles.push(ResourcePickerTile { + key: UNIFORM_KEY.to_string(), + label: tr("Uniform value").to_string(), + group: tr("Uniform"), + thumbnail: Some(app.thumbs.image(ctx, UNIFORM_SWATCH_NAME, &UNIFORM_SWATCH)), + image: None, + preview: Box::new(|| ShelfPreview::Image(UNIFORM_SWATCH_NAME.to_string(), UNIFORM_SWATCH.clone())), + }); + tiles +} + +/// Sets the fill to the resource whose tile key is `key` +fn pick_resource(app: &mut TextureCraftApp, fill: &FillSourceTarget, key: &str) { + let pattern = key.strip_prefix(PATTERN_PREFIX).and_then(ProceduralKind::parse); + match (fill, pattern) { + (FillSourceTarget::Mask { effect }, Some(kind)) => { + app.run("effect.set", json!({"effect": effect, "procedural": kind.label()})); + } + (FillSourceTarget::Mask { effect }, None) => match key.strip_prefix(IMAGE_PREFIX) { + Some(name) => { + app.run("effect.set", json!({"effect": effect, "image": name})); + } + None => { + app.run("effect.set", json!({"effect": effect, "uniform": 1.0})); + } + }, + (FillSourceTarget::Channel { base, channel }, Some(kind)) => { + let (low, high) = pattern_range(*channel); + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "procedural": kind.label(), "low": low, "high": high}))); + } + (FillSourceTarget::Channel { base, channel }, None) => match key.strip_prefix(IMAGE_PREFIX) { + Some(name) => { + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "image": name}))); + } + None => { + app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "value": channel.default_value()}))); + } + }, + } +} + +/// Sets the fill to read anchor point `anchor` in `channel` +fn pick_anchor(app: &mut TextureCraftApp, fill: &FillSourceTarget, anchor: LayerId, channel: Channel) { + let (command, params) = match fill { + FillSourceTarget::Mask { effect } => ("effect.set", json!({"effect": effect, "anchor": anchor.0, "anchorChannel": channel.id()})), + FillSourceTarget::Channel { base, channel } => ("layer.fill.set", with(base, json!({"channel": channel.id(), "anchor": anchor.0}))), + }; + app.run(command, params); +} + +/// The values a new pattern maps to in `channel`: grays for the base color, a small relief for height, most of the range otherwise +fn pattern_range(channel: Channel) -> ([f32; 3], [f32; 3]) { + match channel { + Channel::BaseColor => ([0.15; 3], [0.85; 3]), + Channel::Height => ([-0.05; 3], [0.05; 3]), + _ => ([0.2; 3], [0.8; 3]), + } +} + +#[cfg(test)] +mod tests { + use egui_kittest::{Harness, kittest::Queryable}; + use texturecraft_engine::core::LayerKind; + use texturecraft_engine::{Session, execute, geom::primitives}; + + use super::*; + + fn picker_harness(session: Session, anchors: Vec<(LayerId, String)>) -> Harness<'static, (TextureCraftApp, Vec<(LayerId, String)>)> { + let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); + let app = TextureCraftApp::new(&creation_context, session); + Harness::builder().with_size(vec2(500.0, 700.0)).with_context_setup(crate::theme::install).build_ui_state( + |ui, (app, anchors)| { + let layer = app.session.selected_layer().unwrap(); + let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; + let source = fill.source(Channel::Height); + let target = FillSourceTarget::Channel { base: json!({"layer": layer.0}), channel: Channel::Height }; + show(app, ui, &target, &source, (anchors, "Source")); + app.layer_panel.end(ui.ctx(), &app.session); + }, + (app, anchors), + ) + } + + fn image_preview_count(context: &egui::Context) -> usize { + context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-image-")).count() + } + + #[test] + fn source_picker_images_render_on_scroll_and_release_on_removal() { + const IMAGE_COUNT: usize = 128; + let mut session = Session::new_project("picker", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"height": 0.5})).unwrap(); + for index in 0..IMAGE_COUNT { + let name = format!("picker-image-{index:03}.png"); + session.doc.resources.insert(name.clone(), Arc::new(vec![0])); + session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false })); + } + let mut harness = picker_harness(session, Vec::new()); + + harness.get_by_role_and_label(egui::Role::ComboBox, "Source").click(); + harness.run_steps(30); + let initial_previews = image_preview_count(&harness.ctx); + + assert!(initial_previews > 0 && initial_previews < IMAGE_COUNT, "only visible images should have previews: {initial_previews}"); + harness.run_steps(3); + assert_eq!(image_preview_count(&harness.ctx), initial_previews, "warm frames reuse image previews"); + + let first_name = "picker-image-000.png"; + harness.get_by_role_and_label(egui::Role::Button, first_name).scroll_to_me(); + harness.run_steps(30); + let scrolled_previews = image_preview_count(&harness.ctx); + harness.get_by_role_and_label(egui::Role::Button, first_name).click(); + harness.run_steps(3); + + assert!(scrolled_previews > initial_previews, "scrolling must render newly visible image tiles"); + let app = &mut harness.state_mut().0; + let layer = app.session.selected_layer().unwrap(); + let LayerKind::Fill(fill) = &app.session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; + assert_eq!(fill.source(Channel::Height), Source::image(first_name)); + + app.session.images.clear(); + app.thumbs.sync_images(&app.session.images, app.session.revision + 1); + + assert_eq!(image_preview_count(&harness.ctx), 0, "removed images release all picker preview textures"); + eprintln!("picker image previews: initial {initial_previews}, after scroll {scrolled_previews}, after removal 0"); + } + + #[test] + fn source_tiles_defer_image_previews_until_drawn() { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + for index in 0..128 { + let name = format!("picker-{index:03}.png"); + session.images.insert(name, Arc::new(ImageRes { width: 64, height: 64, rgba: vec![[0.5; 4]; 64 * 64], srgb: false })); + } + let creation_context = eframe::CreationContext::_new_kittest(egui::Context::default()); + let mut app = TextureCraftApp::new(&creation_context, session); + let context = egui::Context::default(); + + let tiles = tiles(&mut app, &context); + let image_previews = context.tex_manager().read().allocated().filter(|(_, metadata)| metadata.name.starts_with("res_picker-")).count(); + + assert_eq!(tiles.iter().filter(|tile| tile.key.starts_with(IMAGE_PREFIX)).count(), 128); + assert_eq!(image_previews, 0, "opening the picker must not resample all project images"); + } +} diff --git a/crates/ui-egui/src/fill_source_target.rs b/crates/ui-egui/src/fill_source_target.rs new file mode 100644 index 00000000..78b5fe63 --- /dev/null +++ b/crates/ui-egui/src/fill_source_target.rs @@ -0,0 +1,12 @@ +//! Which fill a source slot sets + +use serde_json::Value; +use texturecraft_engine::core::Channel; + +/// Which fill the slot sets, and how +pub(crate) enum FillSourceTarget { + /// A mask fill effect: one grayscale value, set with `effect.set` + Mask { effect: u64 }, + /// One channel of a fill layer or content fill (`base` names it), set with `layer.fill.set` + Channel { base: Value, channel: Channel }, +} diff --git a/crates/ui-egui/src/filter_slot.rs b/crates/ui-egui/src/filter_slot.rs index 172017d9..95880e2d 100644 --- a/crates/ui-egui/src/filter_slot.rs +++ b/crates/ui-egui/src/filter_slot.rs @@ -15,7 +15,7 @@ use crate::theme::Tokens; use crate::thumbs::Thumbs; use crate::widgets::elided; -const SLOT_HEIGHT: f32 = 52.0; +pub(crate) const SLOT_HEIGHT: f32 = 52.0; const SLOT_ROUNDING: f32 = 3.0; const BORDER_WIDTH: f32 = 1.0; const THUMBNAIL_SIZE: f32 = 40.0; @@ -48,7 +48,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: } let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup); - paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name); + paint(ui, rect, (highlighted, response.has_focus()), thumbnail.as_ref().map(egui::TextureHandle::id), (tr("Filter"), name)); let items = |thumbs: &mut Thumbs| { filter_effects() @@ -90,11 +90,11 @@ fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool { owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect)) } -/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret -fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) { - let tk = Tokens::get(ui.ctx()); +/// A slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, `caption` over `name`, caret (fill source slots share it) +pub(crate) fn paint(ui: &Ui, rect: Rect, (highlighted, focused): (bool, bool), thumbnail: Option, (caption, name): (&str, &str)) { + let tokens = Tokens::get(ui.ctx()); let painter = ui.painter(); - let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) }; + let (fill, border) = if highlighted { (tokens.row_hover, tokens.button_border) } else { (tokens.field, tokens.field_border) }; painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside); if focused { painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside); @@ -102,19 +102,19 @@ fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Optio if let Some(texture) = thumbnail { let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); - painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + painter.image(texture, image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); } // Long names are cut short rather than run under the thumbnail or the caret let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE; let text_right = rect.right() - CARET_INSET * 2.0; let text_center_x = (text_left + text_right) * 0.5; - let lines = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)]; + let lines = [(caption, CAPTION_FONT_SIZE, tokens.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tokens.text_strong, LINE_GAP * 0.5)]; for (text, size, color, offset) in lines { let galley = elided(painter, text, size, color, text_right - text_left); painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color); } - let caret_color = if highlighted { tk.text } else { tk.text_dim }; + let caret_color = if highlighted { tokens.text } else { tokens.text_dim }; painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color); } diff --git a/crates/ui-egui/src/generator_panel.rs b/crates/ui-egui/src/generator_panel.rs index d5246c68..d15be0e4 100644 --- a/crates/ui-egui/src/generator_panel.rs +++ b/crates/ui-egui/src/generator_panel.rs @@ -10,25 +10,15 @@ use texturecraft_engine::core::{ use crate::TextureCraftApp; use crate::dock::{anchor_entries, anchor_label, anchors_below, effect_anchors_below, image_drop, image_menu, mesh_map_color}; use crate::i18n::{baked_map_label, tr, trf}; +use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, random_seed}; use crate::theme::{Tokens, caption}; use crate::widgets::{combo, section, slider_edit}; -/// Random seeds stay below this, short enough to read and type. -const SEED_RANGE: u32 = 10_000; -/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range. -const SEED_MIX: u32 = 2_654_435_761; - -/// Font size of the notes under a control. -const NOTE_FONT_SIZE: f32 = 10.5; - /// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it. const INPUT_TILE_SIZE: f32 = 32.0; const INPUT_TILE_ROUNDING: f32 = 2.0; const INPUT_TILE_ICON_SIZE: f32 = 16.0; -/// Width of the names in the Attributes section, so their values line up. -const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; - /// The settings of generator effect `id`. pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) { let tokens = Tokens::get(ui.ctx()); @@ -187,18 +177,6 @@ fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: Outpu .on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution.")); } -/// The most powers of two a resolution factor scales by, either way. -const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); - -/// "Same as context", or the fraction or multiple a resolution factor stands for. -fn factor_label(factor: i8) -> String { - match factor { - 0 => tr("Same as context").to_string(), - negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), - positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), - } -} - /// Global invert, blur, balance and contrast: what every generator applies to its finished value. fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) { let (mut invert, mut global) = (generator.invert, generator.global); @@ -258,13 +236,6 @@ fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) { ui.data_mut(|data| data.insert_temp(typing_id, typing)); } -/// A seed different from `current`, from the clock. -fn random_seed(current: u32) -> u32 { - let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); - let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; - if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } -} - /// The `effect.set` params that put generator effect `id` back to the defaults of its kind. fn defaults_of(id: u64, kind: GeneratorKind) -> Value { let defaults = Generator::new(kind); @@ -337,7 +308,7 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64 None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]), Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]), Some(Source::Uniform(_)) => tr("Uniform value").to_string(), - Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel), + Some(Source::Anchor { anchor, channel, .. }) => anchor_label(app, *anchor, *channel), Some(Source::Procedural { .. }) => tr("Procedural").to_string(), }; let group = ui.group(|ui| { diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 5770ae58..baeded21 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -282,6 +282,7 @@ impl GpuLink { if self.aux.get(&texture_set) == Some(&key) { continue; } + let Some(cache) = session.caches.get(texture_set) else { continue }; let resolution = texturecraft_render::aux_size(cache.size); @@ -300,9 +301,20 @@ impl GpuLink { if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { let resolution = session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size)); - if let Some(rgba) = session.mask_view_rgba(id, resolution) { - out.aux.push((texture_set, resolution, rgba)); - } + let rgba = session.mask_view_rgba(id, resolution).unwrap_or_else(|| MASK_VIEW_BLANK.repeat((resolution * resolution) as usize)); + out.aux.push((texture_set, resolution, rgba)); + self.aux.insert(texture_set, key); + } + } + + // The other texture sets show nothing of this mask: a flat dark gray + let shown = session.doc.project.locate(id).map(|(texture_set, _, _)| texture_set); + for texture_set in (0..session.caches.len()).filter(|set| Some(*set) != shown) { + let Some(cache) = session.caches.get(texture_set) else { continue }; + let resolution = texturecraft_render::aux_size(cache.size); + let key = ("maskblank".to_owned(), u64::from(resolution)); + if self.aux.get(&texture_set) != Some(&key) { + out.aux.push((texture_set, resolution, MASK_VIEW_BLANK.repeat((resolution * resolution) as usize))); self.aux.insert(texture_set, key); } } @@ -315,6 +327,7 @@ impl GpuLink { if self.aux.get(&texture_set) == Some(&key) { continue; } + let resolution = texturecraft_render::aux_size(cache.size); if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { out.aux.push((texture_set, resolution, rgba)); @@ -350,6 +363,9 @@ fn record_recreated_uploads(recreated: &mut BTreeMap= 2, "needs another set to blank"); + let layer = texturecraft_engine::core::LayerId(execute(&mut s, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap()); + execute(&mut s, "mask.add.white", &json!({})).unwrap(); + let owner = s.doc.project.locate(layer).unwrap().0; + let sets = s.doc.project.texture_sets.len(); + + let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0); + assert_eq!(out.aux.len(), sets, "every set gets an aux texture"); + for (set, _, rgba) in &out.aux { + let blank = rgba.chunks(4).all(|px| px == MASK_VIEW_BLANK); + assert_eq!(blank, *set != owner, "set {set}: only the other sets are blank"); + } + drop(out); + let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0); + assert!(out.aux.is_empty(), "nothing is sent again while the view stays"); + drop(out); + + execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": false})).unwrap(); + let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0); + assert_eq!(out.aux.len(), 1, "disabling the displayed mask replaces its old upload"); + let (set, resolution, rgba) = &out.aux[0]; + assert_eq!(*set, owner); + assert_eq!(*rgba, MASK_VIEW_BLANK.repeat((resolution * resolution) as usize)); + assert_eq!(gpu.aux.len(), sets, "only view keys remain in the link"); + drop(out); + let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0); + assert!(out.aux.is_empty(), "the disabled view needs no repeat upload"); + drop(out); + + execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": true})).unwrap(); + let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0); + assert_eq!(out.aux.len(), 1, "re-enabling the mask uploads its values again"); + assert!(out.aux[0].2.chunks(4).any(|pixel| pixel != MASK_VIEW_BLANK)); + } + fn kinds(out: &SceneSync) -> BTreeSet { out.tiles.iter().filter(|t| t.0 == 0).map(|t| t.1).collect() } diff --git a/crates/ui-egui/src/gray_slider.rs b/crates/ui-egui/src/gray_slider.rs new file mode 100644 index 00000000..0ea4dfd2 --- /dev/null +++ b/crates/ui-egui/src/gray_slider.rs @@ -0,0 +1,57 @@ +//! A gray value from black to white, as the reference shows a pattern's colors: a gradient bar with a knob, the value, and a button that inverts it + +use egui::{Rect, Sense, Stroke, Ui, vec2}; +use egui_phosphor::regular as ic; + +use crate::i18n::tr; +use crate::theme::Tokens; +use crate::widgets::value_header; + +const BAR_HEIGHT: f32 = 8.0; +const BAR_ROUNDING: f32 = 2.0; +const KNOB_RADIUS: f32 = 6.0; +const KNOB_STROKE: f32 = 1.5; +const BAR_BORDER_WIDTH: f32 = 1.0; +/// The narrowest bar, room for the knob to move +const MIN_BAR_WIDTH: f32 = KNOB_RADIUS * 4.0; + +/// `label` and `value` over a black-to-white bar and an Invert value button: `Some(merge)` on every frame that changes it, as [`crate::widgets::slider_edit`] +pub(crate) fn gray_slider(ui: &mut Ui, label: &str, value: &mut f32) -> Option { + let tokens = Tokens::get(ui.ctx()); + let (field, typed) = value_header(ui, label, value, 0.0..=1.0, 2); + ui.horizontal(|ui| { + let mut edit = typed; + let button_width = ui.spacing().interact_size.y; + let width = (ui.available_width() - button_width - ui.spacing().item_spacing.x).max(MIN_BAR_WIDTH); + let (rect, response) = ui.allocate_exact_size(vec2(width, KNOB_RADIUS * 2.0 + KNOB_STROKE * 2.0), Sense::click_and_drag()); + let bar = Rect::from_center_size(rect.center(), vec2(rect.width() - KNOB_RADIUS * 2.0, BAR_HEIGHT)); + if response.is_pointer_button_down_on() { + // A grab of the bar ends typing, so the field shows the dragged value + ui.data_mut(|data| data.remove_temp::(field)); + ui.memory_mut(|memory| memory.surrender_focus(field)); + } + if let Some(pointer) = response.interact_pointer_pos().filter(|_| response.dragged() || response.clicked()) { + *value = ((pointer.x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); + edit = Some(response.dragged() && !response.drag_started()); + } + + let painter = ui.painter(); + let mut mesh = egui::Mesh::default(); + for (corner, gray) in [(bar.left_top(), 0), (bar.right_top(), 255), (bar.right_bottom(), 255), (bar.left_bottom(), 0)] { + mesh.colored_vertex(corner, egui::Color32::from_gray(gray)); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + painter.add(mesh); + painter.rect_stroke(bar, BAR_ROUNDING, Stroke::new(BAR_BORDER_WIDTH, tokens.field_border), egui::StrokeKind::Outside); + let knob = egui::pos2(bar.left() + bar.width() * value.clamp(0.0, 1.0), bar.center().y); + painter.circle(knob, KNOB_RADIUS, tokens.panel, Stroke::new(KNOB_STROKE, tokens.text_strong)); + + if ui.button(ic::CIRCLE_HALF).on_hover_text(tr("Invert value")).clicked() { + *value = 1.0 - *value; + edit = Some(false); + } + edit + }) + .inner +} diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index f1aaa9b8..84a5a31f 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -101,6 +101,36 @@ pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String { craft_i18n::fmt(tr(template), &args) } +/// An undo step's label in the current language. A label with a layer name, path number or +/// smart mask name in it ("Paint on Rust") is matched to its engine template, which is translated +/// and filled in again; any other label is translated as it is. +pub fn tr_history(label: &str) -> String { + tr_history_with(label, |text| tr(text).to_string()) +} + +/// [`tr_history`] with its own lookup `translate` +fn tr_history_with(label: &str, translate: impl Fn(&str) -> String) -> String { + match history_template(label) { + Some((template, name, value)) => craft_i18n::fmt(&translate(template), &[(name, value)]), + None => translate(label), + } +} + +/// The engine template a history label was made from, its placeholder name and the value in it. +/// The template with the longest fixed start wins. +fn history_template(label: &str) -> Option<(&'static str, &'static str, &str)> { + texturecraft_engine::HISTORY_TEMPLATES + .iter() + .filter_map(|template| { + let (open, close) = (template.find('{')?, template.find('}')?); + let (prefix, suffix) = (&template[..open], &template[close + 1..]); + let value = label.strip_prefix(prefix)?.strip_suffix(suffix)?; + Some((prefix.len(), *template, &template[open + 1..close], value)) + }) + .max_by_key(|(prefix_length, ..)| *prefix_length) + .map(|(_, template, name, value)| (template, name, value)) +} + /// The supported language for a locale such as "de-AT", "pt_BR.UTF-8" or "zh-Hant-TW" ("en" when /// none matches). Chinese locales get Simplified Chinese; Portuguese ones get Brazilian Portuguese. pub fn language_for_locale(locale: &str) -> &'static str { @@ -156,7 +186,9 @@ mod tests { /// The labels of the menu catalog, panels, shortcuts, shelf tabs and engine enums that are /// translated where they are shown. fn catalog_keys() -> Vec<&'static str> { - use texturecraft_engine::core::{BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind}; + use texturecraft_engine::core::{ + BlendMode, Channel, EffectKind, GeneratorKind, ProceduralKind, TileBlending, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, + }; use texturecraft_engine::filter_lib::{FILTERS, build, scalar_params}; let mut keys: Vec<&'static str> = Vec::new(); keys.extend(crate::menus::TOP); @@ -174,8 +206,14 @@ mod tests { keys.extend(BlendMode::all().map(|mode| mode.label())); keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label())); keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label())); + keys.extend(texturecraft_engine::HISTORY_TEMPLATES); keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label())); keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label())); + keys.extend(TileShape::ALL.iter().map(|shape| shape.label())); + keys.extend(TileSizeMode::ALL.iter().map(|mode| mode.label())); + keys.extend(TileInputDistribution::ALL.iter().map(|distribution| distribution.label())); + keys.extend(TileSymmetry::ALL.iter().map(|symmetry| symmetry.label())); + keys.extend(TileBlending::ALL.iter().map(|blending| blending.label())); keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label())); keys.extend(texturecraft_engine::geom::primitives::BUILTINS.iter().map(|(_, label)| *label)); for filter in FILTERS { @@ -285,6 +323,36 @@ mod tests", } } + #[test] + fn history_labels_are_matched_to_their_templates() { + assert_eq!(history_template("Paint on Rust"), Some(("Paint on {layer}", "layer", "Rust"))); + assert_eq!(history_template("Paint on Paint mask of x"), Some(("Paint on {layer}", "layer", "Paint mask of x"))); + assert_eq!(history_template("Paint mask of Paint on x"), Some(("Paint mask of {layer}", "layer", "Paint on x"))); + assert_eq!(history_template("Erase mask of Rust"), Some(("Erase mask of {layer}", "layer", "Rust"))); + assert_eq!(history_template("Edit path 2"), Some(("Edit path {n}", "n", "2"))); + assert_eq!(history_template("Apply smart mask Dirt"), Some(("Apply smart mask {name}", "name", "Dirt"))); + assert_eq!(history_template("Rename layer"), None); + } + + /// The template is translated and the layer name filled in; other labels are translated whole + #[test] + fn history_labels_with_a_layer_name_are_translated_through_their_template() { + let translate = |text: &str| { + match text { + "Paint on {layer}" => "Auf {layer} malen", + "Paint mask of {layer}" => "Maske von {layer} malen", + "Remove layer" => "Ebene entfernen", + other => other, + } + .to_string() + }; + assert_eq!(tr_history_with("Paint on Rust", translate), "Auf Rust malen"); + assert_eq!(tr_history_with("Paint mask of Paint on x", translate), "Maske von Paint on x malen"); + assert_eq!(tr_history_with("Remove layer", translate), "Ebene entfernen"); + assert_eq!(tr_history_with("Clone on Rust", translate), "Clone on Rust"); + assert_eq!(tr_history_with("Paint on {layer}", translate), "Auf {layer} malen"); + } + const UNTRANSLATED: &[&str] = &["RGB", "RGBA"]; #[test] diff --git a/crates/ui-egui/src/import_resources.rs b/crates/ui-egui/src/import_resources.rs index ae3ea3ea..629bc90a 100644 --- a/crates/ui-egui/src/import_resources.rs +++ b/crates/ui-egui/src/import_resources.rs @@ -10,7 +10,7 @@ use serde_json::json; use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{tr, trf}; -use crate::state::{ImportResources, ImportRow, ImportTarget, ResourceUsage}; +use crate::state::{ImportResources, ImportRow, ResourceUsage}; use crate::web_files::{IMAGE_EXTS, MATERIAL_EXTS}; use crate::widgets::primary_button; @@ -21,13 +21,16 @@ const LIST_HEIGHT_POINTS: f32 = 300.0; /// Width of a row's prefix field and usage dropdown const PREFIX_WIDTH_POINTS: f32 = 160.0; const USAGE_WIDTH_POINTS: f32 = 110.0; -/// Room beside the dropdown of the target +/// Width of the destination dropdown const TARGET_WIDTH_POINTS: f32 = 190.0; +/// Keep space for the file name in a narrow row +const MIN_NAME_WIDTH_POINTS: f32 = 40.0; /// Opens the window with an empty list (an open window stays as it is) pub(crate) fn open(app: &mut TextureCraftApp) { static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + app.ui.windows.project_config = None; if app.ui.windows.import_resources.is_none() { app.ui.windows.import_resources = Some(ImportResources { project: app.session.project_id, @@ -95,11 +98,10 @@ fn click_row(window: &mut ImportResources, visible: &[u64], id: u64, modifiers: } pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - let Some(mut window) = app.ui.windows.import_resources.clone() else { return }; + let Some(mut window) = app.ui.windows.import_resources.take() else { return }; // Files chosen for another project cannot be imported here if window.project != app.session.project_id { - app.ui.windows.import_resources = None; return; } @@ -115,7 +117,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::windows::dialog("import_resources", tr("Import resources"), &mut open).default_width(WINDOW_WIDTH_POINTS).show(ctx, |ui| { ui.set_min_width(WINDOW_WIDTH_POINTS); ui.horizontal(|ui| { - ui.label(tr("Import your resources and set their usage")); + ui.label(tr("Choose files and assign their roles")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_enabled_ui(!window.selected.is_empty(), |ui| { remove = ui.button(tr("Remove selected resources")).clicked(); @@ -125,12 +127,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); ui.add_space(4.0); - let all_label = trf("All imported resources ({count})", &[("count", &window.rows.len().to_string())]); + let all_label = trf("All files ({count})", &[("count", &window.rows.len())]); let filter_text = match window.filter { None => all_label.clone(), - Some(usage) => { - trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|r| r.usage == usage).count().to_string())]) - } + Some(usage) => trf("{usage} ({count})", &[("usage", &usage.name()), ("count", &window.rows.iter().filter(|row| row.usage == usage).count())]), }; egui::ComboBox::from_id_salt("import_filter").width(ui.available_width()).selected_text(filter_text).show_ui(ui, |ui| { if ui.selectable_label(window.filter.is_none(), &all_label).clicked() { @@ -147,16 +147,18 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); ui.add_space(4.0); - let visible: Vec = window.rows.iter().filter(|row| window.filter.is_none_or(|usage| row.usage == usage)).map(|row| row.id).collect(); + let filter = window.filter; + let visible = |row: &ImportRow| filter.is_none_or(|usage| row.usage == usage); let modifiers = ui.input(|i| i.modifiers); let mut clicked = None; egui::ScrollArea::vertical().min_scrolled_height(LIST_HEIGHT_POINTS).max_height(LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { - for row in window.rows.iter_mut().filter(|row| visible.contains(&row.id)) { + for row in window.rows.iter_mut().filter(|row| visible(row)) { let material = is_material(row); let selected = window.selected.contains(&row.id); ui.horizontal(|ui| { - let name_width = (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(40.0); + let name_width = + (ui.available_width() - PREFIX_WIDTH_POINTS - USAGE_WIDTH_POINTS - 2.0 * ui.spacing().item_spacing.x).max(MIN_NAME_WIDTH_POINTS); let name = ui.add_sized([name_width, ui.spacing().interact_size.y], egui::Button::selectable(selected, file_name(row)).truncate()); if name.on_hover_text(row.path.display().to_string()).clicked() { clicked = Some(row.id); @@ -192,32 +194,27 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); } }); + if let Some(id) = clicked { + let visible: Vec = if modifiers.shift { window.rows.iter().filter(|row| visible(row)).map(|row| row.id).collect() } else { Vec::new() }; click_row(&mut window, &visible, id, modifiers); } ui.add_space(8.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - egui::ComboBox::from_id_salt("import_target") - .width(TARGET_WIDTH_POINTS) - .selected_text(match window.target { - ImportTarget::Session => tr("current session"), - ImportTarget::Library => tr("library 'your_assets'"), - }) - .show_ui(ui, |ui| { - if ui.selectable_label(window.target == ImportTarget::Session, tr("current session")).clicked() { - window.target = ImportTarget::Session; - } - // Your assets hold smart materials and brush presets, not images - ui.add_enabled(false, egui::Button::selectable(false, tr("library 'your_assets'"))).on_disabled_hover_text(tr("Not available yet")); - }); - ui.label(tr("Import your resources to:")); + egui::ComboBox::from_id_salt("import_target").width(TARGET_WIDTH_POINTS).selected_text(tr("Open project")).show_ui(ui, |ui| { + if ui.selectable_label(true, tr("Open project")).clicked() { + ui.close(); + } + + ui.add_enabled(false, egui::Button::selectable(false, tr("Asset library"))).on_disabled_hover_text(tr("Not available yet")); + }); + ui.label(tr("Destination")); }); }); ui.add_space(4.0); ui.horizontal(|ui| { - ui.label(tr("To add a new library, see the Edit / Settings menu")); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { cancel = ui.button(tr("Cancel")).clicked(); import |= ui.add_enabled(!window.rows.is_empty(), primary_button(ui, tr("Import"))).clicked(); @@ -225,6 +222,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); + if cancel || !open { + return; + } + if remove { window.rows.retain(|row| !window.selected.contains(&row.id)); window.selected.clear(); @@ -237,10 +238,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let opening_id = window.opening_id; app.ask_file(FileDialog::open_many().filter(tr("Resources"), &extensions), Bound::Project, move |app, paths| { let Some(stored) = app.ui.windows.import_resources.as_mut().filter(|stored| stored.opening_id == opening_id) else { return }; + for path in paths { if stored.rows.iter().any(|row| row.path == path) { continue; } + stored.rows.push(ImportRow { id: stored.next_row, path, prefix: String::new(), usage: ResourceUsage::Undefined }); stored.next_row += 1; } @@ -248,45 +251,47 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } if import && !window.rows.is_empty() { - import_rows(app, &window); + window.rows.retain(|row| !import_row(app, row)); + if window.rows.is_empty() { + app.ui.dock.focus(crate::docking::Panel::Assets); + return; + } + + window.selected.clear(); + window.anchor = None; } - if (import && !window.rows.is_empty()) || cancel || !open { - app.ui.windows.import_resources = None; - } else { - // A file answer only arrives between frames, so nothing was added meanwhile - app.ui.windows.import_resources = Some(window); - } + // File picker answers run between frames after the dialog state is restored + app.ui.windows.import_resources = Some(window); } -/// Imports every row in order, each by its usage -fn import_rows(app: &mut TextureCraftApp, window: &ImportResources) { - for row in &window.rows { - let path = row.path.display().to_string(); - if is_material(row) { - app.run("material.load", json!({ "path": path })); - continue; - } +/// Import one row. A failed file is left in the dialog with its settings. +fn import_row(app: &mut TextureCraftApp, row: &ImportRow) -> bool { + let Some(path) = row.path.to_str() else { + app.toast(trf("Could not import a path that is not UTF-8: {path}", &[("path", &row.path.display())]), true); + return false; + }; - let mut params = json!({ "path": path }); - if !row.prefix.trim().is_empty() { - params["prefix"] = json!(row.prefix); - } - let Some(result) = app.run("resource.import", params) else { continue }; - let name = result.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Imported {name}", &[("name", &name)]), false); - - match row.usage { - ResourceUsage::Environment => crate::web_files::use_environment(app, &name), - ResourceUsage::Alpha => { - if app.run("tool.brush", json!({ "alpha": { "image": name } })).is_some() { - app.toast(trf("Brush alpha: {name}", &[("name", &name)]), false); - } - } - ResourceUsage::Undefined | ResourceUsage::Texture | ResourceUsage::ColorLut | ResourceUsage::PostFx => {} - } + if is_material(row) { + return app.run("material.load", json!({ "path": path })).is_some(); } - app.ui.dock.focus(crate::docking::Panel::Assets); + + let Some(result) = app.run("resource.import", json!({ "path": path, "prefix": row.prefix })) else { return false }; + + let name = result["name"].as_str().unwrap_or_default(); + app.toast(trf("Imported {name}", &[("name", &name)]), false); + + match row.usage { + ResourceUsage::Environment => crate::web_files::use_environment(app, name), + ResourceUsage::Alpha => { + if app.run("tool.brush", json!({ "alpha": { "image": name } })).is_some() { + app.toast(trf("Brush alpha: {name}", &[("name", &name)]), false); + } + } + ResourceUsage::Undefined | ResourceUsage::Texture | ResourceUsage::ColorLut | ResourceUsage::PostFx => {} + } + + true } #[cfg(test)] diff --git a/crates/ui-egui/src/inactive_set_hint.rs b/crates/ui-egui/src/inactive_set_hint.rs new file mode 100644 index 00000000..ef0fc2ac --- /dev/null +++ b/crates/ui-egui/src/inactive_set_hint.rs @@ -0,0 +1,29 @@ +//! A brush stroke that starts on a texture set other than the active one paints nothing (only the active set takes paint): say why, once per stroke + +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::{Session, Tool}; + +use crate::TextureCraftApp; +use crate::i18n::trf; + +/// Tools that paint into the active texture set with the brush +fn paints_active_set(tool: Tool) -> bool { + matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone) +} + +/// The name of the texture set under viewport pixel `screen` when a brush stroke started there would paint nothing because that set is not the active one +pub fn inactive_set_under(session: &Session, screen: Vec2) -> Option { + if !paints_active_set(session.tool.tool) { + return None; + } + + let set = session.texture_set_at(screen, session.viewport).filter(|set| *set != session.ts())?; + session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.name.clone()) +} + +/// Show the toast for a stroke that starts at viewport pixel `screen` (call once, when the stroke begins). Returns whether it did. +pub fn hint_on_stroke_start(app: &mut TextureCraftApp, screen: Vec2) -> bool { + let Some(name) = inactive_set_under(&app.session, screen) else { return false }; + app.toast(trf("Texture set '{name}' is not active for painting. Select it in the Texture Sets list.", &[("name", &name)]), false); + true +} diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 6129dbc7..cee050ba 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -1,4 +1,4 @@ -//! Keyboard shortcuts: every menu item and every command with a default shortcut, the user's +//! 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). @@ -26,7 +26,21 @@ pub struct Binding { pub default: Option<&'static str>, } -/// Every bindable item: the menu catalog, then commands with a default shortcut. +/// The menu a command without a menu entry is listed under, from its id. +fn group_of(id: &str) -> &'static str { + match id.split('.').next().unwrap_or("") { + "layer" | "mask" | "effect" | "material" | "textureSet" => "Layers", + "tool" | "brush" | "alpha" | "text" => "Tools", + "camera" | "viewport" => "Viewport", + "file" | "project" | "export" | "resource" => "File", + "edit" => "Edit", + "bake" => "Mode", + _ => "Commands", + } +} + +/// Every bindable item: the menu catalog, then every command that has a default shortcut or that +/// a key can run (see [`texturecraft_engine::CommandSpec::bindable`]). pub fn bindings() -> &'static [Binding] { static ALL: std::sync::OnceLock> = std::sync::OnceLock::new(); ALL.get_or_init(|| { @@ -36,9 +50,9 @@ pub fn bindings() -> &'static [Binding] { v.push(Binding { id: i.id, group: i.menu, label: i.label, default: i.shortcut }); } } - for c in texturecraft_engine::command_specs().iter().filter(|c| c.shortcut.is_some()) { + for c in texturecraft_engine::command_specs().iter().filter(|c| c.shortcut.is_some() || c.bindable()) { if !v.iter().any(|b| b.id == c.id) { - v.push(Binding { id: c.id, group: c.menu.first().copied().unwrap_or("Commands"), label: c.label, default: c.shortcut }); + v.push(Binding { id: c.id, group: c.menu.first().copied().unwrap_or_else(|| group_of(c.id)), label: c.label, default: c.shortcut }); } } v @@ -270,6 +284,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.shortcuts { return; } + let capture_id = Id::unique(CAPTURE); let filter_id = Id::unique("keymap_filter"); let mut capture: Option = ctx.data(|d| d.get_temp(capture_id)); @@ -312,6 +327,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { { continue; } + ui.horizontal(|ui| { ui.label(tr(b.label)); ui.label(RichText::new(tr(b.group)).size(10.5).color(tk.text_dim)); @@ -350,21 +366,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { }); ui.add_space(4.0); section(ui, "keymap_nav", tr("Viewport and brush (fixed)"), false, |ui| { - egui::Grid::new("keymap_fixed").striped(true).show(ui, |ui| { - for (k, v) in [ - (tr("Alt + LMB drag"), tr("Orbit")), - (tr("MMB drag / Alt + MMB"), tr("Pan")), - (tr("Wheel / Alt + RMB drag"), tr("Zoom")), - (tr("LMB"), tr("Paint with the current tool")), - ("[ / ]", tr("Brush size down / up")), - (tr("Shift + wheel"), tr("Brush size")), - ("Esc", tr("Cancel the stroke")), - ] { - ui.label(RichText::new(k).strong()); - ui.label(v); - ui.end_row(); - } - }); + fixed_gestures_grid(ui); }); }); app.ui.windows.shortcuts = open; @@ -384,6 +386,53 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) { }); } +/// The fixed gestures as a two-column grid (the "Viewport and brush" section of the shortcut window) +pub fn fixed_gestures_grid(ui: &mut egui::Ui) { + egui::Grid::new("keymap_fixed").striped(true).show(ui, |ui| { + for (k, v) in fixed_gestures() { + ui.label(RichText::new(k).strong()); + ui.label(v); + ui.end_row(); + } + }); +} + +/// The mouse gestures and hold keys of the viewports, as (gesture, what it does) rows for the +/// shortcut window. The hold keys come from the constants the viewport reads, so a rebound hold key +/// is named from the same constant. +pub fn fixed_gestures() -> Vec<(String, String)> { + let stencil = crate::viewport::STENCIL_KEY.name(); + let clone = crate::viewport::CLONE_SOURCE_KEY.name(); + let keyed = |template: &str| trf(template, &[("key", &stencil)]); + vec![ + (tr("Alt + LMB drag").into(), tr("Orbit").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()), + (tr("Shift + RMB drag").into(), tr("Turn the environment light (3D view)").into()), + (tr("LMB").into(), tr("Paint with the current tool").into()), + (tr("Shift + LMB").into(), tr("Paint a straight line from where the last stroke ended").into()), + (tr("Ctrl + Shift + LMB").into(), tr("Draw snapped straight lines").into()), + ("[ / ]".into(), tr("Brush size down / up").into()), + (tr("Shift + wheel").into(), tr("Brush size").into()), + (tr("Ctrl + wheel").into(), tr("Brush size (wheel up smaller, down larger)").into()), + (tr("Ctrl + RMB drag").into(), tr("Brush size (left/right) and hardness (up/down)").into()), + (tr("Ctrl + LMB drag").into(), tr("Brush flow (left/right) and angle (up/down)").into()), + (tr("Ctrl + Shift + RMB drag").into(), tr("Brush size and hardness in fine steps").into()), + (keyed("{key} + LMB drag"), tr("Projection: rotate the stencil").into()), + (keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()), + (keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()), + (trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()), + (tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()), + (tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()), + (tr("Click the first point (Path tool)").into(), tr("Path: close it (needs 3 points)").into()), + ("Enter".into(), tr("Path: apply it with the brush").into()), + ("Backspace".into(), tr("Path: remove the selected or last point").into()), + ("Esc".into(), tr("Cancel the stroke").into()), + (tr("Esc (Path tool)").into(), tr("Path: cancel it").into()), + ] +} + #[cfg(test)] mod tests { use super::*; @@ -400,6 +449,29 @@ mod tests { assert!(!captured(Modifiers::NONE, Key::M) && !captured(Modifiers::NONE, Key::F), "plain keys need no capture"); } + #[test] + fn gesture_rows_name_the_hold_keys_and_cover_every_gesture() { + let rows = fixed_gestures(); + let has = |gesture: &str, what: &str| rows.iter().any(|(g, w)| g == gesture && w.contains(what)); + let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name()); + assert!(has(&format!("{s} + LMB drag"), "rotate") && has(&format!("{s} + RMB drag"), "scale") && has(&format!("{s} + MMB drag"), "move")); + assert!(has(&format!("{v} + LMB"), "Clone")); + for (gesture, what) in [ + ("Shift + LMB", "straight line"), + ("Shift + RMB drag", "environment light"), + ("Enter", "apply"), + ("Backspace", "remove"), + ("Esc (Path tool)", "cancel"), + ("Click the first point (Path tool)", "close"), + ("LMB drag on a point (Path tool)", "move"), + ("Click (Path tool)", "add a point"), + ] { + assert!(has(gesture, what), "no row {gesture} / {what}"); + } + let mut seen = std::collections::HashSet::new(); + assert!(rows.iter().all(|(g, w)| seen.insert((g.clone(), w.clone()))), "duplicate row"); + } + #[test] fn shortcuts_round_trip_through_parse_and_format() { for b in bindings() { @@ -529,10 +601,12 @@ mod tests { #[test] fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() { let mut keymap = Keymap::new(); - keymap.insert("file.save".into(), "F5".into()); + + // F7 is bound to nothing else, so the stored shortcut alone decides (F5 is Perspective) + keymap.insert("file.save".into(), "F7".into()); keymap.insert("edit.undo".into(), String::new()); let resolved = bindings_for(&keymap); - assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::F7, Modifiers::NONE)).as_deref(), Some("file.save")); assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None); assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None); } @@ -546,6 +620,60 @@ mod tests { assert_eq!(resolved.command_of(&press(Key::S, Modifiers::CTRL)), None, "the Control key is another key"); } + #[test] + fn commands_without_a_default_key_are_listed_unbound_and_filtered_by_their_parameters() { + for id in ["layer.add.fill", "layer.add.paint", "layer.add.group", "mask.invert", "layer.visible"] { + let b = binding(id); + assert!(b.default.is_none() && shortcut(&Keymap::new(), b).is_none(), "{id} is listed without a key"); + } + assert_eq!(binding("mask.invert").group, "Layers"); + for id in ["textureSet.select", "layer.rename", "tool.select", "layer.list", "project.inspect"] { + assert!(bindings().iter().all(|b| b.id != id), "{id} cannot run from a key"); + } + let ids: Vec<_> = bindings().iter().map(|b| b.id).collect(); + let unique: std::collections::BTreeSet<_> = ids.iter().collect(); + assert_eq!(ids.len(), unique.len(), "every id is listed once"); + } + + #[test] + fn every_listed_item_is_implemented() { + for b in bindings() { + assert!(crate::menus::implemented(b.id), "{} is listed but nothing runs it", b.id); + } + } + + #[test] + fn a_command_without_a_default_key_can_be_bound_unbound_and_conflicts() { + let (invert, save) = (binding("mask.invert"), binding("file.save")); + let mut keymap = Keymap::new(); + rebind(&mut keymap, invert, "Ctrl+Alt+I"); + assert_eq!(shortcut_of(&keymap, "mask.invert"), Some("Ctrl+Alt+I")); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.command_of(&press(Key::I, Modifiers::COMMAND | Modifiers::ALT)).as_deref(), Some("mask.invert")); + assert!(resolved.conflict(invert).is_none()); + + // Taking the key of a default shortcut is a conflict, on both items + rebind(&mut keymap, invert, "Ctrl+S"); + let resolved = bindings_for(&keymap); + assert_eq!(resolved.conflict(invert).map(|b| b.id), Some("file.save")); + assert_eq!(resolved.conflict(save).map(|b| b.id), Some("mask.invert")); + + // Unbinding drops the override of an item that has no default + rebind(&mut keymap, invert, ""); + assert_eq!(shortcut_of(&keymap, "mask.invert"), None); + assert!(bindings_for(&keymap).conflict(save).is_none()); + } + + #[test] + fn a_saved_keymap_from_before_every_command_was_bindable_still_loads() { + let old: Keymap = serde_json::from_str(r#"{"file.save":"F5","edit.undo":"","ui.layout.3d":"Ctrl+Shift+H"}"#).unwrap(); + let resolved = bindings_for(&old); + assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save")); + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None); + assert_eq!(shortcut_of(&old, "ui.layout.3d"), Some("Ctrl+Shift+H")); + assert_eq!(shortcut_of(&old, "mask.invert"), None); + } + #[test] fn the_first_item_listed_wins_a_shared_shortcut() { let mut keymap = Keymap::new(); diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index 27dc5f67..d5390546 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -40,20 +40,39 @@ pub struct LayerPanel { service: ThumbService, textures: HashMap, frame: u64, + /// Whether this frame's pictures are begun and not yet finished by [`LayerPanel::end`] + pictures_begun: bool, /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. pub(crate) folded: HashSet<(u64, bool)>, } +/// How soon to look again for pictures still rendering (milliseconds) +const POLL_INTERVAL_MS: u64 = 40; + impl LayerPanel { /// Start drawing the panel for this frame. pub(crate) fn begin(&mut self, session: &Session, now: f64) { - self.frame += 1; - self.service.begin_frame(session, now); + self.begin_pictures(session, now); // Deleted layer IDs must not accumulate in panel state self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); } + /// Advance the picture frame once, whether the panel or a picture outside it asks first + fn begin_pictures(&mut self, session: &Session, now: f64) { + if !self.pictures_begun { + self.pictures_begun = true; + self.frame += 1; + self.service.begin_frame(session, now); + } + } + + /// The texture of `target` for a picture outside the panel (a fill source slot, a source picker's anchor points), which renders while the panel is hidden too + pub(crate) fn texture_outside(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { + self.begin_pictures(session, ctx.input(|input| input.time)); + self.texture(ctx, session, target) + } + /// The texture of `target`, queuing its render (call only for rows that are on screen). pub(crate) fn texture(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { let view = self.service.get(session, target); @@ -72,10 +91,14 @@ impl LayerPanel { Some(id) } - /// Finish the frame: collect pictures and ask for another frame while work is outstanding. + /// Finish the frame once everything shown has asked for its pictures: collect them, start the missing ones and ask for another frame while work is outstanding pub(crate) fn end(&mut self, ctx: &Context, session: &Session) { + if !std::mem::take(&mut self.pictures_begun) { + return; + } + if self.service.poll(session) { - ctx.request_repaint_after(Duration::from_millis(40)); + ctx.request_repaint_after(Duration::from_millis(POLL_INTERVAL_MS)); } if self.textures.len() > CACHE_ENTRIES * 2 { let frame = self.frame; @@ -110,6 +133,57 @@ mod tests { assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state"); } + #[test] + fn a_picture_outside_the_panel_renders_while_the_panel_is_hidden() { + // Long enough for the render worker on a busy machine + const ATTEMPTS: usize = 500; + const WAIT: Duration = Duration::from_millis(10); + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let context = Context::default(); + let mut panel = LayerPanel::default(); + + // The panel never begins a frame: only the outside picture asks + let picture = (0..ATTEMPTS).find_map(|_| { + let picture = panel.texture_outside(&context, &session, target); + panel.end(&context, &session); + if picture.is_none() { + std::thread::sleep(WAIT); + } + picture + }); + + assert!(picture.is_some(), "the picture renders without the Layers panel"); + } + + #[test] + fn outside_pictures_release_old_textures_while_the_panel_is_hidden() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let context = Context::default(); + let initial_textures = context.tex_manager().read().num_allocated(); + let mut panel = LayerPanel::default(); + + // Outside pictures begin frames even when the Layers panel never does + let missing = ThumbTarget::Content { layer: LayerId(u64::MAX), channel: Channel::BaseColor }; + panel.texture_outside(&context, &session, missing); + for index in 0..CACHE_ENTRIES * 2 + 1 { + let target = ThumbTarget::Content { layer: LayerId(index as u64), channel: Channel::BaseColor }; + let image = egui::ColorImage::filled([64, 64], egui::Color32::WHITE); + let texture = context.load_texture("layer-thumb", image, TextureOptions::LINEAR); + panel.textures.insert(target, (1, texture, panel.frame)); + } + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures + CACHE_ENTRIES * 2 + 1); + panel.end(&context, &session); + + for _ in 0..2 { + panel.texture_outside(&context, &session, missing); + panel.end(&context, &session); + } + + assert_eq!(panel.textures.len(), 0, "old outside pictures should leave the GPU cache"); + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures); + } + #[test] fn evicted_and_dropped_thumbnail_handles_release_textures() { let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); @@ -128,7 +202,9 @@ mod tests { panel.textures.insert(target, (1, texture, panel.frame)); } let kept = evicted.pop().unwrap(); + panel.end(&context, &session); panel.begin(&session, 1.0); + panel.end(&context, &session); panel.begin(&session, 2.0); panel.textures.values_mut().find(|(_, texture, _)| texture.id() == kept).unwrap().2 = panel.frame; panel.end(&context, &session); diff --git a/crates/ui-egui/src/layout_dialog.rs b/crates/ui-egui/src/layout_dialog.rs new file mode 100644 index 00000000..fb55aeee --- /dev/null +++ b/crates/ui-egui/src/layout_dialog.rs @@ -0,0 +1,10 @@ +/// The layout dialog being shown (not saved) +#[derive(Clone, Debug, PartialEq)] +pub enum LayoutDialog { + /// Asking for the name to save the current layout under + Save(String), + /// A layout of this name exists: asking whether to replace it + Overwrite(String), + /// The list with rename and delete + Manage { renaming: Option<(String, String)>, deleting: Option }, +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 24f69692..f97008a3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,9 +7,12 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod angle_dial; +mod ask; mod bake_job; pub mod bake_mode; mod bake_scene; +mod color_management; mod color_selection_editor; pub mod control; mod decal_drop; @@ -18,28 +21,43 @@ pub mod docking; pub mod export_templates; #[cfg(not(target_arch = "wasm32"))] pub mod file_dialogs; +mod fill_source_slot; +mod fill_source_target; mod filter_slot; pub mod fonts; mod generator_panel; pub mod gpu; +mod gray_slider; mod grid_tile; pub mod i18n; pub mod id_color_pick; #[cfg(not(target_arch = "wasm32"))] mod import_resources; +mod inactive_set_hint; pub mod keymap; pub mod layer_panel; +mod layout_dialog; mod levels_editor; mod levels_handle; mod levels_properties; +mod line_snap; +mod list_action; mod mask_preview_image; mod material_preview_image; pub mod menus; +mod name_error; +mod named_layout; +pub mod named_layouts; +mod nav_button; +pub mod nav_buttons; +mod nav_view; pub mod new_project_advanced; mod orb_shape; pub mod parity; mod path_hit; mod path_surface_cache; +mod pattern_panel; +mod pattern_target; pub mod pbr_import; mod preview_image; mod preview_request; @@ -51,8 +69,13 @@ pub mod project_form; pub mod properties_popup; mod rail_popup; pub mod render_mode; +mod resource_panel; mod resource_picker; +mod resource_picker_anchor; +mod resource_picker_choice; mod resource_picker_item; +mod resource_picker_tab; +mod resource_picker_tile; mod running_bake; pub mod saved_search; mod screen_color_pick; @@ -64,11 +87,15 @@ pub mod shelf_preview; mod shelf_tabs; mod shelf_toolbar; pub mod shelf_view; +#[cfg(not(target_arch = "wasm32"))] +mod smart_mask_menu; mod soft_box; pub mod state; +mod surface_paint_point; pub mod symmetry; pub mod theme; pub mod thumbs; +mod tile_edits; pub mod titlebar; pub mod toolbar; pub mod ui_state_store; @@ -133,6 +160,8 @@ pub struct TextureCraftApp { pub session: Session, /// A smooth move to a saved camera in progress. camera_glide: Option, + /// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`). + orbit_snap: Option<(f32, f32)>, pub ui: UiState, /// Where `ui` is saved between runs ui_store: ui_state_store::UiStateStore, @@ -160,8 +189,8 @@ pub struct TextureCraftApp { pub ui_ms: f32, /// Frame timing and the scripted paint test (`debug.*` control methods). pub profiler: profile::Profiler, - /// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines. - pub last_paint_point: Option, + /// Where the last 3D stroke ended on the model, scoped to its mesh and texture set, for Shift+click straight lines. + pub last_paint_point: Option, /// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines pub last_paint_uv: Option, /// The decal layer the next click in the 3D view places. @@ -170,6 +199,8 @@ pub struct TextureCraftApp { pub properties_popup: Option, /// The color selection the next click in the 3D or 2D view picks an ID color for pub picking_id_color: Option, + /// Whether the next click on the model places the symmetry planes (Pick point in the symmetry settings) + pub picking_symmetry_plane: bool, /// The wgpu state (screenshots read the renderer's targets). pub render_state: Option, /// CJK fallback fonts for the UI language. @@ -202,9 +233,24 @@ pub struct TextureCraftApp { pub(crate) 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 +pub(crate) fn start_ui(saved: Option, session: &mut Session) -> UiState { + match saved { + Some(ui) => { + ui.tool_settings.apply(&mut session.tool); + ui + } + None => { + let mut ui = UiState::default(); + ui.prefs.language = i18n::os_language().into(); + ui + } + } +} + impl TextureCraftApp { /// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport. - pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { + pub fn new(cc: &eframe::CreationContext<'_>, mut session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); // Bakes cast their rays on a GPU device of their own (created on the first bake) @@ -214,16 +260,19 @@ impl TextureCraftApp { // The first run speaks the OS (or browser) language let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); - let ui = ui_store.load(cc.storage).unwrap_or_else(|| { - let mut ui = UiState::default(); - ui.prefs.language = i18n::os_language().into(); - ui - }); + let mut ui = start_ui(ui_store.load(cc.storage), &mut session); + + // No window opens by itself with no project (a saved layout may have left Export open) + if !session.project_open { + ui.windows.export = false; + } + let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; ui.prefs.apply_resource_limits(); let mut app = TextureCraftApp { camera_glide: None, + orbit_snap: None, session, ui, ui_store, @@ -248,6 +297,7 @@ impl TextureCraftApp { placing_decal: None, properties_popup: None, picking_id_color: None, + picking_symmetry_plane: false, render_state: cc.wgpu_render_state.clone(), fonts: fonts::UiFonts::default(), banner: None, @@ -298,22 +348,38 @@ impl TextureCraftApp { pub fn run(&mut self, id: &str, params: Value) -> Option { self.ui.prefs.apply_resource_limits(); - // Going to a saved camera glides there; the control channel and CLI jump straight away - let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); + // Going to a saved camera or a fixed view glides there; the control channel and CLI jump straight away + let glides = id.starts_with("camera.select") || id.starts_with("camera.bookmark") || id.starts_with("camera.view"); + let before = self.session.camera; + let glide_from = glides.then_some(before); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { Ok(value) => { if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") { self.thumbs.forget_saved_files(); } - // A pending dialog must not import its old source into the replacement project - if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") { + // Pending work and thumbnail snapshots belong to the old project + if matches!(id, "file.open" | "file.new" | "file.close" | "project.new" | "project.sample") { self.pbr_import = None; + self.resize = None; + self.layer_panel = Default::default(); } - if let Some(from) = glide_from.filter(|camera| *camera != self.session.camera) { - self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); - self.session.camera = from; + // The empty state has no baking or rendering to show + if id == "file.close" { + self.ui.mode = state::Mode::Painting; + self.ui.windows.export = false; + } + + match glide_from { + Some(from) if from != self.session.camera => { + self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time }); + self.session.camera = from; + } + + // Already at the destination: drop a glide an earlier command in the same frame started + Some(_) => self.camera_glide = None, + None => self.settle_camera_glide(id, before), } Some(value) @@ -325,6 +391,21 @@ impl TextureCraftApp { } } + /// After command `id` ran without starting a glide (the camera was `before`): a projection switch + /// carries over into a running glide, which would otherwise put back the projection it recorded; + /// any other command that moved the camera, or named where it should be, ends the glide, which + /// would put the camera back or carry it on to the glide's old destination. + pub(crate) fn settle_camera_glide(&mut self, id: &str, before: texturecraft_engine::geom::OrbitCamera) { + if matches!(id, "camera.perspective" | "camera.orthographic") { + if let Some(glide) = &mut self.camera_glide { + glide.from.ortho = self.session.camera.ortho; + glide.to.ortho = self.session.camera.ortho; + } + } else if self.session.camera != before || sets_camera(id) { + self.camera_glide = None; + } + } + fn report_ui_storage_warning(&mut self) { if let Some(warning) = self.ui_store.take_warning() { self.session.log.push(warning.clone()); @@ -522,6 +603,7 @@ impl TextureCraftApp { if self.resize.is_some() { return; } + match self.session.resize_task(ts, resolution) { Ok(task) => { let progress = Arc::new(Progress::new()); @@ -535,10 +617,18 @@ impl TextureCraftApp { /// Apply a finished resize (after any stroke in progress ends). fn poll_resize(&mut self, ctx: &egui::Context) { let Some(job) = &self.resize else { return }; + + // Nothing to resize without a project (a result that arrives after Close is dropped) + if !self.session.project_open { + self.resize = None; + return; + } + ctx.request_repaint_after(std::time::Duration::from_millis(30)); if self.session.stroke_active() { return; } + let result = match job.rx.try_recv() { Ok(r) => r, Err(std::sync::mpsc::TryRecvError::Empty) => return, @@ -610,14 +700,17 @@ impl TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] fn autosave(&mut self, now: f64) { let period = self.ui.prefs.autosave_minutes as f64 * 60.0; - // The clock starts at the first unsaved change. + + // The clock starts at the first unsaved change if period <= 0.0 || !self.session.modified { self.next_autosave = now + period; return; } + if now < self.next_autosave { return; } + self.next_autosave = now + period; let dir = user_dir("autosave"); let path = dir.join(format!( @@ -641,6 +734,13 @@ 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)) +} + /// A smooth move of the viewport camera (see [`TextureCraftApp::run`]). struct CameraGlide { from: texturecraft_engine::geom::OrbitCamera, @@ -664,7 +764,8 @@ impl TextureCraftApp { c.pitch = mix(a.pitch, b.pitch); c.distance = mix(a.distance, b.distance); c.fov = mix(a.fov, b.fov); - // Orthographic switches at the end (the projections cannot be blended). + + // Switch orthographic mode at the end because projections cannot blend c.ortho = if t >= 1.0 { b.ortho } else { a.ortho }; self.session.camera = c; self.session.revision = self.session.revision.wrapping_add(1); @@ -682,6 +783,7 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { + self.ui.tool_settings = texturecraft_engine::ToolSettings::of(&self.session.tool); self.ui_store.save(&self.ui, storage); self.report_ui_storage_warning(); export_templates::save_library(self, storage); @@ -768,7 +870,13 @@ impl eframe::App for TextureCraftApp { #[cfg_attr(target_arch = "wasm32", allow(unused_variables))] fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { let ctx = ui.ctx().clone(); - let t0 = now_ms(); + let started_ms = now_ms(); + + // Baking and rendering need a project (a saved layout may start in one of them) + if !self.session.project_open { + self.ui.mode = state::Mode::Painting; + } + if !self.ui.hide_ui { titlebar::show(self, ui); banner(self, ui); @@ -779,21 +887,28 @@ impl eframe::App for TextureCraftApp { toolbar::rail(self, ui); } } - let hide = self.ui.hide_ui; - let tk = theme::Tokens::get(&ctx); + + let hide_ui = self.ui.hide_ui; + let tokens = theme::Tokens::get(&ctx); + // The dock keeps the cards' gutter from the bars and rails around it - let panel_frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; - egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); + let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) }; + egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); + + // Finish after the dock and windows have requested their thumbnails + self.layer_panel.end(&ctx, &self.session); + #[cfg(not(target_arch = "wasm32"))] updates_ui::show(self, &ctx); toasts(self, &ctx); #[cfg(not(target_arch = "wasm32"))] self.file_dialogs.show_pending(frame); - let end = now_ms(); - let dt = (end - t0) as f32; - self.ui_ms = if self.ui_ms == 0.0 { dt } else { self.ui_ms * 0.9 + dt * 0.1 }; - self.profiler.end_frame(end, dt); + + let ended_ms = now_ms(); + let elapsed_ms = (ended_ms - started_ms) as f32; + self.ui_ms = if self.ui_ms == 0.0 { elapsed_ms } else { self.ui_ms * 0.9 + elapsed_ms * 0.1 }; + self.profiler.end_frame(ended_ms, elapsed_ms); } } diff --git a/crates/ui-egui/src/line_snap.rs b/crates/ui-egui/src/line_snap.rs new file mode 100644 index 00000000..1bfc5105 --- /dev/null +++ b/crates/ui-egui/src/line_snap.rs @@ -0,0 +1,95 @@ +//! Ctrl+Shift+click straight lines: the end point turns about the start to the nearest angle step + +use egui::{Pos2, Vec2}; + +/// The angle step of a snapped line, in degrees +pub const LINE_SNAP_STEP_DEGREES: f32 = 15.0; + +/// `end` turned about `start` to the nearest multiple of `step_degrees` (measured in the plane's +/// own axes); the distance from `start` stays what it was. A zero step or a zero-length line is +/// returned unchanged. +pub fn snap_line_end(start: Pos2, end: Pos2, step_degrees: f32) -> Pos2 { + let offset = end - start; + let length = offset.length(); + if step_degrees <= 0.0 || length == 0.0 { + return end; + } + + let step = step_degrees.to_radians(); + let angle = (offset.y.atan2(offset.x) / step).round() * step; + start + Vec2::new(angle.cos(), angle.sin()) * length +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::pos2; + + const START: Pos2 = pos2(100.0, 50.0); + + /// The angle of `end` from `START` in degrees + fn angle(end: Pos2) -> f32 { + (end - START).angle().to_degrees() + } + + fn assert_close(actual: Pos2, expected: Pos2) { + assert!((actual - expected).length() < 1e-3, "{actual:?} vs {expected:?}"); + } + + #[test] + fn a_line_near_0_degrees_becomes_horizontal() { + let end = snap_line_end(START, pos2(200.0, 55.0), 15.0); + assert_close(end, pos2(100.0 + (100.0f32 * 100.0 + 25.0).sqrt(), 50.0)); + } + + #[test] + fn a_line_near_15_degrees_turns_to_15_degrees() { + let end = snap_line_end(START, START + Vec2::angled(18.0f32.to_radians()) * 80.0, 15.0); + assert!((angle(end) - 15.0).abs() < 1e-3, "{}", angle(end)); + } + + #[test] + fn a_line_near_45_degrees_turns_to_45_degrees() { + let end = snap_line_end(START, START + Vec2::angled(40.0f32.to_radians()) * 60.0, 15.0); + assert!((angle(end) - 45.0).abs() < 1e-3, "{}", angle(end)); + assert_close(end, START + Vec2::angled(45.0f32.to_radians()) * 60.0); + } + + #[test] + fn a_line_near_90_degrees_becomes_vertical() { + let end = snap_line_end(START, pos2(104.0, 150.0), 15.0); + assert!((end.x - START.x).abs() < 1e-3, "{end:?}"); + assert!(end.y > START.y); + } + + #[test] + fn negative_angles_snap_to_negative_multiples() { + let end = snap_line_end(START, START + Vec2::angled((-37.0f32).to_radians()) * 70.0, 15.0); + assert!((angle(end) + 30.0).abs() < 1e-3, "{}", angle(end)); + let backwards = snap_line_end(START, START + Vec2::angled((-172.0f32).to_radians()) * 70.0, 15.0); + assert!((angle(backwards).abs() - 165.0).abs() < 1e-3, "{}", angle(backwards)); + } + + #[test] + fn the_distance_from_the_start_is_kept() { + for degrees in [-170.0f32, -100.0, -33.0, -7.0, 3.0, 22.0, 58.0, 91.0, 133.0, 179.0] { + let end = START + Vec2::angled(degrees.to_radians()) * 123.0; + let snapped = snap_line_end(START, end, 15.0); + assert!(((snapped - START).length() - 123.0).abs() < 1e-3, "{degrees}"); + let multiple = angle(snapped) / 15.0; + assert!((multiple - multiple.round()).abs() < 1e-3, "{degrees}: {}", angle(snapped)); + } + } + + #[test] + fn a_line_already_on_a_step_stays() { + let end = START + Vec2::angled(60.0f32.to_radians()) * 40.0; + assert_close(snap_line_end(START, end, 15.0), end); + } + + #[test] + fn a_zero_length_line_or_zero_step_is_unchanged() { + assert_eq!(snap_line_end(START, START, 15.0), START); + assert_eq!(snap_line_end(START, pos2(130.0, 77.0), 0.0), pos2(130.0, 77.0)); + } +} diff --git a/crates/ui-egui/src/list_action.rs b/crates/ui-egui/src/list_action.rs new file mode 100644 index 00000000..32510bd2 --- /dev/null +++ b/crates/ui-egui/src/list_action.rs @@ -0,0 +1,16 @@ +use texturecraft_engine::formats::ExportPreset; + +/// A template list action +#[derive(Clone, Debug, PartialEq)] +pub enum ListAction { + Select(String), + New, + Duplicate, + StartRename(String), + Rename(String), + Remove, + Import, + /// A template read from a file, added and selected + Imported(ExportPreset), + Export, +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index eeed4f4b..65024d08 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -38,12 +38,14 @@ pub const TOP: [&str; 6] = ["File", "Edit", "Mode", "Window", "Viewport", "Help" pub const CATALOG: &[Item] = &[ it("File", "New project...", "ui.newProject", Some("Ctrl+N")), it("File", "Open...", "file.open", Some("Ctrl+O")), + sep("File"), it("File", "Open sample project...", "project.sample", None), + sep("File"), it("File", "Close", "file.close", Some("Ctrl+F4")), sep("File"), it("File", "Save", "file.save", Some("Ctrl+S")), it("File", "Save as...", "file.saveAs", Some("Ctrl+Shift+S")), - it("File", "Save a copy...", "file.saveCopy", None), + sub("File", "More save options", "Save a copy...", "file.saveCopy", None), it("File", "Remove unused resources...", "file.removeUnused", None), sep("File"), it("File", "Import resources...", "resource.import", None), @@ -57,7 +59,6 @@ pub const CATALOG: &[Item] = &[ it("File", "Quit", "ui.quit", Some("Ctrl+Q")), it("Edit", "Undo", "edit.undo", Some("Ctrl+Z")), it("Edit", "Redo", "edit.redo", Some("Ctrl+Y")), - sep("Edit"), it("Edit", "Project Configuration...", "ui.projectConfig", None), it("Edit", "Reimport mesh", "file.reimportMesh", Some("Ctrl+Shift+R")), it("Edit", "Settings...", "ui.settings", None), @@ -76,9 +77,14 @@ pub const CATALOG: &[Item] = &[ sub("Window", "Views", "Shader Settings", "ui.view.shader", None), sub("Window", "Views", "Texture Sets", "ui.view.textureSetList", None), sub("Window", "Views", "Texture Set Settings", "ui.view.textureSetSettings", None), + sep("Window"), sub("Window", "Save UI Layout", "Save current layout...", "ui.layout.save", None), it("Window", "Load UI Layout", "ui.layout.load", None), + sub("Window", "Layouts", "Save current layout as...", "ui.layout.saveAs", None), + sub("Window", "Layouts", "Manage layouts...", "ui.layout.manage", None), + sep("Window"), it("Window", "Hide UI", "ui.hideUi", Some("Tab")), + it("Window", "Reset panel layout", "ui.resetPanelLayout", None), it("Window", "Reset UI", "ui.resetUi", None), it("Viewport", "Display material", "viewport.displayMaterial", Some("M")), it("Viewport", "Display next channel", "viewport.nextChannel", Some("C")), @@ -87,22 +93,35 @@ pub const CATALOG: &[Item] = &[ it("Viewport", "Display previous mesh map", "viewport.previousMeshMap", Some("Shift+B")), it("Viewport", "UV checker", "ui.uvChecker", None), sep("Viewport"), + it("Viewport", "Frame texture set", "viewport.frameSelection", Some("Shift+F")), it("Viewport", "Show entire mesh", "viewport.frame", Some("F")), + it("Viewport", "Front view", "camera.view.front", None), + it("Viewport", "Back view", "camera.view.back", None), + it("Viewport", "Left view", "camera.view.left", None), + it("Viewport", "Right view", "camera.view.right", None), + it("Viewport", "Top view", "camera.view.top", None), + it("Viewport", "Bottom view", "camera.view.bottom", None), + sep("Viewport"), + it("Viewport", "Perspective", "camera.perspective", Some("F5")), + it("Viewport", "Orthographic", "camera.orthographic", Some("F6")), sep("Viewport"), it("Viewport", "3D/2D views", "ui.layout.split", Some("F1")), it("Viewport", "3D view only", "ui.layout.3d", Some("F2")), it("Viewport", "2D view only", "ui.layout.2d", Some("F3")), 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", "Documentation...", "ui.help.docs", None), it("Help", "Shortcuts list...", "ui.help.shortcuts", None), + sep("Help"), it("Help", "Join the community (Discord)...", "ui.help.discord", None), it("Help", "ArtCraft website...", "ui.help.website", None), it("Help", "Report a bug...", "ui.help.bug", None), - sep("Help"), it("Help", "Show log...", "ui.view.log", None), + sep("Help"), #[cfg(not(target_arch = "wasm32"))] it("Help", "Check for Updates...", "ui.help.checkForUpdates", None), it("Help", "About TextureCraft...", "ui.about", None), @@ -113,6 +132,11 @@ fn is_ui(id: &str) -> bool { id.starts_with("ui.") } +/// Shell items that act on the open project: greyed while none is open +fn ui_needs_project(id: &str) -> bool { + matches!(id, "ui.export" | "ui.projectConfig" | "ui.uvChecker" | "ui.mode.bake" | "ui.mode.paint" | "ui.mode.render") +} + /// Whether an item can run now pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { if let Some(panel) = crate::docking::view_panel(id) { @@ -123,8 +147,12 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { return false; } + if id == "ui.layout.manage" { + return !app.ui.named_layouts.is_empty(); + } + if is_ui(id) { - return true; + return app.session.project_open || !ui_needs_project(id); } // Scripts may pick any tool, but the shelf and its shortcuts offer only those that can act @@ -133,7 +161,7 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool { return false; } - texturecraft_engine::find(id).is_some_and(|command| (command.enabled)(&app.session).is_ok()) + texturecraft_engine::find(id).is_some_and(|command| texturecraft_engine::check_enabled(command, &app.session).is_ok()) } /// Whether an id is implemented at all (parity report). @@ -147,9 +175,7 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { return; } - if matches!(id, "ui.newProject" | "file.open" | "file.close" | "project.sample") - && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) - { + if matches!(id, "file.open" | "file.close" | "project.sample") && crate::windows::ask_to_save(app, crate::state::Unsaved::Command(id.into())) { return; } @@ -177,9 +203,13 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { "ui.mode.paint" => app.ui.mode = Mode::Painting, "ui.mode.render" => app.ui.mode = Mode::Rendering, "ui.hideUi" => app.ui.hide_ui = !app.ui.hide_ui, - "ui.resetUi" => app.ui.adopt_layout(crate::UiState::default()), + "ui.navButtons" => app.ui.nav_buttons = !app.ui.nav_buttons, + "ui.resetPanelLayout" => app.ui.reset_panel_layout(), + "ui.resetUi" => app.ui.windows.confirm_reset_ui = true, "ui.layout.save" => crate::windows::layout_file(app, true), "ui.layout.load" => crate::windows::layout_file(app, false), + "ui.layout.saveAs" => app.ui.layout_dialog = Some(crate::named_layouts::LayoutDialog::Save(String::new())), + "ui.layout.manage" => app.ui.layout_dialog = Some(crate::named_layouts::LayoutDialog::Manage { renaming: None, deleting: None }), "ui.uvChecker" => { app.run("viewport.view", json!({"mode": "uvChecker"})); } @@ -219,18 +249,24 @@ pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { if current_sub == Some(s) { continue; } + current_sub = Some(s); ui.menu_button(tr(s), |ui| { for x in items.iter().filter(|x| x.sub == Some(s)) { menu_item(app, &ctx, ui, x); } + if s == "Layouts" { + crate::named_layouts::entries(app, ui); + } }); continue; } + if item.label == "-" { ui.separator(); continue; } + menu_item(app, &ctx, ui, item); } }); @@ -256,6 +292,9 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, "ui.mode.paint" => Some(app.ui.mode == Mode::Painting), "ui.mode.bake" => Some(app.ui.mode == Mode::Baking), "ui.mode.render" => Some(app.ui.mode == Mode::Rendering), + "ui.navButtons" => Some(app.ui.nav_buttons), + "camera.perspective" => Some(!app.session.camera.ortho), + "camera.orthographic" => Some(app.session.camera.ortho), id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)), }; if let Some(c) = checked { @@ -360,11 +399,18 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke let popup_open = egui::Popup::is_any_open(ctx); + let no_widget_focused = ctx.memory(|memory| memory.focused().is_none()); #[cfg(not(target_arch = "wasm32"))] let nothing_focused = ctx.memory(|memory| memory.focused().is_none()); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect(); + + // Escape and Enter answer the Reset UI question first, even when a shortcut binds them + let confirming_reset = app.ui.windows.confirm_reset_ui; + if confirming_reset && !popup_open { + crate::windows::reset_ui_keys(app, input, no_widget_focused); + } let commands = app.bindings.dispatch(input); for copy in copies { if !input.events.contains(©) { @@ -381,7 +427,12 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - if app.ui.windows.project_config.is_some() { + if confirming_reset { + // Its keys were handled before the shortcuts ran + } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + // The Output templates question: Escape answers it with the safe choice + app.ui.export.ask = None; + } else if app.ui.windows.project_config.is_some() { // Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched #[cfg(not(target_arch = "wasm32"))] crate::project_config::keys_in(app, input, nothing_focused, popup_open); @@ -394,6 +445,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.rail_panel = None; } else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); + } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + app.picking_symmetry_plane = false; } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); diff --git a/crates/ui-egui/src/name_error.rs b/crates/ui-egui/src/name_error.rs new file mode 100644 index 00000000..1d375431 --- /dev/null +++ b/crates/ui-egui/src/name_error.rs @@ -0,0 +1,6 @@ +/// Why a name cannot be used +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NameError { + Empty, + Taken, +} diff --git a/crates/ui-egui/src/named_layout.rs b/crates/ui-egui/src/named_layout.rs new file mode 100644 index 00000000..288cc46f --- /dev/null +++ b/crates/ui-egui/src/named_layout.rs @@ -0,0 +1,12 @@ +use serde::{Deserialize, Serialize}; + +use crate::docking::Dock; + +/// One saved panel arrangement +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct NamedLayout { + pub name: String, + /// The painting mode's dock, which the other modes' docks start from + pub painting: Dock, + pub baking: Dock, +} diff --git a/crates/ui-egui/src/named_layouts.rs b/crates/ui-egui/src/named_layouts.rs new file mode 100644 index 00000000..9b9cb820 --- /dev/null +++ b/crates/ui-egui/src/named_layouts.rs @@ -0,0 +1,378 @@ +//! Window > Layouts: panel arrangements saved under a name and switched from the menu. +//! +//! A named layout holds the painting and the baking dock (which panels are shown, where, and +//! how big). Switching to one touches nothing else: not the mode, the zoom, the wireframes, the +//! windows or the shelf. The layouts persist with `UiState`, so they work in the browser too. + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +pub use crate::layout_dialog::LayoutDialog; +pub use crate::name_error::NameError; +pub use crate::named_layout::NamedLayout; +use crate::state::UiState; +use crate::theme::caption; +use crate::windows::dialog; + +impl UiState { + fn named_layout_index(&self, name: &str) -> Option { + self.named_layouts.iter().position(|layout| layout.name == name) + } + + /// Whether a layout of this name (surrounding spaces ignored) is saved + pub fn has_named_layout(&self, name: &str) -> bool { + self.named_layout_index(name.trim()).is_some() + } + + /// Save the current panel arrangement under `name`, replacing a layout of that name; false for an empty name + pub fn save_named_layout(&mut self, name: &str) -> bool { + let name = name.trim(); + if name.is_empty() { + return false; + } + + let (painting, baking) = if self.dock_is_baking { (&self.inactive_mode_dock, &self.dock) } else { (&self.dock, &self.inactive_mode_dock) }; + let layout = NamedLayout { name: name.to_string(), painting: painting.clone(), baking: baking.clone() }; + match self.named_layout_index(name) { + Some(index) => self.named_layouts[index] = layout, + None => self.named_layouts.push(layout), + } + true + } + + /// Switch to the saved layout's panels; the mode and every other setting stay. False when there is none of that name. + pub fn apply_named_layout(&mut self, name: &str) -> bool { + let Some(layout) = self.named_layout_index(name).map(|index| self.named_layouts[index].clone()) else { return false }; + + let (current, other) = if self.dock_is_baking { (layout.baking, layout.painting) } else { (layout.painting, layout.baking) }; + self.dock = current; + self.inactive_mode_dock = other; + + // A popup open against the rail shows a panel of the old arrangement + self.rail_panel = None; + true + } + + /// Give a saved layout another name + pub fn rename_named_layout(&mut self, from: &str, to: &str) -> Result<(), NameError> { + let to = to.trim(); + if to.is_empty() { + return Err(NameError::Empty); + } + + if to != from && self.named_layout_index(to).is_some() { + return Err(NameError::Taken); + } + + if let Some(index) = self.named_layout_index(from) { + self.named_layouts[index].name = to.to_string(); + } + Ok(()) + } + + pub fn delete_named_layout(&mut self, name: &str) { + self.named_layouts.retain(|layout| layout.name != name); + } +} + +/// One entry per saved layout, under the catalog's items of the Layouts submenu +pub(crate) fn entries(app: &mut TextureCraftApp, ui: &mut egui::Ui) { + if app.ui.named_layouts.is_empty() { + return; + } + + ui.separator(); + for name in app.ui.named_layouts.iter().map(|layout| layout.name.clone()).collect::>() { + if ui.button(&name).clicked() { + app.ui.apply_named_layout(&name); + ui.close(); + } + } +} + +/// The save, overwrite and manage dialogs +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + forget_finished_focus(app, ctx); + let Some(shown) = app.ui.layout_dialog.clone() else { return }; + + let mut open = true; + let next = match shown { + LayoutDialog::Save(name) => save_dialog(app, ctx, &mut open, name), + LayoutDialog::Overwrite(name) => overwrite_dialog(app, ctx, &mut open, name), + LayoutDialog::Manage { renaming, deleting } => manage_dialog(app, ctx, &mut open, renaming, deleting), + }; + app.ui.layout_dialog = if open { next } else { None }; + forget_finished_focus(app, ctx); +} + +/// The next Save or rename focuses its field again. Also runs while no dialog is shown, since +/// loading or resetting the layout closes a dialog from outside. +fn forget_finished_focus(app: &TextureCraftApp, ctx: &egui::Context) { + ctx.data_mut(|data| { + if !matches!(app.ui.layout_dialog, Some(LayoutDialog::Save(_))) { + data.remove_temp::(egui::Id::unique(SAVE_FOCUS)); + } + if !matches!(app.ui.layout_dialog, Some(LayoutDialog::Manage { renaming: Some(_), .. })) { + data.remove_temp::(egui::Id::unique(RENAME_FOCUS)); + } + }); +} + +/// How much of the window height the list of saved layouts may take +const LIST_SCREEN_FRACTION: f32 = 0.5; + +/// Memory keys of the text fields that were already focused for the current edit +const SAVE_FOCUS: &str = "named_layout_save_focused"; +const RENAME_FOCUS: &str = "named_layout_rename_focused"; + +/// Give `edit` the keyboard once per edit (`what` names it), when it starts. Asking every frame +/// would take the focus back from the buttons after Tab. +fn focus_once(ui: &egui::Ui, edit: &egui::Response, key: &'static str, what: String) { + let id = egui::Id::unique(key); + if ui.data(|data| data.get_temp::(id)).as_deref() != Some(what.as_str()) { + edit.request_focus(); + ui.data_mut(|data| data.insert_temp(id, what)); + } +} + +fn save_dialog(app: &mut TextureCraftApp, ctx: &egui::Context, open: &mut bool, mut name: String) -> Option { + let mut done = None; + dialog("save_layout", tr("Save layout"), open).show(ctx, |ui| { + ui.label(tr("Name of the layout")); + let edit = ui.add(egui::TextEdit::singleline(&mut name).desired_width(240.0)); + focus_once(ui, &edit, SAVE_FOCUS, String::new()); + let enter = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + ui.add_space(8.0); + ui.horizontal(|ui| { + let valid = !name.trim().is_empty(); + if ui.add_enabled(valid, egui::Button::new(tr("Save"))).clicked() || (enter && valid) { + done = Some(true); + } + if ui.button(tr("Cancel")).clicked() { + done = Some(false); + } + }); + }); + + match done { + Some(true) if app.ui.has_named_layout(&name) => Some(LayoutDialog::Overwrite(name.trim().to_string())), + Some(true) => { + app.ui.save_named_layout(&name); + app.toast(trf("Saved layout {name}", &[("name", &name.trim())]), false); + None + } + Some(false) => None, + None => Some(LayoutDialog::Save(name)), + } +} + +fn overwrite_dialog(app: &mut TextureCraftApp, ctx: &egui::Context, open: &mut bool, name: String) -> Option { + let mut answer = None; + dialog("overwrite_layout", tr("Replace layout"), open).show(ctx, |ui| { + ui.label(trf("A layout named {name} already exists. Replace it?", &[("name", &name)])); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("Replace")).clicked() { + answer = Some(true); + } + if ui.button(tr("Cancel")).clicked() { + answer = Some(false); + } + }); + }); + + match answer { + Some(true) => { + app.ui.save_named_layout(&name); + app.toast(trf("Saved layout {name}", &[("name", &name)]), false); + None + } + Some(false) => None, + None => Some(LayoutDialog::Overwrite(name)), + } +} + +fn manage_dialog( + app: &mut TextureCraftApp, + ctx: &egui::Context, + open: &mut bool, + mut renaming: Option<(String, String)>, + mut deleting: Option, +) -> Option { + let mut finished = false; + dialog("manage_layouts", tr("Manage layouts"), open).show(ctx, |ui| { + ui.set_min_width(320.0); + if let Some(name) = deleting.clone() { + ui.label(trf("Delete the layout {name}?", &[("name", &name)])); + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button(tr("Delete")).clicked() { + app.ui.delete_named_layout(&name); + deleting = None; + } + if ui.button(tr("Cancel")).clicked() { + deleting = None; + } + }); + return; + } + + if app.ui.named_layouts.is_empty() { + ui.label(caption(tr("No saved layouts"))); + } + + // Many layouts scroll; Close stays below the list + let list_height = ui.ctx().content_rect().height() * LIST_SCREEN_FRACTION; + egui::ScrollArea::vertical().max_height(list_height).auto_shrink([false, true]).show(ui, |ui| { + for name in app.ui.named_layouts.iter().map(|layout| layout.name.clone()).collect::>() { + ui.horizontal(|ui| match renaming.clone().filter(|(from, _)| *from == name) { + Some((from, mut to)) => { + let edit = ui.add(egui::TextEdit::singleline(&mut to).desired_width(180.0)); + focus_once(ui, &edit, RENAME_FOCUS, from.clone()); + let taken = app.ui.named_layouts.iter().any(|layout| layout.name == to.trim() && layout.name != from); + let valid = !to.trim().is_empty() && !taken; + let enter = edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + let mut keep = true; + if ui.add_enabled(valid, egui::Button::new(tr("Rename"))).clicked() || (enter && valid) { + let _ = app.ui.rename_named_layout(&from, &to); + keep = false; + } + if ui.button(tr("Cancel")).clicked() { + keep = false; + } + if taken { + ui.label(caption(tr("That name is taken"))); + } + renaming = keep.then_some((from, to)); + } + None => { + ui.label(&name); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Delete")).clicked() { + deleting = Some(name.clone()); + } + if ui.button(tr("Rename")).clicked() { + renaming = Some((name.clone(), name.clone())); + } + }); + } + }); + } + }); + ui.add_space(8.0); + if ui.button(tr("Close")).clicked() { + finished = true; + } + }); + + (!finished).then_some(LayoutDialog::Manage { renaming, deleting }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::docking::Panel; + use crate::state::{Mode, ViewLayout}; + + fn closed(panel: Panel) -> UiState { + let mut ui = UiState::default(); + ui.dock.close(panel); + ui + } + + #[test] + fn switching_restores_the_panels_and_keeps_zoom_mode_and_wireframes() { + let mut ui = closed(Panel::Assets); + assert!(ui.save_named_layout("Sparse")); + + ui.dock.focus(Panel::Assets); + ui.dock.close(Panel::Layers); + ui.uv_zoom = 3.0; + ui.uv_pan = [0.25, 0.5]; + ui.uv_wireframe = false; + ui.wireframe_3d = true; + ui.layout = ViewLayout::Only3D; + ui.split_ratio = 0.2; + ui.shelf_filter = "rust".into(); + let before = ui.clone(); + + assert!(ui.apply_named_layout("Sparse")); + + assert!(!ui.dock.is_open(Panel::Assets) && ui.dock.is_open(Panel::Layers)); + let expected = UiState { dock: ui.dock.clone(), inactive_mode_dock: ui.inactive_mode_dock.clone(), ..before }; + assert_eq!(ui, expected, "only the docks changed"); + } + + #[test] + fn both_mode_docks_are_saved_and_the_current_mode_stays() { + let mut ui = UiState::default(); + ui.dock.close(Panel::Assets); + ui.save_named_layout("Both"); + + // Saved while painting, applied while baking: each dock lands in its own slot + let mut baking = UiState { mode: Mode::Baking, dock_is_baking: true, ..UiState::default() }; + baking.inactive_mode_dock = UiState::default().dock; + baking.named_layouts = ui.named_layouts.clone(); + baking.apply_named_layout("Both"); + + assert_eq!(baking.mode, Mode::Baking); + assert!(baking.dock_is_baking); + assert!(baking.dock.is_open(Panel::MeshMapBakers) && !baking.dock.is_open(Panel::Layers), "the baking dock is the saved baking dock"); + assert!( + baking.inactive_mode_dock.is_open(Panel::Layers) && !baking.inactive_mode_dock.is_open(Panel::Assets), + "the painting dock is the saved painting dock" + ); + } + + #[test] + fn saving_under_a_taken_name_replaces_it_and_an_empty_name_saves_nothing() { + let mut ui = UiState::default(); + assert!(!ui.save_named_layout(" ")); + ui.save_named_layout(" Mine "); + ui.dock.close(Panel::Assets); + ui.save_named_layout("Mine"); + + assert_eq!(ui.named_layouts.len(), 1); + assert_eq!(ui.named_layouts[0].name, "Mine"); + assert!(!ui.named_layouts[0].painting.is_open(Panel::Assets)); + assert!(ui.has_named_layout("Mine ") && !ui.apply_named_layout("Other")); + } + + #[test] + fn rename_and_delete() { + let mut ui = UiState::default(); + ui.save_named_layout("A"); + ui.save_named_layout("B"); + + assert_eq!(ui.rename_named_layout("A", "B"), Err(NameError::Taken)); + assert_eq!(ui.rename_named_layout("A", " "), Err(NameError::Empty)); + assert_eq!(ui.rename_named_layout("A", "A"), Ok(())); + assert_eq!(ui.rename_named_layout("A", " C "), Ok(())); + let names: Vec<_> = ui.named_layouts.iter().map(|layout| layout.name.as_str()).collect(); + assert_eq!(names, ["C", "B"], "a renamed layout keeps its place"); + + ui.delete_named_layout("C"); + assert_eq!(ui.named_layouts.len(), 1); + assert!(!ui.apply_named_layout("C")); + } + + #[test] + fn named_layouts_persist_and_older_saved_state_loads_without_them() { + let mut ui = closed(Panel::Assets); + ui.save_named_layout("Sparse"); + let back: UiState = serde_json::from_str(&serde_json::to_string(&ui).unwrap()).unwrap(); + assert_eq!(back.named_layouts, ui.named_layouts); + + let mut old = serde_json::to_value(UiState::default()).unwrap(); + assert!(old.as_object_mut().unwrap().remove("named_layouts").is_some()); + let loaded: UiState = serde_json::from_value(old).unwrap(); + assert!(loaded.named_layouts.is_empty()); + } + + #[test] + fn reset_and_loading_a_layout_file_keep_the_named_layouts() { + let mut ui = UiState::default(); + ui.save_named_layout("Mine"); + ui.adopt_layout(UiState::default()); + assert!(ui.has_named_layout("Mine")); + } +} diff --git a/crates/ui-egui/src/nav_button.rs b/crates/ui-egui/src/nav_button.rs new file mode 100644 index 00000000..214f5d7e --- /dev/null +++ b/crates/ui-egui/src/nav_button.rs @@ -0,0 +1,30 @@ +use egui_phosphor::regular as icon; + +use crate::i18n::n_; +use crate::nav_view::NavView; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum NavButton { + Orbit, + Pan, + Zoom, +} + +impl NavButton { + pub(crate) fn icon(self) -> &'static str { + match self { + NavButton::Orbit => icon::ARROWS_CLOCKWISE, + NavButton::Pan => icon::HAND_GRABBING, + NavButton::Zoom => icon::MAGNIFYING_GLASS, + } + } + + pub(crate) fn tooltip(self, view: NavView) -> &'static str { + match (self, view) { + (NavButton::Orbit, _) => n_("Orbit: press and drag to turn the view around the model"), + (NavButton::Pan, _) => n_("Pan: press and drag to move the view"), + (NavButton::Zoom, NavView::Scene) => n_("Zoom: press and drag up to move closer, down to move away"), + (NavButton::Zoom, NavView::Uv) => n_("Zoom: press and drag up to zoom in, down to zoom out"), + } + } +} diff --git a/crates/ui-egui/src/nav_buttons.rs b/crates/ui-egui/src/nav_buttons.rs new file mode 100644 index 00000000..7940dbf9 --- /dev/null +++ b/crates/ui-egui/src/nav_buttons.rs @@ -0,0 +1,110 @@ +//! Orbit, pan and zoom buttons in the corner of the 3D and 2D views. Pressing one with the primary button (mouse or pen tip) and +//! dragging moves the view like the mouse shortcuts do, without painting, so a pen and tablet can navigate without a keyboard or wheel. + +use crate::TextureCraftApp; +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 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 +const BUTTON_SIZE: f32 = 30.0; +const BUTTON_GAP: f32 = 4.0; +const EDGE_MARGIN: f32 = 8.0; + +/// Distance from the view's top edge to the first button: below the row of pickers that sits at the top centre, so the two never overlap +const TOP_OFFSET: f32 = 40.0; + +/// Room kept below the column for the 2D view's texture set name and the view's own corner +const BOTTOM_ROOM: f32 = 40.0; + +/// Narrowest a view may be and still show the column +const MIN_VIEW_WIDTH: f32 = BUTTON_SIZE + 2.0 * EDGE_MARGIN + 20.0; + +/// The 2D zoom a drag changes per point, as a multiple of the wheel's (the 3D drag zoom is also a few times its wheel's) +const UV_DRAG_ZOOM_PER_WHEEL: f32 = 4.0; + +/// The column of buttons in the top right corner of a view of `rect`; `None` when the view is too small to hold it without covering other things +fn strip_rect(rect: Rect, view: NavView) -> Option { + let count = view.buttons().len() as f32; + let size = vec2(BUTTON_SIZE, count * BUTTON_SIZE + (count - 1.0) * BUTTON_GAP); + let fits = rect.width() >= MIN_VIEW_WIDTH && rect.height() >= TOP_OFFSET + size.y + BOTTOM_ROOM; + fits.then(|| Rect::from_min_size(pos2(rect.right() - EDGE_MARGIN - BUTTON_SIZE, rect.top() + TOP_OFFSET), size)) +} + +/// Where `button` sits in a view of `rect`; `None` when the view has no such button or is too small +pub fn button_rect(rect: Rect, view: NavView, button: NavButton) -> Option { + let index = view.buttons().iter().position(|candidate| *candidate == button)?; + let strip = strip_rect(rect, view)?; + Some(Rect::from_min_size(strip.min + vec2(0.0, index as f32 * (BUTTON_SIZE + BUTTON_GAP)), vec2(BUTTON_SIZE, BUTTON_SIZE))) +} + +/// Whether `point` is over the shown buttons of a view of `rect` +pub(crate) fn covers(app: &TextureCraftApp, rect: Rect, view: NavView, point: egui::Pos2) -> bool { + app.ui.nav_buttons && strip_rect(rect, view).is_some_and(|strip| strip.expand(BUTTON_GAP).contains(point)) +} + +/// Draws the buttons over the view `rect` and applies a drag on one to the view's camera +pub(crate) fn show(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, view: NavView) { + if !app.ui.nav_buttons { + return; + } + + let Some(strip) = strip_rect(rect, view) else { return }; + let tokens = Tokens::get(ui.ctx()); + let area_id = ui.scope_id().with(("nav_buttons", view)); + + // Their own layer above the view, so a press on a button never reaches the view's own painting or camera handling + Area::new(area_id).order(Order::Middle).fixed_pos(strip.min).constrain_to(rect).show(ui.ctx(), |ui| { + // The whole column and a gap-wide border own a press, so one landing between buttons never reaches the view + ui.allocate_rect(strip.expand(BUTTON_GAP), Sense::click_and_drag()); + for &button in view.buttons() { + let Some(button_rect) = button_rect(rect, view, button) else { continue }; + let response = ui.interact(button_rect, area_id.with(button), Sense::click_and_drag()); + let response = response.on_hover_text(tr(button.tooltip(view))).on_hover_cursor(CursorIcon::Grab); + let pressed = response.dragged_by(PointerButton::Primary); + if pressed { + ui.ctx().set_cursor_icon(CursorIcon::Grabbing); + apply(app, rect, view, button, response.drag_delta()); + } + + let fill = if pressed { + tokens.tool_active + } else if response.hovered() { + tokens.row_hover + } else { + tokens.panel.gamma_multiply(0.85) + }; + let color = if pressed { tokens.accent } else { tokens.text }; + ui.painter().rect_filled(button_rect, 4.0, fill); + ui.painter().text(button_rect.center(), egui::Align2::CENTER_CENTER, button.icon(), egui::FontId::proportional(BUTTON_SIZE * 0.55), color); + } + }); +} + +/// Moves the view by a drag of `delta` points on `button`, at the speeds and in the directions of the mouse shortcuts +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::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::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; + } + (NavView::Uv, NavButton::Zoom) => { + // About the view's centre: the wheel zooms about the cursor, which is on the button here + let old_zoom = app.ui.uv_zoom; + let scroll = -delta.y * UV_DRAG_ZOOM_PER_WHEEL; + let new_zoom = (old_zoom * (1.0 + scroll * UV_WHEEL_ZOOM_PER_POINT)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); + for axis in 0..2 { + app.ui.uv_pan[axis] *= new_zoom / old_zoom; + } + app.ui.uv_zoom = new_zoom; + } + (NavView::Uv, NavButton::Orbit) => {} + } +} diff --git a/crates/ui-egui/src/nav_view.rs b/crates/ui-egui/src/nav_view.rs new file mode 100644 index 00000000..d056d2a8 --- /dev/null +++ b/crates/ui-egui/src/nav_view.rs @@ -0,0 +1,20 @@ +use crate::nav_button::NavButton; + +/// Which view a column of buttons belongs to +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum NavView { + /// The 3D view: orbit, pan and zoom + Scene, + /// The 2D view: pan and zoom + Uv, +} + +impl NavView { + /// The buttons of the view, top to bottom + pub fn buttons(self) -> &'static [NavButton] { + match self { + NavView::Scene => &[NavButton::Orbit, NavButton::Pan, NavButton::Zoom], + NavView::Uv => &[NavButton::Pan, NavButton::Zoom], + } + } +} diff --git a/crates/ui-egui/src/new_project_advanced.rs b/crates/ui-egui/src/new_project_advanced.rs index 7df3d7d5..8784919e 100644 --- a/crates/ui-egui/src/new_project_advanced.rs +++ b/crates/ui-egui/src/new_project_advanced.rs @@ -3,6 +3,7 @@ //! management), and Cancel / Create fixed below the scrolling form. use std::collections::BTreeSet; +use std::sync::atomic::{AtomicU64, Ordering}; use egui::{RichText, Ui, vec2}; use serde_json::{Value, json}; @@ -11,8 +12,8 @@ use texturecraft_engine::core::NormalFormat; use crate::TextureCraftApp; use crate::i18n::{tr, trf}; use crate::project_form::{ - FIELD_WIDTH, ROW_INDENT, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, - uv_tile_radios, uv_tile_title, + FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, collapsible, color_management, note, physical_size, row, sub_title, tangent_space_row, + unavailable, uv_tile_radios, }; use crate::state::{Mode, NewProject}; use crate::theme::{Tokens, caption}; @@ -26,30 +27,40 @@ const NORMAL_FORMATS: [(NormalFormat, &str, &str); 2] = [(NormalFormat::OpenGl, const RESOLUTIONS: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; /// Width of the dialog's form -const DIALOG_WIDTH: f32 = 560.0; +const DIALOG_WIDTH_POINTS: f32 = 560.0; /// Leave space around the centered dialog on short viewports -const DIALOG_VIEWPORT_MARGIN: f32 = 32.0; +const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; /// Room for the title bar and the button row below the scrolling form -const DIALOG_CHROME_HEIGHT: f32 = 96.0; +const DIALOG_CHROME_HEIGHT_POINTS: f32 = 96.0; /// Width of the Add and Clear buttons -const FILE_BUTTON_WIDTH: f32 = 96.0; +const FILE_BUTTON_WIDTH_POINTS: f32 = 96.0; /// Height of the list of added baked map files (it scrolls when longer) -const FILE_LIST_HEIGHT: f32 = 120.0; +const FILE_LIST_HEIGHT_POINTS: f32 = 120.0; /// Width of the Cancel and Create buttons -const BUTTON_WIDTH: f32 = 90.0; +const BUTTON_WIDTH_POINTS: f32 = 90.0; /// File > New project...: a fresh form (files listed for a failed baked map import stay listed). pub(crate) fn open(app: &mut TextureCraftApp) { let baked_maps = std::mem::take(&mut app.ui.new_project.baked_maps); - app.ui.new_project = NewProject { baked_maps, ..NewProject::default() }; + app.ui.new_project = NewProject { baked_maps, opening_id: next_request_id(), ..NewProject::default() }; app.ui.windows.new_project = true; } +fn next_request_id() -> u64 { + static NEXT_REQUEST_ID: AtomicU64 = AtomicU64::new(1); + NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed) +} + +fn close(app: &mut TextureCraftApp) { + app.ui.windows.new_project = false; + app.ui.new_project.clear_mesh(); +} + /// The New project dialog. pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.new_project { @@ -58,10 +69,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut create, mut cancel) = (false, false); + // A fixed height keeps the centered window still while its sections lay out - let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN - DIALOG_CHROME_HEIGHT).clamp(120.0, crate::project_form::FORM_HEIGHT); - dialog("new_project", tr("New project"), &mut open).default_width(DIALOG_WIDTH).show(ctx, |ui| { - ui.set_width(DIALOG_WIDTH); + let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) + .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); + dialog("new_project", tr("New project"), &mut open).default_width(DIALOG_WIDTH_POINTS).show(ctx, |ui| { + ui.set_width(DIALOG_WIDTH_POINTS); egui::ScrollArea::vertical().id_salt("np_form").min_scrolled_height(form_height).max_height(form_height).auto_shrink([false, true]).show(ui, |ui| { basic_settings(app, ui); ui.add_space(8.0); @@ -72,25 +85,35 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { create = ui - .add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH, 0.0))) + .add_enabled(can_create, primary_button(ui, tr("Create")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))) .on_disabled_hover_text(tr("Select a 3D mesh first")) .clicked(); - cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH, 0.0))).clicked(); + cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(BUTTON_WIDTH_POINTS, 0.0))).clicked(); }); }); }); - if create && create_project(app) { - let new_project = app.ui.new_project.clone(); - app.ui.windows.new_project = false; - app.ui.mode = Mode::Painting; - apply_after_create(app, &new_project); - } if cancel || !open { - app.ui.windows.new_project = false; + close(app); + } else if create && app.ui.windows.unsaved.is_none() { + let opening_id = app.ui.new_project.opening_id; + if !crate::windows::ask_to_save(app, crate::state::Unsaved::CreateProject(opening_id)) { + finish_create(app, opening_id); + } } } +pub(crate) fn finish_create(app: &mut TextureCraftApp, opening_id: u64) -> bool { + if !app.ui.windows.new_project || app.ui.new_project.opening_id != opening_id || !create_project(app) { + return false; + } + + close(app); + app.ui.mode = Mode::Painting; + apply_after_create(app); + true +} + /// The `file.new` command for the form: the chosen mesh file with the settings the engine takes at /// creation (the project is named after the file). None until a mesh file is chosen. pub fn create_command(new_project: &NewProject) -> Option { @@ -115,10 +138,11 @@ fn create_project(app: &mut TextureCraftApp) -> bool { #[cfg(target_arch = "wasm32")] fn create_project(app: &mut TextureCraftApp) -> bool { let new_project = &app.ui.new_project; - let (Some(name), Some(bytes)) = (new_project.file.clone(), new_project.file_bytes.clone()) else { return false }; - let stem = std::path::Path::new(&name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string(); + let (Some(name), Some(bytes)) = (new_project.file.as_deref(), new_project.file_bytes.as_deref()) else { return false }; + + let stem = std::path::Path::new(name).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Untitled").to_string(); let template = app.session.template(&new_project.template); - match texturecraft_engine::Session::from_mesh_bytes_tiled(&name, &bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) { + match texturecraft_engine::Session::from_mesh_bytes_tiled(name, bytes, new_project.resolution, &stem, Some(new_project.uv_tiles == Some(true))) { Ok(mut next) => { if !new_project.import_cameras { next.doc.project.cameras.clear(); @@ -128,6 +152,9 @@ fn create_project(app: &mut TextureCraftApp) -> bool { } app.session.switch_to(next); app.pbr_import = None; + app.resize = None; + app.layer_panel = Default::default(); + app.camera_glide = None; true } Err(error) => { @@ -142,7 +169,7 @@ fn basic_settings(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(caption(&tr("Basic settings").to_uppercase())); let mut select = false; row(ui, tr("3D mesh"), Some(tr("The mesh file to paint. Create is available once one is selected.")), |ui| { - select = ui.add(egui::Button::new(tr("Select...")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked(); + select = ui.add(egui::Button::new(tr("Select...")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))).clicked(); match &app.ui.new_project.file { Some(path) => { ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); @@ -158,7 +185,7 @@ fn basic_settings(app: &mut TextureCraftApp, ui: &mut Ui) { row(ui, tr("Project template"), Some(tr("The channels, resolution, normal map format and display settings a project starts with")), |ui| { let new_project = &mut app.ui.new_project; - egui::ComboBox::from_id_salt("np_template").width(FIELD_WIDTH).selected_text(new_project.template.clone()).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("np_template").width(FIELD_WIDTH_POINTS).selected_text(new_project.template.clone()).show_ui(ui, |ui| { let user_templates = app.session.templates.list.iter(); for template in texturecraft_engine::template_cmds::builtin_templates().iter().chain(user_templates) { if ui.selectable_label(template.name == new_project.template, &template.name).clicked() { @@ -172,7 +199,7 @@ fn basic_settings(app: &mut TextureCraftApp, ui: &mut Ui) { row(ui, tr("Document resolution (px)"), Some(tr("The texture size of every texture set. It can be changed later.")), |ui| { let resolution = &mut app.ui.new_project.resolution; - egui::ComboBox::from_id_salt("np_res").width(FIELD_WIDTH).selected_text(format!("{0} x {0}", *resolution)).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("np_res").width(FIELD_WIDTH_POINTS).selected_text(format!("{0} x {0}", *resolution)).show_ui(ui, |ui| { for size in RESOLUTIONS { ui.selectable_value(resolution, size, format!("{size} x {size}")); } @@ -192,8 +219,8 @@ fn advanced_settings(app: &mut TextureCraftApp, ui: &mut Ui) { tangent_space_row(ui); ui.add_space(4.0); - uv_tile_title(ui, tr("Paint meshes whose UVs span several UV tiles (UDIMs)")); - note(ui, tr("You won't be able to change UV Tile settings after creating the project.")); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("Paint meshes whose UVs span several UV tiles (UDIMs)"))); + note(ui, tr("You can enable or disable UV tiles later in Texture Set Settings.")); let new_project = &mut app.ui.new_project; let mut uv_tiles = new_project.uv_tiles == Some(true); if check_row(ui, None, |ui| ui.checkbox(&mut uv_tiles, tr("Use UV Tile workflow")), |_| {}).changed() { @@ -222,7 +249,7 @@ fn normal_format_combo(app: &mut TextureCraftApp, ui: &mut Ui) { let template_format = app.session.template(&new_project.template).map(|template| template.normal_format).unwrap_or_default(); let current = new_project.normal_format.unwrap_or(template_format); let current_label = NORMAL_FORMATS.iter().find(|(format, _, _)| *format == current).map_or("", |(_, _, label)| label); - egui::ComboBox::from_id_salt("np_normal_format").width(FIELD_WIDTH).selected_text(current_label).show_ui(ui, |ui| { + egui::ComboBox::from_id_salt("np_normal_format").width(FIELD_WIDTH_POINTS).selected_text(current_label).show_ui(ui, |ui| { for (format, _, label) in NORMAL_FORMATS { if ui.selectable_label(format == current, label).clicked() { new_project.normal_format = Some(format); @@ -236,35 +263,37 @@ fn baked_maps(new_project: &mut NewProject, ui: &mut Ui) -> bool { let tokens = Tokens::get(ui.ctx()); let mut add = false; ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); - let buttons_width = 2.0 * FILE_BUTTON_WIDTH + ui.spacing().item_spacing.x; + ui.add_space(ROW_INDENT_POINTS); + let buttons_width = 2.0 * FILE_BUTTON_WIDTH_POINTS + ui.spacing().item_spacing.x; let hint_width = (ui.available_width() - buttons_width - ui.spacing().item_spacing.x).max(0.0); ui.allocate_ui_with_layout(vec2(hint_width, 0.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.set_min_width(hint_width); ui.add(egui::Label::new(tr("Import mesh normal maps and baked maps for all materials.")).wrap()); }); - let add_button = ui.add_enabled(file_dialogs_available(), egui::Button::new(tr("Add")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))); + let add_button = ui.add_enabled(file_dialogs_available(), egui::Button::new(tr("Add")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))); add = unavailable(add_button).clicked(); - if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH, 0.0))).clicked() { + if ui.add_enabled(!new_project.baked_maps.is_empty(), egui::Button::new(tr("Clear")).min_size(vec2(FILE_BUTTON_WIDTH_POINTS, 0.0))).clicked() { new_project.baked_maps.clear(); } }); ui.add_space(4.0); ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); + ui.add_space(ROW_INDENT_POINTS); egui::Frame::new().fill(tokens.field).corner_radius(2.0).inner_margin(4.0).show(ui, |ui| { - egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT).auto_shrink([false, false]).show(ui, |ui| { - for path in &new_project.baked_maps { - ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); - } + egui::ScrollArea::vertical().id_salt("np_baked_map_list").max_height(FILE_LIST_HEIGHT_POINTS).auto_shrink([false, false]).show(ui, |ui| { + ui.vertical(|ui| { + for path in &new_project.baked_maps { + ui.add(egui::Label::new(file_name(path)).truncate()).on_hover_text(path.as_str()); + } + }); }); }); }); ui.add_space(4.0); ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); - ui.label(RichText::new(tr("Automatic normal maps assignation scheme: $(MATERIAL_NAME)_normal")).color(tokens.text_dim)) + ui.add_space(ROW_INDENT_POINTS); + ui.label(RichText::new(tr("Normal map filename: _normal")).color(tokens.text_dim)) .on_hover_text(tr("Name each file after its texture set, like Body_normal.png")); }); add @@ -280,16 +309,17 @@ pub fn add_baked_map_files(new_project: &mut NewProject, paths: Vec) { } /// After creation: set the normal format, import the listed baked maps (one undo step), toast the outcome; a failed import keeps the list -pub(crate) fn apply_after_create(app: &mut TextureCraftApp, new_project: &NewProject) { - let chosen_format = new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); +fn apply_after_create(app: &mut TextureCraftApp) { + let chosen_format = app.ui.new_project.normal_format.filter(|format| *format != app.session.doc.project.normal_format); if let Some((_, id, _)) = chosen_format.and_then(|chosen| NORMAL_FORMATS.iter().find(|(format, _, _)| *format == chosen)) { app.run("textureSet.settings", json!({ "normalFormat": id })); } - if new_project.baked_maps.is_empty() { + + if app.ui.new_project.baked_maps.is_empty() { return; } - let files: Vec = new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); + let files: Vec = app.ui.new_project.baked_maps.iter().map(|path| json!({ "path": path })).collect(); let Some(result) = app.run("textureSet.meshMap.import", json!({ "files": files })) else { return; }; @@ -314,8 +344,12 @@ fn file_name(path: &str) -> String { fn ask_mesh_file(app: &mut TextureCraftApp, _ctx: &egui::Context) { use crate::file_dialogs::{Bound, FileDialog}; let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); - app.ask_file(dialog, Bound::App, |app, paths| { - if let Some(path) = paths.first() { + let opening_id = app.ui.new_project.opening_id; + app.ask_file(dialog, Bound::App, move |app, paths| { + if app.ui.windows.new_project + && app.ui.new_project.opening_id == opening_id + && let Some(path) = paths.first() + { app.ui.new_project.file = Some(path.display().to_string()); app.ui.new_project.file_bytes = None; } @@ -323,15 +357,21 @@ fn ask_mesh_file(app: &mut TextureCraftApp, _ctx: &egui::Context) { } #[cfg(target_arch = "wasm32")] -fn ask_mesh_file(_app: &mut TextureCraftApp, ctx: &egui::Context) { - crate::web_files::pick_new_project_mesh(ctx); +fn ask_mesh_file(app: &mut TextureCraftApp, ctx: &egui::Context) { + let request_id = next_request_id(); + app.ui.new_project.mesh_request_id = request_id; + crate::web_files::pick_new_project_mesh(ctx, request_id); } #[cfg(not(target_arch = "wasm32"))] fn ask_baked_map_files(app: &mut TextureCraftApp) { use crate::file_dialogs::{Bound, FileDialog}; - app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, |app, files| { - add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect()); + + let opening_id = app.ui.new_project.opening_id; + app.ask_file(FileDialog::open_many().filter(tr("Images"), crate::web_files::IMAGE_EXTS), Bound::App, move |app, files| { + if app.ui.windows.new_project && app.ui.new_project.opening_id == opening_id { + add_baked_map_files(&mut app.ui.new_project, files.into_iter().map(|path| path.display().to_string()).collect()); + } }); } diff --git a/crates/ui-egui/src/pattern_panel.rs b/crates/ui-egui/src/pattern_panel.rs new file mode 100644 index 00000000..7afe7662 --- /dev/null +++ b/crates/ui-egui/src/pattern_panel.rs @@ -0,0 +1,378 @@ +//! A pattern's properties under its fill source slot, laid out like the reference app's: attributes, resolution, parameters, image inputs + +use egui::{RichText, Ui}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::core::{ + OutputResolution, Procedural, ProceduralKind, ResolutionMode, TileBlending, TileGenerator, TileInputDistribution, TileShape, TileSizeMode, TileSymmetry, +}; + +use crate::TextureCraftApp; +use crate::dock::{image_drop, image_menu}; +use crate::i18n::{tr, trf}; +use crate::pattern_target::PatternTarget; +use crate::resource_panel::{ATTRIBUTE_KEY_WIDTH, NOTE_FONT_SIZE, factor_label, output_size_label, random_seed}; +use crate::theme::Tokens; +use crate::tile_edits::TileEdits; +use crate::widgets::{combo, section, slider_edit}; + +/// The pattern scale slider's range (repeats per projection unit) +const SCALE_RANGE: std::ops::RangeInclusive = 0.1..=100.0; +const CONTRAST_RANGE: std::ops::RangeInclusive = 0.0..=8.0; + +/// The settings of `pattern`: its attributes, resolution, parameters and, for the Tile Generator, its image inputs +pub(crate) fn pattern_properties(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let id = |name: &str| format!("pattern_{name}_{}", target.salt); + section(ui, &id("attributes"), tr("Attributes"), false, |ui| attributes(ui, pattern.kind)); + section(ui, &id("resolution"), tr("Resolution"), false, |ui| resolution(app, ui, target, pattern)); + section(ui, &id("parameters"), tr("Parameters"), true, |ui| { + seed_row(app, ui, target, pattern); + match pattern.tile.as_deref() { + Some(tile) => tile_parameters(app, ui, target, pattern, tile), + None => pattern_parameters(app, ui, target, pattern), + } + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Restore defaults")).clicked() { + restore_defaults(app, target, pattern); + } + }); + }); + }); + if let Some(tile) = pattern.tile.as_deref() { + section(ui, &id("inputs"), tr("Image inputs"), false, |ui| image_inputs(app, ui, target, pattern, tile)); + } +} + +/// Sends `pattern` again (its kind, scale, seed, contrast, balance and invert) with `extra` to its fill +pub(crate) fn send(app: &mut TextureCraftApp, target: &PatternTarget, pattern: &Procedural, extra: Value) { + let mut params = target.base.clone(); + let fields = json!({ + "procedural": pattern.kind.label(), + "scale": pattern.scale, + "seed": pattern.seed, + "contrast": pattern.contrast, + "balance": pattern.balance, + "invert": pattern.invert, + }); + if let (Some(params), Value::Object(fields), Value::Object(extra)) = (params.as_object_mut(), fields, extra) { + params.extend(fields); + params.extend(extra); + } + app.run(target.command, params); +} + +/// What a pattern makes, its category and its tags (read only) +fn attributes(ui: &mut Ui, kind: ProceduralKind) { + let tokens = Tokens::get(ui.ctx()); + let description = match kind { + ProceduralKind::TileGenerator => tr("Shapes laid out in a grid of tiles: rows, offsets, random size, rotation and brightness."), + _ => tr("A procedural pattern mixing two values."), + }; + let tags = [tr("pattern"), tr(kind.label()), tr("grayscale")].join(", "); + for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Patterns")), (tr("Tags"), tags.as_str())] { + ui.horizontal_top(|ui| { + ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim))); + ui.add(egui::Label::new(value).wrap()); + }); + } +} + +/// What the pattern's resolution is based on, the factor applied to it, and the size it comes to +fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let tokens = Tokens::get(ui.ctx()); + let current = pattern.resolution; + combo(ui, tr("Resolution"), tr(current.mode.label()), |ui| { + for mode in ResolutionMode::ALL { + if ui.selectable_label(mode == current.mode, tr(mode.label())).clicked() { + send(app, target, pattern, json!({"resolution": format!("{mode:?}")})); + } + } + }) + .on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own.")); + if current.mode == ResolutionMode::Custom { + combo(ui, tr("Size"), format!("{0} × {0}", current.custom), |ui| { + for size in OutputResolution::CUSTOM_SIZES { + if ui.selectable_label(size == current.custom, format!("{size} × {size}")).clicked() { + send(app, target, pattern, json!({"customResolution": size})); + } + } + }); + } + combo(ui, tr("Factor"), factor_label(current.factor), |ui| { + for factor in OutputResolution::FACTORS { + if ui.selectable_label(factor == current.factor, factor_label(factor)).clicked() { + send(app, target, pattern, json!({"resolutionFactor": factor})); + } + } + }) + .on_hover_text(tr("Scales the base resolution: below 1 the pattern is drawn coarser and smoothed back up.")); + + let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return }; + let size_label = output_size_label(¤t, texture_set); + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Output size")).color(tokens.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label)); + }); +} + +/// The seed with a button that picks a new one and a pencil that opens a field to type it +fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let typing_id = ui.make_persistent_id(("pattern_seed_typing", &target.salt)); + let mut typing = ui.data(|data| data.get_temp::(typing_id)).unwrap_or(false); + ui.horizontal(|ui| { + ui.label(tr("Seed")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() { + typing = !typing; + } + if typing { + let mut typed = pattern.seed; + let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0)); + if field.changed() { + let merge = field.dragged() && !field.drag_started(); + send(app, target, &Procedural { seed: typed, ..pattern.clone() }, json!({"merge": merge})); + } + } else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &pattern.seed)])).clicked() { + send(app, target, &Procedural { seed: random_seed(pattern.seed), ..pattern.clone() }, json!({})); + } + }); + }); + ui.data_mut(|data| data.insert_temp(typing_id, typing)); +} + +/// Scale, contrast and invert of a pattern other than the Tile Generator +fn pattern_parameters(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural) { + let mut edited = pattern.clone(); + let invert_edit = ui.checkbox(&mut edited.invert, tr("Invert")).changed().then_some(false); + let scale_edit = slider_edit(ui, tr("Pattern scale"), &mut edited.scale, SCALE_RANGE, 1); + let contrast_edit = slider_edit(ui, tr("Contrast"), &mut edited.contrast, CONTRAST_RANGE, 2); + if let Some(merge) = invert_edit.or(scale_edit).or(contrast_edit) { + send(app, target, &edited, json!({"merge": merge})); + } +} + +/// Puts the pattern's parameters and resolution back to the defaults of its kind; its image inputs stay +fn restore_defaults(app: &mut TextureCraftApp, target: &PatternTarget, pattern: &Procedural) { + let defaults = Procedural::new(pattern.kind); + let mut extra = json!({ + "resolution": format!("{:?}", defaults.resolution.mode), + "customResolution": defaults.resolution.custom, + "resolutionFactor": defaults.resolution.factor, + }); + + // The images stay: Restore defaults puts back the parameters, not the inputs + if let Some(tile) = pattern.tile.as_deref() { + extra["tileDefaults"] = json!(true); + extra["tile"] = json!({"inputs": tile.inputs, "backgroundImage": tile.background_image}); + } + send(app, target, &defaults, extra); +} + +/// The Tile Generator's settings, in the reference app's sections +fn tile_parameters(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural, tile: &TileGenerator) { + let mut edits = TileEdits::default(); + let mut invert = pattern.invert; + if ui.checkbox(&mut invert, tr("Invert")).changed() { + edits.merge = Some(false); + } + edits.slider(ui, tr("Position"), "position", tile.position, 0.0..=1.0); + edits.slider(ui, tr("Contrast"), "contrast", tile.contrast, 0.0..=1.0); + let mut amount = tile.amount; + let mut amount_edit = None; + for (label, count) in [tr("X amount"), tr("Y amount")].into_iter().zip(amount.iter_mut()) { + let mut shown = *count as f32; + if let Some(merge) = slider_edit(ui, label, &mut shown, *TileGenerator::AMOUNT.start() as f32..=*TileGenerator::AMOUNT.end() as f32, 0) { + *count = shown.round() as u32; + amount_edit = Some(merge); + } + } + if let Some(merge) = amount_edit { + edits.set("amount", json!(amount), merge); + } + edits.check(ui, tr("Non-square expansion"), "nonSquareExpansion", tile.non_square_expansion); + + let id = |name: &str| format!("tile_{name}_{}", target.salt); + ui.indent(id("sections"), |ui| { + section(ui, &id("pattern"), tr("Pattern"), false, |ui| shape_section(ui, &mut edits, tile)); + section(ui, &id("size"), tr("Size"), false, |ui| size_section(ui, &mut edits, tile)); + section(ui, &id("position"), tr("Position"), false, |ui| position_section(ui, &mut edits, tile)); + section(ui, &id("rotation"), tr("Rotation"), false, |ui| { + edits.angle(ui, tr("Rotation"), "rotation", tile.rotation); + edits.slider(ui, tr("Rotation random"), "rotationRandom", tile.rotation_random, 0.0..=1.0); + }); + section(ui, &id("color"), tr("Color"), false, |ui| color_section(ui, &mut edits, tile)); + }); + + if let Some(merge) = edits.merge { + let edited = (invert != pattern.invert).then(|| Procedural { invert, ..pattern.clone() }); + send(app, target, edited.as_ref().unwrap_or(pattern), json!({"tile": Value::Object(edits.settings), "merge": merge})); + } +} + +/// The shape each tile draws and how it is turned and mirrored +fn shape_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.choice(ui, tr("Type"), "shape", tile.shape, &TileShape::ALL, TileShape::label); + for (index, (label, size)) in [tr("Resolution X"), tr("Resolution Y")].into_iter().zip(tile.shape_resolution).enumerate() { + combo(ui, label, size.to_string(), |ui| { + for option in TileGenerator::SHAPE_RESOLUTIONS { + if ui.selectable_label(option == size, option.to_string()).clicked() { + let mut resolution = tile.shape_resolution; + if let Some(side) = resolution.get_mut(index) { + *side = option; + } + edits.set("shapeResolution", json!(resolution), false); + } + } + }); + } + edits.slider(ui, tr("Specific"), "specific", tile.specific, 0.0..=1.0); + edits.angle(ui, tr("Angle"), "shapeAngle", tile.shape_angle); + edits.slider(ui, tr("Scale"), "shapeScale", tile.shape_scale, 0.0..=1.0); + edits.pair(ui, [tr("Size X"), tr("Size Y")], "shapeSize", tile.shape_size, 0.0..=1.0); + edits.count(ui, tr("Tiling"), "shapeTiling", tile.shape_tiling, TileGenerator::SHAPE_TILING); + edits.check(ui, tr("Rotation 45°"), "shapeDiagonal", tile.shape_diagonal); + edits.check(ui, tr("Non-square expansion"), "shapeNonSquareExpansion", tile.shape_non_square_expansion); + edits.choice(ui, tr("Input distribution"), "inputDistribution", tile.input_distribution, &TileInputDistribution::ALL, TileInputDistribution::label); + combo(ui, tr("Rotation"), format!("{}°", u32::from(tile.quarter_turns) * 90), |ui| { + for turns in 0..4u8 { + if ui.selectable_label(turns == tile.quarter_turns, format!("{}°", u32::from(turns) * 90)).clicked() { + edits.set("quarterTurns", json!(turns), false); + } + } + }); + edits.slider(ui, tr("Rotation random"), "quarterTurnRandom", tile.quarter_turn_random, 0.0..=1.0); + edits.check(ui, tr("Quincunx flip"), "quincunxFlip", tile.quincunx_flip); + edits.slider(ui, tr("Symmetry random"), "symmetryRandom", tile.symmetry_random, 0.0..=1.0); + edits.choice(ui, tr("Symmetry mode"), "symmetry", tile.symmetry, &TileSymmetry::ALL, TileSymmetry::label); +} + +/// How big each shape is: the controls of its size mode, then scale and its randomness +fn size_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.choice(ui, tr("Size mode"), "sizeMode", tile.size_mode, &TileSizeMode::ALL, TileSizeMode::label); + edits.pair(ui, [tr("Middle size horizontal"), tr("Middle size vertical")], "middleSize", tile.middle_size, 0.0..=1.0); + match tile.size_mode { + TileSizeMode::NormalInterstice => { + // Each axis's gap, then its randomness, as the reference lists them + let (mut gap, mut random) = (tile.interstice, tile.interstice_random); + let mut gap_edit = None; + let mut random_edit = None; + let labels = [(tr("Interstice X"), tr("Interstice X random")), (tr("Interstice Y"), tr("Interstice Y random"))]; + for ((gap_label, random_label), (gap, random)) in labels.into_iter().zip(gap.iter_mut().zip(random.iter_mut())) { + gap_edit = gap_edit.or(slider_edit(ui, gap_label, gap, 0.0..=1.0, 2)); + random_edit = random_edit.or(slider_edit(ui, random_label, random, 0.0..=1.0, 2)); + } + if let Some(merge) = gap_edit { + edits.set("interstice", json!(gap), merge); + } + if let Some(merge) = random_edit { + edits.set("intersticeRandom", json!(random), merge); + } + } + TileSizeMode::NormalSize => edits.pair(ui, [tr("Size X"), tr("Size Y")], "size", tile.size, 0.0..=1.0), + + // The shape is the largest square its cell holds: no size of its own + TileSizeMode::KeepRatio => {} + TileSizeMode::Absolute => edits.pair(ui, [tr("Size X"), tr("Size Y")], "sizeAbsolute", tile.size_absolute, 0.0..=1.0), + TileSizeMode::Pixel => edits.pair(ui, [tr("Size X"), tr("Size Y")], "sizePixel", tile.size_pixel, 0.0..=TileGenerator::MAX_SIZE_PIXELS), + } + if matches!(tile.size_mode, TileSizeMode::Absolute | TileSizeMode::Pixel) { + edits.pair(ui, [tr("Size random X"), tr("Size random Y")], "sizeRandom", tile.size_random, 0.0..=1.0); + } + edits.slider(ui, tr("Scale"), "scale", tile.scale, 0.0..=TileGenerator::MAX_SCALE); + edits.slider(ui, tr("Scale random"), "scaleRandom", tile.scale_random, 0.0..=1.0); + edits.count(ui, tr("Scale random seed"), "scaleRandomSeed", tile.scale_random_seed, 0..=TileGenerator::MAX_RANDOM_SEED); +} + +/// Where each shape sits: the row offset, its randomness and the shift of the whole grid +fn position_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.slider(ui, tr("Offset"), "offset", tile.offset, 0.0..=1.0); + edits.slider(ui, tr("Offset random"), "offsetRandom", tile.offset_random, 0.0..=1.0); + edits.count(ui, tr("Offset random seed"), "offsetRandomSeed", tile.offset_random_seed, 0..=TileGenerator::MAX_RANDOM_SEED); + edits.check(ui, tr("Vertical offset"), "verticalOffset", tile.vertical_offset); + edits.pair(ui, [tr("Position random X"), tr("Position random Y")], "positionRandom", tile.position_random, 0.0..=1.0); + edits.pair(ui, [tr("Global offset X"), tr("Global offset Y")], "globalOffset", tile.global_offset, 0.0..=1.0); +} + +/// Each shape's brightness, the tiles hidden and how overlapping shapes combine +fn color_section(ui: &mut Ui, edits: &mut TileEdits, tile: &TileGenerator) { + edits.gray(ui, tr("Color"), "color", tile.color); + edits.slider(ui, tr("Luminance random"), "luminanceRandom", tile.luminance_random, 0.0..=1.0); + edits.check(ui, tr("Luminance by number"), "luminanceByNumber", tile.luminance_by_number); + edits.check(ui, tr("Luminance by scale"), "luminanceByScale", tile.luminance_by_scale); + edits.check(ui, tr("Checker mask"), "checkerMask", tile.checker_mask); + edits.check(ui, tr("Horizontal mask"), "horizontalMask", tile.horizontal_mask); + edits.check(ui, tr("Vertical mask"), "verticalMask", tile.vertical_mask); + edits.slider(ui, tr("Random mask"), "randomMask", tile.random_mask, 0.0..=1.0); + edits.check(ui, tr("Invert mask"), "invertMask", tile.invert_mask); + edits.choice(ui, tr("Blending"), "blending", tile.blending, &TileBlending::ALL, TileBlending::label); + edits.gray(ui, tr("Background"), "background", tile.background); + edits.slider(ui, tr("Global opacity"), "opacity", tile.opacity, 0.0..=1.0); + edits.check(ui, tr("Reverse rendering order"), "reverseOrder", tile.reverse_order); +} + +/// The images the Tile Generator can draw in its tiles, and the one under them +fn image_inputs(app: &mut TextureCraftApp, ui: &mut Ui, target: &PatternTarget, pattern: &Procedural, tile: &TileGenerator) { + let tokens = Tokens::get(ui.ctx()); + let mut inputs = tile.inputs.clone(); + let mut changed = false; + for index in 0..TileGenerator::MAX_INPUTS { + let current = inputs.get(index).cloned(); + let label = trf("Pattern input {number}", &[("number", &(index + 1))]); + if let Some(picked) = input_slot(app, ui, &label, current.as_deref()) { + match (picked, inputs.get_mut(index)) { + (Some(name), Some(slot)) => *slot = name, + (Some(name), None) => inputs.push(name), + (None, Some(_)) => { + inputs.remove(index); + } + (None, None) => {} + } + changed = true; + } + + // Inputs fill in order: one empty slot after the last image + if current.is_none() { + break; + } + } + if changed { + send(app, target, pattern, json!({"tile": {"inputs": inputs}})); + } + if let Some(picked) = input_slot(app, ui, tr("Background"), tile.background_image.as_deref()) { + send(app, target, pattern, json!({"tile": {"backgroundImage": picked}})); + } + if tile.shape != TileShape::Image { + ui.label(RichText::new(tr("The pattern inputs are drawn when the shape type is Custom image input.")).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + } +} + +/// One image input: its name and image, a menu to pick another and a button that empties it. `Some(pick)` when changed (`None`: emptied) +fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, label: &str, current: Option<&str>) -> Option> { + let tokens = Tokens::get(ui.ctx()); + let mut picked = None; + let group = ui.group(|ui| { + ui.horizontal(|ui| { + ui.vertical(|ui| { + ui.label(RichText::new(label).strong()); + ui.label(RichText::new(current.unwrap_or(tr("Empty"))).size(NOTE_FONT_SIZE).color(tokens.text_dim)); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if current.is_some() && ui.button(ic::X).on_hover_text(tr("Empty this input")).clicked() { + picked = Some(None); + } + ui.menu_button(ic::IMAGE, |ui| { + if let Some(name) = image_menu(app, ui) { + picked = Some(Some(name)); + } + }) + .response + .on_hover_text(tr("Pick an image")); + }); + }); + }); + if let Some(name) = image_drop(ui, &group.response) { + picked = Some(Some(name)); + } + picked +} diff --git a/crates/ui-egui/src/pattern_target.rs b/crates/ui-egui/src/pattern_target.rs new file mode 100644 index 00000000..3b01be28 --- /dev/null +++ b/crates/ui-egui/src/pattern_target.rs @@ -0,0 +1,11 @@ +//! Where a pattern panel's edits go + +use serde_json::Value; + +/// Where a pattern's edits go: `command` with `base` params naming its fill (and channel, with the colors a pattern maps to) +pub(crate) struct PatternTarget { + pub command: &'static str, + pub base: Value, + /// Keeps the sections of two patterns shown at once apart + pub salt: String, +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index 7e6469d6..b078e520 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -115,14 +115,17 @@ pub fn procedural_image(kind: ProceduralKind, size: usize) -> ColorImage { use texturecraft_engine::core::{Procedural, Projection}; use texturecraft_engine::geom::glam::{Vec2, Vec3}; - let pattern = Procedural { scale: PROCEDURAL_SCALE, ..Procedural::new(kind) }; - let mut img = ColorImage::filled([size, size], Color32::BLACK); - for (i, px) in img.pixels.iter_mut().enumerate() { - let uv = Vec2::new(((i % size) as f32 + 0.5) / size as f32, ((i / size) as f32 + 0.5) / size as f32); - let v = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); - *px = Color32::from_gray((v.clamp(0.0, 1.0) * 255.0) as u8); + // The Tile Generator's tile counts set its frequency: its swatch shows its grid once + let defaults = Procedural::new(kind); + let scale = if kind == ProceduralKind::TileGenerator { defaults.scale } else { PROCEDURAL_SCALE }; + let pattern = Procedural { scale, ..defaults }; + let mut image = ColorImage::filled([size, size], Color32::BLACK); + for (index, pixel) in image.pixels.iter_mut().enumerate() { + let uv = Vec2::new(((index % size) as f32 + 0.5) / size as f32, ((index / size) as f32 + 0.5) / size as f32); + let value = procedural(&pattern, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y }); + *pixel = Color32::from_gray((value.clamp(0.0, 1.0) * 255.0) as u8); } - img + image } /// White-on-black `size²` swatch of library alpha `alpha` @@ -166,7 +169,7 @@ pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&Imag let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); let radius = size_px as f32 * STROKE_RADIUS_FRACTION; - let shape = Shape { alpha: brush.alpha, image, library, level: 0 }.at_radius(radius); + let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius); // The horizontal inset and vertical wave keep the S curve inside the swatch let curve = |t: f32| { @@ -193,6 +196,7 @@ pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&Imag if travelled < step { continue; } + travelled = 0.0; i += 1; let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index 4e9edfd1..b6ae5bb1 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -14,8 +14,8 @@ use crate::dock::info_icon; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{tr, trf}; use crate::project_form::{ - FIELD_WIDTH, ROW_INDENT, auto_unwrap_row, check_row, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, uv_tile_radios, - uv_tile_title, + FIELD_WIDTH_POINTS, ROW_INDENT_POINTS, auto_unwrap_row, check_row, color_management, note, physical_size, row, sub_title, tangent_space_row, unavailable, + uv_tile_radios, }; use crate::state::ProjectConfig; use crate::theme::{Tokens, caption}; @@ -39,6 +39,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { // Layout resets must not reuse an identity held by a pending file picker static NEXT_OPENING_ID: AtomicU64 = AtomicU64::new(1); + app.ui.windows.import_resources = None; app.ui.windows.project_config = Some(ProjectConfig { mesh: None, reimport: false, @@ -115,38 +116,30 @@ fn format_name(format: NormalFormat) -> &'static str { } pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - let Some(mut config) = app.ui.windows.project_config.clone() else { return }; + let Some(mut config) = app.ui.windows.project_config.take() else { return }; // Choices for another project cannot be applied here if config.project != app.session.project_id { - app.ui.windows.project_config = None; return; } let project = &app.session.doc.project; - let current_mesh_path = project.mesh_path.clone(); + let current_mesh_path = &project.mesh_path; // Show the imported name when there is no file path - let mesh_label = if current_mesh_path.is_empty() { project.mesh_file.clone() } else { current_mesh_path.clone() }; + let mesh_label = if current_mesh_path.is_empty() { &project.mesh_file } else { current_mesh_path }; let source_file_available = app.session.remembered_mesh_path().is_some(); let current_normal_format = project.normal_format; - // Keep each texture set's tiles together for the read-only list - let texture_set_tiles: Vec<(String, Option)> = project - .texture_sets - .iter() - .map(|set| (set.name.clone(), (!set.uv_tiles.is_empty()).then(|| set.uv_tiles.iter().map(u32::to_string).collect::>().join(", ")))) - .collect(); - // Re-selecting the current path cancels an earlier choice - let chosen_mesh = config.mesh.as_ref().filter(|chosen| **chosen != current_mesh_path).cloned(); + let chosen_mesh = config.mesh.as_deref().filter(|chosen| *chosen != current_mesh_path); let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); // A fixed height keeps the centered window still while its sections lay out - let form_height = - (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS).clamp(120.0, crate::project_form::FORM_HEIGHT); + let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) + .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); let dialog = crate::windows::dialog("project_config", tr("Project configuration"), &mut open).default_width(DEFAULT_DIALOG_WIDTH_POINTS); dialog.show(ctx, |ui| { @@ -156,10 +149,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(caption(tr("3D MESH"))); ui.add_space(4.0); ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); + ui.add_space(ROW_INDENT_POINTS); ui.label(tr("3D mesh")); - let display_path = chosen_mesh.clone().unwrap_or_else(|| mesh_label.clone()); + let display_path = chosen_mesh.unwrap_or(mesh_label); let font = egui::TextStyle::Body.resolve(ui.style()); let path_width_points = (ui.available_width() - SELECT_BUTTON_WIDTH_POINTS).max(MIN_FIELD_WIDTH_POINTS); let painter = ui.painter().clone(); @@ -171,7 +164,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if display_path.is_empty() { ui.weak(tr("Built-in mesh")); } else { - ui.label(elide_start(&display_path, measure)).on_hover_text(&display_path); + ui.label(elide_start(display_path, measure)).on_hover_text(display_path); } }); }); @@ -206,7 +199,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { Some(tr("Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it.")), |ui| { egui::ComboBox::from_id_salt(tr("Normal map format")) - .width(FIELD_WIDTH) + .width(FIELD_WIDTH_POINTS) .wrap_mode(egui::TextWrapMode::Truncate) .selected_text(format_name(shown_format)) .show_ui(ui, |ui| { @@ -226,26 +219,27 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // Texture Set Settings owns UV tile changes ui.add_space(4.0); - uv_tile_title(ui, tr("The UV tiles (UDIMs) of each texture set, shown for reference. Change them in Texture Set Settings.")); - note(ui, tr("You can't change UV Tile settings once a project has been created.")); - let has_tiles = texture_set_tiles.iter().any(|(_, tile_text)| tile_text.is_some()); + sub_title(ui, tr("UV Tile settings (UDIMs)"), Some(tr("View the UV tiles assigned to each texture set"))); let tiles_hint = tr("Change the UV tiles of a texture set in Texture Set Settings"); + note(ui, tiles_hint); + let mut has_tiles = project.texture_sets.iter().any(|set| !set.uv_tiles.is_empty()); - // The project's tiles are listed in the hover hint, the window shows only the reference's text - let mut tile_lines: Vec = texture_set_tiles - .iter() - .filter_map(|(name, tile_text)| { - let tile_list = tile_text.as_deref()?; - Some(if texture_set_tiles.len() > 1 { trf("{set}: {tiles}", &[("set", name), ("tiles", &tile_list)]) } else { tile_list.to_string() }) - }) - .collect(); - if tile_lines.is_empty() { - tile_lines.push(tr("No UV tiles").to_string()); - } - tile_lines.push(tiles_hint.to_string()); - let tiles_text = tile_lines.join("\n"); - check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles.clone(), tr("Use UV Tile workflow"))), |_| {}) - .on_disabled_hover_text(&tiles_text); + check_row(ui, None, |ui| ui.add_enabled(false, egui::Checkbox::new(&mut has_tiles, tr("Use UV Tile workflow"))), |_| {}) + .on_disabled_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + if !has_tiles { + ui.label(tr("No UV tiles")); + } + + for set in project.texture_sets.iter().filter(|set| !set.uv_tiles.is_empty()) { + let tiles = set.uv_tiles.iter().map(u32::to_string).collect::>().join(", "); + if project.texture_sets.len() > 1 { + ui.label(trf("{set}: {tiles}", &[("set", &set.name), ("tiles", &tiles)])); + } else { + ui.label(tiles); + } + } + }); uv_tile_radios(ui, false, tiles_hint); ui.add_space(4.0); @@ -273,7 +267,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); ui.add_space(8.0); - ui.label(egui::RichText::new(tr("Please note: Changing any of these settings will cause all channels to be recomputed.")).color(Tokens::get(ui.ctx()).warning)); + ui.label(egui::RichText::new(tr("Changing the mesh or normal format can recalculate texture channels.")).color(Tokens::get(ui.ctx()).warning)); ui.add_space(4.0); ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -289,17 +283,17 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ask_file(dialog, Bound::Project, move |app, paths| { let Some(path) = paths.first().map(|p| p.display().to_string()) else { return }; - let current_mesh_path = app.session.doc.project.mesh_path.clone(); + let current_mesh_path = &app.session.doc.project.mesh_path; if let Some(config) = app.ui.windows.project_config.as_mut().filter(|config| config.opening_id == opening_id) { // Re-selecting the source file drops an earlier choice - config.mesh = (path != current_mesh_path).then_some(path); + config.mesh = (path != *current_mesh_path).then_some(path); } }); } // Apply the mesh first so a failed mesh change leaves the format untouched let mut mesh_applied = false; - let done = ok && { + let done = ok && !cancel && open && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() { // Drop a stale reimport tick so the user can retry the remaining settings @@ -307,7 +301,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { config.reimport = false; false } else { - match mesh_command(chosen_mesh.as_deref(), reimport.as_deref(), config.preserve) { + match mesh_command(chosen_mesh, reimport.as_deref(), config.preserve) { Some((command, params)) => app.run(command, params).is_some(), None => true, } @@ -324,17 +318,13 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } }; - if done || cancel || !open { - app.ui.windows.project_config = None; - } else if let Some(stored) = app.ui.windows.project_config.as_mut() { - // A file answer arrives later through the stored state - (stored.reimport, stored.preserve, stored.normal_format, stored.color_management, stored.confirm) = - (config.reimport, config.preserve, config.normal_format, config.color_management, false); - + if !done && !cancel && open { // A format retry must not reimport an already changed mesh if ok && mesh_applied { - (stored.mesh, stored.reimport) = (None, false); + (config.mesh, config.reimport) = (None, false); } + + app.ui.windows.project_config = Some(config); } } diff --git a/crates/ui-egui/src/project_form.rs b/crates/ui-egui/src/project_form.rs index 3170b31c..171282e3 100644 --- a/crates/ui-egui/src/project_form.rs +++ b/crates/ui-egui/src/project_form.rs @@ -4,6 +4,7 @@ use egui::{Response, RichText, Sense, Ui}; +pub use crate::color_management::ColorManagement; use crate::dock::info_icon; use crate::i18n::{n_, tr}; use crate::theme::{Tokens, caption}; @@ -16,31 +17,16 @@ pub const NOT_AVAILABLE: &str = n_("Not available yet"); pub const OCIO_NOT_AVAILABLE: &str = n_("OpenColorIO is not available yet. The project uses Legacy."); /// Width of the dropdowns and fields at the right of a row. -pub(crate) const FIELD_WIDTH: f32 = 220.0; +pub(crate) const FIELD_WIDTH_POINTS: f32 = 220.0; /// Tallest the scrolling form of the two windows grows (the rest scrolls). -pub(crate) const FORM_HEIGHT: f32 = 760.0; +pub(crate) const FORM_HEIGHT_POINTS: f32 = 760.0; + +/// Scrolling form height when viewport space is limited. +pub(crate) const MIN_FORM_HEIGHT_POINTS: f32 = 120.0; /// Indent of the rows below a section title. -pub(crate) const ROW_INDENT: f32 = 16.0; - -/// How a project manages colour. Only Legacy is implemented; OpenColorIO can be chosen to see its -/// settings, but they stay disabled and a project is always created and kept as Legacy. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum ColorManagement { - #[default] - Legacy, - OpenColorIo, -} - -impl ColorManagement { - fn label(self) -> &'static str { - match self { - ColorManagement::Legacy => n_("Legacy"), - ColorManagement::OpenColorIo => "OpenColorIO", - } - } -} +pub(crate) const ROW_INDENT_POINTS: f32 = 16.0; /// `response` with the not-available hint while it is disabled. pub(crate) fn unavailable(response: Response) -> Response { @@ -50,7 +36,7 @@ pub(crate) fn unavailable(response: Response) -> Response { /// A row: `label` at the left, then `control` right-aligned before the info icon (`info`). pub(crate) fn row(ui: &mut Ui, label: &str, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R) -> R { ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); + ui.add_space(ROW_INDENT_POINTS); ui.label(label); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { info_slot(ui, info); @@ -65,7 +51,7 @@ pub(crate) fn row(ui: &mut Ui, label: &str, info: Option<&str>, control: impl /// `trailing` adds a control just before the icon (a button). pub(crate) fn check_row(ui: &mut Ui, info: Option<&str>, control: impl FnOnce(&mut Ui) -> R, trailing: impl FnOnce(&mut Ui)) -> R { ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); + ui.add_space(ROW_INDENT_POINTS); let inner = control(ui); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { info_slot(ui, info); @@ -79,6 +65,7 @@ pub(crate) fn check_row(ui: &mut Ui, info: Option<&str>, control: impl FnOnce fn info_slot(ui: &mut Ui, info: Option<&str>) { match info { Some(text) => info_icon(ui, text), + // An invisible icon keeps the controls of rows without one in the same column None => { ui.add_visible(false, egui::Label::new(egui_phosphor::regular::INFO)); @@ -89,7 +76,7 @@ fn info_slot(ui: &mut Ui, info: Option<&str>) { /// A bold sub-section title such as Import settings, with an optional info icon at the end. pub(crate) fn sub_title(ui: &mut Ui, title: &str, info: Option<&str>) { ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); + ui.add_space(ROW_INDENT_POINTS); ui.label(caption(title)); if let Some(text) = info { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, text)); @@ -97,29 +84,18 @@ pub(crate) fn sub_title(ui: &mut Ui, title: &str, info: Option<&str>) { }); } -/// The "UV Tile settings (UDIMs)" title: the tutorial icon (not available yet) and the info icon. -pub(crate) fn uv_tile_title(ui: &mut Ui, info: &str) { - ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); - ui.label(caption(tr("UV Tile settings (UDIMs)"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - info_icon(ui, info); - unavailable(ui.add_enabled(false, egui::Button::new(egui_phosphor::regular::GRADUATION_CAP).frame(false))); - }); - }); -} - /// A dim italic note in a section. pub(crate) fn note(ui: &mut Ui, text: &str) { ui.horizontal(|ui| { - ui.add_space(2.0 * ROW_INDENT); + ui.add_space(2.0 * ROW_INDENT_POINTS); ui.add(egui::Label::new(RichText::new(text).italics().color(Tokens::get(ui.ctx()).text_dim)).wrap()); }); } /// A dropdown that cannot be opened, showing `value`, with the not-available hint. pub(crate) fn disabled_combo(ui: &mut Ui, id: &str, value: &str) -> Response { - let response = ui.add_enabled_ui(false, |ui| egui::ComboBox::from_id_salt(id).width(FIELD_WIDTH).selected_text(value).show_ui(ui, |_| {}).response).inner; + let response = + ui.add_enabled_ui(false, |ui| egui::ComboBox::from_id_salt(id).width(FIELD_WIDTH_POINTS).selected_text(value).show_ui(ui, |_| {}).response).inner; unavailable(response) } @@ -129,7 +105,7 @@ pub(crate) fn collapsible(ui: &mut Ui, id: &str, title: &str, default_open: bool let id = ui.make_persistent_id(id); let mut state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); ui.horizontal(|ui| { - ui.add_space(ROW_INDENT); + ui.add_space(ROW_INDENT_POINTS); let header = ui .horizontal(|ui| { ui.add(egui::Label::new(section_chevron(ui, state.is_open())).selectable(false)); @@ -167,14 +143,14 @@ pub(crate) fn uv_tile_radios(ui: &mut Ui, enabled: bool, disabled_hint: &str) { let preserve = check_row( ui, Some(tr("Each material keeps its UV tiles in one texture set, and strokes paint across tiles")), - |ui| ui.add_enabled(enabled, egui::RadioButton::new(true, tr("Preserve UV Tile layout per material and enable painting across tiles"))), + |ui| ui.add_enabled(enabled, egui::RadioButton::new(true, tr("Keep UV tiles together per material"))), |_| {}, ); preserve.on_disabled_hover_text(disabled_hint); check_row( ui, Some(tr("Each UV tile becomes a texture set of its own")), - |ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Convert UV Tiles into individual Texture Sets (legacy)")))), + |ui| unavailable(ui.add_enabled(false, egui::RadioButton::new(false, tr("Use a separate texture set for each tile")))), |_| {}, ); }); @@ -196,13 +172,10 @@ pub(crate) fn auto_unwrap_row(ui: &mut Ui) { /// The Physical size section: the mesh file's own unit scale is what TextureCraft uses; a custom /// scale and physical-size fill layers are not available yet. pub(crate) fn physical_size(ui: &mut Ui, id: &str, default_open: bool) { + const UNIT_FIELD_WIDTH_POINTS: f32 = 60.0; + collapsible(ui, id, tr("Physical size"), default_open, Some(tr("The real-world size of one unit of the mesh")), |ui| { - check_row( - ui, - Some(tr("Use the unit scale stored in the mesh file")), - |ui| ui.radio(true, tr("Use mesh file's internal unit scale (recommended)")), - |_| {}, - ); + check_row(ui, Some(tr("Use the unit scale stored in the mesh file")), |ui| ui.radio(true, tr("Use the mesh file’s unit scale")), |_| {}); check_row( ui, Some(tr("Set the size of one unit yourself")), @@ -210,15 +183,15 @@ pub(crate) fn physical_size(ui: &mut Ui, id: &str, default_open: bool) { |_| {}, ); ui.horizontal(|ui| { - ui.add_space(3.0 * ROW_INDENT); + ui.add_space(3.0 * ROW_INDENT_POINTS); ui.label(tr("1 unit =")); - unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(60.0))); + unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(UNIT_FIELD_WIDTH_POINTS))); ui.label(tr("cm")); }); check_row( ui, Some(tr("Fill layers of applied materials are scaled in physical size instead of UV space")), - |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Switch fill layer scaling to Physical size when assigning materials")))), + |ui| unavailable(ui.add_enabled(false, egui::Checkbox::new(&mut false, tr("Scale material fills in real-world units")))), |_| {}, ); }); @@ -240,14 +213,13 @@ const OCIO_EXPORT: [(&str, &str, Option<&str>); 3] = [ ]; /// The Color management section. `mode` is the dropdown's choice: Legacy shows the working color -/// space; OpenColorIO shows its settings, all disabled, and the dropdown's hover hint says it is not available yet -/// (the project stays Legacy whatever is chosen). +/// space. OpenColorIO previews disabled settings while the project continues to use Legacy. pub(crate) fn color_management(ui: &mut Ui, id: &str, mode: &mut ColorManagement) { collapsible(ui, id, tr("Color management"), true, None, |ui| { ui.label(caption(tr("Configuration"))); row(ui, tr("Color management"), Some(tr("Legacy works in linear sRGB. OpenColorIO manages color through a configuration")), |ui| { let response = egui::ComboBox::from_id_salt(format!("{id}_mode")) - .width(FIELD_WIDTH) + .width(FIELD_WIDTH_POINTS) .selected_text(tr(mode.label())) .show_ui(ui, |ui| { for choice in [ColorManagement::Legacy, ColorManagement::OpenColorIo] { @@ -264,7 +236,7 @@ pub(crate) fn color_management(ui: &mut Ui, id: &str, mode: &mut ColorManagement row(ui, tr(label), info.map(tr), |ui| disabled_combo(ui, &format!("{id}_{label}"), tr(value))); } row(ui, tr("Configuration file"), Some(tr("A custom OpenColorIO configuration file")), |ui| { - unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(FIELD_WIDTH))); + unavailable(ui.add_enabled(false, egui::TextEdit::singleline(&mut String::new()).desired_width(FIELD_WIDTH_POINTS))); }); } diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index 6826c1a0..506d20d7 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -12,11 +12,11 @@ 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] = [ - (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), + (Panel::Log, ic::FILE_TEXT, "ui.view.log"), (Panel::Display, ic::MONITOR, "ui.view.display"), (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), - (Panel::Log, ic::FILE_TEXT, "ui.view.log"), + (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), ]; /// The popup reaches this far into the viewport, so it covers the panels between the viewport and the rail diff --git a/crates/ui-egui/src/resource_panel.rs b/crates/ui-egui/src/resource_panel.rs new file mode 100644 index 00000000..987899bc --- /dev/null +++ b/crates/ui-egui/src/resource_panel.rs @@ -0,0 +1,67 @@ +//! What the generator and pattern panels share: the attribute rows' key width, note size, the resolution factor's label, the output size readout and a random seed + +use texturecraft_engine::core::{OutputResolution, TextureSet}; + +use crate::i18n::tr; + +/// Width of the names in the Attributes section, so their values line up +pub(crate) const ATTRIBUTE_KEY_WIDTH: f32 = 80.0; +/// Font size of the notes under a control +pub(crate) const NOTE_FONT_SIZE: f32 = 10.5; + +/// Random seeds stay below this, short enough to read and type +const SEED_RANGE: u32 = 10_000; +/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range +const SEED_MIX: u32 = 2_654_435_761; +/// The most powers of two a resolution factor scales by, either way +const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs(); + +/// "Same as context", or the fraction or multiple a resolution factor stands for +pub(crate) fn factor_label(factor: i8) -> String { + match factor { + 0 => tr("Same as context").to_string(), + negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)), + } +} + +/// The output size `resolution` gives in `texture_set`: one size, or the smallest and largest when its UV tiles differ +pub(crate) fn output_size_label(resolution: &OutputResolution, texture_set: &TextureSet) -> String { + let sizes = || texture_set.uv_tiles.iter().map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution)); + let whole_set = resolution.output_size(texture_set.resolution, texture_set.resolution); + let (smallest, largest) = (sizes().min().unwrap_or(whole_set), sizes().max().unwrap_or(whole_set)); + if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") } +} + +/// A seed different from `current`, from the clock +pub(crate) fn random_seed(current: u32) -> u32 { + let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos()); + let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE; + if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed } +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::ResolutionMode; + + use super::*; + + #[test] + fn the_output_size_follows_each_uv_tile() { + let mut set = TextureSet::new("Tiles", 0, 1024); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 256); + let per_tile = OutputResolution::default(); + let whole_set = OutputResolution { mode: ResolutionMode::TextureSet, ..per_tile }; + + assert_eq!(output_size_label(&per_tile, &set), "256–1024 × 256–1024", "tiles of different sizes show the smallest and the largest"); + assert_eq!(output_size_label(&whole_set, &set), "1024 × 1024", "the texture set's size is the same for every tile"); + } + + #[test] + fn a_set_without_uv_tiles_shows_its_own_size() { + let set = TextureSet::new("Plain", 0, 512); + + assert_eq!(output_size_label(&OutputResolution::default(), &set), "512 × 512"); + } +} diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 5b119c2f..7f6c28b8 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -1,9 +1,15 @@ -//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name +//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name; a fill source's picker adds a second tab with the anchor points it can read -use egui::{Id, Response, Stroke, Ui}; +use egui::{Id, Response, Sense, Stroke, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use texturecraft_engine::core::LayerId; use crate::i18n::tr; +use crate::resource_picker_anchor::ResourcePickerAnchor; +use crate::resource_picker_choice::ResourcePickerChoice; use crate::resource_picker_item::ResourcePickerItem; +use crate::resource_picker_tab::ResourcePickerTab; +use crate::resource_picker_tile::ResourcePickerTile; use crate::shelf; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; @@ -15,6 +21,33 @@ const PICKER_WIDTH: f32 = 320.0; const PICKER_HEIGHT: f32 = 340.0; const CURRENT_OUTLINE_WIDTH: f32 = 1.5; const TILE_ROUNDING: f32 = 3.0; +/// Group headers read as the shelf's section titles, a size above the tile labels +const GROUP_FONT_SIZE: f32 = 13.0; +const GROUP_GAP: f32 = 2.0; + +/// The tab strip along the popup's top edge: its height, the tabs' padding, rounding and the gap between them +const TAB_STRIP_HEIGHT: f32 = 28.0; +const TAB_PADDING: f32 = 10.0; +const TAB_ICON_GAP: f32 = 6.0; +const TAB_ROUNDING: f32 = 4.0; +const TAB_GAP: f32 = 4.0; +const TAB_INSET: f32 = 4.0; +const TAB_FONT_SIZE: f32 = 12.0; +/// How much darker the strip is than the popup body +const TAB_STRIP_DARKEN: f32 = 0.2; + +/// Anchor tiles: the shelf's tile size, the picture's size and place, the anchor badge in its corner and the channel line's size +const ANCHOR_TILE_SIZE: egui::Vec2 = vec2(72.0, 86.0); +const ANCHOR_PICTURE_SIZE: f32 = 56.0; +const ANCHOR_PICTURE_TOP: f32 = 4.0; +const ANCHOR_BADGE_SIZE: f32 = 13.0; +const ANCHOR_BADGE_INSET: f32 = 2.0; +const ANCHOR_BADGE_ICON_SIZE: f32 = 10.0; +/// Space kept clear at each side of an anchor tile's name +const ANCHOR_LABEL_INSET: f32 = 3.0; +const ANCHOR_LABEL_FONT_SIZE: f32 = 9.5; +const ANCHOR_LABEL_GAP: f32 = 3.0; +const ANCHOR_LINE_HEIGHT: f32 = 11.0; /// Opens the picker `popup_id` with an empty, focused search field, or closes it pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { @@ -30,6 +63,11 @@ pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) { }); } +/// Whether picker `popup_id` is open: its tiles are worth gathering only then +pub(crate) fn is_open(ctx: &egui::Context, popup_id: Id) -> bool { + egui::Popup::is_id_open(ctx, popup_id) +} + /// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then) pub(crate) fn show( slot: &Response, @@ -39,12 +77,60 @@ pub(crate) fn show( items: impl FnOnce(&mut Thumbs) -> Vec, preview: impl Fn(&'static str) -> ShelfPreview, ) -> Option<&'static str> { - let ctx = slot.ctx.clone(); - if !egui::Popup::is_id_open(&ctx, popup_id) { + if !is_open(&slot.ctx, popup_id) { return None; } let items = items(thumbs); + let tiles = items + .iter() + .map(|item| { + let id = item.id; + let preview = &preview; + ResourcePickerTile { + key: id.to_string(), + label: item.label.to_string(), + group: item.group, + thumbnail: item.thumbnail.clone(), + image: None, + preview: Box::new(move || preview(id)), + } + }) + .collect(); + match popup(slot, popup_id, thumbs, (current, None), tiles, None, |_, _| None) { + Some(ResourcePickerChoice::Resource(key)) => items.iter().find(|item| item.id == key).map(|item| item.id), + _ => None, + } +} + +/// Draws fill source picker `popup_id` at `slot` while open, with its Resources and Anchor points tabs: returns the tile clicked; `current` is the key of the source shown, `current_anchor` the anchor it reads (its tab opens first) +pub(crate) fn show_sources( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + (current, current_anchor): (Option<&str>, Option), + tiles: Vec>, + anchors: Vec, + picture: impl FnMut(&Ui, LayerId) -> Option, +) -> Option { + if !is_open(&slot.ctx, popup_id) { + return None; + } + + popup(slot, popup_id, thumbs, (current, current_anchor), tiles, Some(anchors), picture) +} + +/// The popup: the tabs when there are anchors to offer, the search field, then the tiles of the shown tab +fn popup( + slot: &Response, + popup_id: Id, + thumbs: &mut Thumbs, + (current, current_anchor): (Option<&str>, Option), + tiles: Vec>, + anchors: Option>, + mut picture: impl FnMut(&Ui, LayerId) -> Option, +) -> Option { + let ctx = slot.ctx.clone(); let mut picked = None; egui::Popup::from_response(slot) .id(popup_id) @@ -55,11 +141,20 @@ pub(crate) fn show( .show(|ui| { ui.set_width(PICKER_WIDTH); let just_opened = ui.data_mut(|data| data.remove_temp::(focus_id(popup_id))).unwrap_or(false); + let tab = match &anchors { + Some(_) => tab_strip(ui, popup_id, just_opened && current_anchor.is_some()), + None => ResourcePickerTab::Resources, + }; let query = search_field(ui, popup_id, just_opened); egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| { // A search that leaves few tiles must not shrink the popup, or egui moves it ui.set_min_height(PICKER_HEIGHT); - picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview); + picked = match (tab, &anchors) { + (ResourcePickerTab::Anchors, Some(anchors)) => { + anchor_grid(ui, anchors, &query, current_anchor, &mut picture).map(ResourcePickerChoice::Anchor) + } + _ => grid(ui, thumbs, &tiles, &query, current, just_opened).map(ResourcePickerChoice::Resource), + }; }); }); @@ -69,6 +164,52 @@ pub(crate) fn show( picked } +/// The tabs on the popup's top edge: a darker strip, the shown tab in the body's color so it joins the list below. Returns the shown tab +fn tab_strip(ui: &mut Ui, popup_id: Id, open_anchors: bool) -> ResourcePickerTab { + let tokens = Tokens::get(ui.ctx()); + let tab_id = popup_id.with("tab"); + let mut shown = if open_anchors { + ResourcePickerTab::Anchors + } else { + ui.data(|data| data.get_temp::(tab_id)).unwrap_or(ResourcePickerTab::Resources) + }; + + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), TAB_STRIP_HEIGHT), Sense::hover()); + let body = ui.visuals().window_fill; + ui.painter().rect_filled(strip, 0.0, body.lerp_to_gamma(egui::Color32::BLACK, TAB_STRIP_DARKEN)); + let font = egui::FontId::proportional(TAB_FONT_SIZE); + let mut left = strip.left() + TAB_INSET; + for (tab, icon, label) in [(ResourcePickerTab::Resources, ic::SQUARES_FOUR, tr("Resources")), (ResourcePickerTab::Anchors, ic::ANCHOR, tr("Anchor points"))] + { + let icon_width = ui.painter().layout_no_wrap(icon.to_string(), font.clone(), tokens.text).size().x; + let label_width = ui.painter().layout_no_wrap(label.to_string(), font.clone(), tokens.text).size().x; + let width = TAB_PADDING * 2.0 + icon_width + TAB_ICON_GAP + label_width; + let rect = egui::Rect::from_min_max(pos2(left, strip.top() + TAB_INSET), pos2(left + width, strip.bottom())); + let response = ui.interact(rect, popup_id.with(label), Sense::click()); + if response.clicked() { + shown = tab; + } + let on = shown == tab; + if on { + ui.painter().rect_filled(rect, egui::CornerRadius { nw: TAB_ROUNDING as u8, ne: TAB_ROUNDING as u8, sw: 0, se: 0 }, body); + } + let color = if on { + tokens.text_strong + } else if response.hovered() { + tokens.text + } else { + tokens.text_dim + }; + let painter = ui.painter(); + painter.text(pos2(rect.left() + TAB_PADDING, rect.center().y), egui::Align2::LEFT_CENTER, icon, font.clone(), color); + painter.text(pos2(rect.left() + TAB_PADDING + icon_width + TAB_ICON_GAP, rect.center().y), egui::Align2::LEFT_CENTER, label, font.clone(), color); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, on, label)); + left += width + TAB_GAP; + } + ui.data_mut(|data| data.insert_temp(tab_id, shown)); + shown +} + /// The search field, focused the frame the picker opens; returns the lowercase query fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default(); @@ -82,32 +223,38 @@ fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String { query } -/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked -fn grid( - ui: &mut Ui, - thumbs: &mut Thumbs, - items: &[ResourcePickerItem], - query: &str, - current: Option<&str>, - reveal_current: bool, - preview: &impl Fn(&'static str) -> ShelfPreview, -) -> Option<&'static str> { - let tk = Tokens::get(ui.ctx()); - let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect(); +/// A group's title over its tiles, as the shelf's section titles +fn group_header(ui: &mut Ui, text: &str) { + let tokens = Tokens::get(ui.ctx()); + ui.add_space(GROUP_GAP); + ui.label(egui::RichText::new(text).size(GROUP_FONT_SIZE).color(tokens.text)); +} + +/// The tiles matching `query` under group headers, `current` outlined; returns the key of the one clicked +fn grid(ui: &mut Ui, thumbs: &mut Thumbs, tiles: &[ResourcePickerTile<'_>], query: &str, current: Option<&str>, reveal_current: bool) -> Option { + let tokens = Tokens::get(ui.ctx()); + let shown: Vec<&ResourcePickerTile<'_>> = tiles.iter().filter(|tile| shelf::matches(query, &[&tile.label, &tile.key])).collect(); let mut picked = None; - for group in shelf::categories(&shown, |item| item.group) { - shelf::header(ui, group); + for group in shelf::categories(&shown, |tile| tile.group) { + group_header(ui, group); shelf::tiles(ui, |ui| { - for item in shown.iter().filter(|item| item.group == group) { - let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None); - if current == Some(item.id) { + for tile in shown.iter().filter(|tile| tile.group == group) { + let response = shelf::tile( + ui, + thumbs, + |ui, thumbs| tile.image.as_ref().map(|image| thumbs.image(ui.ctx(), &tile.label, image)).or_else(|| tile.thumbnail.clone()), + || (tile.preview)(), + &tile.label, + None, + ); + if current == Some(tile.key.as_str()) { if reveal_current { response.scroll_to_me(Some(egui::Align::Center)); } - ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside); + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tokens.accent), egui::StrokeKind::Inside); } if response.clicked() { - picked = Some(item.id); + picked = Some(tile.key.clone()); } } }); @@ -115,6 +262,76 @@ fn grid( picked } +/// The anchor points matching `query` as tiles: a picture of what each reads, an anchor badge, the layer and the channel +fn anchor_grid( + ui: &mut Ui, + anchors: &[ResourcePickerAnchor], + query: &str, + current: Option, + picture: &mut impl FnMut(&Ui, LayerId) -> Option, +) -> Option { + let tokens = Tokens::get(ui.ctx()); + if anchors.is_empty() { + ui.label(egui::RichText::new(tr("No anchor point below this layer.")).color(tokens.text_dim)); + return None; + } + + let shown: Vec<&ResourcePickerAnchor> = anchors.iter().filter(|anchor| shelf::matches(query, &[&anchor.name, tr(anchor.channel)])).collect(); + let mut picked = None; + shelf::tiles(ui, |ui| { + for anchor in shown { + let response = anchor_tile(ui, anchor, picture); + if current == Some(anchor.anchor) { + ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tokens.accent), egui::StrokeKind::Inside); + } + if response.clicked() { + picked = Some(anchor.anchor); + } + } + }); + picked +} + +/// One anchor tile, the shelf tile's size: the picture, the anchor badge in its corner, the layer's name and the channel under it +fn anchor_tile(ui: &mut Ui, anchor: &ResourcePickerAnchor, picture: &mut impl FnMut(&Ui, LayerId) -> Option) -> Response { + let tokens = Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(ANCHOR_TILE_SIZE, Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &anchor.name)); + + // Offscreen tiles must not queue composition of their anchor stacks + if !ui.is_rect_visible(rect) { + return response; + } + + let texture = picture(ui, anchor.anchor); + let painter = ui.painter(); + if response.hovered() { + painter.rect_filled(rect, TILE_ROUNDING, tokens.row_hover); + } + let picture = egui::Rect::from_min_size( + pos2(rect.center().x - ANCHOR_PICTURE_SIZE * 0.5, rect.top() + ANCHOR_PICTURE_TOP), + vec2(ANCHOR_PICTURE_SIZE, ANCHOR_PICTURE_SIZE), + ); + painter.rect_filled(picture, TILE_ROUNDING, tokens.field); + if let Some(texture) = texture { + painter.image(texture, picture, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE); + } + let badge = egui::Rect::from_min_size( + picture.right_bottom() - vec2(ANCHOR_BADGE_SIZE + ANCHOR_BADGE_INSET, ANCHOR_BADGE_SIZE + ANCHOR_BADGE_INSET), + vec2(ANCHOR_BADGE_SIZE, ANCHOR_BADGE_SIZE), + ); + painter.rect_filled(badge, TILE_ROUNDING, tokens.panel); + painter.text(badge.center(), egui::Align2::CENTER_CENTER, ic::ANCHOR, egui::FontId::proportional(ANCHOR_BADGE_ICON_SIZE), tokens.text); + + let font = egui::FontId::proportional(ANCHOR_LABEL_FONT_SIZE); + let width = rect.width() - ANCHOR_LABEL_INSET * 2.0; + let name = crate::widgets::elided(painter, anchor.layer.clone(), ANCHOR_LABEL_FONT_SIZE, tokens.text, width); + let top = picture.bottom() + ANCHOR_LABEL_GAP; + painter.galley(pos2(rect.center().x - name.size().x * 0.5, top), name, tokens.text); + painter.text(pos2(rect.center().x, top + ANCHOR_LINE_HEIGHT), egui::Align2::CENTER_TOP, tr(anchor.channel), font, tokens.text_dim); + response.on_hover_text(&anchor.name) +} + /// Where the picker keeps its search text fn search_id(popup_id: Id) -> Id { popup_id.with("search") diff --git a/crates/ui-egui/src/resource_picker_anchor.rs b/crates/ui-egui/src/resource_picker_anchor.rs new file mode 100644 index 00000000..1b823d62 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_anchor.rs @@ -0,0 +1,12 @@ +//! One tile of a fill source picker's Anchor points tab + +use texturecraft_engine::core::LayerId; + +/// One tile of the Anchor points tab: the anchor, its layer's name and the channel it is read in +pub(crate) struct ResourcePickerAnchor { + pub anchor: LayerId, + /// The anchor's full name ("layer / anchor"), for its tooltip and screen readers + pub name: String, + pub layer: String, + pub channel: &'static str, +} diff --git a/crates/ui-egui/src/resource_picker_choice.rs b/crates/ui-egui/src/resource_picker_choice.rs new file mode 100644 index 00000000..432be0db --- /dev/null +++ b/crates/ui-egui/src/resource_picker_choice.rs @@ -0,0 +1,9 @@ +//! What a fill source picker's click picked + +use texturecraft_engine::core::LayerId; + +/// What a fill source picker's click picked +pub(crate) enum ResourcePickerChoice { + Resource(String), + Anchor(LayerId), +} diff --git a/crates/ui-egui/src/resource_picker_tab.rs b/crates/ui-egui/src/resource_picker_tab.rs new file mode 100644 index 00000000..3b9c6b87 --- /dev/null +++ b/crates/ui-egui/src/resource_picker_tab.rs @@ -0,0 +1,8 @@ +//! The tabs of a fill source picker + +/// The tabs of a fill source picker +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum ResourcePickerTab { + Resources, + Anchors, +} diff --git a/crates/ui-egui/src/resource_picker_tile.rs b/crates/ui-egui/src/resource_picker_tile.rs new file mode 100644 index 00000000..aa601a5d --- /dev/null +++ b/crates/ui-egui/src/resource_picker_tile.rs @@ -0,0 +1,18 @@ +//! One tile of a resource picker's Resources tab + +use std::sync::Arc; + +use egui::TextureHandle; +use texturecraft_engine::compose::ImageRes; + +use crate::shelf_preview::ShelfPreview; + +/// One tile of the Resources tab: the key a pick returns, its label and group, its picture and its hover preview +pub(crate) struct ResourcePickerTile<'a> { + pub key: String, + pub label: String, + pub group: &'static str, + pub thumbnail: Option, + pub image: Option>, + pub preview: Box ShelfPreview + 'a>, +} diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index e84fe738..5ea5ec0b 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -87,6 +87,8 @@ pub(crate) const TABS: [(Tab, &str, &str); 8] = [ pub enum Asset { Material(&'static str), SmartMask(&'static str), + /// A smart mask file the user saved + SavedMask(String), Filter(&'static str), Alpha(&'static str), Library(String), @@ -112,13 +114,18 @@ pub struct ShelfDrag { pub label: String, } -/// Apply `asset` the way a shelf click does: a material above the selection, a smart mask on -/// the selected layer, a filter on the selection (its mask when the mask is selected), an alpha +/// Apply `asset` the way a shelf click does: a simple material becomes the brush's material (no +/// layer), a smart material does nothing (its tile is highlighted), a smart mask on the selected layer, a filter on the selection (its mask when the mask is selected), an alpha /// on the brush, a texture as an image fill. pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { let (cmd, params) = match asset { - Asset::Material(id) => ("material.apply", json!({"material": id})), + Asset::Material(id) if texturecraft_engine::materials::brush_values(id).is_some() => ("tool.material", json!({"material": id})), + + // A smart material (several layers) is no brush material: a click only highlights its tile, dragging adds the layers + Asset::Material(_) => return, + Asset::Library(path) => ("material.load", json!({"path": path})), Asset::SmartMask(id) => ("mask.smart.apply", json!({"name": id})), + Asset::SavedMask(path) => ("mask.smart.apply", json!({"path": path})), Asset::Filter(id) => { let content = crate::dock::targets_content(app); if app.run("effect.add.filter", json!({"filter": id, "target": if content { "content" } else { "mask" }})).is_some() @@ -131,12 +138,26 @@ pub fn apply(app: &mut TextureCraftApp, asset: &Asset) { return; } Asset::Alpha(id) => ("tool.brush", json!({"alpha": {"library": id}})), - Asset::Library(path) => ("material.load", json!({"path": path})), Asset::Texture(name) => ("layer.add.image", json!({"name": name})), }; + app.run(cmd, params); } +/// Apply `asset` the way a drop on a view does: a material becomes a new fill layer (a smart +/// material a folder) at the top of the stack; everything else as a click +fn apply_dropped(app: &mut TextureCraftApp, asset: &Asset) { + match asset { + Asset::Material(id) => { + app.run("material.apply", json!({"material": id, "top": true})); + } + Asset::Library(path) => { + app.run("material.load", json!({"path": path, "top": true})); + } + _ => apply(app, asset), + } +} + /// The selected layer's name when it is a paint layer with nothing painted (in itself or in its /// content paint effects). fn unpainted_paint_layer(app: &TextureCraftApp) -> Option { @@ -193,7 +214,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Alpha(_) => true, Asset::Material(_) | Asset::Library(_) => zone != DropZone::Brush, Asset::Texture(_) => zone == DropZone::View3d, - Asset::SmartMask(_) | Asset::Filter(_) => false, + Asset::SmartMask(_) | Asset::SavedMask(_) | Asset::Filter(_) => false, }; let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { @@ -222,10 +243,10 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response let Some(ts) = set_under_pointer(app, ui, response) else { return }; if app.run("textureSet.select", json!({"ts": ts})).is_some() { - apply(app, asset); + apply_dropped(app, asset); } } - (asset, _) => apply(app, asset), + (asset, _) => apply_dropped(app, asset), } } @@ -251,12 +272,15 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { // Saved smart materials list under the grid rather than as tiles, so they count apart let in_user_library = folder.len() <= 1 && folder.first().is_none_or(|library| library == crate::shelf_entry::USER); - let saved_materials_matching = saved_materials_matching(app, &filter); - if in_user_library && let Some(smart) = TABS.iter().position(|(tab, _, _)| *tab == Tab::Smart).and_then(|smart| counts.get_mut(smart)) { - *smart += saved_materials_matching; - } - if saved_materials_matching > 0 && crate::shelf_tabs::shows(picked_tab, Tab::Smart) { - applicable.push(vec![crate::shelf_entry::USER.to_string()]); + let saved_materials_matching = saved_matching(app, &filter, false); + let saved_masks_matching = saved_matching(app, &filter, true); + for (tab, saved) in [(Tab::Smart, saved_materials_matching), (Tab::Masks, saved_masks_matching)] { + if in_user_library && let Some(count) = TABS.iter().position(|(shown, _, _)| *shown == tab).and_then(|position| counts.get_mut(position)) { + *count += saved; + } + if saved > 0 && crate::shelf_tabs::shows(picked_tab, tab) { + applicable.push(vec![crate::shelf_entry::USER.to_string()]); + } } crate::shelf_folders::breadcrumb(app, ui, &paths); @@ -288,14 +312,15 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { // Saved smart materials are files in the user's library, without folders of their own let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart); - grid(app, ui, &entries, grid_rect.height(), saved_materials, show_user_brushes, &filter); + let saved_masks = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Masks); + grid(app, ui, &entries, grid_rect.height(), [saved_materials, saved_masks], show_user_brushes, &filter); }); ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui)); drag_preview(&ctx); } -/// The tiles of `entries` in a scroll area `height` high, then user assets when selected -fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: f32, saved_materials: bool, show_user_brushes: bool, filter: &str) { +/// The tiles of `entries` in a scroll area `height` high, then user brushes, saved smart materials and saved smart masks when selected +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: f32, saved: [bool; 2], show_user_brushes: bool, filter: &str) { let ctx = ui.ctx().clone(); let view = app.ui.shelf_view; let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); @@ -315,16 +340,23 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: if show_user_brushes { user_brushes(app, ui, filter); } - if saved_materials { - library(app, ui, filter); + for (shown, masks) in saved.into_iter().zip([false, true]) { + if shown { + library(app, ui, filter, masks); + } } }); }); } -/// How many of the user's saved smart materials match `filter` (none until the library is read) -fn saved_materials_matching(app: &TextureCraftApp, filter: &str) -> usize { - app.library.iter().flatten().filter(|path| matches(filter, &[saved_material_name(path)])).count() +/// Whether a library file is a saved smart mask (not a smart material) +fn is_saved_mask(path: &std::path::Path) -> bool { + path.extension().is_some_and(|extension| extension == texturecraft_engine::smart_masks::SMART_MASK_EXT) +} + +/// How many of the user's saved smart masks (`masks`) or smart materials match `filter` (none until the library is read) +fn saved_matching(app: &TextureCraftApp, filter: &str, masks: bool) -> usize { + app.library.iter().flatten().filter(|path| is_saved_mask(path) == masks && matches(filter, &[saved_material_name(path)])).count() } /// The search field: a live filter on names (and categories) with a clear button while it has text @@ -389,9 +421,12 @@ fn scan_library(app: &mut TextureCraftApp) { return; } - let saved_material = |path: &std::path::PathBuf| path.extension().is_some_and(|extension| extension == "tcmat" || extension == MCMAT_EXT); + let saved_asset = |path: &std::path::PathBuf| { + 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_material).collect()).unwrap_or_default(); + std::fs::read_dir(crate::library_dir()).map(|dir| dir.flatten().map(|entry| entry.path()).filter(saved_asset).collect()).unwrap_or_default(); files.sort(); app.library = Some(files); } @@ -406,34 +441,44 @@ fn saved_material_name(path: &std::path::Path) -> &str { /// The user's saved smart materials matching `filter`, as rows under the grid #[cfg(not(target_arch = "wasm32"))] -fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { +fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { let tokens = Tokens::get(ui.ctx()); - let files = app.library.clone().unwrap_or_default(); + let files: Vec<_> = app.library.clone().unwrap_or_default().into_iter().filter(|path| is_saved_mask(path) == masks).collect(); let shown: Vec<_> = files.iter().filter(|path| matches(filter, &[saved_material_name(path)])).collect(); if !filter.is_empty() && shown.is_empty() { return; } ui.horizontal(|ui| { - header(ui, tr("My smart materials")); + header(ui, if masks { tr("My smart masks") } else { tr("My smart materials") }); if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() { app.library = None; } }); if files.is_empty() { - ui.label(RichText::new(tr("Right-click a layer > Create smart material")).size(HINT_SIZE).color(tokens.text_dim)); + let hint = if masks { tr("Right-click a layer > Create smart mask") } else { tr("Right-click a layer > Create smart material") }; + ui.label(RichText::new(hint).size(HINT_SIZE).color(tokens.text_dim)); } for path in shown { - let (label, asset) = (saved_material_name(path).to_string(), Asset::Library(path.display().to_string())); + let (label, location) = (saved_material_name(path).to_string(), path.display().to_string()); + let asset = if masks { Asset::SavedMask(location) } else { Asset::Library(location) }; // MaterialCraft materials (sent from MaterialCraft) show a graph - let glyph = if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { ic::GRAPH } else { ic::SPHERE }; + let glyph = if masks { + ic::CIRCLE_HALF + } else if path.extension().is_some_and(|extension| extension == MCMAT_EXT) { + ic::GRAPH + } else { + ic::SPHERE + }; let response = ui.add(egui::Button::selectable(false, format!("{glyph} {label}")).sense(Sense::click_and_drag())).on_hover_ui(|ui| { - ui.label(crate::i18n::trf( - "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)", - &[("file", &path.display())], - )); + let hover = if masks { + "{file}: replace the selected layer's mask (or drag it onto a layer in the stack)" + } else { + "{file}: add above the selected layer (or drag it into the layer stack or onto the viewport)" + }; + ui.label(crate::i18n::trf(hover, &[("file", &path.display())])); }); if response.drag_started() { response.dnd_set_drag_payload(ShelfDrag { asset: asset.clone(), label }); @@ -446,7 +491,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) { } #[cfg(target_arch = "wasm32")] -fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {} +fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {} /// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { @@ -463,7 +508,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry let response = tile_in_view( ui, &mut app.thumbs, - texture.as_ref(), + |_, _| texture, |thumbs| match entry { ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)), _ => entry.preview(session), @@ -509,7 +554,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry pub(crate) fn tile( ui: &mut Ui, thumbs: &mut Thumbs, - texture: Option<&egui::TextureHandle>, + texture: impl FnOnce(&Ui, &mut Thumbs) -> Option, preview: impl FnOnce() -> ShelfPreview, label: &str, drag: Option<&Asset>, @@ -521,7 +566,7 @@ pub(crate) fn tile( fn tile_in_view( ui: &mut Ui, thumbs: &mut Thumbs, - texture: Option<&egui::TextureHandle>, + texture: impl FnOnce(&Ui, &mut Thumbs) -> Option, preview: impl FnOnce(&mut Thumbs) -> Option, label: &str, drag: Option<&Asset>, @@ -531,6 +576,7 @@ fn tile_in_view( let sense = if drag.is_some() { Sense::click_and_drag() } else { Sense::click() }; let (rect, response) = ui.allocate_exact_size(view.tile_size(ui.available_width()), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let texture = if ui.is_rect_visible(rect) { texture(ui, thumbs) } else { None }; if let Some(asset) = drag && response.drag_started() { @@ -543,7 +589,7 @@ fn tile_in_view( } let image_rect = view.thumbnail_rect(rect); - thumbnail(painter, texture, image_rect, &tokens); + thumbnail(painter, texture.as_ref(), image_rect, &tokens); if view.name_beside() { let left = image_rect.right() + crate::shelf_view::LIST_NAME_GAP; let galley = painter.layout_job(one_line(label, rect.right() - left - LABEL_MARGIN, tokens.text)); @@ -554,7 +600,7 @@ fn tile_in_view( } let big = if response.hovered() { preview(thumbs).and_then(|preview| big_preview(ui, thumbs, || preview)) } else { None }; - response.on_hover_ui(|ui| hover_preview(ui, texture, big.as_ref(), label)) + response.on_hover_ui(|ui| hover_preview(ui, texture.as_ref(), big.as_ref(), label)) } /// Three light, dark-rimmed dots at the thumbnail's bottom-right corner: the asset includes randomness diff --git a/crates/ui-egui/src/smart_mask_menu.rs b/crates/ui-egui/src/smart_mask_menu.rs new file mode 100644 index 00000000..b41be1e8 --- /dev/null +++ b/crates/ui-egui/src/smart_mask_menu.rs @@ -0,0 +1,61 @@ +//! "Create smart mask" in a layer's context menu: the mask goes to the user library as a `.tcmask` file the shelf lists + +use serde_json::json; +use texturecraft_engine::core::Layer; +use texturecraft_engine::smart_masks::SMART_MASK_EXT; + +use crate::TextureCraftApp; +use crate::i18n::trf; + +/// Save `layer`'s mask into `dir` under the layer's name (a number is added when the name is taken, so no earlier file is overwritten) +pub(crate) fn save(app: &mut TextureCraftApp, layer: &Layer, dir: &std::path::Path) { + let stem = texturecraft_engine::formats::sanitize_resource_name(&layer.name); + let mut file = dir.join(format!("{stem}.{SMART_MASK_EXT}")); + let mut number = 2; + while file.exists() { + file = dir.join(format!("{stem} {number}.{SMART_MASK_EXT}")); + number += 1; + } + + if let Some(saved) = app.run("mask.smart.create", json!({"layer": layer.id.0, "path": file.display().to_string(), "name": layer.name})) { + let path = saved.get("path").and_then(|path| path.as_str()).unwrap_or_default().to_string(); + app.toast(trf("Smart mask saved to {path}", &[("path", &path)]), false); + app.library = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn app() -> (TextureCraftApp, u64) { + let mut session = texturecraft_engine::sample_session(128, 16).unwrap(); + let layer = texturecraft_engine::execute(&mut session, "layer.add.fill", &serde_json::Value::Null).unwrap()["layer"].as_u64().unwrap(); + texturecraft_engine::execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap(); + texturecraft_engine::execute(&mut session, "effect.add.generator", &json!({"layer": layer, "generator": "edgeWear"})).unwrap(); + (TextureCraftApp::new(&eframe::CreationContext::_new_kittest(egui::Context::default()), session), layer) + } + + #[test] + fn saves_the_mask_to_the_library_and_never_over_an_earlier_one() { + let dir = std::env::temp_dir().join(format!("tc-smart-mask-menu-{}", std::process::id())); + let (mut app, id) = app(); + let layer = app.session.doc.project.layer(texturecraft_engine::core::LayerId(id)).unwrap().clone(); + app.library = Some(Vec::new()); + + save(&mut app, &layer, &dir); + save(&mut app, &layer, &dir); + + let stem = texturecraft_engine::formats::sanitize_resource_name(&layer.name); + let first = dir.join(format!("{stem}.{SMART_MASK_EXT}")); + let second = dir.join(format!("{stem} 2.{SMART_MASK_EXT}")); + let (first_saved, second_saved) = (first.exists(), second.exists()); + let bytes = std::fs::read(&first).unwrap_or_default(); + let _ = std::fs::remove_dir_all(&dir); + + assert!(first_saved && second_saved, "the second save gets its own file"); + assert!(texturecraft_engine::formats::load_project_bytes(&bytes).is_ok(), "the file is a project container"); + assert!(app.library.is_none(), "the shelf rescans the library"); + assert_eq!(app.toasts.len(), 2, "each save says where it went"); + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b31705b..43ba3656 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -1,7 +1,7 @@ //! UI state (serde, so the control channel can read and drive it). use serde::{Deserialize, Serialize}; -use texturecraft_engine::core::{BakedMap, Channel, NormalFormat}; +use texturecraft_engine::core::{BakedMap, Channel, ChannelBlend, NormalFormat}; use crate::docking::Dock; use crate::keymap::Keymap; @@ -10,9 +10,13 @@ use crate::shelf_panes::ShelfPanes; use crate::shelf_view::ShelfView; mod import_resources; +mod import_row; mod project_config; -pub use import_resources::{ImportResources, ImportRow, ImportTarget, ResourceUsage}; +mod resource_usage; +pub use import_resources::ImportResources; +pub use import_row::ImportRow; pub use project_config::ProjectConfig; +pub use resource_usage::ResourceUsage; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Mode { @@ -48,7 +52,7 @@ pub struct RenderUi { impl Default for RenderUi { fn default() -> Self { - // The web traces on one thread: fewer bounces keep it interactive. + // The web traces on one thread: fewer bounces keep it interactive RenderUi { max_samples: 256, bounces: if cfg!(target_arch = "wasm32") { 3 } else { 6 }, denoise: true, cpu: false } } } @@ -81,9 +85,6 @@ pub struct Windows { /// Browser File › Export Mesh: the download format choice. #[serde(default)] pub export_mesh: bool, - /// The start window: new, open, recent projects (the app opens it at launch). - #[serde(skip)] - pub start: bool, /// Edit > Project Configuration: what is chosen so far, applied by OK. #[serde(skip)] pub project_config: Option, @@ -93,14 +94,19 @@ pub struct Windows { /// What waits on the unsaved-changes dialog: save, don't save or cancel. #[serde(skip)] pub unsaved: Option, + /// Window ▸ Reset UI is waiting for its answer. + #[serde(skip)] + pub confirm_reset_ui: bool, } /// An action that replaces or ends the project, held while the project has unsaved changes. #[derive(Clone, Debug, PartialEq)] pub enum Unsaved { Quit, - /// A menu command (New project, Open, Close, Open sample project). + /// A menu command (Open, Close, Open sample project). Command(String), + /// Create from the New project form that requested confirmation. + CreateProject(u64), /// Open this project or mesh file. #[cfg(not(target_arch = "wasm32"))] Open(String), @@ -127,8 +133,6 @@ pub struct Prefs { pub accent: crate::theme::Accent, /// The system draws the window's title bar instead of TextureCraft (desktop; read at startup). pub system_title_bar: bool, - /// Show the start window at launch. - pub start_window: bool, /// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at /// startup). Empty or relative: `Documents/TextureCraft`. pub data_folder: String, @@ -151,7 +155,6 @@ impl Default for Prefs { brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), system_title_bar: false, - start_window: true, data_folder: String::new(), reserved_cores: 1, project_open_limit_gib: texturecraft_engine::formats::DEFAULT_PROJECT_OPEN_LIMIT_GIB, @@ -177,6 +180,12 @@ pub struct NewProject { /// The browser's copy of the chosen mesh file, read when Create is pressed. #[serde(skip)] pub file_bytes: Option>>, + /// The active form opening, used to reject late file picker answers. + #[serde(skip)] + pub opening_id: u64, + /// The latest mesh pick requested by this form. + #[serde(skip)] + pub mesh_request_id: u64, /// Use UV Tile workflow: Some(true) makes UV tile (UDIM) texture sets; otherwise each set paints tile 1001. pub uv_tiles: Option, /// Project template name (built-in or the user's). @@ -204,12 +213,23 @@ fn import_cameras_default() -> bool { true } +impl NewProject { + pub(crate) fn clear_mesh(&mut self) { + self.file = None; + self.file_bytes = None; + self.opening_id = 0; + self.mesh_request_id = 0; + } +} + impl Default for NewProject { fn default() -> Self { NewProject { resolution: 1024, file: None, file_bytes: None, + opening_id: 0, + mesh_request_id: 0, uv_tiles: None, template: default_template(), normal_format: None, @@ -248,6 +268,9 @@ pub struct ExportUi { /// Output templates tab: the new name while renaming the selected preset. #[serde(skip)] pub renaming: Option, + /// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit). + #[serde(skip)] + pub ask: Option, } impl Default for ExportUi { @@ -266,6 +289,7 @@ impl Default for ExportUi { tab: 0, draft: None, renaming: None, + ask: None, } } } @@ -285,11 +309,19 @@ fn default_export_dir() -> String { fn default_split_ratio() -> f32 { 0.5 } + +/// Settings that start on, for saved states that predate them +fn default_true() -> bool { + true +} /// The bake layout's version: saved bake docks from an older one load as `Dock::for_baking` const BAKE_LAYOUT_VERSION: u32 = 2; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UiState { + /// Layer menu ▸ Blending options ▸ Copy: each channel's blend mode and opacity of the copied layer. + #[serde(skip)] + pub blend_clipboard: Option>, pub mode: Mode, pub layout: ViewLayout, /// The 3D view's share of the viewport width in the split layout @@ -345,6 +377,9 @@ pub struct UiState { /// Show the mesh wireframe over the 3D view. #[serde(default)] pub wireframe_3d: bool, + /// Show the orbit, pan and zoom buttons in the corner of the 3D and 2D views (Viewport menu) + #[serde(default = "default_true")] + pub nav_buttons: bool, #[serde(default)] pub render: RenderUi, #[serde(default)] @@ -363,9 +398,18 @@ pub struct UiState { /// How the 3D view shows symmetry #[serde(default)] pub symmetry: crate::symmetry::SymmetryDisplay, + /// The brush, symmetry and other tool settings of the last session, which the next one starts with + #[serde(default)] + pub tool_settings: texturecraft_engine::ToolSettings, /// The Baking Visualization panel's settings, under a key of their own since the reference defaults: older saved ones start over #[serde(default, rename = "baking_visualization")] pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, + /// Panel arrangements saved under a name (Window > Layouts), in the order they were saved + #[serde(default)] + pub named_layouts: Vec, + /// The save, replace or manage dialog of the named layouts + #[serde(skip)] + pub layout_dialog: Option, } impl UiState { @@ -391,14 +435,31 @@ impl UiState { self.bake_layout_version = BAKE_LAYOUT_VERSION; } + /// Put the panels, tabs and floating panels of both modes back to their defaults; the view split, + /// zoom, wireframes, symmetry display, mode and every setting stay as they are + pub fn reset_panel_layout(&mut self) { + let (painting, baking) = (Dock::default(), Dock::for_baking()); + (self.dock, self.inactive_mode_dock) = if self.dock_is_baking { (baking, painting) } else { (painting, baking) }; + self.bake_layout_version = BAKE_LAYOUT_VERSION; + self.rail_panel = None; + } + /// Take `layout`'s panels, windows and view settings, keeping this state's dialogs, settings, files and shelf query pub fn adopt_layout(&mut self, layout: UiState) { let keep = std::mem::replace(self, layout); self.new_project = keep.new_project; + if !self.windows.new_project { + self.new_project.clear_mesh(); + } + self.export = keep.export; self.recent = keep.recent; self.prefs = keep.prefs; + self.nav_buttons = keep.nav_buttons; self.keymap = keep.keymap; + self.tool_settings = keep.tool_settings; + self.named_layouts = keep.named_layouts; + self.layout_dialog = None; self.rename = None; // The shelf's search, type and folder are one query, and saved searches are the user's own @@ -426,6 +487,7 @@ impl Default for UiState { uv_zoom: 1.0, uv_pan: [0.0, 0.0], layer_channel: Channel::BaseColor, + blend_clipboard: None, shelf_filter: String::new(), shelf_tab: 0, shelf_path: Vec::new(), @@ -438,6 +500,7 @@ impl Default for UiState { new_project: NewProject::default(), uv_wireframe: true, wireframe_3d: false, + nav_buttons: true, render: RenderUi::default(), prefs: Prefs::default(), export: ExportUi::default(), @@ -445,7 +508,10 @@ impl Default for UiState { keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), symmetry: crate::symmetry::SymmetryDisplay::default(), + tool_settings: Default::default(), bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), + named_layouts: Vec::new(), + layout_dialog: None, } } } @@ -470,6 +536,29 @@ mod tests { assert_eq!(ui.keymap.get("file.save").map(String::as_str), Some("F5")); } + #[test] + fn resetting_the_panel_layout_restores_both_docks_and_keeps_the_rest() { + for baking in [false, true] { + let mode = if baking { Mode::Baking } else { Mode::Painting }; + let mut ui = UiState { mode, ..UiState::default() }; + ui.sync_mode_dock(); + ui.dock.close(crate::docking::Panel::Log); + ui.inactive_mode_dock.close(crate::docking::Panel::Log); + ui.layout = ViewLayout::Only3D; + ui.uv_zoom = 3.0; + ui.wireframe_3d = true; + ui.recent = vec!["a.tcraft".into()]; + + ui.reset_panel_layout(); + + let mut fresh = UiState { mode, ..UiState::default() }; + fresh.sync_mode_dock(); + assert_eq!((&ui.dock, &ui.inactive_mode_dock), (&fresh.dock, &fresh.inactive_mode_dock), "baking: {baking}"); + assert_eq!((ui.layout, ui.uv_zoom, ui.wireframe_3d, ui.mode), (ViewLayout::Only3D, 3.0, true, mode)); + assert_eq!(ui.recent, vec!["a.tcraft".to_string()]); + } + } + #[test] fn adopting_a_layout_keeps_the_shelf_query_and_saved_searches() { let saved = crate::saved_search::SavedSearch { name: "rust".into(), filter: "rust".into(), tab: 2, path: vec!["starter".into()] }; diff --git a/crates/ui-egui/src/state/import_resources.rs b/crates/ui-egui/src/state/import_resources.rs index a3654d0e..583e39c1 100644 --- a/crates/ui-egui/src/state/import_resources.rs +++ b/crates/ui-egui/src/state/import_resources.rs @@ -1,64 +1,6 @@ use std::collections::BTreeSet; -use std::path::PathBuf; -/// What an imported resource is for -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum ResourceUsage { - /// Imported as an image resource, nothing more - #[default] - Undefined, - /// An image resource that also becomes the brush alpha - Alpha, - /// Color lookup tables (not available yet) - ColorLut, - /// An image resource that also lights the scene - Environment, - /// Post effect resources (not available yet) - PostFx, - /// An image resource for fills and stencils - Texture, -} - -impl ResourceUsage { - /// The usages in the dropdown's order - pub const ALL: [ResourceUsage; 6] = [Self::Undefined, Self::Alpha, Self::ColorLut, Self::Environment, Self::PostFx, Self::Texture]; - - /// The name shown in the dropdowns (the same in every language, as in the reference) - pub fn name(self) -> &'static str { - match self { - Self::Undefined => "undefined", - Self::Alpha => "alpha", - Self::ColorLut => "colorlut", - Self::Environment => "environment", - Self::PostFx => "postfx", - Self::Texture => "texture", - } - } - - /// Whether the app can do something with resources of this usage - pub fn available(self) -> bool { - !matches!(self, Self::ColorLut | Self::PostFx) - } -} - -/// Where the resources go -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum ImportTarget { - /// The open project's resources - #[default] - Session, - /// The user's asset library (not available for images yet) - Library, -} - -/// One file waiting in the window -#[derive(Clone, Debug, PartialEq)] -pub struct ImportRow { - pub id: u64, - pub path: PathBuf, - pub prefix: String, - pub usage: ResourceUsage, -} +use super::{ImportRow, ResourceUsage}; /// File > Import resources: the files added so far, imported by the Import button #[derive(Clone, Debug, PartialEq, Default)] @@ -70,7 +12,6 @@ pub struct ImportResources { pub anchor: Option, /// The usage the list is narrowed to (None: all) pub filter: Option, - pub target: ImportTarget, /// Whether Enter requested the import in the next frame pub confirm: bool, /// The project that was open when this window opened diff --git a/crates/ui-egui/src/state/import_row.rs b/crates/ui-egui/src/state/import_row.rs new file mode 100644 index 00000000..305548da --- /dev/null +++ b/crates/ui-egui/src/state/import_row.rs @@ -0,0 +1,12 @@ +use std::path::PathBuf; + +use super::ResourceUsage; + +/// One file waiting in the window +#[derive(Clone, Debug, PartialEq)] +pub struct ImportRow { + pub id: u64, + pub path: PathBuf, + pub prefix: String, + pub usage: ResourceUsage, +} diff --git a/crates/ui-egui/src/state/resource_usage.rs b/crates/ui-egui/src/state/resource_usage.rs new file mode 100644 index 00000000..5cf40d3b --- /dev/null +++ b/crates/ui-egui/src/state/resource_usage.rs @@ -0,0 +1,39 @@ +/// What an imported resource is for +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum ResourceUsage { + /// Imported as an image resource, nothing more + #[default] + Undefined, + /// An image resource that also becomes the brush alpha + Alpha, + /// Color lookup tables (not available yet) + ColorLut, + /// An image resource that also lights the scene + Environment, + /// Post effect resources (not available yet) + PostFx, + /// An image resource for fills and stencils + Texture, +} + +impl ResourceUsage { + /// The usages in the dropdown's order + pub const ALL: [ResourceUsage; 6] = [Self::Undefined, Self::Alpha, Self::ColorLut, Self::Environment, Self::PostFx, Self::Texture]; + + /// The name shown in the dropdowns (the same in every language, as in the reference) + pub fn name(self) -> &'static str { + match self { + Self::Undefined => "undefined", + Self::Alpha => "alpha", + Self::ColorLut => "colorlut", + Self::Environment => "environment", + Self::PostFx => "postfx", + Self::Texture => "texture", + } + } + + /// Whether the app can do something with resources of this usage + pub fn available(self) -> bool { + !matches!(self, Self::ColorLut | Self::PostFx) + } +} diff --git a/crates/ui-egui/src/surface_paint_point.rs b/crates/ui-egui/src/surface_paint_point.rs new file mode 100644 index 00000000..ef3a5869 --- /dev/null +++ b/crates/ui-egui/src/surface_paint_point.rs @@ -0,0 +1,23 @@ +use texturecraft_engine::{Session, geom::glam::Vec3}; + +/// A 3D stroke's endpoint as a point on the model, scoped to its project, mesh and texture set +/// +/// Shift+click projects it to the current view, so the line starts at the same spot on the model +/// after the camera moved. A point the model now hides still starts the line at its projected position. +#[derive(Clone, Copy, Debug)] +pub struct SurfacePaintPoint { + mesh_id: u64, + texture_set: usize, + pos: Vec3, +} + +impl SurfacePaintPoint { + pub(crate) fn new(session: &Session, pos: Vec3) -> Self { + Self { mesh_id: session.mesh_id, texture_set: session.ts(), pos } + } + + /// The point in model space, or `None` once the mesh or texture set is not the one it was made on + pub fn position_for(self, session: &Session) -> Option { + (self.mesh_id == session.mesh_id && self.texture_set == session.ts()).then_some(self.pos) + } +} diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index a3964660..363ddd37 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -1,5 +1,6 @@ //! Symmetry: the toolbar toggle and settings popup, and what the 3D view draws for it +mod plane_pick; mod ribbons; mod settings_popup; mod symmetry_display; @@ -14,6 +15,7 @@ use egui_phosphor::regular as ic; use texturecraft_engine::Tool; use texturecraft_engine::paint::Symmetry; +pub(crate) use plane_pick::input as plane_pick_input; pub use symmetry_display::SymmetryDisplay; pub(crate) use view_overlay::{manipulator_hovered, manipulator_input, overlay, scene_overlay}; @@ -24,9 +26,9 @@ use crate::widgets::{icon_badge_dropdown_button, icon_button}; /// Radial copies a brush gets when radial symmetry is enabled const DEFAULT_RADIAL_COUNT: u8 = 6; -/// Whether `tool` paints symmetry copies +/// Whether `tool` paints or fills symmetry copies pub(crate) fn applies_to(tool: Tool) -> bool { - matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path) + matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path | Tool::PolygonFill) } /// Whether the 3D view shows symmetry now: not while the active tool can't act on the selection diff --git a/crates/ui-egui/src/symmetry/plane_pick.rs b/crates/ui-egui/src/symmetry/plane_pick.rs new file mode 100644 index 00000000..4dfcde97 --- /dev/null +++ b/crates/ui-egui/src/symmetry/plane_pick.rs @@ -0,0 +1,86 @@ +//! Placing the symmetry planes by clicking the model: the next click sets the offsets so the planes pass through the clicked point + +use egui::{Align2, Color32, CursorIcon, FontId, PointerButton, Response, Ui, pos2}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; + +use super::movable_axes; +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// Distance from the view's top edge to the hint (points) +const HINT_INSET: f32 = 12.0; +const HINT_SIZE: f32 = 14.0; + +/// The offsets that put the movable planes and axes through `point`, the others unchanged, kept inside the mesh bounds like the sliders +pub(crate) fn offsets_through(symmetry: &texturecraft_engine::paint::Symmetry, bounds: (Vec3, Vec3), point: Vec3) -> [f32; 3] { + let center = (bounds.0 + bounds.1) * 0.5; + let half_extent = (bounds.1 - bounds.0) * 0.5; + let movable = movable_axes(symmetry); + let mut offset = symmetry.offset; + for axis in 0..3 { + if movable[axis] { + offset[axis] = (point[axis] - center[axis]).clamp(-half_extent[axis], half_extent[axis]); + } + } + + offset +} + +/// While picking: a click on the model places the planes there and ends picking, and nothing paints. +/// Returns whether picking owns the view's input this frame. +pub(crate) fn input(app: &mut TextureCraftApp, ui: &Ui, response: &Response, rect: egui::Rect) -> bool { + if !app.picking_symmetry_plane { + return false; + } + + // Picking is only for the Painting mode (the settings popup lives there) + if app.ui.mode != crate::state::Mode::Painting { + app.picking_symmetry_plane = false; + return false; + } + + if !movable_axes(&app.session.tool.brush.symmetry).contains(&true) { + app.picking_symmetry_plane = false; + return false; + } + + ui.ctx().set_cursor_icon(CursorIcon::Crosshair); + ui.painter_at(rect).text( + pos2(rect.center().x, rect.top() + HINT_INSET), + Align2::CENTER_TOP, + tr("Click the model to place the symmetry plane there (Esc cancels)"), + FontId::proportional(HINT_SIZE), + Color32::WHITE, + ); + + if response.clicked_by(PointerButton::Primary) + && !ui.input(|input| input.modifiers.alt) + && let Some(pointer) = response.interact_pointer_pos() + { + let local = Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); + if let Some(hit) = app.session.pick(local, app.session.viewport) { + let offset = offsets_through(&app.session.tool.brush.symmetry, app.session.mesh.bounds(), hit.pos); + app.run("tool.brush", serde_json::json!({"symmetryOffset": offset})); + app.picking_symmetry_plane = false; + } + } + + true +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::paint::Symmetry; + + use super::*; + + #[test] + fn only_the_movable_axes_move_and_stay_inside_the_mesh() { + let bounds = (Vec3::new(0.0, 0.0, 0.0), Vec3::new(2.0, 4.0, 6.0)); + let symmetry = Symmetry { x: true, z: true, offset: [0.0, 0.25, 0.0], ..Symmetry::default() }; + + let offset = offsets_through(&symmetry, bounds, Vec3::new(1.5, 3.0, 9.0)); + + assert_eq!(offset, [0.5, 0.25, 3.0], "x is picked minus center, y is untouched, z is clamped to the mesh"); + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs index 4d11e82a..b92e37cd 100644 --- a/crates/ui-egui/src/symmetry/settings_popup.rs +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -80,6 +80,23 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { for (axis, name) in AXIS_NAMES.into_iter().enumerate() { ui.add_enabled_ui(movable[axis], |ui| slider(ui, name, &mut symmetry.offset[axis], -half_extent[axis]..=half_extent[axis], 2)); } + + // One button per axis: the plane goes back to the middle of the model + ui.horizontal(|ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (axis, name) in AXIS_NAMES.into_iter().enumerate() { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + let label = format!("{} {name}", tr("Center")); + if ui.add_enabled(movable[axis], egui::Button::new(label)).clicked() { + symmetry.offset[axis] = 0.0; + } + }); + } + }); + let picking = app.picking_symmetry_plane; + if ui.add_enabled(movable.contains(&true), egui::Button::new(tr("Pick point")).selected(picking)).clicked() { + app.picking_symmetry_plane = !picking; + } }); section(ui, "symmetry_display", tr("Display"), true, |ui| { diff --git a/crates/ui-egui/src/tile_edits.rs b/crates/ui-egui/src/tile_edits.rs new file mode 100644 index 00000000..e05c33a9 --- /dev/null +++ b/crates/ui-egui/src/tile_edits.rs @@ -0,0 +1,85 @@ +//! The edits one frame of the Tile Generator's controls makes + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::angle_dial::angle_dial; +use crate::gray_slider::gray_slider; +use crate::i18n::tr; +use crate::widgets::{combo, slider_edit}; + +/// The edits one frame of the Tile Generator's controls makes: settings by command name, and whether they continue a drag +#[derive(Default)] +pub(crate) struct TileEdits { + pub settings: serde_json::Map, + pub merge: Option, +} + +impl TileEdits { + pub(crate) fn set(&mut self, key: &str, value: Value, merge: bool) { + self.settings.insert(key.to_string(), value); + self.merge = Some(self.merge.unwrap_or(true) && merge); + } + + pub(crate) fn slider(&mut self, ui: &mut Ui, label: &str, key: &str, mut value: f32, range: std::ops::RangeInclusive) { + if let Some(merge) = slider_edit(ui, label, &mut value, range, 2) { + self.set(key, json!(value), merge); + } + } + + pub(crate) fn count(&mut self, ui: &mut Ui, label: &str, key: &str, value: u32, range: std::ops::RangeInclusive) { + let mut shown = value as f32; + if let Some(merge) = slider_edit(ui, label, &mut shown, *range.start() as f32..=*range.end() as f32, 0) { + self.set(key, json!(shown.round() as u32), merge); + } + } + + /// Two sliders for one `[horizontal, vertical]` setting + pub(crate) fn pair(&mut self, ui: &mut Ui, labels: [&str; 2], key: &str, mut value: [f32; 2], range: std::ops::RangeInclusive) { + let mut merge = None; + for (label, component) in labels.into_iter().zip(value.iter_mut()) { + merge = merge.or(slider_edit(ui, label, component, range.clone(), 2)); + } + if let Some(merge) = merge { + self.set(key, json!(value), merge); + } + } + + pub(crate) fn check(&mut self, ui: &mut Ui, label: &str, key: &str, mut value: bool) { + if ui.checkbox(&mut value, label).changed() { + self.set(key, json!(value), false); + } + } + + pub(crate) fn angle(&mut self, ui: &mut Ui, label: &str, key: &str, mut degrees: f32) { + if let Some(merge) = angle_dial(ui, label, &mut degrees) { + self.set(key, json!(degrees), merge); + } + } + + /// A gray from black to white with a button that inverts it, as the reference's color rows + pub(crate) fn gray(&mut self, ui: &mut Ui, label: &str, key: &str, mut value: f32) { + if let Some(merge) = gray_slider(ui, label, &mut value) { + self.set(key, json!(value), merge); + } + } + + /// A menu of `choices`, sent by their saved names + pub(crate) fn choice( + &mut self, + ui: &mut Ui, + label: &str, + key: &str, + current: T, + choices: &[T], + name: fn(T) -> &'static str, + ) { + combo(ui, label, tr(name(current)), |ui| { + for choice in choices { + if ui.selectable_label(*choice == current, tr(name(*choice))).clicked() { + self.set(key, json!(format!("{choice:?}")), false); + } + } + }); + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index ce998917..76a5c742 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -76,27 +76,31 @@ 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, two separators and the five gaps between them - 2.0 * button_size + 2.0 * icon_dropdown_button_width(button_size) + 2.0 * BAR_SEPARATOR_WIDTH + 5.0 * spacing + // 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 } -/// View buttons in a right-to-left layout, with the screenshot button at the end +/// View buttons in a right-to-left layout: the layout, then the camera type, then the screenshot and UV checker fn view_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; - if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { - app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); - } + // Only the layout works without a project: the others act on it + let project_open = app.session.project_open; + + // Right-to-left: the UV checker is added first and sits rightmost + ui.add_enabled_ui(project_open, |ui| { + let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; + if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { + let mode = if checker { "material" } else { "uvChecker" }; + app.run("viewport.view", json!({"mode": mode})); + } + if icon_button(ui, ic::CAMERA, tr("Screenshot of the viewport"), false, button_size).clicked() { + app.toast(tr("Use the control channel or `texturecraft-cli render` for screenshots"), false); + } + }); ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - projection_dropdown(app, ui); + ui.add_enabled_ui(project_open, |ui| projection_dropdown(app, ui)); layout_dropdown(app, ui); - - ui.add(egui::Separator::default().spacing(BAR_SEPARATOR_WIDTH)); - let checker = app.session.view == texturecraft_engine::ViewMode::UvChecker; - if icon_button(ui, ic::CHECKERBOARD, &tip(&app.ui.keymap, tr("UV checker"), "ui.uvChecker"), checker, button_size).clicked() { - let mode = if checker { "material" } else { "uvChecker" }; - app.run("viewport.view", json!({"mode": mode})); - } } /// The 3D/2D, 3D-only and 2D-only layouts, showing the current one's icon @@ -293,7 +297,11 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) path_controls(app, ui); } } - Tool::PolygonFill => fill_mode_buttons(app, ui), + Tool::PolygonFill => { + fill_mode_buttons(app, ui); + ui.separator(); + crate::symmetry::toolbar_controls(app, ui); + } Tool::ColorPicker => { ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim)); } @@ -311,7 +319,10 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { (Mode::Painting, ic::PALETTE, tr("Painting"), "ui.mode.paint"), (Mode::Baking, ic::ATOM, tr("Bake Mesh Maps"), "ui.mode.bake"), ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size).clicked() { + // Greyed (Painting stays shown as the current mode) while no project is open + let on = crate::menus::enabled(app, command); + let button = ui.add_enabled_ui(on, |ui| icon_button(ui, icon, &tip(&app.ui.keymap, label, command), app.ui.mode == mode, button_size)).inner; + if button.clicked() { crate::menus::invoke(app, &ui.ctx().clone(), command); } } @@ -341,6 +352,7 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let (closed, fill) = (path.closed, path.fill); let selected = path.selected.is_some_and(|i| i < path.points.len()); let has_points = !path.points.is_empty(); + let corner = path.selected.is_some_and(|i| path.is_corner(i)); if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { app.session.set_path_closed(!closed); } @@ -350,6 +362,11 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { app.session.set_path_fill(!fill); } + if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::ANGLE, tr("Corner point (Shift+click places one)"), corner, button_size)).inner.clicked() { + // The command repaints an edited path and is one undo step + app.run("path.corner", json!({})); + } + if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() { app.session.remove_selected_path_point(); } @@ -515,23 +532,6 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { .size(11.0) .color(tk.text_dim), ); - ui.separator(); - let m = app.session.memory(); - let mb = |b: usize| b as f64 / (1024.0 * 1024.0); - let total = mb(m.total()); - let decimals = if total < 10.0 { 1 } else { 0 }; - let mb1 = |b: usize| format!("{:.1}", mb(b)); - ui.label(RichText::new(trf("Layer memory: {mb} MB", &[("mb", &format!("{total:.decimals$}"))])).size(11.0).color(tk.text_dim)).on_hover_ui( - |ui| { - ui.label(trf( - "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", - &[("pixels", &mb1(m.pixels)), ("composites", &mb1(m.composites)), ("cache", &mb1(m.cache))], - )); - }, - ); - ui.separator(); - ui.label(RichText::new(trf("UI {ms} ms", &[("ms", &format!("{:.1}", app.ui_ms))])).size(11.0).color(tk.text_dim)); - ui.add_space(vec2(0.0, 0.0).x); }); }); }); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 7bd1a539..05748e74 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -243,9 +243,11 @@ fn read_bytes(_file: &Path) -> std::io::Result> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "UI settings use browser storage")) } -/// Whether both docks were read rather than replaced by a default +/// Whether every dock, the two in use and those of the named layouts, was read rather than replaced by a default fn fully_read(ui: &UiState) -> bool { - !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() + !ui.dock.replaced_unreadable() + && !ui.inactive_mode_dock.replaced_unreadable() + && ui.named_layouts.iter().all(|layout| !layout.painting.replaced_unreadable() && !layout.baking.replaced_unreadable()) } /// The `n`th copy name of an unreadable state: `.unreadable.`, then `.unreadable-N.` @@ -409,6 +411,39 @@ pub(crate) mod tests { std::fs::remove_dir_all(&folder).unwrap(); } + #[test] + fn an_unreadable_named_layout_keeps_a_copy_of_the_state_before_the_next_save() { + let folder = test_folder("unreadable-named"); + let file = folder.join("ui.json"); + let mut ui = UiState { dock: moved_panels(), ..UiState::default() }; + assert!(ui.save_named_layout("mine")); + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + + // The last "Assets" belongs to the saved layout; the docks in use come first + let at = saved.rfind("\"Assets\"").expect("the named layout holds Assets"); + let broken = format!("{}\"Bogus\"{}", &saved[..at], &saved[at + "\"Assets\"".len()..]); + std::fs::write(&file, &broken).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)).expect("the state loads"); + assert_eq!(loaded.dock, ui.dock, "the docks in use were readable"); + assert!(!fully_read(&loaded), "the damaged named layout counts as unread"); + + store.save(&loaded, &mut storage); + assert_eq!(std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "json"))).unwrap(), broken); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn valid_named_layouts_and_none_at_all_count_as_read() { + let mut ui = UiState::default(); + assert!(fully_read(&ui)); + ui.save_named_layout("mine"); + assert!(fully_read(&restart(&ui))); + } + #[test] fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { let folder = test_folder("frozen"); @@ -678,4 +713,53 @@ pub(crate) mod tests { store.save(&loaded, &mut storage); assert_eq!(storage.values["ui.unreadable.json"], original); } + + #[test] + fn tool_settings_survive_a_restart() { + let mut tool = texturecraft_engine::ToolState::default(); + tool.brush.size = 0.31; + tool.brush.hardness = 0.9; + tool.brush.symmetry.z = true; + tool.smudge_strength = 0.8; + tool.clone_from = texturecraft_engine::CloneFrom::Layer; + tool.path.fill = true; + let ui = UiState { tool_settings: texturecraft_engine::ToolSettings::of(&tool), ..UiState::default() }; + + let restarted = restart(&ui); + + assert_eq!(restarted.tool_settings, ui.tool_settings); + let mut next = texturecraft_engine::ToolState::default(); + restarted.tool_settings.apply(&mut next); + assert_eq!((next.brush.size, next.brush.hardness, next.smudge_strength), (0.31, 0.9, 0.8)); + assert!(next.brush.symmetry.z && next.path.fill); + assert_eq!(next.clone_from, texturecraft_engine::CloneFrom::Layer); + } + + #[test] + fn a_state_saved_before_tool_settings_existed_loads_with_the_defaults() { + let mut saved = serde_json::to_value(UiState::default()).unwrap(); + saved.as_object_mut().unwrap().remove("tool_settings").expect("the saved state has tool settings"); + let mut storage = MemoryStorage::default(); + storage.values.insert(STORAGE_KEY.into(), saved.to_string()); + let mut store = UiStateStore::default(); + + let loaded = store.load(Some(&storage)).expect("the old state loads"); + + assert_eq!(loaded.tool_settings, texturecraft_engine::ToolSettings::default()); + + // Nothing was unreadable, so nothing is kept beside the state on the next save + assert!(store.unreadable.is_none()); + } + + #[test] + fn the_app_starts_with_the_saved_tool_settings() { + let mut tool = texturecraft_engine::ToolState::default(); + tool.brush.size = 0.31; + let ui = UiState { tool_settings: texturecraft_engine::ToolSettings::of(&tool), ..UiState::default() }; + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + + crate::start_ui(Some(restart(&ui)), &mut session); + + assert_eq!(session.tool.brush.size, 0.31); + } } diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index 20736bdd..072977e2 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -126,7 +126,6 @@ mod tests { let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().updates_rt.updater = Updater::new(&crate::UPDATE_APP, "0.0.1").with_source(ask).with_paths(Paths::under(&root)).with_pins_path(root.join("pins.json")); - h.state_mut().ui.windows.start = false; h.run_steps(2); h } diff --git a/crates/ui-egui/src/uv_paint_point.rs b/crates/ui-egui/src/uv_paint_point.rs index 5ff1cafb..0d4e1910 100644 --- a/crates/ui-egui/src/uv_paint_point.rs +++ b/crates/ui-egui/src/uv_paint_point.rs @@ -2,6 +2,8 @@ use texturecraft_engine::{Session, geom::glam::Vec2}; +pub use crate::surface_paint_point::SurfacePaintPoint; + /// A line anchor scoped to its project, UV layout and texture set #[derive(Clone, Copy, Debug)] pub struct UvPaintPoint { diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index d7030d9c..4c453f04 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -22,6 +22,11 @@ use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; +/// Hold this key with the Projection tool to rotate, scale or move the stencil with the mouse +pub const STENCIL_KEY: egui::Key = egui::Key::S; +/// Hold this key with the Clone tool and click to set the source +pub const CLONE_SOURCE_KEY: egui::Key = egui::Key::V; + pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -60,8 +65,26 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::toolbar::paint_bar(app, ui); } + // No project open: empty views with only their view-mode picker + if !app.session.project_open { + if app.render.is_active() { + crate::render_mode::stop(app); + } + + // The closed project's last frames must not stay readable (`viewport.screenshot`) + if let Some(render_state) = app.render_state.as_ref() + && let Some(gpu) = render_state.renderer.write().callback_resources.get_mut::() + { + gpu.renderer.drop_view(VIEW_3D); + gpu.renderer.drop_view(VIEW_2D); + } + empty_views(app, ui); + return; + } + let stroke_end = ui.scope_id().with("paint_2d_stroke_end"); - // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture. + + // A cancelled stroke can leave a pending 2D endpoint; do not attach it to a later gesture let pending_2d_endpoint = if !app.session.stroke_active() || !tool_acts(app) { ui.data_mut(|data| { let endpoint = data.get_temp(stroke_end); @@ -75,7 +98,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { crate::id_color_pick::IdColorPick::end_when_stale(app); let tokens = Tokens::get(ui.ctx()); let aux_view = match app.session.view { - _ if mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => Some(crate::gpu::AuxView::QuickMask), + _ if quick_mask_shown(app) => Some(crate::gpu::AuxView::QuickMask), ViewMode::MeshMap(map) => Some(crate::gpu::AuxView::MeshMap(map)), ViewMode::Mask(id) => Some(crate::gpu::AuxView::Mask(id)), _ if mode == crate::state::Mode::Baking && app.ui.bake_visualization.bent_normal_shown() => Some(crate::gpu::AuxView::MeshMap(BakedMap::BentNormal)), @@ -133,6 +156,28 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// The views while no project is open: no mesh, no texture, each with its view-mode picker +fn empty_views(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); + let full = ui.available_rect_before_wrap(); + let regions: Vec<(Rect, &str)> = match app.ui.layout { + ViewLayout::Only3D => vec![(full, "v3d")], + 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"), + ] + } + }; + + for (rect, id) in regions { + ui.painter().rect_filled(rect, 0.0, tokens.viewport); + view_header(app, ui, rect, id); + } +} + /// Half the split divider's line width: each view starts this far from the line's centre const SPLIT_LINE_HALF_WIDTH: f32 = 1.0; @@ -182,13 +227,13 @@ fn split_divider_x(app: &mut TextureCraftApp, ui: &Ui, full: Rect) -> f32 { } /// Lowest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 0.05) -const UV_VIEW_MIN_ZOOM: f32 = 0.1; +pub(crate) const UV_VIEW_MIN_ZOOM: f32 = 0.1; /// Highest 2D zoom, for the wheel and the divider (inside the renderer's own limit of 64) -const UV_VIEW_MAX_ZOOM: f32 = 40.0; +pub(crate) const UV_VIEW_MAX_ZOOM: f32 = 40.0; /// UV zoom change per point of mouse wheel, as a fraction of the zoom -const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; +pub(crate) const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002; /// Dash length of the straight-line preview, in points const RUBBER_BAND_DASH: f32 = 6.0; @@ -269,7 +314,7 @@ const VIEW_MODE_UV_CHECKER: u32 = 3; fn shade(app: &TextureCraftApp) -> Shade { let (view_mode, channel) = match app.session.view { - _ if app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() => (VIEW_MODE_AUX_TEXTURE, 0), + _ if quick_mask_shown(app) => (VIEW_MODE_AUX_TEXTURE, 0), ViewMode::Material => (VIEW_MODE_MATERIAL, 0), ViewMode::Channel(selected_channel) => (VIEW_MODE_CHANNEL, selected_channel.index() as u32), ViewMode::MeshMap(_) | ViewMode::Mask(_) => (VIEW_MODE_AUX_TEXTURE, 0), @@ -420,28 +465,51 @@ fn view_header_rect(rect: Rect) -> Option { }) } +/// Where the solo notice sits from a view's top-left corner, and its text size +const SOLO_NOTICE_OFFSET: egui::Vec2 = vec2(12.0, 12.0); +const SOLO_NOTICE_TEXT_SIZE: f32 = 12.0; + +/// While a layer is soloed, a line in the view's corner says so: the view does not show the whole stack +fn solo_notice(app: &TextureCraftApp, ui: &Ui, rect: Rect) { + let Some(solo) = app.session.solo else { return }; + let Some(layer) = app.session.doc.project.layers.get(&solo.layer) else { return }; + let text = if solo.ignore_mask { trf("Solo: {layer} (mask ignored)", &[("layer", &layer.name)]) } else { trf("Solo: {layer}", &[("layer", &layer.name)]) }; + let tokens = Tokens::get(ui.ctx()); + ui.painter_at(rect).text( + rect.left_top() + SOLO_NOTICE_OFFSET, + egui::Align2::LEFT_TOP, + text, + egui::FontId::proportional(SOLO_NOTICE_TEXT_SIZE), + tokens.warning, + ); +} + /// The camera and view pickers at the top of a view, left out when the view is too narrow to hold them fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { let Some(header) = view_header_rect(rect) else { return }; let mut child = ui.new_child(egui::UiBuilder::new().max_rect(header).layout(egui::Layout::left_to_right(egui::Align::Center))); + // With no project open there is no camera to pick: the view keeps only its view-mode picker + let project_open = app.session.project_open; 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); - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |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})); + if project_open { + egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { + if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { + app.run("camera.select", json!({})); } - } - ui.separator(); - if ui.selectable_label(false, tr("Save view as camera")).clicked() { - app.run("camera.add", json!({})); - } - }); + for (index, name) in names.iter().enumerate() { + if ui.selectable_label(current == Some(index), name).clicked() { + app.run("camera.select", json!({"index": index})); + } + } + ui.separator(); + if ui.selectable_label(false, tr("Save view as camera")).clicked() { + app.run("camera.add", json!({})); + } + }); + } // 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; @@ -452,33 +520,43 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { _ => app.session.view.label(), }; let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); - egui::ComboBox::from_id_salt(format!("{id}_mode")).width(VIEW_PICKER_WIDTH).selected_text(tr(&label)).show_ui(&mut 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"})); - } - if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() { - // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone - app.ui.bake_visualization.neutral_shown &= !baking; - app.run("viewport.view", json!({"mode": "material"})); - } - ui.separator(); - if baking { - mesh_map_entries(app, ui); - return; - } - for channel in channels { - if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { - app.run("viewport.view", json!({"mode": channel.id()})); + // 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| { + if baking && ui.selectable_label(neutral, tr("Neutral Material")).clicked() { + app.ui.bake_visualization.neutral_shown = true; + app.run("viewport.view", json!({"mode": "material"})); } - } - ui.separator(); - mesh_map_entries(app, ui); - ui.separator(); - if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { - app.run("viewport.view", json!({"mode": "uvChecker"})); - } + if ui.selectable_label(app.session.view == ViewMode::Material && !neutral, tr("Material")).clicked() && project_open { + // Only bake mode's pick turns the neutral material off; painting mode's Material leaves bake mode's choice alone + app.ui.bake_visualization.neutral_shown &= !baking; + app.run("viewport.view", json!({"mode": "material"})); + } + + // Nothing else to show without a project + if !project_open { + return; + } + + ui.separator(); + if baking { + mesh_map_entries(app, ui); + return; + } + + for channel in channels { + if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel.label())).clicked() { + app.run("viewport.view", json!({"mode": channel.id()})); + } + } + ui.separator(); + mesh_map_entries(app, ui); + ui.separator(); + if ui.selectable_label(app.session.view == ViewMode::UvChecker, tr("UV checker")).clicked() { + app.run("viewport.view", json!({"mode": "uvChecker"})); + } + }) }); } @@ -492,6 +570,43 @@ fn mesh_map_entries(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// Height above a view's bottom edge of the "Mask" label, clear of the axis gizmo +const MASK_BADGE_RAISE: f32 = 70.0; + +/// Left inset of the "Mask" label +const MASK_BADGE_INSET: f32 = 14.0; + +/// Text size of the "Mask" label +const MASK_BADGE_TEXT_SIZE: f32 = 15.0; + +/// Whether the quick mask replaces whatever view mode is chosen: editing it in Painting mode, unless picking an ID colour +fn quick_mask_shown(app: &TextureCraftApp) -> bool { + app.ui.mode == crate::state::Mode::Painting && app.session.quick_mask.editing && app.picking_id_color.is_none() +} + +/// The layer whose mask the view really displays: none while the quick mask takes over the view +fn mask_view_layer(app: &TextureCraftApp) -> Option { + match app.session.view { + ViewMode::Mask(layer) if !quick_mask_shown(app) => Some(layer), + _ => None, + } +} + +/// The label that says a view shows one layer's mask alone and how to leave it +fn mask_view_badge(app: &TextureCraftApp, ui: &Ui, rect: Rect) { + let Some(layer) = mask_view_layer(app) else { return }; + let tk = Tokens::get(ui.ctx()); + let name = app.session.doc.project.layers.get(&layer).map(|layer| layer.name.as_str()).unwrap_or_default(); + let text = trf("MASK: {layer}", &[("layer", &name)]); + ui.painter_at(rect).text( + pos2(rect.left() + MASK_BADGE_INSET, rect.bottom() - MASK_BADGE_RAISE), + egui::Align2::LEFT_BOTTOM, + text, + egui::FontId::proportional(MASK_BADGE_TEXT_SIZE), + tk.viewport_accent, + ); +} + fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { let tk = Tokens::get(ui.ctx()); let o = pos2(rect.left() + 28.0, rect.bottom() - 28.0); @@ -517,10 +632,10 @@ fn axis_gizmo(ui: &Ui, rect: Rect, app: &TextureCraftApp, uv: bool) { } /// Camera turn per point of a drag (radians) -const ORBIT_RADIANS_PER_POINT: f32 = 0.008; +pub(crate) const ORBIT_RADIANS_PER_POINT: f32 = 0.008; /// Camera zoom per point of an Alt+right drag -const DRAG_ZOOM_PER_POINT: f32 = 0.01; +pub(crate) const DRAG_ZOOM_PER_POINT: f32 = 0.01; /// Camera zoom per point of mouse wheel const WHEEL_ZOOM_PER_POINT: f32 = 0.0025; @@ -534,6 +649,9 @@ const WHEEL_BRUSH_SIZE_PER_POINT: f32 = 0.002; /// Stencil turn per point of an S+left drag (degrees) const STENCIL_DEGREES_PER_POINT: f32 = 0.4; +/// Step of an S+Shift+left drag's turn (degrees) +const STENCIL_SNAP_DEGREES: f32 = 15.0; + /// Stencil scale change per point of an S+right drag, as a fraction of the scale const STENCIL_SCALE_PER_POINT: f32 = 0.005; @@ -546,19 +664,46 @@ const MAX_STENCIL_SCALE: f32 = 10.0; /// Smallest viewport the camera projects into, so a collapsed view keeps a usable aspect (points) const MIN_CAMERA_VIEWPORT: f32 = 16.0; +/// Remember the model point under viewport pixel `screen` as the start of the next Shift+click line +fn remember_line_anchor(app: &mut TextureCraftApp, screen: Vec2) { + if let Some(hit) = app.session.pick(screen, app.session.viewport) { + app.last_paint_point = Some(crate::uv_paint_point::SurfacePaintPoint::new(&app.session, hit.pos)); + } +} + +/// Where the remembered line start is in the view now (viewport pixels), also when the model hides it +fn line_anchor_screen(app: &TextureCraftApp, rect: Rect) -> Option { + let pos = app.last_paint_point?.position_for(&app.session)?; + let screen = project(app, rect, pos)?; + Some(Vec2::new(screen.x - rect.left(), screen.y - rect.top())) +} + +/// Alt+Shift+left drag: orbit in 90° steps. The drag's own yaw and pitch follow the pointer; the +/// camera takes the nearest step, with the pitch held inside the orbit's ±89° limit. +fn snapped_orbit(app: &mut TextureCraftApp, delta: egui::Vec2) { + let step = std::f32::consts::FRAC_PI_2; + let limit = 89f32.to_radians(); + let camera = &mut app.session.camera; + let (yaw, pitch) = app.orbit_snap.get_or_insert((camera.yaw, camera.pitch)); + *yaw -= delta.x * ORBIT_RADIANS_PER_POINT; + *pitch = (*pitch + delta.y * ORBIT_RADIANS_PER_POINT).clamp(-step, step); + camera.yaw = (*yaw / step).round() * step; + camera.pitch = ((*pitch / step).round() * step).clamp(-limit, limit); +} + fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) { let response = ui.interact(rect, ui.scope_id().with("view3d"), Sense::click_and_drag()); app.viewport_rect = rect; let size = rect.size(); app.session.viewport = Vec2::new(size.x.max(MIN_CAMERA_VIEWPORT), size.y.max(MIN_CAMERA_VIEWPORT)); - let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); + let (alt, shift, snap) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift, input.modifiers.shift && input.modifiers.command)); let local = |pointer: egui::Pos2| Vec2::new(pointer.x - rect.left(), pointer.y - rect.top()); let adjusting = brush_drag(app, ui, &response); let navigating = !adjusting && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); // Navigation; S + drag moves the projection stencil instead, below let delta = ui.input(|input| input.pointer.delta()); - let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(egui::Key::S)) && !ui.ctx().egui_wants_keyboard_input(); + let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !ui.ctx().egui_wants_keyboard_input(); // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; @@ -566,10 +711,18 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if stencil_drag || adjusting { // The stencil or the brush changes instead of the camera } else if response.dragged_by(PointerButton::Middle) { + app.camera_glide = None; app.session.camera.pan(delta.x / size.y, delta.y / size.y); } else if alt && response.dragged_by(PointerButton::Primary) { - app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + // Navigating takes over from a glide in progress, which would put the camera back + app.camera_glide = None; + if shift { + snapped_orbit(app, delta); + } else { + app.session.camera.orbit(delta.x * ORBIT_RADIANS_PER_POINT, delta.y * ORBIT_RADIANS_PER_POINT); + } } else if response.dragged_by(PointerButton::Secondary) { + app.camera_glide = None; if alt { app.session.camera.zoom(-delta.y * DRAG_ZOOM_PER_POINT); } else if shift { @@ -580,16 +733,26 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } + // The next snapping drag starts again from where the camera is + if !(alt && shift && response.dragged_by(PointerButton::Primary)) { + app.orbit_snap = None; + } + if response.hovered() { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); + size_brush_by_ctrl_wheel(app, ui); + if ui.input(|input| input.multi_touch().is_none()) { + let pinch = trackpad_pinch(ui); + if pinch != 1.0 { + app.session.camera.zoom(pinch.ln()); + } + } + + let scroll = wheel_scroll(ui, shift); if scroll != 0.0 { - if shift && app.ui.mode == crate::state::Mode::Painting { - // A tool that can't act keeps its size: its controls are hidden - if tool_acts(app) { - let brush = &mut app.session.tool.brush; - brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); - } + if shift && wheel_sizes_brush(app) { + scale_brush_by_wheel(app, scroll); } else { + app.camera_glide = None; app.session.camera.zoom(scroll * WHEEL_ZOOM_PER_POINT); } } @@ -602,6 +765,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.cancel_stroke(); } + app.camera_glide = None; let moved = gesture.translation_delta; if gesture.num_touches >= 3 { app.session.camera.pan(moved.x / size.y, moved.y / size.y); @@ -613,13 +777,25 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // Stencil: S + left drag turns it, S + right drag scales it, S + middle drag moves it + let raw_id = ui.scope_id().with("stencil_snap_raw"); + if !(s_held && shift && response.dragged_by(PointerButton::Primary)) { + ui.data_mut(|data| data.remove::(raw_id)); + } + + // Stencil: S + left drag turns it (with Shift in snapped steps), S + right drag scales it, S + middle drag moves it if s_held && stencil_moves && let Some(stencil) = app.session.tool.stencil.as_mut() { if response.dragged_by(PointerButton::Primary) { - stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); + if shift { + // The unsnapped angle is kept so slow drags still reach the next step + let raw: f32 = ui.data(|data| data.get_temp(raw_id)).unwrap_or(stencil.rotation) + delta.x * STENCIL_DEGREES_PER_POINT; + ui.data_mut(|data| data.insert_temp(raw_id, raw)); + stencil.rotation = ((raw / STENCIL_SNAP_DEGREES).round() * STENCIL_SNAP_DEGREES).rem_euclid(360.0); + } else { + stencil.rotation = (stencil.rotation + delta.x * STENCIL_DEGREES_PER_POINT).rem_euclid(360.0); + } } else if response.dragged_by(PointerButton::Secondary) { stencil.scale = (stencil.scale * (1.0 + delta.x * STENCIL_SCALE_PER_POINT)).clamp(MIN_STENCIL_SCALE, MAX_STENCIL_SCALE); } else if response.dragged_by(PointerButton::Middle) { @@ -658,7 +834,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); - if let Some(layer) = placing { + if let Some(target) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt && !rail_popup @@ -667,7 +843,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && let Some(pointer) = response.interact_pointer_pos() { let (at, viewport) = (local(pointer), app.session.viewport); - app.run("layer.decal.set", json!({"layer": layer.0, "x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); + let mut params = json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]}); + + // The id is a decal layer's or a mask fill effect's + params[if app.session.doc.project.effect(target).is_some() { "effect" } else { "layer" }] = json!(target.0); + app.run("layer.decal.set", params); app.placing_decal = None; } } @@ -699,7 +879,18 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()) && decal_input(app, ui, &response, rect); + let plane_pick = !popup + && !s_held + && !v_held + && !focus_pick + && placing.is_none() + && !picking_id_color + && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()) + && !decal_drag + && crate::symmetry::plane_pick_input(app, ui, &response, rect); let symmetry_drag = !alt + && !plane_pick && !adjusting && !s_held && !v_held @@ -727,6 +918,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !picking_id_color && touch.is_none() && !decal_drag + && !plane_pick && !symmetry_drag && !symmetry_handle && !DecalDrop::blocks_input(ui.ctx()); @@ -747,15 +939,18 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { - // Shift+click paints a straight line from where the last stroke ended - let line_from = if shift { app.last_paint_point } else { None }; + // Shift+click paints a straight line from where the last stroke ended on the model; Ctrl+Shift snaps its angle + let line_from = if shift { line_anchor_screen(app, rect) } else { None }; if let Some(pointer) = response.interact_pointer_pos() { - match app.session.begin_stroke(line_from.unwrap_or(local(pointer)), app.session.viewport, pressure) { + let pointer = snapped_end(line_from.filter(|_| snap).map(|from| pos2(rect.left() + from.x, rect.top() + from.y)), pointer); + let start = line_from.unwrap_or(local(pointer)); + match app.session.begin_stroke(start, app.session.viewport, pressure) { Ok(_) => { + crate::inactive_set_hint::hint_on_stroke_start(app, start); if line_from.is_some() { app.session.continue_stroke(local(pointer), pressure); } - app.last_paint_point = Some(local(pointer)); + remember_line_anchor(app, local(pointer)); } Err(error) => app.toast(tr(&error.to_string()).to_string(), true), } @@ -770,7 +965,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && let Some(pointer) = response.interact_pointer_pos() { app.session.continue_stroke(local(pointer), pressure); - app.last_paint_point = Some(local(pointer)); + remember_line_anchor(app, local(pointer)); } if response.drag_stopped_by(PointerButton::Primary) && let Err(error) = app.session.end_stroke() @@ -791,7 +986,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); - // Shelf drops: a material goes above the selection of the set under the pointer, an image opens the decal menu there, an alpha goes on the brush + // Route shelf drops by asset type to a layer, decal, or brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began @@ -817,12 +1012,13 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin clone_marker(app, ui, rect, source); } - // Shift: preview the straight line Shift+click paints from the last stroke + // Shift: preview the straight line Shift+click paints from the last stroke (snapped with Ctrl) if shift && !path_tool - && let Some(from) = app.last_paint_point + && let Some(from) = line_anchor_screen(app, rect) { - rubber_band(ui, rect, &[pos2(rect.left() + from.x, rect.top() + from.y), hover_pos]); + let from = pos2(rect.left() + from.x, rect.top() + from.y); + rubber_band(ui, rect, &[from, snapped_end(snap.then_some(from), hover_pos)]); } } @@ -845,8 +1041,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if app.ui.mode == crate::state::Mode::Baking { crate::bake_mode::bake_visualization_panel(app, ui, rect); } + solo_notice(app, ui, rect); view_header(app, ui, rect, "v3d"); + mask_view_badge(app, ui, rect); axis_gizmo(ui, rect, app, false); + crate::nav_buttons::show(app, ui, rect, crate::nav_buttons::NavView::Scene); } /// Where the quick-mask editing notice sits from the 3D view's top-left corner, its text size and its warning red @@ -923,9 +1122,11 @@ struct DecalFrame { } impl DecalFrame { - fn of(app: &TextureCraftApp, rect: Rect) -> Option { + /// The selected decal: its layer (the mask's owner for an effect), the mask fill effect holding it when placed as a mask, and the decal + fn selected( + app: &TextureCraftApp, + ) -> Option<(texturecraft_engine::core::LayerId, Option, texturecraft_engine::core::Decal)> { use texturecraft_engine::StackTarget; - use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; if app.ui.mode != crate::state::Mode::Painting { @@ -934,12 +1135,12 @@ impl DecalFrame { let layers = &app.session.doc.project; let selected = app.session.selected_layer()?; - let (layer, effect, decal) = match app.session.target { + match app.session.target { StackTarget::Content => { let layer = layers.content_layer(selected)?; let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - (layer.id, None, decal) + Some((layer.id, None, *decal)) } StackTarget::Effect(effect) => { // Only the selected layer's effective mask may supply a decal frame, including an instance's inherited mask @@ -948,10 +1149,17 @@ impl DecalFrame { let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; - (owner, Some(effect), decal) + Some((owner, Some(effect), *decal)) } - StackTarget::Mask => return None, - }; + StackTarget::Mask => None, + } + } + + fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; + + let (layer, effect, decal) = Self::selected(app)?; + let decal = &decal; let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; let center = project(app, rect, decal_axes(decal)?.0)?; @@ -1039,12 +1247,10 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { } let tk = Tokens::get(ui.ctx()); - use texturecraft_engine::core::{Fill, LayerKind, Projection}; - let p = &app.session.doc.project; - let sel = app.session.selected_layer().and_then(|id| p.content_layer(id)); - let is_decal = matches!(sel.map(|l| &l.kind), Some(LayerKind::Fill(Fill { projection: Projection::Decal(_), .. }))); - // Placing follows the selection: another layer selected stops it. - if app.placing_decal.is_some() && app.placing_decal != sel.map(|l| l.id).filter(|_| is_decal) { + + // Placing follows the selection: another layer or effect selected stops it + let selected_decal = DecalFrame::selected(app).map(|(layer, effect, _)| effect.unwrap_or(layer)); + if app.placing_decal.is_some() && app.placing_decal != selected_decal { app.placing_decal = None; } let painter = ui.painter_at(rect); @@ -1067,7 +1273,8 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { for stroke in [shadow, Stroke::new(1.2, frame_color)] { painter.add(egui::Shape::dashed_line(&outline, stroke, 6.0, 4.0)); } - // The projection direction from the center. + + // The projection direction from the center if let Some((o, _, _, n)) = texturecraft_engine::compose::pattern::decal_axes(&f.decal) && let Some(tip) = project(app, rect, o + n * f.decal.size[0].max(f.decal.size[1]) * 0.25) { @@ -1075,7 +1282,8 @@ fn decal_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { painter.line_segment([f.center, tip], Stroke::new(1.4, tk.viewport_accent)); } painter.circle(f.center, 3.5, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(180))); - // Handles: white, the one under the pointer or being dragged in the accent color. + + // Handles: white, the one under the pointer or being dragged in the accent color let fill = |g: DecalGrab| if active == Some(g) || (active.is_none() && hovered == Some(g)) { tk.viewport_accent } else { Color32::WHITE }; let edge = Stroke::new(1.0, Color32::from_black_alpha(200)); painter.line_segment([f.top, f.knob], shadow); @@ -1190,9 +1398,9 @@ fn other_paths(app: &TextureCraftApp) -> Vec<(texturecraft_engine::core::LayerId } /// The screen curve through `points` per segment, each starting on its first point -fn screen_segments(points: &[Pos2], closed: bool) -> Vec> { +fn screen_segments(points: &[Pos2], corners: &[bool], closed: bool) -> Vec> { let pts: Vec = points.iter().map(|p| Vec2::new(p.x, p.y)).collect(); - texturecraft_engine::paint::spline_segments(&pts, closed, PATH_SCREEN_STEP) + texturecraft_engine::paint::spline_segments_with_corners(&pts, corners, closed, PATH_SCREEN_STEP) .into_iter() .zip(points) .map(|(samples, first)| std::iter::once(*first).chain(samples.into_iter().map(|v| pos2(v.x, v.y))).collect()) @@ -1226,12 +1434,16 @@ fn curve_on_screen( ) -> ScreenCurve { if uv { let Some(points) = path.points.iter().map(|p| show(app, *p)).collect::>>() else { return Vec::new() }; - return screen_segments(&points, path.closed).into_iter().map(|segment| segment.into_iter().map(|at| Some((at, true))).collect()).collect(); + return screen_segments(&points, &path.corners, path.closed) + .into_iter() + .map(|segment| segment.into_iter().map(|at| Some((at, true))).collect()) + .collect(); } + let s = &app.session; let surface = stored .and_then(|(eid, index)| stored_surface(app, ui, eid, index)) - .unwrap_or_else(|| Arc::new(s.path_surface(&path.points, path.closed, s.camera, s.viewport))); + .unwrap_or_else(|| Arc::new(s.path_surface_with_corners(&path.points, &path.corners, path.closed, s.camera, s.viewport))); surface .iter() .map(|segment| segment.iter().map(|p| p.and_then(|p| show(app, p).map(|at| (at, !depth_test || path_point_visible(app, rect, p, at))))).collect()) @@ -1288,9 +1500,21 @@ fn path_input( { let path = &app.session.tool.path; let (closed, len) = (path.closed, path.points.len()); - let hit = path_hit(app, ui, (rect, uv), at, &show); + let corner = ui.input(|i| i.modifiers.shift); + + // Points live in one view's coordinates; a press in the other view keeps them and says why + let other_view = (len > 0 || path.editing.is_some()) && path.uv != uv; + let hit = if other_view { PathHit::Miss } else { path_hit(app, ui, (rect, uv), at, &show) }; let grab = match hit { + _ if other_view => { + let hint = + if path.uv { "Finish or cancel the path first; it is in the 2D view" } else { "Finish or cancel the path first; it is in the 3D view" }; + if !app.toasts.iter().any(|t| t.text == tr(hint)) { + app.toast(tr(hint), false); + } + None + } PathHit::Point(0) if clicked && !closed && len >= 3 => { app.session.set_path_closed(true); None @@ -1305,7 +1529,10 @@ fn path_input( } hit => match place(app, if let PathHit::Curve(_, on) = hit { on } else { at }) { Some(p) => match hit { + // Shift+click places a corner point + PathHit::Curve(i, _) if corner => app.session.insert_path_corner(i + 1, p), PathHit::Curve(i, _) => app.session.insert_path_point(i + 1, p), + _ if corner => app.session.append_path_corner(p, uv), _ => app.session.append_path_point(p, uv), }, None => { @@ -1379,6 +1606,7 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons let tk = Tokens::get(ui.ctx()); let painter = ui.painter_at(rect); let hint = tr("Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels"); + // Wrapped to the view: the hint is longer than a narrow split view let at = rect.left_bottom() + PATH_HINT_OFFSET; let wrap = (rect.right() - at.x - PATH_HINT_MARGIN).max(PATH_HINT_MIN_WIDTH); @@ -1389,6 +1617,7 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons let hit = hover.map(|at| (at, path_hit(app, ui, (rect, uv), at, &show))); for (eid, i, other) in other_paths(app).iter().filter(|(_, _, other)| other.uv == uv) { let curve = curve_on_screen(app, ui, (rect, uv, true), other, Some((*eid, *i)), &show); + // The path a click opens lights up let opened = matches!(hit, Some((_, PathHit::Stored(e, n))) if (e, n) == (*eid, *i)); draw_path_curve(&painter, &curve, if opened { Color32::WHITE } else { Color32::WHITE.gamma_multiply(PATH_STORED_OPACITY) }); @@ -1402,9 +1631,11 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons && !handles.is_empty() && let Some((to, PathHit::Miss)) = hit { + // The preview segment starts on the last placed point, which may be a corner let mut next = handles.clone(); next.push(to); - if let Some(segment) = screen_segments(&next, false).last() { + let flags: Vec = path.points.iter().enumerate().filter(|(_, q)| show(app, **q).is_some()).map(|(i, _)| path.is_corner(i)).collect(); + if let Some(segment) = screen_segments(&next, &flags, false).last() { rubber_band(ui, rect, segment); } } @@ -1415,10 +1646,19 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons // Keep the point's original index when earlier points project behind the camera let hovered = hover.is_some_and(|m| m.distance(handle) < HANDLE_GRAB); let radius = if hovered { PATH_POINT_RADIUS + PATH_POINT_HOVER_GROWTH } else { PATH_POINT_RADIUS }; + + // A corner point is drawn as a square, a smooth one as a circle + let marker = |radius: f32, fill: Color32, stroke: Stroke| { + if path.is_corner(index) { + painter.rect(Rect::from_center_size(handle, vec2(radius * 2.0, radius * 2.0)), 0.0, fill, stroke, egui::StrokeKind::Middle); + } else { + painter.circle(handle, radius, fill, stroke); + } + }; if path.selected == Some(index) { - painter.circle(handle, radius + PATH_POINT_SELECTED_GROWTH, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(160))); + marker(radius + PATH_POINT_SELECTED_GROWTH, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(160))); } else { - painter.circle(handle, radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 }))); + marker(radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 }))); } } } @@ -1565,14 +1805,19 @@ fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option) { /// V held with the Clone tool in painting mode: clicks set the clone source fn clone_source_key(app: &TextureCraftApp, ui: &Ui) -> bool { - tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(egui::Key::V)) && !ui.ctx().egui_wants_keyboard_input() + tool_acts(app) && app.session.tool.tool == Tool::Clone && ui.input(|input| input.key_down(CLONE_SOURCE_KEY)) && !ui.ctx().egui_wants_keyboard_input() } /// Crosshair where the Clone tool reads from. fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { - let tokens = Tokens::get(ui.ctx()); - let Some(center) = project(app, rect, pos) else { return }; + if let Some(center) = project(app, rect, pos) { + clone_marker_at(ui, rect, center); + } +} +/// The clone source crosshair centred on the screen point `center` +fn clone_marker_at(ui: &Ui, rect: Rect, center: Pos2) { + let tokens = Tokens::get(ui.ctx()); let painter = ui.painter_at(rect); for (stroke_width, color) in [(3.0, Color32::from_black_alpha(140)), (1.2, tokens.viewport_accent)] { painter.circle_stroke(center, 7.0, Stroke::new(stroke_width, color)); @@ -1586,6 +1831,11 @@ fn tool_acts(app: &TextureCraftApp) -> bool { app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) } +/// Whether the 2D view says that the equipped Projection tool paints in the 3D view only (the quick mask is painted like with a brush) +fn projection_hint_shown(app: &TextureCraftApp) -> bool { + tool_acts(app) && app.session.tool.tool == Tool::Projection && !app.session.quick_mask.editing +} + /// Both views must close gestures even when the selection disables their input handlers. fn finish_unavailable_tool_gestures(app: &mut TextureCraftApp, pending_2d_endpoint: Option) { if !tool_acts(app) { @@ -1608,16 +1858,88 @@ fn brush_tool(t: Tool) -> bool { matches!(t, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone | Tool::Path) } +/// Wheel travel this frame in points. egui turns a Shift+wheel into a horizontal scroll, so with Shift held +/// the travel arrives on x (on a mac the system already does this); the sum covers both. +fn wheel_scroll(ui: &Ui, shift: bool) -> f32 { + ui.input(|input| { + let delta = input.smooth_scroll_delta; + if shift { delta.x + delta.y } else { delta.y } + }) +} + +/// Only command-wheel input resizes the brush. A pinch zooms the viewport. +fn size_brush_by_ctrl_wheel(app: &mut TextureCraftApp, ui: &Ui) { + if !wheel_sizes_brush(app) { + return; + } + + let line = ui.ctx().options(|options| options.input_options.line_scroll_speed); + let points: f32 = ui.input(|input| { + input + .raw + .events + .iter() + .filter_map(|event| { + let egui::Event::MouseWheel { unit, delta, modifiers, .. } = event else { return None }; + let scale = match unit { + egui::MouseWheelUnit::Point => 1.0, + egui::MouseWheelUnit::Line => line, + egui::MouseWheelUnit::Page => input.viewport_rect().height(), + }; + modifiers.command.then_some(delta.y * scale) + }) + .sum() + }); + if points.is_finite() && points != 0.0 { + scale_brush_by_wheel(app, -points); + } +} + +fn trackpad_pinch(ui: &Ui) -> f32 { + ui.input(|input| { + input + .raw + .events + .iter() + .filter_map(|event| match event { + egui::Event::Zoom(factor) if factor.is_finite() && *factor > 0.0 => Some(*factor), + _ => None, + }) + .product() + }) +} + +/// Shift+wheel sizes the brush while a brush tool can act; otherwise the wheel zooms as usual. +fn wheel_sizes_brush(app: &TextureCraftApp) -> bool { + tool_acts(app) && brush_tool(app.session.tool.tool) +} + +/// Shift+wheel: scale the brush size. +fn scale_brush_by_wheel(app: &mut TextureCraftApp, scroll: f32) { + let brush = &mut app.session.tool.brush; + brush.size = (brush.size * (1.0 + scroll * WHEEL_BRUSH_SIZE_PER_POINT)).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); +} + /// Ctrl (Cmd on macOS) + drag changes the brush instead of painting: true while it applies (see `adjust_brush`) fn brush_drag(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) -> bool { - let held = tool_acts(app) && brush_tool(app.session.tool.tool) && !app.session.stroke_active() && ui.input(|input| input.modifiers.command); + // Ctrl+Shift+left is not a brush change: it is left to the snapped straight line + let held = tool_acts(app) + && brush_tool(app.session.tool.tool) + && !app.session.stroke_active() + && ui.input(|input| input.modifiers.command && (!input.modifiers.shift || input.pointer.secondary_down())); if held && let Some(right) = brush_drag_button(response) { - adjust_brush(&mut app.session.tool.brush, right, ui.input(|input| input.pointer.delta())); + let (delta, fine) = ui.input(|input| (input.pointer.delta(), input.modifiers.shift)); + adjust_brush(&mut app.session.tool.brush, right, if fine { delta * CTRL_DRAG_FINE_FACTOR } else { delta }); } held } +/// Where a straight line to `pointer` ends: turned to a multiple of 15 degrees about `from` when it is set (Ctrl+Shift), else at `pointer` +fn snapped_end(from: Option, pointer: Pos2) -> Pos2 { + from.map_or(pointer, |from| crate::line_snap::snap_line_end(from, pointer, crate::line_snap::LINE_SNAP_STEP_DEGREES)) +} + /// The button of a drag on `resp`: Some(true) right, Some(false) left. fn brush_drag_button(resp: &egui::Response) -> Option { let right = resp.dragged_by(PointerButton::Secondary); @@ -1650,6 +1972,9 @@ fn brush_readout(app: &TextureCraftApp, ui: &Ui, response: &egui::Response, adju painter.galley(readout_rect.min + vec2(6.0, 3.0), galley, tokens.text_strong); } +/// Part of the change a Ctrl+right drag makes while Shift is also held (fine mode) +const CTRL_DRAG_FINE_FACTOR: f32 = 0.1; + /// Size fraction, hardness and flow change per point of a Ctrl+drag const CTRL_DRAG_RATE_PER_POINT: f32 = 0.005; @@ -1670,34 +1995,63 @@ fn adjust_brush(brush: &mut texturecraft_engine::paint::BrushSettings, right: bo } } -pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, position: Vec3, normal: Vec3, radius: f32) { - const CIRCLE_SEGMENTS: usize = 48; +/// Segments of the brush outline and hardness ring +const CURSOR_OUTLINE_SEGMENTS: usize = 48; - let tangent = normal.any_orthonormal_vector(); +/// The roundness the cursor shows: only the procedural Round alpha has one +fn cursor_roundness(brush: &texturecraft_engine::paint::BrushSettings) -> f32 { + let round = brush.alpha == texturecraft_engine::paint::BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); + if round { brush.alpha_params.roundness } else { 1.0 } +} + +/// Whether the outline is a plain circle (equal sizes, full roundness), drawn as one +fn cursor_is_circle(brush: &texturecraft_engine::paint::BrushSettings) -> bool { + brush.alpha_params.size_x == brush.alpha_params.size_y && cursor_roundness(brush) >= 1.0 +} + +/// The stamp's outline scaled by `scale` (the hardness ring's share of the radius), as points around the +/// stamp center in a y-up frame in units of the stamp radius: the alpha's extent (Size X and Y), the +/// squarer corners of a Round alpha with low roundness, then turned by the brush angle. +fn cursor_outline(brush: &texturecraft_engine::paint::BrushSettings, scale: f32) -> Vec { + let params = brush.alpha_params; + let roundness = cursor_roundness(brush); + let (sin, cos) = brush.angle.to_radians().sin_cos(); + (0..=CURSOR_OUTLINE_SEGMENTS) + .map(|segment| { + let angle = segment as f32 / CURSOR_OUTLINE_SEGMENTS as f32 * std::f32::consts::TAU; + let direction = Vec2::new(angle.cos(), angle.sin()); + + // Distance of the unit direction in the Round alpha's metric: between the square's and the circle's + let square = direction.x.abs().max(direction.y.abs()); + let reach = 1.0 / (square + (1.0 - square) * roundness); + let point = direction * reach * scale * Vec2::new(params.size_x, params.size_y); + Vec2::new(point.x * cos - point.y * sin, point.x * sin + point.y * cos) + }) + .collect() +} + +pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, position: Vec3, normal: Vec3, radius: f32) { + let brush = &app.session.tool.brush; + + // The stamp's frame as the stroke builds it: the camera's up direction seen along the surface + let forward = app.session.camera.forward(); + let camera_up = forward.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X).cross(forward); + let up = (camera_up - normal * normal.dot(camera_up)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + let tangent = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); let bitangent = normal.cross(tangent); let to_screen = |point: Vec3| project(app, rect, point); - let mut outline = Vec::with_capacity(CIRCLE_SEGMENTS + 1); - for segment in 0..=CIRCLE_SEGMENTS { - let angle = segment as f32 / CIRCLE_SEGMENTS as f32 * std::f32::consts::TAU; - if let Some(screen) = to_screen(position + (tangent * angle.cos() + bitangent * angle.sin()) * radius) { - outline.push(screen); - } - } + let ring = |scale: f32| -> Vec { + cursor_outline(brush, scale).into_iter().filter_map(|local| to_screen(position + (tangent * local.x + bitangent * local.y) * radius)).collect() + }; + let outline = ring(1.0); let painter = ui.painter_at(rect); painter.add(egui::Shape::line(outline.clone(), Stroke::new(2.5, Color32::from_black_alpha(140)))); painter.add(egui::Shape::line(outline, Stroke::new(1.2, Color32::from_white_alpha(230)))); - let hardness = app.session.tool.brush.hardness; + let hardness = brush.hardness; if hardness > 0.05 { - let mut inner = Vec::new(); - for segment in 0..=CIRCLE_SEGMENTS { - let angle = segment as f32 / CIRCLE_SEGMENTS as f32 * std::f32::consts::TAU; - if let Some(screen) = to_screen(position + (tangent * angle.cos() + bitangent * angle.sin()) * radius * hardness) { - inner.push(screen); - } - } - painter.add(egui::Shape::dashed_line(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); + painter.add(egui::Shape::dashed_line(&ring(hardness), Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); } if let Some(center) = to_screen(position) { @@ -1783,7 +2137,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let tokens = Tokens::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag()); let size = rect.size(); - let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift)); + let (alt, shift, snap) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift, input.modifiers.shift && input.modifiers.command)); let adjusting = brush_drag(app, ui, &response); // Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor @@ -1793,11 +2147,17 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.ui.uv_pan[1] -= delta.y / size.y * 2.0; } if response.hovered() { - let scroll = ui.input(|input| input.smooth_scroll_delta.y); - if scroll != 0.0 { + size_brush_by_ctrl_wheel(app, ui); + let scroll = wheel_scroll(ui, shift); + if scroll != 0.0 && shift && wheel_sizes_brush(app) { + scale_brush_by_wheel(app, scroll); + } else { + let pinch = ui.input(|input| input.multi_touch().map(|touch| touch.zoom_delta)).unwrap_or_else(|| trackpad_pinch(ui)); let old_zoom = app.ui.uv_zoom; - let new_zoom = (old_zoom * (1.0 + scroll * UV_WHEEL_ZOOM_PER_POINT)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); - if let Some(hover_pos) = response.hover_pos() { + let new_zoom = (old_zoom * pinch * (1.0 + scroll * UV_WHEEL_ZOOM_PER_POINT)).clamp(UV_VIEW_MIN_ZOOM, UV_VIEW_MAX_ZOOM); + if old_zoom != new_zoom + && let Some(hover_pos) = response.hover_pos() + { let cursor = [(hover_pos.x - rect.left()) / size.x * 2.0 - 1.0, 1.0 - (hover_pos.y - rect.top()) / size.y * 2.0]; for axis in 0..2 { app.ui.uv_pan[axis] = cursor[axis] - (cursor[axis] - app.ui.uv_pan[axis]) * new_zoom / old_zoom; @@ -1855,14 +2215,17 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // Painting in UV space + // Painting in UV space; the Projection tool only paints in the 3D view, with or without a stencil + let projection_hint = projection_hint_shown(app); let painting = tool_acts(app) + && !projection_hint && app.properties_popup.is_none() && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !alt && !adjusting && !v_held && !picking_id_color + && !app.picking_symmetry_plane && !DecalDrop::blocks_input(ui.ctx()); let mut fill_box = None; if painting && path_tool { @@ -1876,7 +2239,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin |session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)), ); } else if painting { - paint_2d_input(app, ui, &response, shift, &to_uv); + paint_2d_input(app, ui, &response, (shift, snap), &to_uv, &to_screen); } if response.double_clicked() && !(painting && path_tool) { app.ui.uv_zoom = 1.0; @@ -1895,6 +2258,15 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); + if projection_hint { + ui.painter_at(rect).text( + rect.left_top() + QUICK_MASK_NOTICE_OFFSET, + egui::Align2::LEFT_TOP, + tr("Projection paints in the 3D view"), + egui::FontId::proportional(QUICK_MASK_NOTICE_TEXT_SIZE), + QUICK_MASK_NOTICE_COLOR, + ); + } // The UV tile outlines (numbered for UDIM sets) and the path being edited let painter = ui.painter_at(rect); @@ -1927,7 +2299,15 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin path_overlay(app, ui, rect, &response, true, show); } - // Shift: preview the straight line Shift+click paints from the last stroke + // Clone source: where the tool reads, as in the 3D view + if tool_acts(app) + && app.session.tool.tool == Tool::Clone + && let Some(source) = app.session.clone_source_marker_uv(response.hover_pos().map(to_uv)) + { + clone_marker_at(ui, rect, to_screen(source.x, source.y)); + } + + // Shift: preview the straight line Shift+click paints from the last stroke (snapped with Ctrl) if painting && shift && !path_tool @@ -1935,7 +2315,8 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && let Some(from) = app.last_paint_uv.and_then(|point| point.uv_for(&app.session)) && let Some(hover) = response.hover_pos() { - rubber_band(ui, rect, &[to_screen(from.x, from.y), hover]); + let from = to_screen(from.x, from.y); + rubber_band(ui, rect, &[from, snapped_end(snap.then_some(from), hover)]); } if app.ui.mode == crate::state::Mode::Baking { @@ -1953,12 +2334,16 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !path_tool && brush_tool(app.session.tool.tool) && !response.dragged_by(PointerButton::Middle) + // Egui keeps hover during drags; adjustment may continue outside the view && (adjusting || pointer_in_view) + // Keep the brush outline at the press origin while adjusting && let Some(cursor_center) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos().or_else(|| response.interact_pointer_pos()) } + // Header pickers need the normal pointer && !view_header_rect(rect).is_some_and(|header| header.expand(2.0).contains(cursor_center)) + && !crate::nav_buttons::covers(app, rect, crate::nav_buttons::NavView::Uv, cursor_center) { // Match the pressure-scaled radius used by continue_stroke_uv let radius_points = @@ -1966,11 +2351,14 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if pointer_in_view { ui.ctx().set_cursor_icon(egui::CursorIcon::None); } - brush_cursor_2d(&painter, cursor_center, radius_points, app.session.tool.brush.hardness); + brush_cursor_2d(&painter, cursor_center, radius_points, &app.session.tool.brush); } brush_readout(app, ui, &response, adjusting); + solo_notice(app, ui, rect); view_header(app, ui, rect, "v2d"); + mask_view_badge(app, ui, rect); axis_gizmo(ui, rect, app, true); + crate::nav_buttons::show(app, ui, rect, crate::nav_buttons::NavView::Uv); let name = app.session.doc.project.texture_sets.get(texture_set_index).map(|texture_set| texture_set.name.clone()).unwrap_or_default(); let name_position = rect.right_bottom() - SET_NAME_INSET; ui.painter().text(name_position, egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(SET_NAME_TEXT_SIZE), tokens.viewport_text); @@ -1979,30 +2367,37 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin /// Smallest visible 2D brush outline, in points const BRUSH_CURSOR_MIN_RADIUS_POINTS: f32 = 1.5; -/// Hardness ring segments, balancing smoothness and per-frame shape work -const BRUSH_CURSOR_RING_SEGMENTS: usize = 48; - /// Smaller hardness rings overlap the center dot const BRUSH_CURSOR_MIN_RING_HARDNESS: f32 = 0.05; /// The brush outline and hardness ring around `center`, with `radius_points` in screen points -fn brush_cursor_2d(painter: &egui::Painter, center: egui::Pos2, radius_points: f32, hardness: f32) { - painter.circle_stroke(center, radius_points, Stroke::new(2.5, Color32::from_black_alpha(140))); - painter.circle_stroke(center, radius_points, Stroke::new(1.2, Color32::from_white_alpha(230))); - if hardness > BRUSH_CURSOR_MIN_RING_HARDNESS { - let inner_ring: Vec = (0..=BRUSH_CURSOR_RING_SEGMENTS) - .map(|point_index| { - let angle = point_index as f32 / BRUSH_CURSOR_RING_SEGMENTS as f32 * std::f32::consts::TAU; - center + vec2(angle.cos(), angle.sin()) * radius_points * hardness - }) - .collect(); - painter.add(egui::Shape::dashed_line(&inner_ring, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); +fn brush_cursor_2d(painter: &egui::Painter, center: egui::Pos2, radius_points: f32, brush: &texturecraft_engine::paint::BrushSettings) { + let ring = |scale: f32| -> Vec { cursor_outline(brush, scale).into_iter().map(|local| center + vec2(local.x, -local.y) * radius_points).collect() }; + if cursor_is_circle(brush) { + let radius = radius_points * brush.alpha_params.size_x; + painter.circle_stroke(center, radius, Stroke::new(2.5, Color32::from_black_alpha(140))); + painter.circle_stroke(center, radius, Stroke::new(1.2, Color32::from_white_alpha(230))); + } else { + let outline = ring(1.0); + painter.add(egui::Shape::line(outline.clone(), Stroke::new(2.5, Color32::from_black_alpha(140)))); + painter.add(egui::Shape::line(outline, Stroke::new(1.2, Color32::from_white_alpha(230)))); + } + if brush.hardness > BRUSH_CURSOR_MIN_RING_HARDNESS { + painter.add(egui::Shape::dashed_line(&ring(brush.hardness), Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); } painter.circle_filled(center, 1.5, Color32::WHITE); } -/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke. -fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) { +/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke +/// (`(shift, snap)`: Ctrl+Shift turns the line to a multiple of 15 degrees on screen). +fn paint_2d_input( + app: &mut TextureCraftApp, + ui: &Ui, + response: &egui::Response, + (shift, snap): (bool, bool), + to_uv: &dyn Fn(egui::Pos2) -> Vec2, + to_screen: &dyn Fn(f32, f32) -> egui::Pos2, +) { let pressure = pen_pressure(ui); // Where the stroke under way is; it becomes the line start only when the stroke finishes @@ -2011,7 +2406,8 @@ fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { let line_start = app.last_paint_uv.filter(|_| shift).and_then(|point| point.uv_for(&app.session)); if let Some(pointer) = response.interact_pointer_pos() { - let uv = to_uv(pointer); + let from = line_start.filter(|_| snap).map(|start| to_screen(start.x, start.y)); + let uv = to_uv(snapped_end(from, pointer)); match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) { Ok(()) => { if line_start.is_some() { @@ -2078,7 +2474,7 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t let tex = match cached { Some((c, t)) if c == key => t, _ => { - // At most 256 texels a side: the overlay is a guide, not the map. + // At most 256 texels a side: the overlay is a guide, not the map let (w, h) = (k.width as usize, k.height as usize); let (ow, oh) = (w.min(256), h.min(256)); let mut rgba = Vec::with_capacity(ow * oh * 4); @@ -2103,9 +2499,39 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t #[cfg(test)] mod tests { use super::*; + use texturecraft_engine::paint::{AlphaParams, BrushAlpha, BrushSettings}; + + fn extent(points: &[Vec2]) -> Vec2 { + let (low, high) = points.iter().fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(low, high), point| (low.min(*point), high.max(*point))); + high - low + } + + #[test] + fn the_cursor_outline_follows_size_roundness_and_angle() { + let plain = cursor_outline(&BrushSettings::default(), 1.0); + assert!(extent(&plain).abs_diff_eq(Vec2::splat(2.0), 1e-3), "a circle at the defaults: {:?}", extent(&plain)); + assert!(plain.iter().all(|point| (point.length() - 1.0).abs() < 1e-3)); + + let params = AlphaParams { size_x: 0.5, size_y: 0.25, ..AlphaParams::default() }; + let narrow = BrushSettings { alpha_params: params, ..BrushSettings::default() }; + assert!(extent(&cursor_outline(&narrow, 1.0)).abs_diff_eq(Vec2::new(1.0, 0.5), 1e-3)); + assert!(extent(&cursor_outline(&narrow, 0.5)).abs_diff_eq(Vec2::new(0.5, 0.25), 1e-3), "the hardness ring scales with it"); + + let turned = BrushSettings { angle: 90.0, ..narrow.clone() }; + assert!(extent(&cursor_outline(&turned, 1.0)).abs_diff_eq(Vec2::new(0.5, 1.0), 1e-3), "the brush angle turns the extent"); + + let square = BrushSettings { alpha_params: AlphaParams { roundness: 0.0, ..AlphaParams::default() }, ..BrushSettings::default() }; + let corner = cursor_outline(&square, 1.0).into_iter().map(Vec2::length).fold(0.0, f32::max); + assert!((corner - 2f32.sqrt()).abs() < 0.05, "roundness 0 reaches the corners: {corner}"); + + let star = BrushSettings { alpha: BrushAlpha::Star, ..square }; + assert!(cursor_outline(&star, 1.0).iter().all(|point| (point.length() - 1.0).abs() < 1e-3), "only the Round alpha has a roundness"); + } #[test] fn unavailable_tools_finish_strokes_and_box_fills() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{StackTarget, core::LayerId, geom::primitives}; for tool in [Tool::Paint, Tool::PolygonFill] { @@ -2131,8 +2557,29 @@ mod tests { } } + #[test] + fn the_mask_label_hides_while_the_quick_mask_replaces_the_mask_view() { + use texturecraft_engine::{core::LayerId, geom::primitives}; + + // The harness draws the UI, so another test's interface language must not be active + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.ui.mode = crate::state::Mode::Painting; + app.session.view = ViewMode::Mask(LayerId(7)); + assert_eq!(mask_view_layer(app), Some(LayerId(7))); + app.session.quick_mask.editing = true; + assert!(quick_mask_shown(app)); + assert_eq!(mask_view_layer(app), None, "the quick mask is on screen, not the layer mask"); + app.session.quick_mask.editing = false; + assert_eq!(mask_view_layer(app), Some(LayerId(7)), "the label returns with the mask view"); + } + #[test] fn stored_surfaces_release_after_a_frame_without_paths() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{core::EffectKind, execute, geom::primitives}; let mut session = Session::new_project("Path cache", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); @@ -2219,6 +2666,8 @@ mod tests { #[test] fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::{StackTarget, execute}; for texture_set in [0, 1] { @@ -2250,6 +2699,8 @@ mod tests { #[test] fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; let mut harness = decal_frame_app(false); @@ -2274,6 +2725,8 @@ mod tests { #[test] fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; let mut harness = decal_frame_app(false); @@ -2292,6 +2745,8 @@ mod tests { #[test] #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] fn decal_frame_selection_snapshots() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); use texturecraft_engine::execute; let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; @@ -2320,6 +2775,8 @@ mod tests { #[test] fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 76e12e3a..51dbd4b7 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -32,22 +32,22 @@ pub const MATERIAL_EXTS: &[&str] = &["tcmat", "mcmat", "mcraft"]; /// Texture size of a project made from an opened mesh (smaller on the single-threaded web). const MESH_RESOLUTION: u32 = if cfg!(target_arch = "wasm32") { 1024 } else { 2048 }; -/// What a picked file is for. +/// What a picked file is for; project-bound picks carry their originating project id. #[derive(Clone, Copy, PartialEq)] #[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] enum Pick { /// File > Open / a dropped file: a project, a mesh or an image resource. Open, /// Display settings > Import HDR. - Environment, + Environment(u64), /// Bake mode: a high-definition mesh. - HighPoly, + HighPoly(u64), /// Bake mode: the cage mesh. - Cage, + Cage(u64), /// Export dialog › Output templates: an export template (`.json`). ExportPreset, /// New project › 3D mesh › Select...: the mesh the project is created from. - NewProjectMesh, + NewProjectMesh(u64), } /// Files picked in the browser, waiting for the next frame: (file name, bytes, purpose). @@ -56,20 +56,39 @@ static INBOX: Mutex, Pick)>> = Mutex::new(Vec::new()); /// Load files that arrived since the last frame. Call once per frame. pub fn poll(app: &mut TextureCraftApp) { let picked = std::mem::take(&mut *INBOX.lock().unwrap_or_else(PoisonError::into_inner)); + apply_picked(app, picked); +} + +fn apply_picked(app: &mut TextureCraftApp, picked: Vec<(String, Vec, Pick)>) { for (name, bytes, pick) in picked { let done = match pick { Pick::Open => { load(app, &name, bytes); continue; } - Pick::Environment => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), - Pick::HighPoly => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)), - Pick::Cage => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)), - Pick::NewProjectMesh => { - app.ui.new_project.file = Some(name); - app.ui.new_project.file_bytes = Some(std::sync::Arc::new(bytes)); + + // A late project-bound pick must not modify the placeholder or a replacement project + Pick::Environment(_) | Pick::HighPoly(_) | Pick::Cage(_) if !app.session.project_open => { + app.toast(tr("No project is open"), true); continue; } + + Pick::Environment(project_id) | Pick::HighPoly(project_id) | Pick::Cage(project_id) if project_id != app.session.project_id => { + app.toast(tr("The project changed while the dialog was open, so nothing was done"), true); + continue; + } + + Pick::Environment(_) => app.session.import_resource_bytes(&name, bytes).map(|res| use_environment(app, &res)), + Pick::HighPoly(_) => app.session.add_high_poly_bytes(&name, bytes).map(|n| app.toast(trf("High poly: {name}", &[("name", &n)]), false)), + Pick::Cage(_) => app.session.set_cage_bytes(&name, bytes).map(|n| app.toast(trf("Cage: {name}", &[("name", &n)]), false)), + Pick::NewProjectMesh(request_id) => { + if app.ui.windows.new_project && app.ui.new_project.mesh_request_id == request_id { + app.ui.new_project.file = Some(name); + app.ui.new_project.file_bytes = Some(std::sync::Arc::new(bytes)); + } + continue; + } + Pick::ExportPreset => { match texturecraft_engine::formats::preset_from_json(&String::from_utf8_lossy(&bytes)) { Ok(p) => crate::export_templates::import(app, &p), @@ -126,6 +145,11 @@ pub(crate) fn use_environment(app: &mut TextureCraftApp, name: &str) { pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { let path = std::path::Path::new(name); let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase(); + if (IMAGE_EXTS.contains(&ext.as_str()) || MATERIAL_EXTS.contains(&ext.as_str())) && !app.session.project_open { + app.toast(tr("No project is open"), true); + return; + } + if IMAGE_EXTS.contains(&ext.as_str()) { match app.session.import_resource_bytes(name, bytes) { Ok(res) => { @@ -136,22 +160,27 @@ pub fn load(app: &mut TextureCraftApp, name: &str, bytes: Vec) { } return; } + if MATERIAL_EXTS.contains(&ext.as_str()) { if let Err(e) = app.session.add_smart_material_bytes(&bytes) { app.toast(trf("Couldn't import {name}: {error}", &[("name", &name), ("error", &e)]), true); } return; } + let bytes = std::sync::Arc::new(bytes); if crate::windows::ask_to_save(app, crate::state::Unsaved::Load(name.into(), bytes.clone())) { return; } + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled"); let next = if ext == PROJECT_EXT { Session::from_project_bytes(&bytes) } else { Session::from_mesh_bytes(name, &bytes, MESH_RESOLUTION, stem) }; match next { Ok(next) => { app.session.switch_to(next); app.pbr_import = None; + app.resize = None; + app.layer_panel = Default::default(); app.toast(trf("Opened {name}", &[("name", &name)]), false); } Err(e) => app.toast(trf("Couldn't open {name}: {error}", &[("name", &name), ("error", &e)]), true), @@ -253,13 +282,13 @@ mod web { /// Display settings › Import HDR: pick an equirect image; it becomes the environment on a /// later frame. - pub fn import_environment(_app: &mut TextureCraftApp, ctx: &egui::Context) { - pick(ctx, tr("HDR environments"), ENV_EXTS, false, Pick::Environment); + pub fn import_environment(app: &mut TextureCraftApp, ctx: &egui::Context) { + pick(ctx, tr("HDR environments"), ENV_EXTS, false, Pick::Environment(app.session.project_id)); } /// Bake mode: pick high-definition meshes (or the cage); they load on a later frame. - pub fn import_bake_mesh(_app: &mut TextureCraftApp, ctx: &egui::Context, cage: bool) { - pick(ctx, tr("Meshes"), &MESH_EXTENSIONS, !cage, if cage { Pick::Cage } else { Pick::HighPoly }); + pub fn import_bake_mesh(app: &mut TextureCraftApp, ctx: &egui::Context, cage: bool) { + pick(ctx, tr("Meshes"), &MESH_EXTENSIONS, !cage, if cage { Pick::Cage(app.session.project_id) } else { Pick::HighPoly(app.session.project_id) }); } /// Export dialog › Output templates › Import: pick a template; it is added on a later frame. @@ -268,8 +297,8 @@ mod web { } /// New project › Select...: pick the mesh file; Create reads it once it has arrived. - pub fn pick_new_project_mesh(ctx: &egui::Context) { - pick(ctx, tr("3D meshes"), &MESH_EXTENSIONS, false, Pick::NewProjectMesh); + pub fn pick_new_project_mesh(ctx: &egui::Context, request_id: u64) { + pick(ctx, tr("3D meshes"), &MESH_EXTENSIONS, false, Pick::NewProjectMesh(request_id)); } fn pick(ctx: &egui::Context, filter: &'static str, exts: &'static [&'static str], multiple: bool, kind: Pick) { @@ -372,6 +401,101 @@ mod web { mod tests { use super::*; + use egui_kittest::Harness; + + #[test] + fn mesh_picks_only_update_the_current_new_project_request() { + let session = Session::closed().unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + crate::new_project_advanced::open(app); + app.ui.new_project.mesh_request_id = 2; + + apply_picked(app, vec![("new.obj".into(), vec![2; 4096], Pick::NewProjectMesh(2)), ("stale.obj".into(), vec![1; 8192], Pick::NewProjectMesh(1))]); + + assert_eq!(app.ui.new_project.file.as_deref(), Some("new.obj")); + assert_eq!(app.ui.new_project.file_bytes.as_deref().unwrap().as_slice(), &[2; 4096]); + let previous_buffer = std::sync::Arc::downgrade(app.ui.new_project.file_bytes.as_ref().unwrap()); + + crate::new_project_advanced::open(app); + apply_picked(app, vec![("previous.obj".into(), vec![3; 2048], Pick::NewProjectMesh(2))]); + + assert!(app.ui.new_project.file.is_none()); + assert!(app.ui.new_project.file_bytes.is_none()); + assert!(previous_buffer.upgrade().is_none()); + } + + #[test] + fn environment_pick_after_close_does_not_edit_the_placeholder() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let old_project_id = harness.state().session.project_id; + + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + + apply_picked(harness.state_mut(), vec![("environment.png".into(), png.clone(), Pick::Environment(old_project_id))]); + + assert!(!harness.state().session.can_undo()); + assert!(!harness.state().session.doc.resources.contains_key("environment.png")); + + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + let project_id = harness.state().session.project_id; + + apply_picked(harness.state_mut(), vec![("environment.png".into(), png, Pick::Environment(project_id))]); + + assert!(harness.state().session.doc.resources.contains_key("environment.png")); + } + + #[test] + fn environment_pick_from_replaced_project_does_not_edit_the_new_project() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let png = texturecraft_engine::formats::gray16_png(1, 1, [0.5].into_iter()).unwrap(); + let old_project_id = harness.state().session.project_id; + + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + + apply_picked(harness.state_mut(), vec![("old-environment.png".into(), png, Pick::Environment(old_project_id))]); + + assert!(!harness.state().session.doc.resources.contains_key("old-environment.png")); + assert!(!harness.state().session.modified); + assert!(!harness.state().session.can_undo()); + assert!(harness.state().toasts.iter().any(|toast| toast.error)); + } + + #[test] + fn bake_mesh_picks_after_close_do_not_edit_the_placeholder() { + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + let mut harness = Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let old_project_id = harness.state().session.project_id; + assert!(harness.state_mut().run("file.close", serde_json::Value::Null).is_some()); + let cage = harness.state().session.mesh_obj_bytes(); + + apply_picked( + harness.state_mut(), + vec![("high.obj".into(), cage.clone(), Pick::HighPoly(old_project_id)), ("cage.obj".into(), cage, Pick::Cage(old_project_id))], + ); + + assert!(harness.state().session.bake_meshes.high.is_empty()); + assert!(harness.state().session.bake_meshes.cage.is_none()); + assert!(!harness.state().session.modified); + assert_eq!(harness.state().toasts.iter().filter(|toast| toast.error).count(), 2); + + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": "cube", "resolution": 128})).is_some()); + let project_id = harness.state().session.project_id; + let mesh = harness.state().session.mesh_obj_bytes(); + + apply_picked( + harness.state_mut(), + vec![("high.obj".into(), mesh.clone(), Pick::HighPoly(project_id)), ("cage.obj".into(), mesh, Pick::Cage(project_id))], + ); + + assert_eq!(harness.state().session.bake_meshes.high.len(), 1); + assert!(harness.state().session.bake_meshes.cage.is_some()); + } + #[test] fn zip_round_trips_every_export_file() { let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index bdf0bb7a..fa5ecd4c 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -29,15 +29,16 @@ pub fn slider_edit(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::R slider_inner(ui, label, value, range, decimals).1 } -fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { +/// The row above a slider's track, `label` and `value` as a field to type in: the field's id, and `Some(false)` on the frame a typed value replaces `value` +pub(crate) fn value_header(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (egui::Id, Option) { + const MIN_VALUE_WIDTH: f32 = 44.0; let tokens = Tokens::get(ui.ctx()); let (minimum, maximum) = (*range.start(), *range.end()); - let width = ui.available_width(); let font = egui::TextStyle::Body.resolve(ui.style()); let value_width = [minimum, maximum] .into_iter() .map(|bound| ui.painter().layout_no_wrap(format!("{bound:.decimals$}"), font.clone(), tokens.text).size().x) - .fold(44.0, f32::max); + .fold(MIN_VALUE_WIDTH, f32::max); let mut edit = None; let field = ui .horizontal(|ui| { @@ -45,6 +46,7 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let id = ui.next_auto_id(); let shown = format!("{value:.decimals$}"); + // Keep unfinished input while the document value is re-read each frame let mut text = ui.data(|data| data.get_temp::(id)).unwrap_or_else(|| shown.clone()); let response = ui.add( @@ -59,6 +61,7 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang ui.data_mut(|data| data.insert_temp(id, text.clone())); } else { ui.data_mut(|data| data.remove_temp::(id)); + // Escape can lose focus before the app consumes the key let escape = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); @@ -78,7 +81,18 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang .inner }) .inner; - let (rect, mut response) = ui.allocate_exact_size(vec2(width, 14.0), Sense::click_and_drag()); + (field, edit) +} + +fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, decimals: usize) -> (Response, Option) { + const TRACK_HEIGHT: f32 = 14.0; + const TRACK_INSET: f32 = 5.0; + const TRACK_WIDTH: f32 = 2.0; + const KNOB_RADIUS: f32 = 4.5; + let (minimum, maximum) = (*range.start(), *range.end()); + let width = ui.available_width(); + let (field, mut edit) = value_header(ui, label, value, range, decimals); + let (rect, mut response) = ui.allocate_exact_size(vec2(width, TRACK_HEIGHT), Sense::click_and_drag()); if response.is_pointer_button_down_on() { ui.data_mut(|data| data.remove_temp::(field)); ui.memory_mut(|memory| memory.surrender_focus(field)); @@ -89,11 +103,12 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang if (response.dragged() || response.clicked()) && let Some(pointer) = response.interact_pointer_pos() { - let fraction = ((pointer.x - rect.left() - 5.0) / (rect.width() - 10.0).max(1.0)).clamp(0.0, 1.0); + let fraction = ((pointer.x - rect.left() - TRACK_INSET) / (rect.width() - TRACK_INSET * 2.0).max(1.0)).clamp(0.0, 1.0); let next = minimum + (maximum - minimum) * fraction; if (next - *value).abs() > f32::EPSILON { *value = next; response.mark_changed(); + // Later frames of one drag share its undo step edit = Some(ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(response.id), true))); } @@ -103,7 +118,7 @@ fn slider_inner(ui: &mut Ui, label: &str, value: &mut f32, range: std::ops::Rang } let fraction = if maximum > minimum { ((*value - minimum) / (maximum - minimum)).clamp(0.0, 1.0) } else { 0.0 }; - track(ui, &response, rect.left() + 5.0..=rect.right() - 5.0, rect.center().y, fraction, 2.0, 4.5); + track(ui, &response, rect.left() + TRACK_INSET..=rect.right() - TRACK_INSET, rect.center().y, fraction, TRACK_WIDTH, KNOB_RADIUS); (response, edit) } @@ -367,6 +382,7 @@ pub fn chip(ui: &mut Ui, text: &str, on: bool) -> Response { let galley = ui.painter().layout_no_wrap(text.into(), egui::FontId::proportional(11.0), tk.text); let size = vec2(galley.size().x + 14.0, 20.0); let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, text)); let p = ui.painter(); let fill = if on { tk.tool_active diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 9b26e3be..54863a7c 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -4,21 +4,20 @@ use egui::{Color32, RichText, Ui, vec2}; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::core::ToneMapping; -use texturecraft_engine::core::project::ENV_RESOURCE_PREFIX; +use texturecraft_engine::core::project::{DisplaySettings, ENV_RESOURCE_PREFIX}; 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, trf}; +use crate::i18n::{tr, tr_history, trf}; #[cfg(not(target_arch = "wasm32"))] use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; -use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, slider}; +use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, section_with_reset, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - start(app, ctx); crate::new_project_advanced::show(app, ctx); about(app, ctx); settings(app, ctx); @@ -33,6 +32,46 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { export_mesh(app, ctx); crate::pbr_import::window(app, ctx); unsaved(app, ctx); + reset_ui(app, ctx); + crate::named_layouts::show(app, ctx); +} + +/// Window ▸ Reset UI asks first: Escape closes the question, Enter answers Reset. +pub(crate) fn reset_ui_keys(app: &mut TextureCraftApp, input: &mut egui::InputState, nothing_focused: bool) { + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { + app.ui.windows.confirm_reset_ui = false; + } else if nothing_focused && input.consume_key(egui::Modifiers::NONE, egui::Key::Enter) { + app.ui.adopt_layout(crate::UiState::default()); + app.ui.windows.confirm_reset_ui = false; + } +} + +fn reset_ui(app: &mut TextureCraftApp, ctx: &egui::Context) { + if !app.ui.windows.confirm_reset_ui { + return; + } + + let mut open = true; + let (mut reset, mut cancel) = (false, false); + dialog("reset_ui", tr("Reset UI"), &mut open).show(ctx, |ui| { + ui.label(tr("Reset the panels, view layout, zoom and every other view setting to their defaults? Settings and shortcuts stay. To reset only the panels, use Reset panel layout.")); + 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| { + reset = ui.add(primary_button(ui, tr("Reset"))).clicked(); + cancel = ui.button(tr("Cancel")).clicked(); + }); + }); + }); + + if reset { + app.ui.adopt_layout(crate::UiState::default()); + } + if reset || cancel || !open { + app.ui.windows.confirm_reset_ui = false; + } } /// Hold `then` (quitting, opening or closing a project) behind the unsaved-changes dialog when @@ -117,6 +156,7 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { } } + let discard_after_create = matches!(pending, Unsaved::CreateProject(_)) && save_first == Some(false) && app.session.modified; match save_first { Some(true) => { // An untitled project is saved from a dialog that answers on a later frame @@ -136,10 +176,16 @@ fn unsaved(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.session.modified { return; } + app.ui.windows.unsaved = None; match pending { Unsaved::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), Unsaved::Command(id) => crate::menus::invoke(app, ctx, &id), + Unsaved::CreateProject(opening_id) => { + if !crate::new_project_advanced::finish_create(app, opening_id) && discard_after_create { + app.session.modified = true; + } + } #[cfg(not(target_arch = "wasm32"))] Unsaved::Open(path) => open_path(app, &path), Unsaved::Load(name, bytes) => crate::web_files::load(app, &name, std::sync::Arc::unwrap_or_clone(bytes)), @@ -225,6 +271,22 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { } }); 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")); @@ -348,6 +410,7 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); + // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; @@ -366,8 +429,8 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { let done_count = done.len() as i64; let rows = std::iter::once(RichText::new(tr("Project opened")).color(tokens.text_dim)) - .chain(done.iter().map(RichText::new)) - .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", label)])).color(tokens.text_dim))); + .chain(done.iter().map(|label| RichText::new(tr_history(label)))) + .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", &tr_history(label))])).color(tokens.text_dim))); for (row, text) in rows.enumerate() { // Each row is the state after that many steps let steps = done_count - row as i64; @@ -391,78 +454,6 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// What the start window was asked for. -enum Start { - Menu(&'static str), - #[cfg(not(target_arch = "wasm32"))] - Recent(String), - Close, -} - -/// The start window: a new project, a project file or a recent one, or the sample that is open. -fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { - if !app.ui.windows.start { - return; - } - - #[cfg(not(target_arch = "wasm32"))] - let tokens = Tokens::get(ctx); - let mut open = true; - let mut action = None; - dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| { - ui.horizontal(|ui| { - if ui.add(primary_button(ui, tr("New project..."))).clicked() { - action = Some(Start::Menu("ui.newProject")); - } - if ui.button(tr("Open...")).clicked() { - action = Some(Start::Menu("file.open")); - } - }); - #[cfg(not(target_arch = "wasm32"))] - if file_dialogs_available() { - ui.add_space(8.0); - ui.label(caption(tr("Recent projects"))); - if app.ui.recent.is_empty() { - ui.label(RichText::new(tr("No recent projects yet")).color(tokens.text_dim)); - } - for path in &app.ui.recent { - let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path); - if ui - .add(egui::Button::selectable(false, format!("{} {name}", ic::FILE)).min_size(vec2(ui.available_width(), 0.0))) - .on_hover_text(path) - .clicked() - { - action = Some(Start::Recent(path.clone())); - } - } - } - ui.add_space(8.0); - ui.separator(); - ui.horizontal(|ui| { - ui.checkbox(&mut app.ui.prefs.start_window, tr("Show at startup")); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Continue with the sample project")).clicked() { - action = Some(Start::Close); - } - }); - }); - }); - - if let Some(action) = action { - app.ui.windows.start = false; - match action { - Start::Menu(id) => crate::menus::invoke(app, ctx, id), - #[cfg(not(target_arch = "wasm32"))] - Start::Recent(path) => open_path(app, &path), - Start::Close => {} - } - } - - if !open { - app.ui.windows.start = false; - } -} - #[cfg(not(target_arch = "wasm32"))] fn settings_resources(ctx: &egui::Context) -> (u32, u64) { let id = egui::Id::unique("settings_resources"); @@ -485,13 +476,15 @@ fn settings_resources(ctx: &egui::Context) -> (u32, u64) { 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. + + // 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. + + // 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| { @@ -543,9 +536,6 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { .on_hover_text(tr("Use the operating system's window frame and buttons instead of TextureCraft's own title bar")); ui.end_row(); } - ui.label(tr("Start window")); - ui.checkbox(&mut p.start_window, tr("Show at startup")); - ui.end_row(); }); ui.add_space(8.0); ui.label(caption(tr("Viewport"))); @@ -726,7 +716,7 @@ pub fn layout_file(app: &mut TextureCraftApp, save: bool) { app.ask_file(dialog.filter(tr("UI layout"), &["json"]).directory(dir.clone()), Bound::App, move |app, paths| { let Some(path) = paths.first() else { return }; let result = if save { - let layout = crate::UiState { recent: Vec::new(), ..app.ui.clone() }; + let layout = crate::UiState { recent: Vec::new(), named_layouts: Vec::new(), ..app.ui.clone() }; std::fs::create_dir_all(&dir) .map_err(|e| e.to_string()) .and_then(|_| serde_json::to_vec_pretty(&layout).map_err(|e| e.to_string())) @@ -759,16 +749,16 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> match id { "file.open" => { app.ask_file(FileDialog::open().filter(tr("TextureCraft project or mesh"), crate::web_files::OPEN_EXTS), Bound::App, |app, paths| { - if let Some(p) = paths.first() { - open_path(app, &p.display().to_string()); + if let Some(path) = paths.first() { + open_path(app, &path.display().to_string()); } }); true } "file.save" if app.session.path.is_some() => { - if let Some(r) = app.run("file.save", json!({})) { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Saved {path}", &[("path", &p)]), false); + if let Some(result) = app.run("file.save", json!({})) { + let saved_path = result["path"].as_str().unwrap_or_default(); + app.toast(trf("Saved {path}", &[("path", &saved_path)]), false); } true } @@ -782,8 +772,8 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } "material.load" => { app.ask_file(FileDialog::open_many().filter(tr("Materials"), crate::web_files::MATERIAL_EXTS), Bound::Project, |app, paths| { - for p in paths { - app.run("material.load", json!({"path": p.display().to_string()})); + for path in paths { + app.run("material.load", json!({"path": path.display().to_string()})); } }); true @@ -794,12 +784,12 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> } "file.importMaterialX" => { app.ask_file(FileDialog::open().filter(tr("MaterialX materials"), &["mtlx"]), Bound::Project, |app, paths| { - if let Some(p) = paths.first() - && let Some(r) = app.run("file.importMaterialX", json!({"path": p.display().to_string()})) + if let Some(path) = paths.first() + && let Some(result) = app.run("file.importMaterialX", json!({"path": path.display().to_string()})) { - let name = r.get("material").and_then(|n| n.as_str()).unwrap_or_default().to_string(); - for w in r.get("warnings").and_then(|w| w.as_array()).into_iter().flatten().filter_map(|w| w.as_str()) { - app.session.log.push(format!("MaterialX {name}: {w}")); + let name = result["material"].as_str().unwrap_or_default(); + for warning in result["warnings"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str) { + app.session.log.push(format!("MaterialX {name}: {warning}")); } app.toast(trf("Imported {name}", &[("name", &name)]), false); app.ui.dock.focus(crate::docking::Panel::Layers); @@ -821,25 +811,26 @@ pub fn file_action(app: &mut TextureCraftApp, _ctx: &egui::Context, id: &str) -> .filter(tr("USD binary, textures alongside"), &["usdc"]) .file_name(name); app.ask_file(dialog, Bound::Project, |app, paths| { - if let Some(p) = paths.first() - && let Some(r) = app.run("file.exportMesh", json!({"path": p.display().to_string()})) + if let Some(path) = paths.first() + && let Some(result) = app.run("file.exportMesh", json!({"path": path.display().to_string()})) { - let p = r.get("path").and_then(|p| p.as_str()).unwrap_or_default().to_string(); - app.toast(trf("Exported mesh to {path}", &[("path", &p)]), false); + let saved_path = result["path"].as_str().unwrap_or_default(); + app.toast(trf("Exported mesh to {path}", &[("path", &saved_path)]), false); } }); true } "file.reimportMesh" => { - // The file the mesh came from is read again from disk; ask only when it's gone. + // Ask for a replacement only when the mesh source is missing if let Some(path) = app.session.remembered_mesh_path().map(str::to_string) { reimport_mesh(app, path); return true; } + let dialog = FileDialog::open().filter(tr("3D meshes"), &texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS); app.ask_file(dialog, Bound::Project, |app, paths| { - if let Some(p) = paths.first() { - reimport_mesh(app, p.display().to_string()); + if let Some(path) = paths.first() { + reimport_mesh(app, path.display().to_string()); } }); true @@ -966,7 +957,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"))); egui::Grid::new("exp_grid").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - // The browser downloads the files instead. + // The browser downloads the files instead #[cfg(not(target_arch = "wasm32"))] { ui.label(tr("Output directory")); @@ -983,6 +974,7 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur ui.end_row(); } ui.label(tr("Output template")); + let before = app.ui.export.preset.clone(); egui::ComboBox::from_id_salt("exp_preset").width(360.0).selected_text(app.ui.export.preset.clone()).show_ui(ui, |ui| { for p in presets { ui.selectable_value(&mut app.ui.export.preset, p.name.clone(), &p.name); @@ -994,6 +986,10 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur ui.selectable_value(&mut app.ui.export.preset, p.name.clone(), &p.name); } }); + if app.ui.export.preset != before { + let picked = std::mem::replace(&mut app.ui.export.preset, before); + crate::export_templates::select(app, picked); + } ui.end_row(); ui.label(tr("File type")); ui.horizontal(|ui| { @@ -1076,12 +1072,20 @@ fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, presets: &[textur pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); if !app.ui.windows.export { + app.ui.export.ask = None; return; } + 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| { + // Nothing to export without a project + if !app.session.project_open { + ui.label(tr("No project is open")); + return; + } + 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() { @@ -1096,6 +1100,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::export_templates::tab(app, ui, &presets); return; } + ui.vertical(|ui| { ui.set_width(180.0); ui.label(RichText::new(tr("Texture sets")).strong()); @@ -1151,6 +1156,7 @@ pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); }); + crate::export_templates::ask(app, ctx); if do_export && export_sets(app) { app.ui.windows.export = false; } @@ -1211,6 +1217,8 @@ mod tests { #[test] fn a_save_a_copy_answer_does_not_end_the_prompts_wait() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut h = harness(); let app = h.state_mut(); app.file_dialogs.set_override(Some(Box::new(|_| crate::file_dialogs::Answer::Cancelled))); @@ -1222,9 +1230,12 @@ mod tests { #[test] fn a_save_as_already_on_its_way_ends_the_prompts_wait() { + // The harness draws the UI, and the i18n tests switch the process-wide language to ones its fonts cannot draw + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut h = harness(); let app = h.state_mut(); - // One call site, as File › Save As and the prompt's Save share one. + + // One call site, as File › Save As and the prompt's Save share one for waiting in [false, true] { app.saving_for_prompt = waiting; ask_save_project(app, "file.saveAs"); @@ -1237,7 +1248,7 @@ mod tests { /// question open with buttons that still answer. #[test] fn a_change_after_the_dialog_saved_leaves_the_prompt_usable() { - // The harness keeps the process-wide language at English while this asserts on labels. + // The harness keeps the process-wide language at English while this asserts on labels let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut h = harness(); let app = h.state_mut(); @@ -1251,4 +1262,35 @@ mod tests { h.run_steps(2); assert!(h.state().ui.windows.unsaved.is_none()); } + + /// The History panel runs each step name through the translator (skipped when this build + /// embeds no catalog that translates "Remove layer"; `i18n` tests cover the template matching) + #[test] + fn history_rows_are_shown_in_the_interface_language() { + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(code) = crate::i18n::LANGUAGES.iter().map(|l| l.code).find(|code| { + crate::i18n::set_language(code); + *code != "en" && crate::i18n::tr("Remove layer") != "Remove layer" + }) else { + crate::i18n::set_language("en"); + return; + }; + + let translated = crate::i18n::tr("Remove layer").to_string(); + let mut h = harness(); + { + let app = h.state_mut(); + let layer = app.session.selected_layer().unwrap(); + texturecraft_engine::execute(&mut app.session, "layer.remove", &json!({"layer": layer.0})).unwrap(); + app.ui.dock.focus(crate::docking::Panel::History); + app.ui.prefs.language = code.into(); + } + h.run_steps(4); + let shown = h.query_all_by_label(&translated).count(); + let untranslated = h.query_all_by_label("Remove layer").count(); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + assert!(shown > 0 && untranslated == 0, "{code}: translated rows {shown}, English rows {untranslated}"); + assert!(h.query_all_by_label("Remove layer").count() > 0); + } } diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs new file mode 100644 index 00000000..3a261eed --- /dev/null +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -0,0 +1,102 @@ +//! The Alpha tab's Parameters group: hardness and the parameters every alpha shares, with the Parameters reset + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::paint::{AlphaParams, BrushAlpha, BrushSettings}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::PropsTab; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); +const STARTUP_FRAMES: usize = 4; +const SETTLE_FRAMES: usize = 3; + +fn changed_params() -> AlphaParams { + AlphaParams { size_x: 0.5, size_y: 0.25, roundness: 0.2, contrast: 3.0, invert: true } +} + +/// The app showing the Alpha tab of Properties, with `brush` +fn app_with_brush(brush: BrushSettings) -> 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.state_mut().session.tool.brush = brush; + harness.state_mut().ui.props_tab = PropsTab::Alpha; + harness.run_steps(STARTUP_FRAMES); + harness +} + +fn restore_defaults<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'tree> { + harness.get_by_role_and_label(egui::Role::Button, "Parameters: Reset to defaults") +} + +fn invert_checkbox<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> Option> { + harness.query_all_by_role_and_label(egui::Role::CheckBox, "Invert").next() +} + +/// Scrolls the checkbox into view and clicks it +fn click_invert(harness: &mut Harness<'_, TextureCraftApp>) { + if let Some(node) = invert_checkbox(harness) { + node.scroll_to_me(); + } + harness.run_steps(SETTLE_FRAMES); + if let Some(node) = invert_checkbox(harness) { + node.click(); + } + harness.run_steps(SETTLE_FRAMES); +} + +fn show_group(harness: &mut Harness<'_, TextureCraftApp>) { + restore_defaults(harness).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_group_shows_hardness_and_every_shared_parameter() { + let harness = app_with_brush(BrushSettings::default()); + + for label in ["Parameters", "Hardness", "Size X", "Size Y", "Roundness", "Contrast"] { + assert!(harness.query_by_label(label).is_some(), "{label} is in the Alpha tab"); + } + assert!(invert_checkbox(&harness).is_some()); +} + +#[test] +fn restore_defaults_puts_back_hardness_and_the_parameters_but_keeps_the_alpha() { + let brush = BrushSettings { hardness: 0.9, alpha: BrushAlpha::Star, alpha_params: changed_params(), size: 0.1, flow: 0.4, ..BrushSettings::default() }; + let mut harness = app_with_brush(brush.clone()); + show_group(&mut harness); + assert!(!restore_defaults(&harness).accesskit_node().is_disabled()); + + restore_defaults(&harness).click(); + harness.run_steps(SETTLE_FRAMES); + + let defaults = BrushSettings::default(); + let expected = BrushSettings { hardness: defaults.hardness, alpha_params: defaults.alpha_params, ..brush }; + assert_eq!(harness.state().session.tool.brush, expected); + assert!(restore_defaults(&harness).accesskit_node().is_disabled(), "nothing left to restore"); +} + +#[test] +fn the_invert_checkbox_sets_the_brush_parameter() { + let mut harness = app_with_brush(BrushSettings::default()); + show_group(&mut harness); + assert!(restore_defaults(&harness).accesskit_node().is_disabled(), "at the defaults there is nothing to restore"); + + click_invert(&mut harness); + + assert!(harness.state().session.tool.brush.alpha_params.invert); + assert!(!restore_defaults(&harness).accesskit_node().is_disabled()); + + click_invert(&mut harness); + assert_eq!(harness.state().session.tool.brush, BrushSettings::default()); +} + +#[test] +fn hardness_left_the_brush_tab_and_its_reset() { + let mut harness = app_with_brush(BrushSettings::default()); + harness.state_mut().ui.props_tab = PropsTab::Brush; + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.query_by_label("Hardness").is_none(), "Hardness is in the Alpha tab now"); + assert!(harness.query_by_label("Flow").is_some()); +} diff --git a/crates/ui-egui/tests/it/brush_drag.rs b/crates/ui-egui/tests/it/brush_drag.rs index 9a8b1d10..ecc5393f 100644 --- a/crates/ui-egui/tests/it/brush_drag.rs +++ b/crates/ui-egui/tests/it/brush_drag.rs @@ -29,18 +29,145 @@ fn ctrl_drag_changes_the_brush_instead_of_painting_or_orbiting() { let s = &h.state().session; (s.tool.brush.clone(), s.camera.yaw, s.history_labels().len()) }; - // Right drag to the right and up: a bigger, harder brush; the camera stays. + + // Right drag to the right and up: a bigger, harder brush; the camera stays drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::COMMAND); let b = h.state().session.tool.brush.clone(); assert!(b.size > brush.size && b.hardness > brush.hardness, "{} {} → {} {}", brush.size, brush.hardness, b.size, b.hardness); assert_eq!(h.state().session.camera.yaw, yaw, "no orbit"); - // Left drag to the left and up: less flow, a turned brush, and no stroke. + + // Left drag to the left and up: less flow, a turned brush, and no stroke drag(&mut h, PointerButton::Primary, c, vec2(-80.0, -40.0), Modifiers::COMMAND); let b2 = h.state().session.tool.brush.clone(); assert!(b2.flow < b.flow && b2.angle != b.angle, "{} {} → {} {}", b.flow, b.angle, b2.flow, b2.angle); assert_eq!(h.state().session.history_labels().len(), history, "nothing painted"); - // Without Ctrl, a right drag orbits again and the brush keeps its values. + + // Without Ctrl, a right drag orbits again and the brush keeps its values drag(&mut h, PointerButton::Secondary, c, vec2(80.0, -40.0), Modifiers::NONE); assert_ne!(h.state().session.camera.yaw, yaw); assert_eq!(h.state().session.tool.brush, b2); } + +fn app(layout: texturecraft_ui_egui::state::ViewLayout) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = layout; + h.run_steps(4); + h +} + +/// One wheel notch of `delta_y` points with `modifiers` held, as egui gets it from the system. +fn wheel(h: &mut Harness<'_, TextureCraftApp>, at: Pos2, delta_y: f32, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.hover_at(at); + h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, delta_y), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers, + }); + h.run_steps(12); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn shift_wheel_changes_the_brush_size_in_the_3d_view_and_does_not_zoom() { + let mut h = app(texturecraft_ui_egui::state::ViewLayout::Only3D); + let c = h.state().viewport_rect.center(); + let (size, distance) = (h.state().session.tool.brush.size, h.state().session.camera.distance); + wheel(&mut h, c, 20.0, Modifiers::SHIFT); + let bigger = h.state().session.tool.brush.size; + assert!(bigger > size, "{size} -> {bigger}"); + assert_eq!(h.state().session.camera.distance, distance, "no zoom"); + wheel(&mut h, c, -20.0, Modifiers::SHIFT); + assert!(h.state().session.tool.brush.size < bigger); + + // Without Shift the wheel zooms and keeps the size + let size = h.state().session.tool.brush.size; + wheel(&mut h, c, 20.0, Modifiers::NONE); + assert_eq!(h.state().session.tool.brush.size, size); + assert_ne!(h.state().session.camera.distance, distance, "plain wheel zooms"); +} + +#[test] +fn shift_wheel_changes_the_brush_size_in_the_2d_view_and_does_not_zoom() { + let mut h = app(texturecraft_ui_egui::state::ViewLayout::Only2D); + let c = egui::pos2(800.0, 480.0); + let (size, zoom) = (h.state().session.tool.brush.size, h.state().ui.uv_zoom); + wheel(&mut h, c, 20.0, Modifiers::SHIFT); + assert!(h.state().session.tool.brush.size > size); + assert_eq!(h.state().ui.uv_zoom, zoom, "no zoom"); +} + +#[test] +fn shift_during_a_ctrl_right_drag_changes_size_and_hardness_in_fine_steps() { + let mut h = app(texturecraft_ui_egui::state::ViewLayout::Only3D); + let c = h.state().viewport_rect.center(); + let before = h.state().session.tool.brush.clone(); + let history = h.state().session.history_labels().len(); + + // Compare Ctrl and Ctrl+Shift on the same right drag + drag(&mut h, PointerButton::Secondary, c, vec2(10.0, -40.0), Modifiers::COMMAND); + let coarse = h.state().session.tool.brush.clone(); + h.state_mut().session.tool.brush = before.clone(); + h.run_steps(2); + drag(&mut h, PointerButton::Secondary, c, vec2(10.0, -40.0), Modifiers::COMMAND | Modifiers::SHIFT); + let fine = h.state().session.tool.brush.clone(); + assert_eq!(h.state().session.history_labels().len(), history, "nothing painted"); + let (coarse_hardness, fine_hardness) = (coarse.hardness - before.hardness, fine.hardness - before.hardness); + assert!(coarse_hardness > 0.05 && fine_hardness > 0.0, "{coarse_hardness} {fine_hardness}"); + assert!((fine_hardness * 10.0 - coarse_hardness).abs() < 0.01, "hardness {coarse_hardness} vs {fine_hardness}"); + let (coarse_size, fine_size) = (coarse.size / before.size - 1.0, fine.size / before.size - 1.0); + assert!(coarse_size > 0.01 && fine_size > 0.0 && fine_size < coarse_size / 5.0, "size {coarse_size} vs {fine_size}"); +} + +#[test] +fn ctrl_shift_left_drag_does_not_change_flow_or_angle() { + let mut h = app(texturecraft_ui_egui::state::ViewLayout::Only3D); + let c = h.state().viewport_rect.center(); + let before = h.state().session.tool.brush.clone(); + drag(&mut h, PointerButton::Primary, c, vec2(-80.0, -40.0), Modifiers::COMMAND | Modifiers::SHIFT); + let after = &h.state().session.tool.brush; + assert_eq!((after.flow, after.angle), (before.flow, before.angle)); +} + +#[test] +fn ctrl_wheel_sizes_the_brush_in_both_views_up_smaller_and_does_not_zoom() { + for layout in [texturecraft_ui_egui::state::ViewLayout::Only3D, texturecraft_ui_egui::state::ViewLayout::Only2D] { + let mut h = app(layout); + let c = if layout == texturecraft_ui_egui::state::ViewLayout::Only3D { h.state().viewport_rect.center() } else { egui::pos2(800.0, 480.0) }; + let (size, distance, zoom) = (h.state().session.tool.brush.size, h.state().session.camera.distance, h.state().ui.uv_zoom); + wheel(&mut h, c, 20.0, Modifiers::COMMAND); + let smaller = h.state().session.tool.brush.size; + assert!(smaller < size, "{layout:?}: wheel up makes it smaller: {size} -> {smaller}"); + wheel(&mut h, c, -20.0, Modifiers::COMMAND); + assert!(h.state().session.tool.brush.size > smaller, "{layout:?}: wheel down makes it larger"); + assert_eq!(h.state().session.camera.distance, distance, "{layout:?}: no camera zoom"); + assert_eq!(h.state().ui.uv_zoom, zoom, "{layout:?}: no 2D zoom"); + } +} + +#[test] +fn a_trackpad_pinch_zooms_each_view_and_keeps_the_brush_size() { + use texturecraft_ui_egui::state::ViewLayout; + for layout in [ViewLayout::Only3D, ViewLayout::Only2D] { + let mut h = app(layout); + let at = if layout == ViewLayout::Only3D { h.state().viewport_rect.center() } else { egui::pos2(800.0, 480.0) }; + let size = h.state().session.tool.brush.size; + let distance = h.state().session.camera.distance; + let zoom = h.state().ui.uv_zoom; + + h.hover_at(at); + h.event(Event::Zoom(1.25)); + h.run_steps(2); + + assert_eq!(h.state().session.tool.brush.size, size); + if layout == ViewLayout::Only3D { + assert!(h.state().session.camera.distance < distance); + } else { + assert!(h.state().ui.uv_zoom > zoom); + } + } +} diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 12e4f08b..c01726ad 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -23,7 +23,7 @@ const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) }), ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { - (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + (brush.flow, brush.opacity, brush.spacing) = (defaults.flow, defaults.opacity, defaults.spacing) }), ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), ("Jitters", "Size jitter", false, |brush, defaults| { diff --git a/crates/ui-egui/tests/it/camera_views.rs b/crates/ui-egui/tests/it/camera_views.rs new file mode 100644 index 00000000..3148c55f --- /dev/null +++ b/crates/ui-egui/tests/it/camera_views.rs @@ -0,0 +1,275 @@ +//! F5 and F6 switch the projection, the Viewport menu goes to fixed views, and Alt+Shift+drag orbits +//! in 90° steps. + +use std::f32::consts::FRAC_PI_2; + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key) { + h.event(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// Drag with the left button and `modifiers` from `from` by `by` in a few moves. +fn drag(h: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: egui::Vec2, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.hover_at(from); + h.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(2); + for k in 1..=4 { + h.hover_at(from + by * (k as f32 / 4.0)); + h.run_steps(1); + } + h.event(Event::PointerButton { pos: from + by, button: PointerButton::Primary, pressed: false, modifiers }); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(3); +} + +#[test] +fn f6_switches_to_orthographic_and_f5_back_to_perspective_keeping_the_view() { + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 30, "pitch": 15})); + h.run_steps(2); + let before = h.state().session.camera; + assert!(!before.ortho); + press(&mut h, Key::F6); + let camera = h.state().session.camera; + assert!(camera.ortho, "F6 is orthographic"); + assert_eq!((camera.yaw, camera.pitch, camera.distance, camera.target), (before.yaw, before.pitch, before.distance, before.target)); + press(&mut h, Key::F6); + assert!(h.state().session.camera.ortho, "F6 again stays orthographic: not a toggle"); + press(&mut h, Key::F5); + assert_eq!(h.state().session.camera, before, "F5 is perspective"); +} + +#[test] +fn the_viewport_menu_goes_to_the_front_view_and_orbit_works_afterwards() { + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 70, "pitch": 30, "ortho": true})); + h.run_steps(2); + + // The menu bar's "Viewport", above the dock's tab of the same name + h.get_all_by_label("Viewport").min_by(|a, b| a.rect().top().total_cmp(&b.rect().top())).unwrap().click(); + h.run_steps(2); + h.get_by_label_contains("Front view").click(); + + // The UI glides there over about a third of a second + h.run_steps(6); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the eye is in front of the mesh: {looking_from}"); + assert!(camera.ortho, "the projection stays"); + + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(60.0, 30.0), Modifiers::ALT); + let orbited = h.state().session.camera; + assert!(orbited.yaw != camera.yaw && orbited.pitch != camera.pitch, "Alt+drag still orbits"); +} + +#[test] +fn alt_shift_drag_orbits_in_quarter_turns() { + let mut h = harness(); + h.state_mut().run("camera.set", json!({"yaw": 17, "pitch": 11})); + h.run_steps(2); + let center = h.state().viewport_rect.center(); + let at_step = |angle: f32, steps: f32| (angle - steps * FRAC_PI_2).abs() < 1e-5; + + // A short drag stays at the nearest quarter turn: straight on, level + drag(&mut h, center, vec2(10.0, 5.0), Modifiers::ALT | Modifiers::SHIFT); + let camera = h.state().session.camera; + assert!(at_step(camera.yaw, 0.0) && at_step(camera.pitch, 0.0), "yaw {} pitch {}", camera.yaw.to_degrees(), camera.pitch.to_degrees()); + + // A long drag to the left turns a quarter: the eye moves to the right side + drag(&mut h, center, vec2(-200.0, 0.0), Modifiers::ALT | Modifiers::SHIFT); + let camera = h.state().session.camera; + assert!(at_step(camera.yaw, 1.0) && at_step(camera.pitch, 0.0), "yaw {} pitch {}", camera.yaw.to_degrees(), camera.pitch.to_degrees()); + + // Dragging down far enough looks from above, at the orbit's 89° limit + drag(&mut h, center, vec2(0.0, 200.0), Modifiers::ALT | Modifiers::SHIFT); + let camera = h.state().session.camera; + assert!(at_step(camera.yaw, 1.0) && (camera.pitch - 89f32.to_radians()).abs() < 1e-5, "pitch {}", camera.pitch.to_degrees()); +} + +/// A harness whose frames are 10 ms apart, so a 0.35 s glide spans about 35 frames and a drag fits inside it. +fn slow_glide_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(0.01).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +/// Start the glide to the front view from a turned camera. +fn start_front_glide(h: &mut Harness<'_, TextureCraftApp>) { + h.state_mut().run("camera.set", json!({"yaw": 70, "pitch": 30})); + h.run_steps(2); + h.state_mut().run("camera.view.front", json!({})); + h.run_steps(2); +} + +#[test] +fn f6_during_a_glide_keeps_the_orthographic_projection_when_the_glide_ends() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + assert!(!h.state().session.camera.ortho); + press(&mut h, Key::F6); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the glide still reaches the front view: {looking_from}"); + assert!(camera.ortho, "F6 pressed during the glide is not undone when it ends"); + + // And back: F5 during a glide to a view of an orthographic camera + start_front_glide(&mut h); + press(&mut h, Key::F5); + h.run_steps(60); + assert!(!h.state().session.camera.ortho, "F5 pressed during the glide is not undone either"); +} + +#[test] +fn a_view_that_returns_to_the_starting_camera_cancels_the_glide_of_the_earlier_view() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + h.run_steps(60); + + // Back, then Front again before a frame runs: the camera is already at the front + h.state_mut().run("camera.view.back", json!({})); + h.state_mut().run("camera.view.front", json!({})); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the camera stays at the front instead of gliding to the back: {looking_from}"); +} + +#[test] +fn a_camera_command_from_the_control_channel_during_a_glide_is_not_overwritten_by_it() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let context = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &context, "command.run", &json!({"id": "camera.set", "params": {"yaw": 20, "pitch": 10}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.run_steps(60); + let camera = h.state().session.camera; + assert!( + (camera.yaw.to_degrees() - 20.0).abs() < 1e-3 && (camera.pitch.to_degrees() - 10.0).abs() < 1e-3, + "yaw {} pitch {}", + camera.yaw.to_degrees(), + camera.pitch.to_degrees() + ); +} + +#[test] +fn a_control_command_that_leaves_the_camera_alone_does_not_stop_the_glide() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let context = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &context, "command.run", &json!({"id": "camera.get", "params": {}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the glide still reaches the front view: {looking_from}"); +} + +#[test] +fn a_control_view_command_naming_the_current_camera_ends_a_glide_started_in_the_same_frame() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + h.run_steps(60); + + // At the front: the UI starts a glide to the back, then a script asks for the front before a frame runs + h.state_mut().run("camera.view.back", json!({})); + let context = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &context, "command.run", &json!({"id": "camera.view.front", "params": {}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the explicit front view wins over the pending glide to the back: {looking_from}"); +} + +#[test] +fn f_during_a_glide_frames_the_mesh_and_the_glide_does_not_take_it_back() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + press(&mut h, Key::F); + let framed = h.state().session.camera; + h.run_steps(60); + assert_eq!(h.state().session.camera, framed, "Show entire mesh pressed during the glide keeps its view"); +} + +#[test] +fn a_projection_switch_from_the_control_channel_during_a_glide_lets_the_glide_finish() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let context = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &context, "command.run", &json!({"id": "camera.orthographic", "params": {}})); + assert_eq!(reply["ok"], true, "{reply}"); + h.run_steps(60); + let camera = h.state().session.camera; + let looking_from = (camera.eye() - camera.target).normalize(); + assert!(looking_from.z > 0.999, "the glide still reaches the front view: {looking_from}"); + assert!(camera.ortho, "and keeps the orthographic projection"); +} + +#[test] +fn alt_shift_drag_during_a_glide_is_not_overwritten_by_it() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(-100.0, 0.0), Modifiers::ALT | Modifiers::SHIFT); + h.run_steps(60); + let camera = h.state().session.camera; + assert!( + (camera.yaw - FRAC_PI_2).abs() < 1e-5 && camera.pitch.abs() < 1e-5, + "the snapped orbit stays: yaw {} pitch {}", + camera.yaw.to_degrees(), + camera.pitch.to_degrees() + ); +} + +#[test] +fn alt_drag_during_a_glide_is_not_overwritten_by_it() { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let center = h.state().viewport_rect.center(); + drag(&mut h, center, vec2(-200.0, 0.0), Modifiers::ALT); + h.run_steps(60); + let camera = h.state().session.camera; + + // The glide ends at yaw 0 and pitch 0; the drag turned the camera away from the front by far more than a degree + assert!(camera.yaw.abs() > 0.1, "the orbit stays: yaw {}", camera.yaw.to_degrees()); +} + +#[test] +fn the_wheel_during_a_glide_is_not_overwritten_by_it() { + let end_distance = |scroll: f32| { + let mut h = slow_glide_harness(); + start_front_glide(&mut h); + let center = h.state().viewport_rect.center(); + h.hover_at(center); + h.run_steps(1); + if scroll != 0.0 { + h.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, scroll), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + } + h.run_steps(80); + h.state().session.camera.distance + }; + assert!(end_distance(100.0) != end_distance(0.0), "the wheel zoom stays"); +} diff --git a/crates/ui-egui/tests/it/clone_source_view.rs b/crates/ui-egui/tests/it/clone_source_view.rs new file mode 100644 index 00000000..16297442 --- /dev/null +++ b/crates/ui-egui/tests/it/clone_source_view.rs @@ -0,0 +1,113 @@ +//! The Clone tool marks its source in the 2D view, forgets it when another texture set becomes +//! active, and has an Aligned option in its panel. + +use egui::{Pos2, Shape}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// Radius of the crosshair's circle, and the stroke width of its coloured pass +const MARKER_RADIUS: f32 = 7.0; +const MARKER_STROKE: f32 = 1.2; + +fn clone_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + execute(&mut harness.state_mut().session, "tool.clone", &serde_json::Value::Null).unwrap(); + harness.run_steps(4); + harness +} + +fn set_source(harness: &mut Harness<'_, TextureCraftApp>, uv: [f32; 2]) { + execute(&mut harness.state_mut().session, "tool.cloneSource", &json!({ "uv": uv })).unwrap(); + harness.run_steps(3); +} + +/// Centres of the crosshair circles in the last frame +fn markers(harness: &Harness<'_, TextureCraftApp>) -> Vec { + fn walk(shape: &Shape, out: &mut Vec) { + match shape { + Shape::Vec(shapes) => shapes.iter().for_each(|shape| walk(shape, out)), + Shape::Circle(circle) if circle.radius == MARKER_RADIUS && (circle.stroke.width - MARKER_STROKE).abs() < 1e-3 => out.push(circle.center), + _ => {} + } + } + let mut out = Vec::new(); + harness.output().shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut out)); + out +} + +fn marker_at(harness: &Harness<'_, TextureCraftApp>) -> Pos2 { + let found = markers(harness); + assert_eq!(found.len(), 1, "one crosshair: {found:?}"); + found[0] +} + +#[test] +fn the_2d_view_draws_a_crosshair_at_the_clone_source() { + let mut harness = clone_app(); + assert!(markers(&harness).is_empty(), "no source, no crosshair"); + set_source(&mut harness, [0.25, 0.5]); + let left = marker_at(&harness); + set_source(&mut harness, [0.5, 0.5]); + let middle = marker_at(&harness); + set_source(&mut harness, [0.75, 0.5]); + let right = marker_at(&harness); + assert!((left.y - middle.y).abs() < 0.5 && (right.y - middle.y).abs() < 0.5, "same texture row: {left:?} {middle:?} {right:?}"); + assert!(middle.x - left.x > 50.0, "the crosshair follows the source in u: {left:?} {middle:?}"); + assert!(((middle.x - left.x) - (right.x - middle.x)).abs() < 0.5, "evenly spaced in u: {left:?} {middle:?} {right:?}"); + set_source(&mut harness, [0.5, 0.25]); + let top = marker_at(&harness); + assert!((top.x - middle.x).abs() < 0.5 && top.y < middle.y - 50.0, "v runs upwards on screen: {top:?} {middle:?}"); +} + +#[test] +fn the_2d_view_draws_the_crosshair_for_a_source_on_the_far_edge() { + let mut harness = clone_app(); + set_source(&mut harness, [1.0, 0.5]); + let edge = marker_at(&harness); + set_source(&mut harness, [0.5, 0.5]); + let middle = marker_at(&harness); + assert!(edge.x > middle.x + 50.0, "the edge source sits right of the middle: {edge:?} {middle:?}"); + set_source(&mut harness, [0.5, 1.0]); + let bottom = marker_at(&harness); + assert!(bottom.y > middle.y + 50.0, "v = 1.0 shows too: {bottom:?} {middle:?}"); +} + +#[test] +fn the_2d_crosshair_only_shows_for_the_clone_tool() { + let mut harness = clone_app(); + set_source(&mut harness, [0.5, 0.5]); + assert_eq!(markers(&harness).len(), 1); + execute(&mut harness.state_mut().session, "tool.paint", &serde_json::Value::Null).unwrap(); + harness.run_steps(3); + assert!(markers(&harness).is_empty(), "the paint tool shows no source"); +} + +#[test] +fn switching_the_texture_set_removes_the_clone_source_and_its_crosshair() { + let mut harness = clone_app(); + set_source(&mut harness, [0.5, 0.5]); + assert_eq!(markers(&harness).len(), 1); + let other = if harness.state().session.ts() == 0 { 1 } else { 0 }; + execute(&mut harness.state_mut().session, "textureSet.select", &json!({ "ts": other })).unwrap(); + harness.run_steps(3); + assert!(harness.state().session.tool.clone_source.is_none()); + assert!(markers(&harness).is_empty(), "no crosshair for a source of the other set"); +} + +#[test] +fn the_aligned_checkbox_sets_the_clone_mode() { + let mut harness = clone_app(); + assert!(harness.state().session.tool.clone_aligned, "aligned by default"); + harness.get_by_label("Aligned").click(); + harness.run_steps(3); + assert!(!harness.state().session.tool.clone_aligned); + harness.get_by_label("Aligned").click(); + harness.run_steps(3); + assert!(harness.state().session.tool.clone_aligned); +} diff --git a/crates/ui-egui/tests/it/close_unsaved.rs b/crates/ui-egui/tests/it/close_unsaved.rs index 47996530..e1b74688 100644 --- a/crates/ui-egui/tests/it/close_unsaved.rs +++ b/crates/ui-egui/tests/it/close_unsaved.rs @@ -102,7 +102,7 @@ fn closing_the_project_with_changes_asks_first() { assert_eq!(name(&h), "Edited", "the project stays until answered"); h.get_by_label("Don't save").click(); h.run_steps(2); - assert_ne!(name(&h), "Edited", "Don't save closes the project"); + assert!(!h.state().session.project_open, "Don't save closes the project"); assert!(h.state().ui.windows.unsaved.is_none() && !h.state().session.modified); } diff --git a/crates/ui-egui/tests/it/decal_proportions.rs b/crates/ui-egui/tests/it/decal_proportions.rs new file mode 100644 index 00000000..aa267486 --- /dev/null +++ b/crates/ui-egui/tests/it/decal_proportions.rs @@ -0,0 +1,113 @@ +//! A decal's Width and Height keep the image's proportions, and Flip U / Flip V mirror its image + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::json; +use texturecraft_engine::core::{Decal, LayerId, LayerKind, Projection}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Frames for a click or a typed value to reach the document and the panel +const SETTLE_FRAMES: usize = 3; + +/// The longest text a side's number field shows, cleared before typing a value +const FIELD_TEXT_LIMIT: usize = 12; + +/// The sample app with a decal of a twice-as-wide-as-tall image selected, and its layer +fn app_with_decal() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(8, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("wide.png", png).unwrap(); + let placed = texturecraft_engine::execute( + &mut session, + "layer.add.decal", + &json!({"image": name, "position": [0.0, 0.0, 0.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "size": [0.8, 0.4]}), + ) + .unwrap(); + let layer = LayerId(placed["layer"].as_u64().unwrap()); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, layer) +} + +fn decal(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Decal { + let LayerKind::Fill(fill) = &harness.state().session.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") }; + let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; + *decal +} + +/// Type `value` into the number field of the row labelled `label` and confirm it +fn type_side(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + let field = |harness: &Harness<'_, TextureCraftApp>| { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).map(|node| node.rect().center()).unwrap() + }; + harness.drag_at(field(harness)); + harness.drop_at(field(harness)); + harness.run_steps(2); + harness.key_press(egui::Key::End); + for _ in 0..FIELD_TEXT_LIMIT { + harness.key_press(egui::Key::Backspace); + harness.run_steps(1); + } + for character in value.chars() { + harness.get_all(by().role(Role::TextInput)).find(|node| node.is_focused()).unwrap().type_text(&character.to_string()); + harness.run_steps(1); + } + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn width_and_height_follow_each_other_by_the_image_aspect() { + let (mut harness, layer) = app_with_decal(); + + type_side(&mut harness, "Width", "0.6"); + assert_eq!(decal(&harness, layer).size, [0.6, 0.3], "the width sets the height"); + + type_side(&mut harness, "Height", "0.1"); + assert_eq!(decal(&harness, layer).size, [0.2, 0.1], "the height sets the width"); +} + +#[test] +fn unticking_keep_proportions_frees_each_side() { + let (mut harness, layer) = app_with_decal(); + harness.get_by_label("Keep proportions").click(); + harness.run_steps(SETTLE_FRAMES); + + type_side(&mut harness, "Width", "0.6"); + assert_eq!(decal(&harness, layer).size, [0.6, 0.4], "only the width changes"); + + // Ticking it again fits the height to the width, in one undo step + let steps = harness.state().session.history_labels().len(); + harness.get_by_label("Keep proportions").click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(decal(&harness, layer).size, [0.6, 0.3]); + assert_eq!(harness.state().session.history_labels().len(), steps + 1); +} + +#[test] +fn flip_toggles_mirror_the_image_and_undo_one_step_at_a_time() { + let (mut harness, layer) = app_with_decal(); + assert_eq!(decal(&harness, layer).flip, [false, false]); + + harness.get_by_label("Flip U").click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(decal(&harness, layer).flip, [true, false]); + + harness.get_by_label("Flip V").click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(decal(&harness, layer).flip, [true, true]); + + harness.get_by_label("Flip U").click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(decal(&harness, layer).flip, [false, true], "Flip U toggles back and leaves Flip V"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "edit.undo", &json!({})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(decal(&harness, layer).flip, [true, true]); +} diff --git a/crates/ui-egui/tests/it/decal_symmetry.rs b/crates/ui-egui/tests/it/decal_symmetry.rs new file mode 100644 index 00000000..e97a24a8 --- /dev/null +++ b/crates/ui-egui/tests/it/decal_symmetry.rs @@ -0,0 +1,106 @@ +//! The decal editor's Mirror across and Flip controls set the decal's mirrored copy + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{DecalFlip, LayerKind, Projection}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Tall enough that Properties shows the whole decal editor without scrolling +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1700.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click or selection change to reach the panel +const SETTLE_FRAMES: usize = 3; + +fn red_png() -> Vec { + let mut out = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255])).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out +} + +/// The app with a new decal layer selected in Properties, and its layer id +fn app_with_decal() -> (Harness<'static, TextureCraftApp>, u64) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let image = session.import_resource_bytes("logo.png", red_png()).unwrap(); + let placed = json!({"image": image, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "size": 0.3}); + let layer = texturecraft_engine::execute(&mut session, "layer.add.decal", &placed).unwrap()["layer"].as_u64().unwrap(); + + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + (harness, layer) +} + +fn offset_of(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> f32 { + let project = &harness.state().session.doc.project; + let LayerKind::Fill(fill) = &project.layer(texturecraft_engine::core::LayerId(layer)).unwrap().kind else { panic!("a fill layer") }; + let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; + decal.symmetry.expect("a mirrored copy").offset +} + +fn symmetry_of(harness: &Harness<'_, TextureCraftApp>, layer: u64) -> Option<(u8, DecalFlip)> { + let project = &harness.state().session.doc.project; + let LayerKind::Fill(fill) = &project.layer(texturecraft_engine::core::LayerId(layer)).unwrap().kind else { panic!("a fill layer") }; + let Projection::Decal(decal) = &fill.projection else { panic!("a decal") }; + decal.symmetry.map(|symmetry| (symmetry.axis, symmetry.flip)) +} + +/// Opens the combo showing `current` and picks `choice` in its menu +fn pick(harness: &mut Harness<'_, TextureCraftApp>, current: &str, choice: &str) { + harness.get_all_by_role(Role::ComboBox).find(|combo| combo.value().as_deref() == Some(current)).expect("the combo").click(); + harness.run_steps(SETTLE_FRAMES); + harness.get_all_by_label(choice).last().expect("the menu entry").click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_mirror_axis_and_flip_are_set_from_the_decal_editor() { + let (mut harness, layer) = app_with_decal(); + assert!(harness.query_by_label("Mirror across").is_some()); + assert!(harness.query_by_label("Flip the copy's image").is_none(), "the flip needs a copy to flip"); + assert_eq!(symmetry_of(&harness, layer), None); + + pick(&mut harness, "Off", "X"); + assert_eq!(symmetry_of(&harness, layer), Some((0, DecalFlip::None))); + assert!(harness.query_by_label("Flip the copy's image").is_some()); + + pick(&mut harness, "None", "V"); + assert_eq!(symmetry_of(&harness, layer), Some((0, DecalFlip::V))); + + pick(&mut harness, "X", "Z"); + assert_eq!(symmetry_of(&harness, layer), Some((2, DecalFlip::V)), "a new axis keeps the flip"); + + pick(&mut harness, "Z", "Off"); + assert_eq!(symmetry_of(&harness, layer), None); + assert!(harness.query_by_label("Flip the copy's image").is_none()); +} + +#[test] +fn the_axis_position_slider_moves_the_mirror_plane() { + let (mut harness, layer) = app_with_decal(); + assert!(harness.query_by_label("Axis position").is_none(), "the position needs a copy to place"); + pick(&mut harness, "Off", "Y"); + assert_eq!(offset_of(&harness, layer), 0.0); + + // Press near the track's left end, drag toward its middle and right, release there + let label_rect = harness.get_by_label("Axis position").rect(); + let y = label_rect.bottom() + 10.0; + harness.drag_at(egui::pos2(label_rect.left() + 20.0, y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(label_rect.left() + 120.0, y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(label_rect.left() + 120.0, y)); + harness.run_steps(SETTLE_FRAMES); + assert!(offset_of(&harness, layer).abs() > 0.01, "the dragged position applies: {}", offset_of(&harness, layer)); + assert_eq!(symmetry_of(&harness, layer).map(|symmetry| symmetry.0), Some(1), "the axis is kept"); +} diff --git a/crates/ui-egui/tests/it/display_post_effects.rs b/crates/ui-egui/tests/it/display_post_effects.rs new file mode 100644 index 00000000..61c44c34 --- /dev/null +++ b/crates/ui-egui/tests/it/display_post_effects.rs @@ -0,0 +1,165 @@ +//! Display Settings > Post effects: a switch and the glow, vignette, sharpen and film grain amounts, with a reset on the header. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::project::DisplaySettings; +use texturecraft_ui_egui::TextureCraftApp; + +const SECTION: &str = "Post effects"; +const SWITCH: &str = "Post effects (viewport and Rendering mode)"; +const SLIDERS: [&str; 4] = ["Glow", "Vignette", "Sharpen", "Film grain"]; +const SETTLE_FRAMES: usize = 3; + +/// The four amounts in the order of [`SLIDERS`] +fn amounts(d: &DisplaySettings) -> [f32; 4] { + [d.bloom, d.vignette, d.sharpen, d.grain] +} + +fn display(harness: &Harness<'_, TextureCraftApp>) -> DisplaySettings { + harness.state().session.doc.project.display.clone() +} + +/// The app with Display Settings open from the rail and the Post effects section unfolded +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness + .get_all_by_role(Role::Button) + .find(|b| b.accesskit_node().label().is_some_and(|l| l == "Display Settings" || l.starts_with("Display Settings ("))) + .unwrap() + .click(); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.query_by_label(SWITCH).is_none(), "the section starts folded"); + harness.get_by_label(SECTION).click(); + harness.run_steps(SETTLE_FRAMES * 3); + harness.hover_at(egui::pos2(5.0, 5.0)); + harness.run_steps(SETTLE_FRAMES); + harness +} + +fn reset_icon<'t>(harness: &'t Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'t> { + harness.get_by_role_and_label(Role::Button, "Post effects: Reset to defaults") +} + +fn set_switch(harness: &mut Harness<'_, TextureCraftApp>, on: bool) { + if display(harness).post_effects != on { + harness.get_by_label(SWITCH).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + harness.get_by_label(SWITCH).click(); + harness.run_steps(SETTLE_FRAMES); + } + assert_eq!(display(harness).post_effects, on); +} + +/// Drags the slider labelled `label` from its left end to `x` pixels in +fn drag(harness: &mut Harness<'_, TextureCraftApp>, label: &str, x: f32) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + let l = harness.get_by_label(label).rect(); + let y = l.bottom() + 10.0; + harness.drag_at(egui::pos2(l.left() + 6.0, y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(l.left() + x, y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(l.left() + x, y)); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn the_defaults_are_off() { + let harness = app(); + let d = display(&harness); + assert!(!d.post_effects); + assert_eq!(amounts(&d), [0.0; 4]); + assert!(reset_icon(&harness).accesskit_node().is_disabled(), "nothing to reset yet"); +} + +#[test] +fn each_slider_sets_only_its_own_amount() { + for (i, label) in SLIDERS.into_iter().enumerate() { + let mut harness = app(); + set_switch(&mut harness, true); + drag(&mut harness, label, 120.0); + let got = amounts(&display(&harness)); + assert!(got[i] > 0.05 && got[i] < 1.0, "{label} follows the drag: {got:?}"); + for (j, v) in got.into_iter().enumerate() { + if j != i { + assert_eq!(v, 0.0, "{label} leaves {} alone", SLIDERS[j]); + } + } + } +} + +#[test] +fn sliders_do_nothing_while_the_switch_is_off_and_switching_off_keeps_the_amounts() { + let mut harness = app(); + drag(&mut harness, "Glow", 120.0); + assert_eq!(display(&harness).bloom, 0.0, "the amounts are locked while the effects are off"); + + set_switch(&mut harness, true); + drag(&mut harness, "Glow", 120.0); + let glow = display(&harness).bloom; + assert!(glow > 0.05); + + set_switch(&mut harness, false); + let d = display(&harness); + assert!(!d.post_effects, "the renderer reads this switch, so every effect is off"); + assert_eq!(d.bloom, glow, "the amount is kept for the next time"); + drag(&mut harness, "Film grain", 120.0); + assert_eq!(display(&harness).grain, 0.0); +} + +#[test] +fn the_values_agree_with_the_view_command_and_survive_save_and_open() { + let mut harness = app(); + set_switch(&mut harness, true); + for label in SLIDERS { + drag(&mut harness, label, 120.0); + } + let shown = display(&harness); + assert!(amounts(&shown).iter().all(|v| *v > 0.05)); + + // The command reports the same document values the panel changed + let session = &mut harness.state_mut().session; + let reported = texturecraft_engine::execute(session, "display.set", &json!({})).unwrap(); + assert_eq!(reported["post_effects"], json!(true)); + for (key, want) in [("bloom", shown.bloom), ("vignette", shown.vignette), ("sharpen", shown.sharpen), ("grain", shown.grain)] { + assert_eq!(reported[key].as_f64().unwrap() as f32, want, "{key}"); + } + + let dir = std::env::temp_dir().join(format!("texturecraft-display-post-effects-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("p.tcraft").display().to_string(); + texturecraft_engine::execute(session, "file.saveAs", &json!({"path": path})).unwrap(); + + // Wipe the values, then open the saved file + texturecraft_engine::execute(session, "display.set", &json!({"postEffects": false, "bloom": 0, "vignette": 0, "sharpen": 0, "grain": 0})).unwrap(); + texturecraft_engine::execute(session, "file.open", &json!({"path": path})).unwrap(); + std::fs::remove_dir_all(&dir).ok(); + harness.run_steps(SETTLE_FRAMES); + let loaded = display(&harness); + assert!(loaded.post_effects); + assert_eq!(amounts(&loaded), amounts(&shown)); +} + +#[test] +fn reset_puts_back_only_the_post_effects() { + let mut harness = app(); + harness.state_mut().session.doc.project.display = + DisplaySettings { post_effects: true, bloom: 0.5, vignette: 0.4, sharpen: 0.3, grain: 0.2, env_opacity: 0.5, ..DisplaySettings::default() }; + harness.run_steps(SETTLE_FRAMES); + assert!(!reset_icon(&harness).accesskit_node().is_disabled()); + reset_icon(&harness).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + reset_icon(&harness).focus(); + harness.run_steps(SETTLE_FRAMES); + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + let d = display(&harness); + assert_eq!(DisplaySettings { env_opacity: 0.5, ..DisplaySettings::default() }, d, "post effects are back to the defaults, the rest is untouched"); + assert!(reset_icon(&harness).accesskit_node().is_disabled()); +} diff --git a/crates/ui-egui/tests/it/effect_decal.rs b/crates/ui-egui/tests/it/effect_decal.rs new file mode 100644 index 00000000..101fac1c --- /dev/null +++ b/crates/ui-egui/tests/it/effect_decal.rs @@ -0,0 +1,65 @@ +//! A decal held by a mask fill effect has the same editor as a layer's decal: sliders and the placing click + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{Decal, EffectKind, LayerId, Projection}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with a new decal mask fill effect selected, and that effect's id +fn selected_mask_decal() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let image = { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + session.import_resource_bytes("decal.png", png).unwrap() + }; + let placed = json!({"image": image, "channel": "mask", "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "up": [0.0, 0.0, 1.0], "size": 0.5}); + let effect = LayerId(texturecraft_engine::execute(&mut session, "layer.add.decal", &placed).unwrap()["maskEffect"].as_u64().unwrap()); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, effect) +} + +fn decal(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Decal { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { projection: Projection::Decal(decal), .. } => *decal, + _ => panic!("a decal fill effect"), + } +} + +#[test] +fn the_width_slider_resizes_a_mask_effects_decal_in_one_undo_step() { + let (mut harness, effect) = selected_mask_decal(); + + // Free width and height: with Keep proportions (on by default) the height would follow + harness.get_by_label("Keep proportions").click(); + harness.run_steps(2); + let before = decal(&harness, effect); + let steps = harness.state().session.history_labels().len(); + + let label_rect = harness.get_by_label("Width").rect(); + let y = label_rect.bottom() + 10.0; + harness.drag_at(egui::pos2(label_rect.left() + 10.0, y)); + harness.run_steps(2); + harness.hover_at(egui::pos2(label_rect.left() + 150.0, y)); + harness.run_steps(2); + harness.drop_at(egui::pos2(label_rect.left() + 150.0, y)); + harness.run_steps(3); + + let after = decal(&harness, effect); + assert!(after.size[0] > before.size[0], "the dragged width applies: {} -> {}", before.size[0], after.size[0]); + assert_eq!(after.size[1], before.size[1]); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); + harness.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(decal(&harness, effect), before); +} + +#[test] +fn place_on_the_surface_stays_armed_for_a_mask_effects_decal() { + let (mut harness, effect) = selected_mask_decal(); + harness.get_by_label_contains("Place on the surface").click(); + harness.run_steps(3); + assert_eq!(harness.state().placing_decal, Some(effect), "the click arms placing for the effect, not its layer"); +} diff --git a/crates/ui-egui/tests/it/empty_start.rs b/crates/ui-egui/tests/it/empty_start.rs new file mode 100644 index 00000000..54f4e925 --- /dev/null +++ b/crates/ui-egui/tests/it/empty_start.rs @@ -0,0 +1,395 @@ +//! The app starts with no project and no popup; File > Close goes back to that empty state. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::Session; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +fn harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The exact-text checks below need English, whatever the OS language is + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness +} + +fn empty() -> Harness<'static, TextureCraftApp> { + harness(Session::closed().unwrap()) +} + +fn open_project() -> Harness<'static, TextureCraftApp> { + harness(texturecraft_engine::sample_session(256, 64).unwrap()) +} + +/// Texts painted this frame as (text, left edge) +fn painted(harness: &Harness<'static, TextureCraftApp>) -> Vec<(String, f32)> { + harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some((text.galley.text().to_string(), text.pos.x)), + _ => None, + }) + .collect() +} + +fn has_camera_picker(harness: &Harness<'static, TextureCraftApp>) -> bool { + painted(harness).iter().any(|(text, _)| text == "Default camera") +} + +fn invoke(harness: &mut Harness<'static, TextureCraftApp>, id: &str) { + let ctx = harness.ctx.clone(); + menus::invoke(harness.state_mut(), &ctx, id); + harness.run_steps(3); +} + +#[test] +fn starts_with_no_project_and_no_popup() { + let harness = empty(); + let ui = &harness.state().ui; + + assert!(!harness.state().session.project_open); + assert!(!ui.windows.new_project && !ui.windows.about && !ui.windows.settings && !ui.windows.export, "no window opens by itself"); + assert!(harness.query_by_label("Continue with the sample project").is_none() && harness.query_by_label("Recent projects").is_none(), "no start window"); + assert!(harness.query_by_label("No properties found").is_some(), "Properties says it has nothing"); +} + +#[test] +fn project_items_are_disabled_without_a_project() { + let harness = empty(); + let app = harness.state(); + for id in [ + "file.save", + "file.saveAs", + "file.saveCopy", + "file.close", + "ui.export", + "file.exportMesh", + "ui.projectConfig", + "edit.undo", + "edit.redo", + "file.reimportMesh", + "ui.mode.bake", + "ui.mode.render", + "ui.uvChecker", + "viewport.displayMaterial", + "tool.paint", + "tool.eraser", + "viewport.quickMask", + "layer.add.paint", + "layer.add.fill", + "layer.remove", + "bake.run", + "resource.import", + "material.load", + ] { + assert!(!menus::enabled(app, id), "{id} needs a project"); + } + for id in + ["ui.newProject", "file.open", "project.sample", "ui.settings", "ui.about", "ui.quit", "ui.hideUi", "ui.resetUi", "viewport.frame", "ui.layout.split"] + { + assert!(menus::enabled(app, id), "{id} works without a project"); + } + let open = open_project(); + for id in ["file.save", "file.close", "ui.export", "layer.add.paint", "ui.mode.bake"] { + assert!(menus::enabled(open.state(), id), "{id} is on with a project"); + } +} + +#[test] +fn the_empty_views_keep_the_view_picker_and_drop_the_camera_picker() { + let empty = empty(); + + assert!(!has_camera_picker(&empty), "no camera picker"); + + // The picker shows "Material" right of the tool shelf and the Assets panel: one per view in the split layout + let pickers = painted(&empty).iter().filter(|(text, x)| text == "Material" && *x > 400.0).count(); + + assert_eq!(pickers, 2, "each of the two views keeps its view picker"); + + let open = open_project(); + + assert!(has_camera_picker(&open), "with a project the camera picker is there"); +} + +#[test] +fn the_status_bar_has_the_version_but_no_frame_time_or_layer_memory() { + for harness in [empty(), open_project()] { + assert!(harness.query_by_label_contains("Version:").is_some()); + assert!(harness.query_by_label_contains("Layer memory").is_none()); + assert!(harness.query_by_label_contains(" ms").is_none(), "no frame time"); + } +} + +#[test] +fn close_unloads_the_project_back_to_the_empty_state() { + let mut harness = open_project(); + + assert!(harness.state().session.project_open && harness.state().session.set_count() == 2); + + invoke(&mut harness, "file.close"); + + assert!(!harness.state().session.project_open, "Close leaves no project open"); + assert!(harness.state().session.path.is_none() && !harness.state().session.modified); + assert!(harness.query_by_label("No properties found").is_some()); + assert!(!has_camera_picker(&harness)); + assert!(!menus::enabled(harness.state(), "file.save")); +} + +#[test] +fn creating_or_opening_a_project_from_the_empty_state_works() { + let mut harness = empty(); + + assert!(harness.state_mut().run("project.new", json!({"mesh": "cube", "resolution": 128})).is_some()); + harness.run_steps(3); + + assert!(harness.state().session.project_open); + assert!(menus::enabled(harness.state(), "file.save") && has_camera_picker(&harness)); + + invoke(&mut harness, "file.close"); + invoke(&mut harness, "ui.newProject"); + + assert!(harness.state().ui.windows.new_project, "New project opens its dialog from the empty state"); + + let mut harness = empty(); + + invoke(&mut harness, "project.sample"); + + assert!(harness.state().session.project_open && harness.state().session.set_count() == 2, "the sample is still one menu click away"); +} + +#[test] +fn using_every_panel_and_menu_item_in_the_empty_state_does_not_panic() { + let mut harness = empty(); + for item in menus::CATALOG + .iter() + .filter(|item| item.label != "-" && !matches!(item.id, "ui.quit" | "file.open" | "project.sample" | "ui.layout.load" | "ui.help.checkForUpdates")) + { + invoke(&mut harness, item.id); + } + for mode in ["ui.mode.bake", "ui.mode.render", "ui.mode.paint"] { + invoke(&mut harness, mode); + } + for id in ["ui.layout.2d", "ui.layout.3d", "ui.layout.split"] { + invoke(&mut harness, id); + } + assert!(!harness.state().session.project_open, "none of these opened a project"); + assert!(!harness.state().session.can_undo(), "and none changed it"); +} + +#[test] +fn close_drops_the_pending_resize_and_the_viewport_images() { + let mut harness = open_project(); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some(), "a resize is running"); + + let had_image = texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_some(); + + invoke(&mut harness, "file.close"); + + assert!(harness.state().resize.is_none(), "Close drops the resize of the closed project"); + assert!(!harness.state().session.modified, "a late resize result does not mark the empty project modified"); + if had_image { + assert!( + texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none(), + "no image of the closed project" + ); + } +} + +fn assert_eventually_released(reference: &std::sync::Weak) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while reference.strong_count() > 0 && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + + assert_eq!(reference.strong_count(), 0, "the old project must be released after background work finishes"); +} + +#[test] +fn control_project_replacement_discards_the_old_resize() { + let mut harness = open_project(); + let resource = std::sync::Arc::new(vec![0; 1_048_576]); + let old_resource = std::sync::Arc::downgrade(&resource); + harness.state_mut().session.doc.resources.insert("lifetime-probe.bin".into(), resource); + let old_mesh = std::sync::Arc::downgrade(&harness.state().session.mesh); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some()); + + let resize_progress = std::sync::Arc::downgrade(&harness.state().resize.as_ref().unwrap().progress); + let owners_before = resize_progress.strong_count(); + + let ctx = harness.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle( + harness.state_mut(), + &ctx, + "command.run", + &json!({"id": "project.new", "params": {"mesh": "cube", "resolution": 128}}), + ); + + assert_eq!(reply["ok"], true); + assert!(harness.state().session.project_open); + assert!(harness.state().resize.is_none(), "the previous project's resize must be discarded"); + + let owners_after = resize_progress.strong_count(); + eprintln!("control resize progress owners: {owners_before} before, {owners_after} after replacement"); + + assert!(owners_after < owners_before && owners_after <= 1); + + assert_eventually_released(&resize_progress); + assert_eventually_released(&old_mesh); + assert_eventually_released(&old_resource); + eprintln!( + "released old mesh and 1_048_576-byte resource after replacement: mesh={}, resource={}, progress={}", + old_mesh.strong_count(), + old_resource.strong_count(), + resize_progress.strong_count() + ); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo(), "the old resize must not change the new project"); +} + +#[test] +fn control_close_rejects_a_viewport_capture_before_the_next_frame() { + let mut harness = open_project(); + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, "command.run", &json!({"id": "file.close"})); + + assert_eq!(reply["ok"], true); + assert!(!harness.state().session.project_open); + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none()); +} + +#[test] +fn control_close_dismisses_the_export_dialog() { + let mut harness = open_project(); + harness.state_mut().ui.windows.export = true; + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, "command.run", &json!({"id": "file.close"})); + + assert_eq!(reply["ok"], true); + assert!(!harness.state().session.project_open); + assert!(!harness.state().ui.windows.export, "Close dismisses the dialog before the next frame"); +} + +#[test] +fn uploaded_project_replacement_discards_the_old_resize() { + let mut harness = open_project(); + let bytes = harness.state().session.to_project_bytes().unwrap(); + let resource = std::sync::Arc::new(vec![0; 2_097_152]); + let old_resource = std::sync::Arc::downgrade(&resource); + harness.state_mut().session.doc.resources.insert("lifetime-probe.bin".into(), resource); + let old_mesh = std::sync::Arc::downgrade(&harness.state().session.mesh); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some()); + + let resize_progress = std::sync::Arc::downgrade(&harness.state().resize.as_ref().unwrap().progress); + let owners_before = resize_progress.strong_count(); + + texturecraft_ui_egui::web_files::load(harness.state_mut(), "replacement.tcraft", bytes); + + assert!(harness.state().session.project_open); + assert!(harness.state().resize.is_none(), "the previous project's resize must be discarded"); + + let owners_after = resize_progress.strong_count(); + eprintln!("upload resize progress owners: {owners_before} before, {owners_after} after replacement"); + + assert!(owners_after < owners_before && owners_after <= 1); + + assert_eventually_released(&resize_progress); + assert_eventually_released(&old_mesh); + assert_eventually_released(&old_resource); + eprintln!( + "released old mesh and 2_097_152-byte resource after replacement: mesh={}, resource={}, progress={}", + old_mesh.strong_count(), + old_resource.strong_count(), + resize_progress.strong_count() + ); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo(), "the old resize must not change the uploaded project"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn file_new_discards_the_old_resize() { + let path = std::env::temp_dir().join(format!("texturecraft-file-new-resize-{}.obj", std::process::id())); + std::fs::write(&path, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap(); + let mut harness = open_project(); + harness.state_mut().start_resize(0, 128); + + assert!(harness.state().resize.is_some()); + + let result = harness.state_mut().run("file.new", json!({"mesh": path.display().to_string(), "resolution": 128})); + let _ = std::fs::remove_file(&path); + + assert!(result.is_some()); + assert!(harness.state().session.project_open); + assert!(harness.state().resize.is_none(), "the previous project's resize must be discarded"); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo(), "the old resize must not change the mesh project"); +} + +#[test] +fn closed_session_rejects_project_control_operations() { + for (method, params) in [("ui.bake.start", json!({"ts": 0})), ("debug.paintTest", json!({"from": [640, 400], "to": [650, 400], "frames": 2}))] { + let mut harness = empty(); + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, method, ¶ms); + + assert_eq!(reply["ok"], false, "{method}: {reply}"); + assert!(reply["error"].as_str().unwrap().contains("no project is open")); + assert!(harness.state().bake.is_none()); + assert!(harness.state().session.bake_preview.is_none()); + + harness.run_steps(3); + + assert!(!harness.state().session.modified && !harness.state().session.can_undo()); + } +} + +#[test] +fn close_releases_the_layer_thumbnail_snapshot() { + for _ in 0..2 { + let mut harness = open_project(); + let old_mesh = std::sync::Arc::downgrade(&harness.state().session.mesh); + let old_maps: Vec<_> = harness + .state() + .session + .doc + .baked + .values() + .flat_map(|maps| maps.maps.values()) + .map(|pixels| (std::sync::Arc::downgrade(pixels), std::mem::size_of_val(pixels.as_slice()))) + .collect(); + let tracked_bytes: usize = old_maps.iter().map(|(_, bytes)| bytes).sum(); + + invoke(&mut harness, "file.close"); + + assert!(!harness.state().session.project_open); + assert_eventually_released(&old_mesh); + for (pixels, _) in &old_maps { + assert_eventually_released(pixels); + } + eprintln!( + "closed thumbnail snapshot: mesh owners={}, {} baked-map allocations ({} bytes) released", + old_mesh.strong_count(), + old_maps.len(), + tracked_bytes + ); + } +} diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs new file mode 100644 index 00000000..9cfc0071 --- /dev/null +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -0,0 +1,168 @@ +//! Export dialog > Output templates: deleting a template asks first, and switching away from a +//! template whose last edit does not validate (so is not saved) asks before dropping that edit. + +use egui::Key; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; + +mod library; + +use library::Library; + +/// The Output templates tab with two user templates, "Alpha tpl" (selected) and "Beta tpl", saved in `library`. +fn harness(library: &Library) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h.state_mut().session.load_export_presets(library.0.clone()); + let base = texturecraft_engine::formats::builtin_presets().remove(0); + for name in ["Alpha tpl", "Beta tpl"] { + let preset = texturecraft_engine::formats::ExportPreset { name: name.into(), ..base.clone() }; + h.state_mut().run("export.preset.save", json!({ "preset": preset })).unwrap(); + } + let ui = &mut h.state_mut().ui; + ui.windows.export = true; + ui.export.tab = 1; + ui.export.preset = "Alpha tpl".into(); + h.run_steps(4); + h +} + +/// Type an invalid file name into the first output of the selected template, as the editor would. +fn break_draft(h: &mut Harness<'_, TextureCraftApp>) { + let draft = h.state_mut().ui.export.draft.as_mut().unwrap(); + draft.maps[0].file = "a/b".into(); + assert!(draft.validate().is_err()); + h.run_steps(3); +} + +fn selected(h: &Harness<'_, TextureCraftApp>) -> String { + h.state().ui.export.preset.clone() +} + +#[test] +fn delete_asks_and_cancel_keeps_the_template() { + let library = Library::new("delete-cancel"); + let mut h = harness(&library); + assert_eq!(library.files(), 2); + h.get_by_label("Delete the selected template").click(); + h.run_steps(3); + assert_eq!(library.files(), 2, "nothing is deleted before the answer"); + + // The export dialog has a Cancel too; the question's comes last + h.get_all_by_label("Cancel").last().unwrap().click(); + h.run_steps(3); + assert!(h.state().ui.windows.export, "the export dialog stays open"); + assert_eq!(library.files(), 2, "Cancel keeps the file"); + assert!(h.state().session.export_presets.list.iter().any(|p| p.name == "Alpha tpl")); + assert!(h.state().ui.export.ask.is_none()); +} + +#[test] +fn escape_keeps_the_template_being_deleted() { + let library = Library::new("delete-escape"); + let mut h = harness(&library); + h.get_by_label("Delete the selected template").click(); + h.run_steps(3); + h.key_press(Key::Escape); + h.run_steps(3); + assert_eq!(library.files(), 2); + assert!(h.state().ui.export.ask.is_none(), "Escape closes the question"); +} + +#[test] +fn delete_ok_removes_the_template_and_its_file() { + let library = Library::new("delete-ok"); + let mut h = harness(&library); + h.get_by_label("Delete the selected template").click(); + h.run_steps(3); + h.get_by_label("Delete").click(); + h.run_steps(3); + assert_eq!(library.files(), 1, "the file is gone"); + assert!(!h.state().session.export_presets.list.iter().any(|p| p.name == "Alpha tpl")); + assert!(h.state().ui.export.ask.is_none()); +} + +#[test] +fn unfinished_edit_asks_before_selecting_another_template_and_keep_editing_stays() { + let library = Library::new("keep-editing"); + let mut h = harness(&library); + break_draft(&mut h); + h.get_by_label_contains("Beta tpl").scroll_to_me(); + h.run_steps(12); + h.get_by_label_contains("Beta tpl").click(); + h.run_steps(3); + assert_eq!(selected(&h), "Alpha tpl", "the selection waits for the answer"); + h.get_by_label("Keep editing").click(); + h.run_steps(3); + assert_eq!(selected(&h), "Alpha tpl"); + assert_eq!(h.state().ui.export.draft.as_ref().unwrap().maps[0].file, "a/b", "the edit is intact"); + assert!(h.state().ui.export.ask.is_none()); +} + +#[test] +fn unfinished_edit_discard_switches_to_the_other_template() { + let library = Library::new("discard"); + let mut h = harness(&library); + break_draft(&mut h); + h.get_by_label_contains("Beta tpl").scroll_to_me(); + h.run_steps(12); + h.get_by_label_contains("Beta tpl").click(); + h.run_steps(3); + h.get_by_label("Discard changes").click(); + h.run_steps(3); + assert_eq!(selected(&h), "Beta tpl"); + let draft = h.state().ui.export.draft.as_ref().unwrap(); + assert_eq!(draft.name, "Beta tpl"); + assert!(draft.validate().is_ok(), "the dropped edit did not follow"); + let alpha = h.state().session.export_preset("Alpha tpl").unwrap(); + assert_ne!(alpha.maps[0].file, "a/b", "the invalid edit was never saved"); +} + +#[test] +fn unfinished_edit_also_asks_before_new_template() { + let library = Library::new("new"); + let mut h = harness(&library); + break_draft(&mut h); + h.get_by_label("New template").click(); + h.run_steps(3); + assert_eq!(library.files(), 2, "no template is added before the answer"); + h.key_press(Key::Escape); + h.run_steps(3); + assert_eq!(selected(&h), "Alpha tpl"); + assert_eq!(library.files(), 2); +} + +#[test] +fn a_saved_edit_switches_without_asking() { + let library = Library::new("saved"); + let mut h = harness(&library); + let mut draft = h.state().ui.export.draft.clone().unwrap(); + draft.maps[0].file = "$mesh_Edited".into(); + assert!(draft.validate().is_ok()); + h.state_mut().run("export.preset.save", json!({ "preset": draft })).unwrap(); + h.run_steps(3); + h.get_by_label_contains("Beta tpl").scroll_to_me(); + h.run_steps(12); + h.get_by_label_contains("Beta tpl").click(); + h.run_steps(3); + assert!(h.state().ui.export.ask.is_none(), "nothing to ask: the edit is saved"); + assert_eq!(selected(&h), "Beta tpl"); + assert_eq!(h.state().session.export_preset("Alpha tpl").unwrap().maps[0].file, "$mesh_Edited"); +} + +#[test] +fn the_settings_dropdown_asks_about_an_unfinished_edit_too() { + let library = Library::new("dropdown"); + let mut h = harness(&library); + break_draft(&mut h); + texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into()); + assert_eq!(selected(&h), "Alpha tpl"); + assert!(h.state().ui.export.ask.is_some()); + h.state_mut().ui.export.ask = None; + h.state_mut().ui.export.draft.as_mut().unwrap().maps[0].file = "$mesh_ok".into(); + texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into()); + assert_eq!(selected(&h), "Beta tpl", "a valid edit switches at once"); +} diff --git a/crates/ui-egui/tests/it/export_template_guards/library.rs b/crates/ui-egui/tests/it/export_template_guards/library.rs new file mode 100644 index 00000000..f5a112b1 --- /dev/null +++ b/crates/ui-egui/tests/it/export_template_guards/library.rs @@ -0,0 +1,22 @@ +use std::path::PathBuf; + +/// A library folder removed when its owner drops +pub(super) struct Library(pub(super) PathBuf); + +impl Library { + pub(super) fn new(test: &str) -> Self { + let path = std::env::temp_dir().join(format!("texturecraft-template-guards-{test}-{}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + pub(super) fn files(&self) -> usize { + std::fs::read_dir(&self.0).unwrap().flatten().filter(|entry| entry.path().extension().is_some_and(|extension| extension == "json")).count() + } +} + +impl Drop for Library { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} diff --git a/crates/ui-egui/tests/it/fill_channel_image.rs b/crates/ui-egui/tests/it/fill_channel_image.rs index ea48beb4..b03a4440 100644 --- a/crates/ui-egui/tests/it/fill_channel_image.rs +++ b/crates/ui-egui/tests/it/fill_channel_image.rs @@ -1,4 +1,4 @@ -//! A fill channel takes an image resource from its source menu. +//! A fill channel takes an image resource from its source picker use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -6,26 +6,22 @@ use serde_json::json; use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source}; use texturecraft_ui_egui::TextureCraftApp; -/// The Roughness channel's name in Properties (the rightmost "Roughness" label). +/// The Roughness channel's source slot in Properties fn roughness<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - harness.get_all_by_label("Roughness").max_by(|a, b| a.rect().right().total_cmp(&b.rect().right())).unwrap() + harness.get_by_role_and_label(egui::Role::ComboBox, "Roughness") } -/// Opens the source menu of the Roughness channel, which sits in the row of the channel's name. -fn open_roughness_source_menu(harness: &mut Harness<'_, TextureCraftApp>) { - const ROW_CENTER_TOLERANCE_POINTS: f32 = 6.0; - - // Allow the scroll animation to finish before locating the menu +/// Opens the source picker of the Roughness channel from its slot +fn open_roughness_source_picker(harness: &mut Harness<'_, TextureCraftApp>) { + // Allow the scroll animation to finish before the click roughness(harness).scroll_to_me(); harness.run_steps(30); - let row = roughness(harness).rect().center().y; - let menu = harness.get_all_by_label(egui_phosphor::regular::DOTS_THREE).find(|n| (n.rect().center().y - row).abs() < ROW_CENTER_TOLERANCE_POINTS).unwrap(); - menu.click(); - harness.run_steps(2); + roughness(harness).click(); + harness.run_steps(3); } #[test] -fn a_fill_channel_takes_an_image_from_its_source_menu() { +fn a_fill_channel_takes_an_image_from_its_source_picker() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut png_bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 255])).write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap(); @@ -38,8 +34,8 @@ fn a_fill_channel_takes_an_image_from_its_source_menu() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_menu(&mut harness); - harness.get_by_label(&name).click(); + open_roughness_source_picker(&mut harness); + harness.get_by_role_and_label(egui::Role::Button, &name).click(); harness.run_steps(3); let LayerKind::Fill(fill) = &harness.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; @@ -48,7 +44,7 @@ fn a_fill_channel_takes_an_image_from_its_source_menu() { /// A resource that did not decode is not offered, since the commands that take an image refuse it. #[test] -fn the_source_menu_offers_only_images_that_were_decoded() { +fn the_source_picker_offers_only_images_that_were_decoded() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut png_bytes = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([90, 90, 90, 255])).write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap(); @@ -63,7 +59,7 @@ fn the_source_menu_offers_only_images_that_were_decoded() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - open_roughness_source_menu(&mut harness); + open_roughness_source_picker(&mut harness); assert!(harness.query_by_label(&name).is_some(), "a decoded image is offered"); assert!(harness.query_by_label("broken.png").is_none(), "an image that did not decode is not"); @@ -130,11 +126,12 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { harness.state_mut().ui.prefs.language = "en".into(); harness.run_steps(4); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().scroll_to_me(); + // The mask fill's slot opens the source picker + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").scroll_to_me(); harness.run_steps(30); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click(); - harness.run_steps(2); - harness.get_by_label(&image_name).click(); + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, &image_name).click(); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; @@ -148,10 +145,10 @@ fn a_mask_fill_selects_an_image_edits_projection_and_returns_to_uniform() { let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; assert!(matches!(effect, EffectKind::Fill { projection: Projection::Triplanar { .. }, .. })); - let image_label = format!("Image: {image_name}"); - harness.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some(image_label.as_str())).unwrap().click(); - harness.run_steps(2); - harness.get_by_label("Uniform value").click(); + assert_eq!(harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").value().as_deref(), Some(image_name.as_str()), "the slot names the image"); + harness.get_by_role_and_label(egui::Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Uniform value").click(); harness.run_steps(3); let effect = &harness.state().session.doc.project.effect(effect_id).unwrap().1.kind; diff --git a/crates/ui-egui/tests/it/frame_selection.rs b/crates/ui-egui/tests/it/frame_selection.rs new file mode 100644 index 00000000..f93c8b51 --- /dev/null +++ b/crates/ui-egui/tests/it/frame_selection.rs @@ -0,0 +1,36 @@ +//! Shift+F frames the active texture set, F the whole mesh; a floor plane must not decide the view + +use egui::{Event, Key, Modifiers}; +use egui_kittest::Harness; +use texturecraft_engine::Session; +use texturecraft_ui_egui::TextureCraftApp; + +const SCENE_OBJ: &str = "o Hydrant\nusemtl Hydrant\nv 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n\ +o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n"; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn press(h: &mut Harness<'_, TextureCraftApp>, key: Key, modifiers: Modifiers) { + h.event(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + h.run_steps(2); +} + +#[test] +fn shift_f_frames_the_painted_object_and_f_the_whole_scene() { + let mut h = harness(); + let whole = h.state().session.camera; + + press(&mut h, Key::F, Modifiers::SHIFT); + let framed = h.state().session.camera; + assert!((framed.target - texturecraft_engine::geom::glam::Vec3::new(0.5, 0.5, 0.0)).length() < 1e-4, "{:?}", framed.target); + assert!(framed.distance < whole.distance * 0.05, "{} vs {}", framed.distance, whole.distance); + + press(&mut h, Key::F, Modifiers::NONE); + let back = h.state().session.camera; + assert!((back.target - whole.target).length() < 1e-4 && (back.distance - whole.distance).abs() < 1e-3, "{back:?} vs {whole:?}"); +} diff --git a/crates/ui-egui/tests/it/gradient_map_menu.rs b/crates/ui-egui/tests/it/gradient_map_menu.rs new file mode 100644 index 00000000..a19e6cb5 --- /dev/null +++ b/crates/ui-egui/tests/it/gradient_map_menu.rs @@ -0,0 +1,55 @@ +//! The Gradient Map item of a fill's Base color source menu turns color stops on and off. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::{Channel, LayerId, LayerKind}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The Base color channel's name in Properties (the rightmost "Base color" label). +fn base_color<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_all_by_label("Base color").max_by(|a, b| a.rect().right().total_cmp(&b.rect().right())).unwrap() +} + +/// Opens the Base color source menu and clicks its Gradient Map item. +fn click_gradient_map(h: &mut Harness<'_, TextureCraftApp>) { + base_color(h).scroll_to_me(); + + // The scroll animates for about twenty frames + h.run_steps(30); + let row = base_color(h).rect().center().y; + let menu = h.get_all_by_label(egui_phosphor::regular::DOTS_THREE).find(|n| (n.rect().center().y - row).abs() < 6.0).unwrap(); + let at = menu.rect().center(); + menu.click(); + h.run_steps(2); + + // The filter of the same name may show elsewhere (the shelf): the menu's item is the nearest + let item = h.get_all_by_label("Gradient Map").min_by(|a, b| a.rect().center().distance(at).total_cmp(&b.rect().center().distance(at))).unwrap(); + item.click(); + h.run_steps(3); +} + +fn ramp(h: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Vec<[f32; 3]> { + let LayerKind::Fill(fill) = &h.state().session.doc.project.layers[&layer].kind else { panic!("a fill layer") }; + fill.source(Channel::BaseColor).ramp().to_vec() +} + +#[test] +fn the_base_color_menu_turns_a_procedural_gradient_map_on_and_off() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let out = texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + let layer = LayerId(out["layer"].as_u64().unwrap()); + let set = json!({"layer": layer.0, "channel": "baseColor", "procedural": "Clouds", "low": [0.0, 0.25, 0.5], "high": [1.0, 0.75, 0.5]}); + texturecraft_engine::execute(&mut session, "layer.fill.set", &set).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // The labels below are English; a first run would speak the system's language + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + // The stops start at low, halfway and high, so the fill looks the same until they change + click_gradient_map(&mut h); + assert_eq!(ramp(&h, layer), vec![[0.0, 0.25, 0.5], [0.5; 3], [1.0, 0.75, 0.5]]); + click_gradient_map(&mut h); + assert!(ramp(&h, layer).is_empty(), "the item turns the stops off again"); +} diff --git a/crates/ui-egui/tests/it/import_resources.rs b/crates/ui-egui/tests/it/import_resources.rs index a88a6eb4..173a3dc9 100644 --- a/crates/ui-egui/tests/it/import_resources.rs +++ b/crates/ui-egui/tests/it/import_resources.rs @@ -10,27 +10,7 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; -/// A test folder removed when its owner drops -struct TempDir(PathBuf); - -impl TempDir { - fn new(test: &str) -> Self { - let path = std::env::temp_dir().join(format!("texturecraft-{test}-{}", std::process::id())); - std::fs::create_dir_all(&path).unwrap(); - - Self(path) - } - - fn path(&self) -> &Path { - &self.0 - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - std::fs::remove_dir_all(&self.0).ok(); - } -} +use super::temp_dir::TempDir; const TITLE: &str = "Import resources"; /// The prefix field's tooltip, which is its accessible label. @@ -99,26 +79,26 @@ fn the_menu_opens_the_window_without_importing_or_asking() { assert!(is_open(&h)); assert!(resources(&h).is_empty()); - assert!(h.query_by_label("Import your resources and set their usage").is_some()); - assert!(combos(&h, "All imported resources (0)").next().is_some()); + assert!(h.query_by_label("Choose files and assign their roles").is_some()); + assert!(combos(&h, "All files (0)").next().is_some()); assert!(h.get_by_label("Remove selected resources").accesskit_node().is_disabled(), "nothing is selected"); } #[test] fn added_files_are_listed_and_import_keeps_their_names() { let dir = TempDir::new("import-resources-add"); - let (a, b) = (png(dir.path(), "bluenoise.png"), png(dir.path(), "scratch.png")); + let (a, b) = (png(&dir, "bluenoise.png"), png(&dir, "scratch.png")); let mut h = app(); invoke(&mut h); add(&mut h, &[a.clone(), b]); - assert!(combos(&h, "All imported resources (2)").next().is_some()); + assert!(combos(&h, "All files (2)").next().is_some()); assert!(h.query_by_label("bluenoise.png").is_some() && h.query_by_label("scratch.png").is_some()); assert!(resources(&h).is_empty(), "adding only lists"); // The same file twice is one row add(&mut h, &[a]); - assert!(combos(&h, "All imported resources (2)").next().is_some()); + assert!(combos(&h, "All files (2)").next().is_some()); click(&mut h, "Import"); assert!(!is_open(&h)); @@ -130,7 +110,7 @@ fn remove_selected_drops_only_the_selected_rows() { let dir = TempDir::new("import-resources-remove"); let mut h = app(); invoke(&mut h); - add(&mut h, &[png(dir.path(), "one.png"), png(dir.path(), "two.png")]); + add(&mut h, &[png(&dir, "one.png"), png(&dir, "two.png")]); h.get_by_label("one.png").click(); h.run_steps(3); @@ -138,7 +118,7 @@ fn remove_selected_drops_only_the_selected_rows() { assert!(h.query_by_label("one.png").is_none()); assert!(h.query_by_label("two.png").is_some()); - assert!(combos(&h, "All imported resources (1)").next().is_some()); + assert!(combos(&h, "All files (1)").next().is_some()); click(&mut h, "Import"); assert_eq!(resources(&h), ["two.png"]); } @@ -148,7 +128,7 @@ fn the_usage_defaults_to_undefined_and_the_choice_reaches_the_import() { let dir = TempDir::new("import-resources-usage"); let mut h = app(); invoke(&mut h); - add(&mut h, &[png(dir.path(), "plain.png"), png(dir.path(), "brush.png"), png(dir.path(), "sky.png")]); + add(&mut h, &[png(&dir, "plain.png"), png(&dir, "brush.png"), png(&dir, "sky.png")]); assert_eq!(combos(&h, "undefined").count(), 3); choose_usage(&mut h, 1, "alpha"); @@ -166,7 +146,7 @@ fn a_prefix_goes_in_front_of_the_resource_name() { let dir = TempDir::new("import-resources-prefix"); let mut h = app(); invoke(&mut h); - add(&mut h, &[png(dir.path(), "dust.png")]); + add(&mut h, &[png(&dir, "dust.png")]); h.get_by_role_and_label(Role::TextInput, PREFIX_HINT).click(); h.run_steps(2); @@ -182,7 +162,7 @@ fn unsupported_usages_and_the_user_library_are_listed_but_disabled() { let dir = TempDir::new("import-resources-disabled"); let mut h = app(); invoke(&mut h); - add(&mut h, &[png(dir.path(), "x.png")]); + add(&mut h, &[png(&dir, "x.png")]); combos(&h, "undefined").next().expect("the dropdown").click(); h.run_steps(3); @@ -193,10 +173,9 @@ fn unsupported_usages_and_the_user_library_are_listed_but_disabled() { h.get_by_label("texture").click(); h.run_steps(3); - combos(&h, "current session").next().expect("the dropdown").click(); + combos(&h, "Open project").next().expect("the dropdown").click(); h.run_steps(3); - assert!(h.get_by_label("library 'your_assets'").accesskit_node().is_disabled()); - assert!(h.query_by_label("To add a new library, see the Edit / Settings menu").is_some(), "the note at the bottom left"); + assert!(h.get_by_label("Asset library").accesskit_node().is_disabled()); } #[test] @@ -204,7 +183,7 @@ fn cancel_imports_nothing() { let dir = TempDir::new("import-resources-cancel"); let mut h = app(); invoke(&mut h); - add(&mut h, &[png(dir.path(), "never.png")]); + add(&mut h, &[png(&dir, "never.png")]); click(&mut h, "Cancel"); assert!(!is_open(&h)); @@ -212,13 +191,13 @@ fn cancel_imports_nothing() { // Reopening starts empty invoke(&mut h); - assert!(combos(&h, "All imported resources (0)").next().is_some()); + assert!(combos(&h, "All files (0)").next().is_some()); } #[test] fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { let dir = TempDir::new("import-resources-command"); - let file = png(dir.path(), "tile.png"); + let file = png(&dir, "tile.png"); let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let plain = texturecraft_engine::execute(&mut session, "resource.import", &serde_json::json!({"path": file.display().to_string()})).unwrap(); @@ -228,3 +207,64 @@ fn the_engine_command_still_imports_a_path_with_an_optional_prefix() { assert_eq!(plain["name"], "tile.png"); assert_eq!(prefixed["name"], "a_b_tile.png"); } + +#[test] +fn only_failed_rows_remain_after_a_partial_import() { + let dir = TempDir::new("import-resources-retry"); + let good = png(&dir, "good.png"); + let failed = dir.join("retry.png"); + let mut h = app(); + invoke(&mut h); + add(&mut h, &[good, failed.clone()]); + choose_usage(&mut h, 1, "alpha"); + { + let rows = &mut h.state_mut().ui.windows.import_resources.as_mut().unwrap().rows; + rows[1].prefix = "brush_".into(); + } + h.run_steps(2); + + click(&mut h, "Import"); + + let rows = &h.state().ui.windows.import_resources.as_ref().expect("failed row stays open").rows; + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].path, failed); + assert_eq!(rows[0].prefix, "brush_"); + assert_eq!(resources(&h), ["good.png"]); + + png(&dir, "retry.png"); + click(&mut h, "Import"); + + assert!(!is_open(&h)); + assert_eq!(resources(&h), ["brush_retry.png", "good.png"]); + assert_eq!(h.state().session.tool.brush.alpha_image.as_deref(), Some("brush_retry.png")); +} + +#[test] +fn opening_import_resources_replaces_project_configuration() { + let mut h = app(); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "ui.projectConfig"); + assert!(h.state().ui.windows.project_config.is_some()); + + invoke(&mut h); + + assert!(is_open(&h)); + assert!(h.state().ui.windows.project_config.is_none()); +} + +#[test] +#[ignore = "offscreen GPU snapshot; set TC_UI_SNAPSHOTS to an output directory"] +fn import_resources_snapshot() { + let output_dir = PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + let dir = TempDir::new("import-resources-snapshot"); + let session = Session::new_project("Resources", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + + invoke(&mut h); + add(&mut h, &[png(&dir, "panel_basecolor.png"), png(&dir, "brush_alpha.png")]); + choose_usage(&mut h, 1, "alpha"); + + std::fs::create_dir_all(&output_dir).unwrap(); + h.render().unwrap().save(output_dir.join("import-resources.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/inactive_set_hint.rs b/crates/ui-egui/tests/it/inactive_set_hint.rs new file mode 100644 index 00000000..c6f1f8f1 --- /dev/null +++ b/crates/ui-egui/tests/it/inactive_set_hint.rs @@ -0,0 +1,111 @@ +//! A brush stroke that starts on a texture set that is not the active one paints nothing and says why, once per stroke + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use texturecraft_engine::Tool; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; + +/// Distance between the view points searched for a set +const SEARCH_STEP: f32 = 8.0; + +/// The sample project (the ball is set 0, the base set 1) with the Ball active and the paint tool, at 1600 x 960 +fn sample_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + assert_eq!(harness.state().session.ts(), 0); + assert_eq!(harness.state().session.tool.tool, Tool::Paint); + harness +} + +/// How far around a point `set` must still show, so a drag that starts there stays on the set +const MARGIN: f32 = 32.0; + +/// The first point of the 3D view with texture set `set` all around it +fn point_over(harness: &Harness<'_, TextureCraftApp>, set: usize) -> Pos2 { + let app = harness.state(); + let rect = app.viewport_rect; + let steps = |length: f32| (1..(length / SEARCH_STEP) as usize).map(|step| step as f32 * SEARCH_STEP); + + steps(rect.height()) + .flat_map(|y| steps(rect.width()).map(move |x| (x, y))) + .find(|&(x, y)| { + [(0.0, 0.0), (MARGIN, 0.0), (-MARGIN, 0.0), (0.0, MARGIN), (0.0, -MARGIN)] + .iter() + .all(|(dx, dy)| app.session.texture_set_at(Vec2::new(x + dx, y + dy), app.session.viewport) == Some(set)) + }) + .map(|(x, y)| rect.min + vec2(x, y)) + .unwrap() +} + +/// Press at `from`, move by `by` in a few steps and release +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, by: egui::Vec2) { + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=6 { + harness.hover_at(from + by * (step as f32 / 6.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +/// The text of the toast that says the sample project's second set is not active +fn hint_text(harness: &Harness<'_, TextureCraftApp>) -> String { + let name = &harness.state().session.doc.project.texture_sets[1].name; + format!("Texture set '{name}' is not active for painting. Select it in the Texture Sets list.") +} + +/// How many toasts say that the sample project's second set is not active +fn hint_count(harness: &Harness<'_, TextureCraftApp>) -> usize { + let hint = hint_text(harness); + harness.state().toasts.iter().filter(|toast| toast.text == hint).count() +} + +#[test] +fn a_stroke_starting_on_another_set_shows_the_hint_once_and_paints_nothing() { + let mut harness = sample_app(); + let history = harness.state().session.history_labels().len(); + + let base = point_over(&harness, 1); + drag(&mut harness, base, vec2(24.0, 0.0)); + + assert_eq!(hint_count(&harness), 1, "one toast for the whole drag, not one per frame"); + assert_eq!(harness.state().session.history_labels().len(), history, "nothing was painted"); + assert_eq!(harness.state().session.ts(), 0, "the stroke does not switch the active set"); + + // A second stroke on that set says it again (the first toast may have expired by then) + let hint = hint_text(&harness); + let first_until = harness.state().toasts.iter().filter(|toast| toast.text == hint).map(|toast| toast.until).fold(f64::MIN, f64::max); + drag(&mut harness, base + vec2(0.0, 12.0), vec2(24.0, 0.0)); + assert!( + harness.state().toasts.iter().any(|toast| toast.text == hint && toast.until > first_until), + "the second stroke shows a new inactive-set hint, not just any toast" + ); +} + +#[test] +fn a_stroke_on_the_active_set_shows_no_hint_and_paints() { + let mut harness = sample_app(); + let history = harness.state().session.history_labels().len(); + + let ball = point_over(&harness, 0); + drag(&mut harness, ball, vec2(24.0, 0.0)); + + assert!(harness.state().toasts.iter().all(|toast| !toast.text.contains("is not active for painting"))); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the stroke painted"); +} + +#[test] +fn the_color_picker_shows_no_hint_on_another_set() { + let mut harness = sample_app(); + harness.state_mut().session.tool.tool = Tool::ColorPicker; + harness.run_steps(2); + + let base = point_over(&harness, 1); + drag(&mut harness, base, vec2(24.0, 0.0)); + + assert_eq!(hint_count(&harness), 0, "the color picker reads any set, so it needs no hint"); +} diff --git a/crates/ui-egui/tests/it/layer_blending_options.rs b/crates/ui-egui/tests/it/layer_blending_options.rs new file mode 100644 index 00000000..d20dc7b4 --- /dev/null +++ b/crates/ui-egui/tests/it/layer_blending_options.rs @@ -0,0 +1,112 @@ +//! Layer menu ▸ Blending options: apply the displayed channel's blending to all channels, copy and paste it between layers. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{BlendMode, Channel, ChannelBlend, LayerId}; +use texturecraft_ui_egui::TextureCraftApp; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn blending(h: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Vec<(Channel, ChannelBlend)> { + h.state().session.doc.project.layers[&layer].channels.iter().map(|(c, b)| (*c, *b)).collect() +} + +/// Gives `layer` a distinct blending on base color and, when it has it, roughness. +fn set_distinct(h: &mut Harness<'_, TextureCraftApp>, layer: LayerId) { + let s = &mut h.state_mut().session; + texturecraft_engine::execute(s, "layer.blend", &json!({"layer": layer.0, "channel": "baseColor", "mode": "Multiply", "opacity": 0.4})).unwrap(); + texturecraft_engine::execute(s, "layer.blend", &json!({"layer": layer.0, "channel": "roughness", "mode": "Overlay", "opacity": 0.7})).unwrap(); +} + +fn menu_item(h: &mut Harness<'_, TextureCraftApp>, layer: LayerId, item: &str) { + let name = h.state().session.doc.project.layers[&layer].name.clone(); + h.get_by_label(&name).click_secondary(); + h.run_steps(3); + h.get_all_by_label("Blending options").last().unwrap().click(); + h.run_steps(3); + h.get_all_by_label(item).last().unwrap().click(); + h.run_steps(3); +} + +fn first_layer(h: &Harness<'_, TextureCraftApp>) -> LayerId { + h.state().session.selected_layer().unwrap() +} + +#[test] +fn apply_both_copies_mode_and_opacity_to_every_channel_in_one_undo_step() { + let mut h = harness(); + let layer = first_layer(&h); + set_distinct(&mut h, layer); + let before = blending(&h, layer); + assert!(before.len() > 2, "the layer has several channels"); + menu_item(&mut h, layer, "Apply both to all channels"); + for (c, b) in blending(&h, layer) { + assert_eq!((b.mode, b.opacity), (BlendMode::Multiply, 0.4), "{c:?}"); + } + texturecraft_engine::execute(&mut h.state_mut().session, "edit.undo", &json!({})).unwrap(); + assert_eq!(blending(&h, layer), before, "one undo restores every channel"); +} + +#[test] +fn apply_mode_leaves_opacity_and_apply_opacity_leaves_mode() { + let mut h = harness(); + let layer = first_layer(&h); + set_distinct(&mut h, layer); + menu_item(&mut h, layer, "Apply blending mode to all channels"); + let after = blending(&h, layer); + assert!(after.iter().all(|(_, b)| b.mode == BlendMode::Multiply)); + assert_eq!(after.iter().find(|(c, _)| *c == Channel::Roughness).unwrap().1.opacity, 0.7, "opacity stays"); + set_distinct(&mut h, layer); + menu_item(&mut h, layer, "Apply opacity to all channels"); + let after = blending(&h, layer); + assert!(after.iter().all(|(_, b)| b.opacity == 0.4)); + assert_eq!(after.iter().find(|(c, _)| *c == Channel::Roughness).unwrap().1.mode, BlendMode::Overlay, "mode stays"); +} + +#[test] +fn copy_from_one_layer_and_paste_into_another() { + let mut h = harness(); + let a = first_layer(&h); + set_distinct(&mut h, a); + let b = LayerId(texturecraft_engine::execute(&mut h.state_mut().session, "layer.add.paint", &json!({"name": "Other"})).unwrap()["layer"].as_u64().unwrap()); + h.run_steps(3); + assert_ne!(blending(&h, a), blending(&h, b)); + menu_item(&mut h, a, "Copy channel blending settings"); + menu_item(&mut h, b, "Paste channel blending settings"); + assert_eq!(blending(&h, b), blending(&h, a), "B has A's blending on every channel"); + texturecraft_engine::execute(&mut h.state_mut().session, "edit.undo", &json!({})).unwrap(); + assert_ne!(blending(&h, b), blending(&h, a), "pasting was one undo step"); +} + +#[test] +fn paste_is_disabled_until_something_is_copied() { + let mut h = harness(); + let layer = first_layer(&h); + let name = h.state().session.doc.project.layers[&layer].name.clone(); + h.get_by_label(&name).click_secondary(); + h.run_steps(3); + h.get_all_by_label("Blending options").last().unwrap().click(); + h.run_steps(3); + assert!(h.get_all_by_label("Paste channel blending settings").last().unwrap().accesskit_node().is_disabled(), "nothing copied yet"); + assert!(h.state().ui.blend_clipboard.is_none()); +} + +#[test] +fn paste_keeps_a_disabled_channel_disabled() { + let mut h = harness(); + let a = first_layer(&h); + set_distinct(&mut h, a); + let b = LayerId(texturecraft_engine::execute(&mut h.state_mut().session, "layer.add.paint", &json!({"name": "Other"})).unwrap()["layer"].as_u64().unwrap()); + texturecraft_engine::execute(&mut h.state_mut().session, "layer.blend", &json!({"layer": b.0, "channel": "roughness", "enabled": false})).unwrap(); + h.run_steps(3); + menu_item(&mut h, a, "Copy channel blending settings"); + menu_item(&mut h, b, "Paste channel blending settings"); + assert!(!blending(&h, b).iter().any(|(c, _)| *c == Channel::Roughness)); + assert_eq!(blending(&h, b).iter().find(|(c, _)| *c == Channel::BaseColor).unwrap().1.mode, BlendMode::Multiply); +} diff --git a/crates/ui-egui/tests/it/layer_multi_select.rs b/crates/ui-egui/tests/it/layer_multi_select.rs new file mode 100644 index 00000000..92201b7c --- /dev/null +++ b/crates/ui-egui/tests/it/layer_multi_select.rs @@ -0,0 +1,202 @@ +//! Shift+click and Ctrl/Cmd+click on Layers panel rows select several layers, as in the +//! reference app, and the selected rows are highlighted. + +use egui::accesskit::Toggled; +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +/// Paint layers "Row A" (bottom) to "Row D" (top) in the active texture set, "Row D" selected. +fn harness() -> (Harness<'static, TextureCraftApp>, [LayerId; 4]) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let rows = ["Row A", "Row B", "Row C", "Row D"] + .map(|name| LayerId(execute(&mut session, "layer.add.paint", &json!({ "name": name })).unwrap()["layer"].as_u64().unwrap())); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, rows) +} + +/// Click the row `name` while `modifiers` are held (pressed before and released after the click). +fn click(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: Modifiers) { + let at: Pos2 = h.get_by_label(name).rect().center(); + h.event(Event::PointerMoved(at)); + h.event(Event::ModifiersChanged(modifiers)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(2); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +fn highlighted(h: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + // egui reports a selected list item as toggled on + h.get_by_label(name).accesskit_node().toggled() == Some(Toggled::True) +} + +#[test] +fn shift_click_selects_a_range_and_highlights_its_rows() { + let (mut h, [a, b, c, d]) = harness(); + click(&mut h, "Row B", Modifiers::NONE); + click(&mut h, "Row D", Modifiers::SHIFT); + assert_eq!(h.state().session.selected_layers(), [d, c, b]); + assert_eq!(h.state().session.selected_layer(), Some(d), "the clicked row is the active layer"); + for name in ["Row B", "Row C", "Row D"] { + assert!(highlighted(&h, name), "{name} is highlighted"); + } + assert!(!highlighted(&h, "Row A")); + + // A second Shift+click ranges from B again, and Delete removes both layers + click(&mut h, "Row A", Modifiers::SHIFT); + assert_eq!(h.state().session.selected_layers(), [b, a], "the range starts at the last plain click"); + h.key_press(egui::Key::Delete); + h.run_steps(3); + let project = &h.state().session.doc.project; + assert!(project.layer(a).is_err() && project.layer(b).is_err()); + assert!(project.layer(c).is_ok() && project.layer(d).is_ok()); +} + +#[test] +fn ctrl_click_adds_and_takes_out_a_row() { + let (mut h, [a, _, c, _]) = harness(); + click(&mut h, "Row A", Modifiers::NONE); + click(&mut h, "Row C", Modifiers::COMMAND); + assert_eq!(h.state().session.selected_layers(), [c, a]); + assert!(highlighted(&h, "Row A") && highlighted(&h, "Row C") && !highlighted(&h, "Row B")); + click(&mut h, "Row C", Modifiers::COMMAND); + assert_eq!(h.state().session.selected_layers(), [a]); + assert!(!highlighted(&h, "Row C")); + assert!(h.state().ui.rename.is_none(), "two quick Ctrl+clicks do not start a rename"); +} + +/// Click the eye of the row `name` (it sits at the left of a top-level row, after the 7-point edge). +fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str) { + let row = h.get_by_label(name).rect(); + let eye = egui::pos2(row.left() + 7.0 + 8.0, row.center().y); + h.drag_at(eye); + h.drop_at(eye); + h.run_steps(3); +} + +fn visible(h: &Harness<'_, TextureCraftApp>, layer: LayerId) -> bool { + h.state().session.doc.project.layer(layer).unwrap().visible +} + +#[test] +fn the_eye_of_a_selected_row_shows_or_hides_that_layer_only() { + let (mut h, [a, _, c, _]) = harness(); + click(&mut h, "Row A", Modifiers::NONE); + click(&mut h, "Row C", Modifiers::COMMAND); + click_eye(&mut h, "Row C"); + assert!(!visible(&h, c), "C is hidden"); + assert!(visible(&h, a), "A, also selected, stays shown"); + assert_eq!(h.state().session.selected_layers(), [c, a], "the selection stays"); + click_eye(&mut h, "Row C"); + assert!(visible(&h, c), "a second click shows C again"); +} + +#[test] +fn the_eye_of_an_unselected_row_acts_on_its_own_layer_and_keeps_the_selection() { + let (mut h, [a, b, c, _]) = harness(); + click(&mut h, "Row A", Modifiers::NONE); + click(&mut h, "Row C", Modifiers::COMMAND); + click_eye(&mut h, "Row B"); + assert!(!visible(&h, b), "B is hidden"); + assert!(visible(&h, a) && visible(&h, c), "the selected layers stay shown"); + assert_eq!(h.state().session.selected_layers(), [c, a], "the selection stays"); +} + +#[test] +fn ctrl_a_over_the_layers_panel_selects_every_shown_row_but_not_the_layers_in_a_collapsed_folder() { + let (mut h, [a, b, c, d]) = harness(); + let session = &mut h.state_mut().session; + let folder = LayerId(execute(session, "layer.add.group", &json!(null)).unwrap()["layer"].as_u64().unwrap()); + execute(session, "layer.move", &json!({"layers": [a.0, b.0], "above": folder.0, "inside": true})).unwrap(); + if let LayerKind::Group { collapsed, .. } = &mut session.doc.project.layer_mut(folder).unwrap().kind { + *collapsed = true; + } + execute(session, "layer.select", &json!({"layer": d.0})).unwrap(); + h.run_steps(3); + let at = h.get_by_label("Row C").rect().center(); + h.event(Event::PointerMoved(at)); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.run_steps(3); + let session = &h.state().session; + let every_row = texturecraft_engine::layer_selection::stack_rows(&session.doc.project, 0, true); + for layer in [c, d, folder] { + assert!(session.is_layer_selected(layer), "layer {} is selected", layer.0); + } + assert_eq!(session.selected_layers().len(), every_row.len(), "every shown row is selected"); + assert!(!session.is_layer_selected(a) && !session.is_layer_selected(b), "the collapsed folder's layers are not"); + assert_eq!(h.state().session.selected_layer(), Some(d), "the active layer stays"); +} + +#[test] +fn ctrl_a_leaves_text_fields_and_other_panels_alone() { + let (mut h, [_, _, c, d]) = harness(); + + // Pointer outside every panel: nothing is selected + h.event(Event::PointerGone); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.run_steps(3); + assert_eq!(h.state().session.selected_layers(), [d], "no pointer over the Layers panel"); + + // A rename field over the panel keeps Ctrl+A for its own text + h.state_mut().ui.rename = Some((c.0, "Row C".into())); + h.run_steps(3); + let at = h.get_by_label("Row B").rect().center(); + h.event(Event::PointerMoved(at)); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.run_steps(3); + assert_eq!(h.state().session.selected_layers().len(), 1, "Ctrl+A in the rename field selects text, not layers"); +} + +/// Right-click the row `name` and choose the menu item whose label starts with `item`. +fn row_menu(h: &mut Harness<'_, TextureCraftApp>, name: &str, item: &str) { + h.get_by_label(name).click_secondary(); + h.run_steps(3); + h.get_by(|node| node.label().is_some_and(|label| label.starts_with(item))).click(); + h.run_steps(3); +} + +#[test] +fn the_row_menu_of_a_selected_row_acts_on_the_whole_selection() { + let (mut h, [a, b, c, _]) = harness(); + click(&mut h, "Row A", Modifiers::NONE); + click(&mut h, "Row C", Modifiers::COMMAND); + row_menu(&mut h, "Row C", "Duplicate layer(s)"); + let names: Vec = h.state().session.selected_layers().iter().map(|id| h.state().session.doc.project.layer(*id).unwrap().name.clone()).collect(); + assert_eq!(names, ["Row C copy", "Row A copy"], "both selected layers are duplicated"); + + click(&mut h, "Row A", Modifiers::NONE); + click(&mut h, "Row C", Modifiers::COMMAND); + row_menu(&mut h, "Row A", "Group layer(s)"); + let folder = h.state().session.selected_layer().unwrap(); + assert_eq!(h.state().session.doc.project.layer(folder).unwrap().children(), [a, c], "both go into the folder"); + + // On a row outside the selection, only that row + row_menu(&mut h, "Row B", "Remove layer(s)"); + let project = &h.state().session.doc.project; + assert!(project.layer(b).is_err()); + assert!(project.layer(a).is_ok() && project.layer(c).is_ok()); +} + +#[test] +fn the_row_menu_of_an_unselected_row_acts_on_that_row_only() { + let (mut h, [a, b, c, _]) = harness(); + click(&mut h, "Row A", Modifiers::NONE); + click(&mut h, "Row C", Modifiers::COMMAND); + row_menu(&mut h, "Row B", "Duplicate layer(s)"); + let project = &h.state().session.doc.project; + assert_eq!(project.layers.values().filter(|layer| layer.name.ends_with(" copy")).count(), 1); + assert!(project.layers.values().any(|layer| layer.name == "Row B copy")); + assert!(project.layer(a).is_ok() && project.layer(b).is_ok() && project.layer(c).is_ok()); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index 50e4458e..ccbd9074 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -120,3 +120,287 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let content = &h.state().session.doc.project.layers[&layer].content_effects; assert!(!content.iter().find(|effect| effect.name == "Effect A").unwrap().visible, "the compact eye toggles the effect instead of missing the panel"); } + +/// Every painted shape of the last frame, folded groups flattened. +fn shapes(h: &Harness<'_, TextureCraftApp>) -> Vec { + fn flatten(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(inner) => inner.iter().for_each(|shape| flatten(shape, out)), + other => out.push(other.clone()), + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|clipped| flatten(&clipped.shape, &mut out)); + out +} + +fn hidpi_harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer")); + execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Active one"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).with_pixels_per_point(2.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, layer) +} + +#[test] +fn the_active_layer_row_has_its_own_strong_fill_and_a_wide_edge_at_scale_two() { + use texturecraft_ui_egui::dock::selected_layer_fill; + use texturecraft_ui_egui::theme::{Accent, Brightness, Tokens}; + + let (h, _) = hidpi_harness(); + assert_eq!(h.ctx.pixels_per_point(), 2.0); + let tokens = Tokens::get(&h.ctx); + let row = h.get_by_label("Active one").rect(); + let fill = selected_layer_fill(&tokens); + assert_ne!(fill, tokens.row_selected, "the active layer row is more tinted than the plain selected shade"); + let painted = shapes(&h); + let rects: Vec<_> = painted + .iter() + .filter_map(|shape| match shape { + egui::Shape::Rect(rect) => Some((rect.rect, rect.fill)), + _ => None, + }) + .collect(); + assert!( + rects.iter().any(|(rect, color)| *color == fill && rect.width() >= row.width() - 1.0 && rect.contains(row.center())), + "the whole active row gets the highlight fill" + ); + assert!( + rects.iter().any(|(rect, color)| *color == tokens.accent + && (rect.width() - 4.0).abs() < 0.01 + && rect.left() <= row.left() + 0.5 + && rect.contains(egui::pos2(rect.center().x, row.center().y))), + "a 4 point accent edge marks the row" + ); + + // Neighbouring rows keep the alternating shades + assert!(rects.iter().all(|(rect, color)| *color != fill || rect.contains(row.center())), "only the active row carries the highlight"); + + // The lettering keeps its contrast on the stronger fill in every theme + let lum = |c: egui::Color32| { + let f = |v: u8| { + let v = f32::from(v) / 255.0; + if v <= 0.03928 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + }; + 0.2126 * f(c.r()) + 0.7152 * f(c.g()) + 0.0722 * f(c.b()) + }; + let contrast = |a: egui::Color32, b: egui::Color32| (lum(a).max(lum(b)) + 0.05) / (lum(a).min(lum(b)) + 0.05); + for brightness in Brightness::ALL { + for accent in Accent::ALL { + let tokens = Tokens::for_brightness(brightness).with_accent(accent); + let fill = selected_layer_fill(&tokens); + assert!(contrast(tokens.text_strong, fill) >= 4.5, "{brightness:?} {accent:?}: name on the active row"); + assert!( + contrast(tokens.text_dim, fill) >= (contrast(tokens.text_dim, tokens.row_selected) - 0.5).min(3.0), + "{brightness:?} {accent:?}: subtitle on the active row is not much dimmer than on the plain selected shade" + ); + assert!(contrast(fill, tokens.panel) >= 1.15, "{brightness:?} {accent:?}: the active row stands out from the panel"); + } + } +} + +#[test] +fn the_layer_eye_looks_clearly_different_when_visible_and_hidden_at_scale_two() { + let (mut h, layer) = hidpi_harness(); + let tokens = texturecraft_ui_egui::theme::Tokens::get(&h.ctx); + let row = h.get_by_label("Active one").rect(); + let eye_center = egui::pos2(row.left() + 7.0 + 8.0, row.center().y); + + // What is painted on the eye: (glyph, glyph colour, chip fill behind it) + let eye = |h: &Harness<'_, TextureCraftApp>| { + let painted = shapes(h); + let glyph = painted + .iter() + .find_map(|shape| match shape { + egui::Shape::Text(text) if text.visual_bounding_rect().contains(eye_center) && !text.galley.text().trim().is_empty() => { + Some((text.galley.text().to_string(), text.galley.job.sections[0].format.color)) + } + _ => None, + }) + .expect("the eye glyph is painted"); + let chip = painted.iter().find_map(|shape| match shape { + egui::Shape::Rect(rect) if rect.rect.contains(eye_center) && rect.rect.width() < 20.0 => Some(rect.fill), + _ => None, + }); + (glyph.0, glyph.1, chip) + }; + let (on_glyph, on_color, on_chip) = eye(&h); + execute(&mut h.state_mut().session, "layer.visible", &json!({"layer": layer.0})).unwrap(); + h.run_steps(3); + let (off_glyph, off_color, off_chip) = eye(&h); + assert_ne!(on_glyph, off_glyph, "a hidden layer shows the crossed-out eye"); + assert_ne!(on_color, off_color, "the glyph colour changes with the state"); + assert_eq!(on_color, tokens.text_strong); + assert_eq!(off_color, tokens.text_dim); + assert_eq!(on_chip, Some(tokens.accent_dim), "a visible layer's eye sits on an accent chip"); + assert_eq!(off_chip, None, "a hidden layer's eye has no chip"); +} + +const LONG_NAME: &str = "Weathered painted steel plate with scratched edges"; + +/// The app in a 1280 x 800 window with one layer named `LONG_NAME`. +fn narrow_harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + execute(&mut session, "layer.rename", &json!({"layer": layer, "name": LONG_NAME})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h +} + +#[test] +fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() { + let h = narrow_harness(); + let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect()); + + // The effect menu button is the wand left of the paint button (effect rows draw wands too) + let wand = h + .query_all_by_label(egui_phosphor::regular::MAGIC_WAND) + .map(|n| n.rect()) + .filter(|r| r.right() < buttons[0].left()) + .max_by(|a, b| a.right().total_cmp(&b.right())) + .expect("the effect menu button"); + let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect(); + for rect in buttons.into_iter().chain([remove]) { + assert!((rect.center().y - wand.center().y).abs() < 1.0, "the toolbar wrapped: {rect:?} against {wand:?}"); + } + let row = h.get_by_label(LONG_NAME).rect(); + assert!(remove.right() <= row.right() + 1.0, "the last button stays inside the panel: {remove:?} against {row:?}"); +} + +#[test] +fn a_layer_name_cut_short_shows_in_full_on_hover() { + let mut h = narrow_harness(); + let row = h.get_by_label(LONG_NAME).rect(); + let before = h.query_all_by_label_contains(LONG_NAME).count(); + h.hover_at(egui::pos2(row.left() + 125.0, row.center().y)); + h.run_steps(30); + assert_eq!(h.query_all_by_label_contains(LONG_NAME).count(), before + 1, "the tooltip carries the full name"); +} + +const LONG_EFFECT_NAME: &str = "Edge wear from curvature with dirt accumulation"; + +#[test] +fn an_effect_name_cut_short_shows_in_full_on_hover() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": LONG_EFFECT_NAME})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1280.0, 800.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + + let row = h.get_by_label(LONG_EFFECT_NAME).rect(); + let before = h.query_all_by_label_contains(LONG_EFFECT_NAME).count(); + h.hover_at(egui::pos2(row.left() + 75.0, row.center().y)); + h.run_steps(30); + assert_eq!(h.query_all_by_label_contains(LONG_EFFECT_NAME).count(), before + 1, "the tooltip carries the full effect name"); +} + +fn right_click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + h.hover_at(at); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }); + } + h.run_steps(3); +} + +/// Click the eye of the top-level row `name` with `modifiers` held (the eye sits in the first 20 points after the 7-point edge). +fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: egui::Modifiers) { + let row = h.get_by_label(name).rect(); + h.event(egui::Event::ModifiersChanged(modifiers)); + click(h, egui::pos2(row.left() + 17.0, row.center().y)); + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn the_context_menu_solos_a_layer_without_touching_the_document() { + let (mut h, layer) = harness(); + let (project, history, modified) = (h.state().session.doc.project.clone(), h.state().session.history_labels(), h.state().session.modified); + let row = h.get_by_label("Masked fill").rect(); + right_click(&mut h, row.center()); + h.get_by_label("Solo layer").click(); + h.run_steps(3); + assert_eq!(h.state().session.solo, Some(texturecraft_engine::Solo { layer, ignore_mask: false })); + assert_eq!(h.state().session.doc.project, project, "soloing is not an edit"); + assert_eq!((h.state().session.history_labels(), h.state().session.modified), (history.clone(), modified)); + + // The entry is lit while the layer is soloed; clicking it again ends the solo + right_click(&mut h, row.center()); + h.get_by_label("Solo layer").click(); + h.run_steps(3); + assert_eq!(h.state().session.solo, None); + + right_click(&mut h, row.center()); + h.get_by_label("Solo layer without its mask").click(); + h.run_steps(3); + assert_eq!(h.state().session.solo, Some(texturecraft_engine::Solo { layer, ignore_mask: true })); + right_click(&mut h, row.center()); + h.get_by_label("Solo layer without its mask").click(); + h.run_steps(3); + assert_eq!(h.state().session.solo, Some(texturecraft_engine::Solo { layer, ignore_mask: false }), "the second entry only switches the mask back on"); + assert_eq!((h.state().session.doc.project.clone(), h.state().session.history_labels()), (project, history)); +} + +#[test] +fn alt_click_on_the_eye_solos_and_a_plain_click_still_hides() { + let (mut h, layer) = harness(); + click_eye(&mut h, "Masked fill", egui::Modifiers::ALT); + assert_eq!(h.state().session.solo, Some(texturecraft_engine::Solo { layer, ignore_mask: false })); + assert!(h.state().session.doc.project.layers[&layer].visible, "Alt+click does not touch the layer's own eye"); + click_eye(&mut h, "Masked fill", egui::Modifiers::ALT); + assert_eq!(h.state().session.solo, None, "Alt+click on the soloed layer ends the solo"); + click_eye(&mut h, "Masked fill", egui::Modifiers::ALT | egui::Modifiers::SHIFT); + assert_eq!(h.state().session.solo, Some(texturecraft_engine::Solo { layer, ignore_mask: true }), "Alt+Shift also ignores the mask"); + click_eye(&mut h, "Masked fill", egui::Modifiers::ALT); + assert_eq!(h.state().session.solo, None); + click_eye(&mut h, "Masked fill", egui::Modifiers::NONE); + assert!(!h.state().session.doc.project.layers[&layer].visible, "a plain click hides the layer as before"); + assert_eq!(h.state().session.solo, None); +} + +fn alt_click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + h.event(egui::Event::ModifiersChanged(egui::Modifiers::ALT)); + h.hover_at(at); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }); + h.run_steps(2); + } + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.run_steps(3); +} + +#[test] +fn alt_click_on_a_mask_thumbnail_shows_that_mask_alone_without_changing_the_document() { + let (mut h, layer) = harness(); + let history = h.state().session.history_labels().len(); + let project = h.state().session.doc.project.clone(); + + let at = thumb(&h, "Masked fill", true); + click(&mut h, at); + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material, "a plain click only selects"); + + alt_click(&mut h, at); + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Mask(layer)); + let gray = h.state().session.mask_view_rgba(layer, 64).unwrap(); + assert!(gray.chunks(4).all(|px| px[0] == px[1] && px[1] == px[2] && px[3] == 255), "the mask is shown in gray"); + assert!(gray.chunks(4).any(|px| px[0] != gray[0]), "the position generator shapes the mask"); + assert_eq!(h.state().session.history_labels().len(), history, "view only: no history step"); + assert_eq!(h.state().session.doc.project, project, "view only: the project is unchanged"); + + execute(&mut h.state_mut().session, "viewport.displayMaterial", &Value::Null).unwrap(); + h.run_steps(2); + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material, "Display material (M) returns"); +} + +#[test] +fn alt_click_on_the_content_thumbnail_leaves_the_view_alone() { + let (mut h, _) = harness(); + let at = thumb(&h, "Masked fill", false); + alt_click(&mut h, at); + assert_eq!(h.state().session.view, texturecraft_engine::ViewMode::Material); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 56cee771..03c5713c 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,28 +1,45 @@ //! One integration-test executable avoids linking the same dependencies for every feature. //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. +mod alpha_parameters; mod bake_job_mesh; mod bake_mode; mod brush_drag; mod brush_section_reset; +mod camera_views; +mod clone_source_view; mod close_unsaved; mod color_picker; mod color_selection_editor; mod curvature_generator; +mod decal_proportions; +mod decal_symmetry; +mod display_post_effects; +mod effect_decal; mod effect_rows; mod effect_sliders; +mod empty_start; +mod export_template_guards; mod file_dialogs; mod fill_channel_image; mod fill_projection_section; mod filter_picker; +mod frame_selection; mod generator_panel; +mod gradient_map_menu; mod history_panel; mod import_resources; +mod inactive_set_hint; +mod layer_blending_options; mod layer_clipboard; +mod layer_multi_select; mod layer_rename; mod layers_panel; mod levels_editor; +mod mask_export; mod mask_value_swap; +mod named_layouts; +mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod path_in_view; @@ -32,15 +49,29 @@ mod polygon_fill; mod project_config; mod properties_popup; mod rail; +mod reference_order; +mod rename_anchor; +mod reset_ui; +mod shelf_click; mod shelf_drop; mod shelf_hover_preview; mod shelf_panel; mod shift_lines_2d; +mod shift_lines_3d; +mod shortcut_gestures; mod shortcut_keys; mod skew_paint; +mod smudge_channels; +mod snapped_lines; mod split_divider; -mod start_window; +mod temp_dir; +mod template_invert; mod tool_availability; +mod tool_settings_saved; mod toolbar; +mod user_smart_mask; +mod stencil; mod symmetry; +mod symmetry_2d; +mod tile_generator_panel; diff --git a/crates/ui-egui/tests/it/mask_export.rs b/crates/ui-egui/tests/it/mask_export.rs new file mode 100644 index 00000000..808c4055 --- /dev/null +++ b/crates/ui-egui/tests/it/mask_export.rs @@ -0,0 +1,105 @@ +//! A layer's context menu saves its evaluated mask as an image file or copies it to the clipboard. + +use std::path::PathBuf; + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; + +const RESOLUTION: u32 = 128; +const LAYER: &str = "Masked layer"; + +/// A project with a layer named [`LAYER`], whose mask is 0.5 where the mesh covers the texture +/// when `mask` is set, and a harness showing it. +fn harness(mask: bool) -> Harness<'static, TextureCraftApp> { + let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, RESOLUTION).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"name": LAYER})).unwrap(); + if mask { + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"value": 0.5})).unwrap(); + } + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn open_menu(h: &mut Harness<'_, TextureCraftApp>) { + h.get_by_label(LAYER).click_secondary(); + h.run_steps(3); +} + +/// A path in a new temporary folder. +fn temp_file(test: &str, name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-mask-export-ui-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join(name) +} + +fn copied_images(h: &Harness<'_, TextureCraftApp>) -> Vec { + h.output() + .platform_output + .commands + .iter() + .filter_map(|command| match command { + egui::OutputCommand::CopyImage(image) => Some(image.clone()), + _ => None, + }) + .collect() +} + +#[test] +fn export_mask_to_file_writes_the_mask_where_the_dialog_answered() { + let mut h = harness(true); + let file = temp_file("file", "picked.png"); + let answer = file.clone(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answer.clone()])))); + open_menu(&mut h); + h.get_by_label("Export mask to file...").click(); + h.run_steps(4); + + let gray = image::open(&file).expect("the mask file was written").into_luma16(); + assert_eq!(gray.dimensions(), (RESOLUTION, RESOLUTION), "the texture set's size"); + assert!(gray.pixels().any(|p| p.0[0] == 32768), "the mask's 0.5 as a 16-bit level"); + assert!(h.state().toasts.iter().any(|t| !t.error && t.text.contains("picked.png")), "{:?}", h.state().toasts.iter().map(|t| &t.text).collect::>()); + let _ = std::fs::remove_dir_all(file.parent().unwrap()); +} + +#[test] +fn a_canceled_dialog_writes_nothing() { + let mut h = harness(true); + h.state_mut().file_dialogs.set_override(Some(Box::new(|_| Answer::Cancelled))); + open_menu(&mut h); + h.get_by_label("Export mask to file...").click(); + h.run_steps(4); + assert!(h.state().toasts.is_empty()); +} + +#[test] +fn copy_mask_to_clipboard_puts_the_gray_image_on_the_clipboard() { + let mut h = harness(true); + open_menu(&mut h); + h.get_by_label("Copy mask to clipboard").click(); + + // The copy command is in the output of the frame that handled the click only + h.step(); + + let images = copied_images(&h); + assert_eq!(images.len(), 1, "one image was copied"); + assert_eq!(images[0].size, [RESOLUTION as usize, RESOLUTION as usize]); + assert!(images[0].pixels.iter().any(|p| *p == egui::Color32::from_gray(128)), "the mask's 0.5 as 8-bit gray"); + assert!(h.state().toasts.iter().any(|t| !t.error && t.text.contains("clipboard"))); +} + +#[test] +fn a_layer_without_a_mask_cannot_export_or_copy_one() { + let mut h = harness(false); + open_menu(&mut h); + h.get_by_label("Copy mask to clipboard").click(); + h.step(); + assert!(copied_images(&h).is_empty(), "nothing to copy"); + assert_eq!(h.state().file_dialogs.pending(), 0); +} diff --git a/crates/ui-egui/tests/it/named_layouts.rs b/crates/ui-egui/tests/it/named_layouts.rs new file mode 100644 index 00000000..2bd65c55 --- /dev/null +++ b/crates/ui-egui/tests/it/named_layouts.rs @@ -0,0 +1,215 @@ +//! Window > Layouts: save the panel arrangement under a name and switch to it from the menu. + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::Mode; + +fn app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_accessibility_check(false).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// Open Window > Layouts, click `entry`, and let the app answer +fn layouts_menu(harness: &mut Harness<'_, TextureCraftApp>, entry: &str) { + harness.get_by_role_and_label(Role::Button, "Window").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, "Layouts").click(); + harness.run_steps(3); + harness.get_by_role_and_label(Role::Button, entry).click(); + harness.run_steps(3); +} + +/// The dialog's text field: the one nearest the window center, where dialogs open (the shelf search is another) +fn dialog_input<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { + let center = harness.ctx.content_rect().center(); + harness + .get_all_by_role(Role::TextInput) + .min_by(|a, b| a.rect().center().distance(center).total_cmp(&b.rect().center().distance(center))) + .expect("the dialog's field") +} + +fn save_as(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + layouts_menu(harness, "Save current layout as..."); + dialog_input(&*harness).type_text(name); + harness.run_steps(2); + harness.get_by_role_and_label(Role::Button, "Save").click(); + harness.run_steps(3); +} + +#[test] +fn a_layout_saved_from_the_menu_comes_back_from_the_menu() { + let mut harness = app(); + harness.state_mut().ui.dock.close(Panel::Assets); + save_as(&mut harness, "No shelf"); + assert!(harness.state().ui.has_named_layout("No shelf")); + + harness.state_mut().ui.dock.focus(Panel::Assets); + harness.state_mut().ui.uv_zoom = 4.0; + harness.state_mut().ui.wireframe_3d = true; + harness.state_mut().ui.mode = Mode::Rendering; + harness.run_steps(2); + + layouts_menu(&mut harness, "No shelf"); + + let ui = &harness.state().ui; + assert!(!ui.dock.is_open(Panel::Assets), "the saved panels are back"); + assert_eq!((ui.uv_zoom, ui.wireframe_3d, ui.mode), (4.0, true, Mode::Rendering), "zoom, wireframe and mode stay"); +} + +#[test] +fn saving_under_a_taken_name_asks_before_replacing() { + let mut harness = app(); + harness.state_mut().ui.dock.close(Panel::Assets); + save_as(&mut harness, "Mine"); + harness.state_mut().ui.dock.close(Panel::Layers); + + save_as(&mut harness, "Mine"); + assert!(harness.state().ui.named_layouts[0].painting.is_open(Panel::Layers), "nothing is replaced before the answer"); + harness.get_by_label("A layout named Mine already exists. Replace it?"); + harness.get_by_role_and_label(Role::Button, "Replace").click(); + harness.run_steps(3); + + assert_eq!(harness.state().ui.named_layouts.len(), 1); + assert!(!harness.state().ui.named_layouts[0].painting.is_open(Panel::Layers)); +} + +#[test] +fn a_layout_is_renamed_and_deleted_from_the_manage_dialog() { + let mut harness = app(); + save_as(&mut harness, "First"); + layouts_menu(&mut harness, "Manage layouts..."); + + harness.get_by_role_and_label(Role::Button, "Rename").click(); + harness.run_steps(2); + + // The field starts with the old name; typing continues it + dialog_input(&harness).type_text("2"); + harness.run_steps(2); + harness.get_by_role_and_label(Role::Button, "Rename").click(); + harness.run_steps(3); + assert!(harness.state().ui.has_named_layout("First2") && !harness.state().ui.has_named_layout("First")); + + harness.get_by_role_and_label(Role::Button, "Delete").click(); + harness.run_steps(3); + assert_eq!(harness.state().ui.named_layouts.len(), 1, "delete asks first"); + harness.get_by_label("Delete the layout First2?"); + harness.get_by_role_and_label(Role::Button, "Delete").click(); + harness.run_steps(3); + assert!(harness.state().ui.named_layouts.is_empty()); +} + +fn invoke(harness: &mut Harness<'_, TextureCraftApp>, params: serde_json::Value) -> serde_json::Value { + let context = harness.ctx.clone(); + texturecraft_ui_egui::control::handle(harness.state_mut(), &context, "ui.menu.invoke", ¶ms) +} + +#[test] +fn the_layout_items_are_in_the_menu_catalog_and_open_their_dialogs() { + use texturecraft_ui_egui::menus::CATALOG; + use texturecraft_ui_egui::named_layouts::LayoutDialog; + + for id in ["ui.layout.saveAs", "ui.layout.manage"] { + assert!(CATALOG.iter().any(|item| item.id == id && item.menu == "Window" && item.sub == Some("Layouts")), "{id}"); + } + let mut harness = app(); + assert!(!texturecraft_ui_egui::menus::enabled(harness.state(), "ui.layout.manage"), "nothing to manage yet"); + + assert_eq!(invoke(&mut harness, serde_json::json!({"id": "ui.layout.saveAs"}))["ok"], true); + assert!(matches!(harness.state().ui.layout_dialog, Some(LayoutDialog::Save(_)))); + + harness.state_mut().ui.save_named_layout("A"); + harness.state_mut().ui.layout_dialog = None; + assert_eq!(invoke(&mut harness, serde_json::json!({"id": "ui.layout.manage"}))["ok"], true); + assert!(matches!(harness.state().ui.layout_dialog, Some(LayoutDialog::Manage { .. }))); +} + +#[test] +fn the_control_channel_switches_to_a_layout_by_name_and_rejects_unknown_names() { + let mut harness = app(); + harness.state_mut().ui.dock.close(Panel::Assets); + harness.state_mut().ui.save_named_layout("No shelf"); + harness.state_mut().ui.dock.focus(Panel::Assets); + harness.state_mut().ui.uv_zoom = 2.0; + + let reply = invoke(&mut harness, serde_json::json!({"id": "ui.layout.apply", "name": "No shelf"})); + assert_eq!(reply["ok"], true, "{reply}"); + assert!(!harness.state().ui.dock.is_open(Panel::Assets)); + assert_eq!(harness.state().ui.uv_zoom, 2.0); + + harness.state_mut().ui.dock.focus(Panel::Assets); + for params in [serde_json::json!({"id": "ui.layout.apply", "name": "Nope"}), serde_json::json!({"id": "ui.layout.apply"})] { + let reply = invoke(&mut harness, params); + assert_eq!(reply["ok"], false, "{reply}"); + } + assert!(harness.state().ui.dock.is_open(Panel::Assets), "an unknown name changes nothing"); +} + +#[test] +fn tab_moves_from_the_save_field_to_the_buttons_and_stays_there() { + let mut harness = app(); + layouts_menu(&mut harness, "Save current layout as..."); + dialog_input(&harness).type_text("Mine"); + harness.run_steps(2); + harness.key_press(egui::Key::Tab); + harness.run_steps(30); + assert!(harness.get_by_role_and_label(Role::Button, "Save").is_focused(), "the field did not take the focus back"); +} + +#[test] +fn tab_moves_from_the_rename_field_to_the_buttons_and_stays_there() { + let mut harness = app(); + save_as(&mut harness, "First"); + layouts_menu(&mut harness, "Manage layouts..."); + harness.get_by_role_and_label(Role::Button, "Rename").click(); + harness.run_steps(2); + dialog_input(&harness).type_text("2"); + harness.run_steps(2); + harness.key_press(egui::Key::Tab); + harness.run_steps(30); + assert!(harness.get_by_role_and_label(Role::Button, "Rename").is_focused(), "the field did not take the focus back"); +} + +#[test] +fn a_second_save_dialog_focuses_its_field_again() { + let mut harness = app(); + save_as(&mut harness, "First"); + layouts_menu(&mut harness, "Save current layout as..."); + harness.run_steps(3); + assert!(dialog_input(&harness).is_focused(), "the field is ready for typing"); +} + +#[test] +fn a_long_list_of_layouts_scrolls_and_keeps_close_on_screen() { + let mut harness = app(); + for n in 0..60 { + harness.state_mut().ui.save_named_layout(&format!("Layout {n}")); + } + layouts_menu(&mut harness, "Manage layouts..."); + harness.run_steps(3); + let screen = harness.ctx.content_rect(); + let close = harness.get_by_role_and_label(Role::Button, "Close").rect(); + assert!(screen.contains_rect(close), "Close is inside the window: {close:?} in {screen:?}"); +} + +#[test] +fn a_save_dialog_closed_by_a_reset_still_focuses_its_field_next_time() { + let mut harness = app(); + layouts_menu(&mut harness, "Save current layout as..."); + harness.run_steps(3); + assert!(dialog_input(&harness).is_focused()); + + // Reset UI closes the dialog from outside + harness.state_mut().ui.adopt_layout(texturecraft_ui_egui::state::UiState::default()); + harness.run_steps(3); + assert!(harness.state().ui.layout_dialog.is_none()); + + layouts_menu(&mut harness, "Save current layout as..."); + harness.run_steps(3); + assert!(dialog_input(&harness).is_focused(), "the field is ready for typing again"); +} diff --git a/crates/ui-egui/tests/it/nav_buttons.rs b/crates/ui-egui/tests/it/nav_buttons.rs new file mode 100644 index 00000000..41c6b47f --- /dev/null +++ b/crates/ui-egui/tests/it/nav_buttons.rs @@ -0,0 +1,256 @@ +//! The on-screen orbit, pan and zoom buttons move the views with a primary-button drag, without painting. +//! A pen tip reaches egui as the same pointer events a mouse sends, so these drags stand for a pen drag too. + +use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2}; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::nav_buttons::{NavButton, NavView, button_rect}; +use texturecraft_ui_egui::state::{UiState, ViewLayout}; +use texturecraft_ui_egui::ui_state_store::UiStateStore; + +mod memory_storage; + +use memory_storage::MemoryStorage; + +const WINDOW: egui::Vec2 = vec2(1280.0, 800.0); + +/// The app showing only one view, so that the view fills the viewport rect the 3D view reports +fn app(layout: ViewLayout) -> (Harness<'static, TextureCraftApp>, Rect) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW).with_pixels_per_point(1.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = texturecraft_engine::Tool::Paint; + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(4); + let view = harness.state().viewport_rect; + harness.state_mut().ui.layout = layout; + harness.run_steps(4); + (harness, view) +} + +/// Zoom the camera in and shift the 2D view so that the model and the texture lie under the buttons: a press there paints +fn fill_views(harness: &mut Harness<'_, TextureCraftApp>) { + harness.state_mut().session.camera.distance = 1.2 * harness.state().session.camera.scene_radius; + harness.state_mut().ui.uv_pan = [0.9, 0.0]; + harness.run_steps(4); +} + +/// Press at `from` with the primary button, move to `to` in steps and release +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(2); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(3); +} + +fn drag_button(harness: &mut Harness<'_, TextureCraftApp>, view: Rect, kind: NavView, button: NavButton, by: egui::Vec2) { + let from = button_rect(view, kind, button).expect("the button is shown").center(); + drag(harness, from, from + by); +} + +/// What painting changes: the undo steps and the tiles the selected layer's base color has allocated +fn history(harness: &Harness<'_, TextureCraftApp>) -> (Vec, usize) { + let session = &harness.state().session; + let layer = session.selected_layer().expect("a selected layer"); + let tiles = session.doc.pixels.layer(layer, texturecraft_engine::core::Channel::BaseColor).map_or(0, |image| image.allocated_count()); + (session.history_labels(), tiles) +} + +#[test] +fn dragging_the_orbit_button_turns_the_camera_and_paints_nothing() { + let (mut harness, view) = app(ViewLayout::Only3D); + fill_views(&mut harness); + let (camera, labels) = (harness.state().session.camera, history(&harness)); + + drag_button(&mut harness, view, NavView::Scene, NavButton::Orbit, vec2(40.0, 20.0)); + + let after = harness.state().session.camera; + assert!(after.yaw != camera.yaw && after.pitch != camera.pitch, "orbit: {camera:?} -> {after:?}"); + assert_eq!((after.target, after.distance), (camera.target, camera.distance), "only the angles change"); + assert_eq!(history(&harness), labels, "nothing painted"); +} + +#[test] +fn orbit_button_turns_the_camera_as_far_as_the_mouse_drag_does() { + let (mut harness, view) = app(ViewLayout::Only3D); + let start = harness.state().session.camera; + drag_button(&mut harness, view, NavView::Scene, NavButton::Orbit, vec2(40.0, 0.0)); + let by_button = harness.state().session.camera.yaw - start.yaw; + + // The same drag with the right mouse button over the view + let (mut reference, view) = app(ViewLayout::Only3D); + let from = view.center(); + reference.hover_at(from); + reference.run_steps(2); + reference.event(Event::PointerButton { pos: from, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + reference.run_steps(2); + for step in 1..=4 { + reference.hover_at(from + vec2(40.0, 0.0) * (step as f32 / 4.0)); + reference.run_steps(1); + } + reference.event(Event::PointerButton { pos: from + vec2(40.0, 0.0), button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + reference.run_steps(3); + let by_mouse = reference.state().session.camera.yaw - start.yaw; + + assert!(by_button != 0.0 && (by_button - by_mouse).abs() < 1e-4, "button {by_button}, mouse {by_mouse}"); +} + +#[test] +fn dragging_the_pan_button_moves_the_camera_target_and_paints_nothing() { + let (mut harness, view) = app(ViewLayout::Only3D); + let (camera, labels) = (harness.state().session.camera, history(&harness)); + + drag_button(&mut harness, view, NavView::Scene, NavButton::Pan, vec2(-30.0, 20.0)); + + let after = harness.state().session.camera; + assert!((after.target - camera.target).length() > 1e-3, "pan: {camera:?} -> {after:?}"); + assert_eq!((after.yaw, after.pitch, after.distance), (camera.yaw, camera.pitch, camera.distance)); + assert_eq!(history(&harness), labels, "nothing painted"); +} + +#[test] +fn dragging_the_zoom_button_up_moves_closer_and_down_moves_away() { + let (mut harness, view) = app(ViewLayout::Only3D); + let (camera, labels) = (harness.state().session.camera, history(&harness)); + + drag_button(&mut harness, view, NavView::Scene, NavButton::Zoom, vec2(0.0, -20.0)); + let closer = harness.state().session.camera; + assert!(closer.distance < camera.distance, "{} -> {}", camera.distance, closer.distance); + assert_eq!((closer.yaw, closer.pitch, closer.target), (camera.yaw, camera.pitch, camera.target)); + + drag_button(&mut harness, view, NavView::Scene, NavButton::Zoom, vec2(0.0, 40.0)); + assert!(harness.state().session.camera.distance > closer.distance); + assert_eq!(history(&harness), labels, "nothing painted"); +} + +#[test] +fn the_2d_view_pans_and_zooms_with_its_buttons_and_paints_nothing() { + let (mut harness, view) = app(ViewLayout::Only2D); + let (zoom, pan, labels, camera) = { + let state = harness.state(); + (state.ui.uv_zoom, state.ui.uv_pan, history(&harness), state.session.camera) + }; + + drag_button(&mut harness, view, NavView::Uv, NavButton::Pan, vec2(40.0, 20.0)); + let panned = harness.state().ui.uv_pan; + assert!(panned[0] > pan[0] && panned[1] < pan[1], "dragging right and down moves the texture right and down: {pan:?} -> {panned:?}"); + assert_eq!(harness.state().ui.uv_zoom, zoom); + + drag_button(&mut harness, view, NavView::Uv, NavButton::Zoom, vec2(0.0, -30.0)); + let zoomed_in = harness.state().ui.uv_zoom; + assert!(zoomed_in > zoom, "dragging up zooms in"); + drag_button(&mut harness, view, NavView::Uv, NavButton::Zoom, vec2(0.0, 60.0)); + assert!(harness.state().ui.uv_zoom < zoomed_in, "dragging down zooms out"); + assert_eq!(history(&harness), labels, "nothing painted"); + assert_eq!(harness.state().session.camera, camera, "the 3D camera stays"); +} + +#[test] +fn the_same_drags_paint_where_there_is_no_button() { + let (mut harness, view) = app(ViewLayout::Only3D); + fill_views(&mut harness); + harness.state_mut().ui.nav_buttons = false; + harness.run_steps(2); + let labels = history(&harness); + drag_button(&mut harness, view, NavView::Scene, NavButton::Orbit, vec2(40.0, 20.0)); + assert!(history(&harness) != labels, "with the buttons off the press paints, so the other tests prove the buttons stop it"); + + let (mut harness, view) = app(ViewLayout::Only2D); + fill_views(&mut harness); + harness.state_mut().ui.nav_buttons = false; + harness.run_steps(2); + let labels = history(&harness); + drag_button(&mut harness, view, NavView::Uv, NavButton::Pan, vec2(40.0, 20.0)); + assert!(history(&harness) != labels, "the 2D view paints there too"); +} + +#[test] +fn a_press_in_the_gap_between_buttons_or_in_the_margin_paints_nothing() { + for (layout, kind) in [(ViewLayout::Only3D, NavView::Scene), (ViewLayout::Only2D, NavView::Uv)] { + let (mut harness, view) = app(layout); + fill_views(&mut harness); + let first = button_rect(view, kind, kind.buttons()[0]).unwrap(); + let labels = history(&harness); + let gap = first.left_bottom() + vec2(15.0, 2.0); + drag(&mut harness, gap, gap + vec2(30.0, 10.0)); + let margin = first.right_center() + vec2(3.0, 0.0); + drag(&mut harness, margin, margin + vec2(-30.0, 10.0)); + assert_eq!(history(&harness), labels, "{kind:?}: nothing painted"); + } +} + +#[test] +fn the_2d_view_has_no_orbit_button() { + let view = Rect::from_min_size(Pos2::ZERO, vec2(600.0, 500.0)); + assert!(button_rect(view, NavView::Uv, NavButton::Orbit).is_none()); + assert!(button_rect(view, NavView::Scene, NavButton::Orbit).is_some()); +} + +#[test] +fn buttons_stay_clear_of_the_pickers_the_gizmo_and_the_split_divider_at_1280_by_800() { + let (harness, _) = app(ViewLayout::Split); + let view = harness.state().viewport_rect; + assert!(view.width() >= 300.0, "the pickers fit the 3D side: {view:?}"); + + // Keep navigation buttons clear of the pickers, axis gizmo, set name, and divider + let pickers = Rect::from_min_size(egui::pos2(view.center().x - 150.0, view.top() + 8.0), vec2(300.0, 22.0)); + let gizmo = Rect::from_min_size(egui::pos2(view.left(), view.bottom() - 56.0), vec2(80.0, 56.0)); + let set_name = Rect::from_min_size(egui::pos2(view.right() - 160.0, view.bottom() - 24.0), vec2(160.0, 24.0)); + for button in NavView::Scene.buttons() { + let at = button_rect(view, NavView::Scene, *button).expect("shown at 1280 x 800"); + assert!(view.contains_rect(at), "{button:?} inside the view"); + assert!(!at.intersects(pickers) && !at.intersects(gizmo) && !at.intersects(set_name), "{button:?} overlaps an overlay"); + assert!(view.right() - at.right() >= 4.0, "{button:?} stays off the divider's grab zone"); + } + + // The 2D side is as wide as the 3D side or wider at the default ratio + let uv_view = Rect::from_min_size(egui::pos2(view.right() + 2.0, view.top()), vec2(view.width(), view.height())); + for button in NavView::Uv.buttons() { + let at = button_rect(uv_view, NavView::Uv, *button).expect("shown at 1280 x 800"); + assert!(!at.intersects(Rect::from_min_size(egui::pos2(uv_view.center().x - 150.0, uv_view.top() + 8.0), vec2(300.0, 22.0)))); + assert!(!at.intersects(Rect::from_min_size(egui::pos2(uv_view.right() - 160.0, uv_view.bottom() - 24.0), vec2(160.0, 24.0))), "the texture set name"); + } +} + +#[test] +fn views_too_small_for_the_column_show_no_buttons() { + assert!(button_rect(Rect::from_min_size(Pos2::ZERO, vec2(30.0, 600.0)), NavView::Scene, NavButton::Pan).is_none()); + assert!(button_rect(Rect::from_min_size(Pos2::ZERO, vec2(600.0, 120.0)), NavView::Scene, NavButton::Pan).is_none()); +} + +#[test] +fn the_view_menu_item_hides_the_buttons_and_the_choice_is_saved() { + let (mut harness, view) = app(ViewLayout::Only3D); + assert!(harness.state().ui.nav_buttons, "shown by default"); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.navButtons"); + harness.run_steps(3); + assert!(!harness.state().ui.nav_buttons); + + // A drag where the orbit button was no longer turns the camera + let camera = harness.state().session.camera; + drag_button(&mut harness, view, NavView::Scene, NavButton::Orbit, vec2(40.0, 20.0)); + assert_eq!(harness.state().session.camera, camera, "the button is gone"); + + // Saved with the other UI settings and read back; a state saved before the setting existed shows the buttons + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(&harness.state().ui, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); + assert!(!restored.nav_buttons); + + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("nav_buttons").is_some(), "the saved state names the setting"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + assert!(UiStateStore::default().load(Some(&storage)).expect("an older saved state loads").nav_buttons); + assert!(UiState::default().nav_buttons); + + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.navButtons"); + harness.run_steps(3); + drag_button(&mut harness, view, NavView::Scene, NavButton::Orbit, vec2(40.0, 20.0)); + assert_ne!(harness.state().session.camera, camera, "shown again"); +} diff --git a/crates/ui-egui/tests/it/nav_buttons/memory_storage.rs b/crates/ui-egui/tests/it/nav_buttons/memory_storage.rs new file mode 100644 index 00000000..281923a5 --- /dev/null +++ b/crates/ui-egui/tests/it/nav_buttons/memory_storage.rs @@ -0,0 +1,19 @@ +/// App storage held in memory, saved the way the app saves its state between runs +#[derive(Default)] +pub(super) struct MemoryStorage(pub(super) std::collections::HashMap); + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} +} diff --git a/crates/ui-egui/tests/it/new_project_baked_maps.rs b/crates/ui-egui/tests/it/new_project_baked_maps.rs index 9f1c8fee..13904e22 100644 --- a/crates/ui-egui/tests/it/new_project_baked_maps.rs +++ b/crates/ui-egui/tests/it/new_project_baked_maps.rs @@ -1,6 +1,6 @@ //! New project ▸ Import baked maps: added files are listed, Clear empties the list, Create imports them -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -8,13 +8,15 @@ use texturecraft_engine::core::{BakedMap, NormalFormat}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::new_project_advanced::add_baked_map_files; +use super::temp_dir::TempDir; + /// Two quads with the materials Ball and Base, like the sample's texture sets const TWO_MATERIALS: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nv 0 0 1\nv 1 0 1\nv 1 1 1\nv 0 1 1\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\n\ usemtl Ball\nf 1/1 2/2 3/3 4/4\nusemtl Base\nf 5/1 6/2 7/3 8/4\n"; /// The New project window with `test`'s mesh file (materials Ball and Base) selected -fn harness_for(test: &str) -> Harness<'static, TextureCraftApp> { - let mesh = test_dir(test).join("Ball.obj"); +fn harness_for(dir: &Path) -> Harness<'static, TextureCraftApp> { + let mesh = dir.join("Ball.obj"); std::fs::write(&mesh, TWO_MATERIALS).unwrap(); let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); @@ -25,12 +27,6 @@ fn harness_for(test: &str) -> Harness<'static, TextureCraftApp> { h } -fn test_dir(test: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("texturecraft-np-baked-maps-{test}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - dir -} - /// Click Create (fixed below the form) fn create(h: &mut Harness<'_, TextureCraftApp>) { h.get_by_label("Create").click(); @@ -38,8 +34,7 @@ fn create(h: &mut Harness<'_, TextureCraftApp>) { } /// 4×4 PNGs named `files` in a fresh folder, as their full paths; green 0.2 shows which way a normal map was read -fn bake_files(test: &str, files: &[&str]) -> Vec { - let dir = test_dir(test); +fn bake_files(dir: &Path, files: &[&str]) -> Vec { files .iter() .map(|file| { @@ -52,17 +47,19 @@ fn bake_files(test: &str, files: &[&str]) -> Vec { #[test] fn added_files_are_listed_once_and_clear_empties_the_list() { - let mut h = harness_for("list"); - let paths = bake_files("list", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + let dir = TempDir::new("new-project-baked-maps-list"); + let mut h = harness_for(&dir); + let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); add_baked_map_files(&mut h.state_mut().ui.new_project, paths); h.run_steps(3); assert_eq!(h.state().ui.new_project.baked_maps.len(), 3, "each file once"); - for file in ["Ball_normal.png", "Base_ao.png", "Ball_notes.png"] { - h.get_by_label(file); - } + let first = h.get_by_label("Ball_normal.png").rect(); + let second = h.get_by_label("Base_ao.png").rect(); + let third = h.get_by_label("Ball_notes.png").rect(); + assert!(first.bottom() < second.top() && second.bottom() < third.top(), "the files appear on separate rows"); h.get_by_label("Clear").click(); h.run_steps(3); @@ -72,8 +69,9 @@ fn added_files_are_listed_once_and_clear_empties_the_list() { #[test] fn create_imports_the_listed_maps_in_the_chosen_normal_format() { - let mut h = harness_for("create"); - let paths = bake_files("create", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + let dir = TempDir::new("new-project-baked-maps-create"); + let mut h = harness_for(&dir); + let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); add_baked_map_files(&mut h.state_mut().ui.new_project, paths); h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); h.run_steps(3); @@ -97,8 +95,9 @@ fn create_imports_the_listed_maps_in_the_chosen_normal_format() { #[test] fn a_failed_import_keeps_the_file_list_and_created_project() { - let mut h = harness_for("failure"); - let paths = bake_files("failure", &["Ball_normal.png", "Base_ao.png"]); + let dir = TempDir::new("new-project-baked-maps-failure"); + let mut h = harness_for(&dir); + let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png"]); std::fs::write(&paths[1], b"not an image").unwrap(); add_baked_map_files(&mut h.state_mut().ui.new_project, paths.clone()); h.run_steps(3); @@ -126,13 +125,14 @@ fn new_project_baked_maps_snapshots() { eprintln!("snapshot adapter: {adapter:?}"); TextureCraftApp::new(cc, session) }); - let mesh = test_dir("snapshots").join("Ball.obj"); + let dir = TempDir::new("new-project-baked-maps-snapshots"); + let mesh = dir.join("Ball.obj"); std::fs::write(&mesh, TWO_MATERIALS).unwrap(); h.state_mut().ui.windows.new_project = true; h.state_mut().ui.new_project.resolution = 256; h.state_mut().ui.new_project.file = Some(mesh.display().to_string()); h.run_steps(6); - let paths = bake_files("snapshots", &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); + let paths = bake_files(&dir, &["Ball_normal.png", "Base_ao.png", "Ball_notes.png"]); add_baked_map_files(&mut h.state_mut().ui.new_project, paths); h.state_mut().ui.new_project.normal_format = Some(NormalFormat::DirectX); h.run_steps(6); @@ -150,7 +150,8 @@ fn new_project_baked_maps_snapshots() { #[test] fn normal_format_preview_uses_the_same_template_lookup_as_creation() { - let mut h = harness_for("template"); + let dir = TempDir::new("new-project-baked-maps-template"); + let mut h = harness_for(&dir); h.state_mut().session.templates.dir = None; h.state_mut().run("textureSet.settings", serde_json::json!({"normalFormat": "directX"})).unwrap(); h.state_mut().run("project.template.save", serde_json::json!({"name": "Custom DirectX"})).unwrap(); diff --git a/crates/ui-egui/tests/it/new_project_window.rs b/crates/ui-egui/tests/it/new_project_window.rs index 4935ae9c..7c5b4324 100644 --- a/crates/ui-egui/tests/it/new_project_window.rs +++ b/crates/ui-egui/tests/it/new_project_window.rs @@ -11,6 +11,8 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::new_project_advanced::create_command; use texturecraft_ui_egui::project_form::{NOT_AVAILABLE, OCIO_NOT_AVAILABLE}; +use super::temp_dir::TempDir; + /// A quad whose UVs lie in UV tile 1002 and a camera-free OBJ const TILE_1002_QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 1.1 0.1\nvt 1.9 0.1\nvt 1.9 0.9\nvt 1.1 0.9\nf 1/1 2/2 3/3 4/4\n"; @@ -30,14 +32,62 @@ fn harness_sized(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { h } -fn mesh_file(test: &str, contents: &str) -> String { - let dir = std::env::temp_dir().join(format!("texturecraft-np-window-{test}-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); +fn mesh_file(dir: &std::path::Path, contents: &str) -> String { let path = dir.join("tiles.obj"); std::fs::write(&path, contents).unwrap(); + path.display().to_string() } +#[test] +fn cancel_drops_the_selected_mesh_buffer() { + let mut h = harness(); + let bytes = std::sync::Arc::new(vec![0; 1024 * 1024]); + let buffer = std::sync::Arc::downgrade(&bytes); + h.state_mut().ui.new_project.file = Some("cancel.obj".into()); + h.state_mut().ui.new_project.file_bytes = Some(bytes); + h.run_steps(3); + + h.get_by_role_and_label(Role::Button, "Cancel").click(); + h.run_steps(3); + + assert!(!h.state().ui.windows.new_project); + assert!(buffer.upgrade().is_none()); +} + +#[test] +fn create_keeps_the_mesh_buffer_for_retry_and_drops_it_after_success() { + let dir = TempDir::new("new-project-create-retry"); + let path = dir.join("retry.obj"); + let mut h = harness(); + let bytes = std::sync::Arc::new(vec![0; 2 * 1024 * 1024]); + let buffer = std::sync::Arc::downgrade(&bytes); + h.state_mut().ui.new_project.resolution = 128; + h.state_mut().ui.new_project.file = Some(path.display().to_string()); + h.state_mut().ui.new_project.file_bytes = Some(bytes); + h.run_steps(3); + + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + assert!(h.state().ui.windows.new_project); + assert!(buffer.upgrade().is_some()); + assert_eq!(h.state().session.doc.project.name, "Open"); + + std::fs::write(&path, TILE_1002_QUAD).unwrap(); + let color_map = dir.join("retry_basecolor.png"); + image::RgbaImage::new(4, 4).save(&color_map).unwrap(); + texturecraft_ui_egui::pbr_import::begin(h.state_mut(), serde_json::json!({"files": [color_map]})); + assert!(h.state().pbr_import.is_some()); + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + assert!(!h.state().ui.windows.new_project); + assert!(buffer.upgrade().is_none()); + assert!(h.state().pbr_import.is_none()); + assert_eq!(h.state().session.doc.project.name, "retry"); +} + fn top(h: &Harness<'_, TextureCraftApp>, label: &str) -> f32 { h.get_all_by_label(label).map(|node| node.rect().top()).fold(f32::INFINITY, f32::min) } @@ -51,7 +101,7 @@ fn ticked(h: &Harness<'_, TextureCraftApp>, role: Role, label: &str) -> bool { } #[test] -fn the_sections_follow_the_reference_order() { +fn the_sections_follow_the_project_setup_order() { let h = harness(); let order = [ "BASIC SETTINGS", @@ -62,20 +112,20 @@ fn the_sections_follow_the_reference_order() { "Normal map format", "Compute tangent space per fragment", "UV Tile settings (UDIMs)", - "You won't be able to change UV Tile settings after creating the project.", + "You can enable or disable UV tiles later in Texture Set Settings.", "Use UV Tile workflow", - "Preserve UV Tile layout per material and enable painting across tiles", - "Convert UV Tiles into individual Texture Sets (legacy)", + "Keep UV tiles together per material", + "Use a separate texture set for each tile", "Import settings", "Import cameras", "Auto-unwrap", "Import baked maps", "Import mesh normal maps and baked maps for all materials.", - "Automatic normal maps assignation scheme: $(MATERIAL_NAME)_normal", + "Normal map filename: _normal", "Physical size", - "Use mesh file's internal unit scale (recommended)", + "Use the mesh file’s unit scale", "Custom unit scale", - "Switch fill layer scaling to Physical size when assigning materials", + "Scale material fills in real-world units", "Color management", "Working color space", ]; @@ -97,12 +147,12 @@ fn the_defaults_match_the_reference() { assert!(h.query_by_value("Legacy").is_some()); assert!(!ticked(&h, Role::CheckBox, "Compute tangent space per fragment")); assert!(!ticked(&h, Role::CheckBox, "Use UV Tile workflow")); - assert!(ticked(&h, Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles")); - assert!(disabled(&h, Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles"), "greyed while UV tiles are off"); + assert!(ticked(&h, Role::RadioButton, "Keep UV tiles together per material")); + assert!(disabled(&h, Role::RadioButton, "Keep UV tiles together per material"), "greyed while UV tiles are off"); assert!(ticked(&h, Role::CheckBox, "Import cameras") && !disabled(&h, Role::CheckBox, "Import cameras")); assert!(ticked(&h, Role::CheckBox, "Auto-unwrap")); - assert!(ticked(&h, Role::RadioButton, "Use mesh file's internal unit scale (recommended)")); - assert!(!ticked(&h, Role::CheckBox, "Switch fill layer scaling to Physical size when assigning materials")); + assert!(ticked(&h, Role::RadioButton, "Use the mesh file’s unit scale")); + assert!(!ticked(&h, Role::CheckBox, "Scale material fills in real-world units")); } #[test] @@ -121,7 +171,8 @@ fn create_waits_for_a_mesh_file() { assert!(disabled(&h, Role::Button, "Create")); - h.state_mut().ui.new_project.file = Some(mesh_file("create-enabled", TILE_1002_QUAD)); + let dir = TempDir::new("new-project-create-enabled"); + h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD)); h.run_steps(2); assert!(!disabled(&h, Role::Button, "Create")); @@ -133,17 +184,16 @@ fn settings_not_available_yet_are_disabled_with_a_hint() { let mut h = harness(); let unavailable = [ (Role::CheckBox, "Compute tangent space per fragment"), - (Role::Button, egui_phosphor::regular::GRADUATION_CAP), - (Role::RadioButton, "Convert UV Tiles into individual Texture Sets (legacy)"), + (Role::RadioButton, "Use a separate texture set for each tile"), (Role::CheckBox, "Auto-unwrap"), (Role::Button, "Auto-unwrap options"), (Role::RadioButton, "Custom unit scale"), - (Role::CheckBox, "Switch fill layer scaling to Physical size when assigning materials"), + (Role::CheckBox, "Scale material fills in real-world units"), ]; for (role, label) in unavailable { assert!(disabled(&h, role, label), "{label} is disabled"); } - assert!(!disabled(&h, Role::RadioButton, "Use mesh file's internal unit scale (recommended)")); + assert!(!disabled(&h, Role::RadioButton, "Use the mesh file’s unit scale")); for (role, label) in unavailable { let center = h.get_by_role_and_label(role, label).rect().center(); @@ -236,13 +286,14 @@ fn the_supported_settings_reach_the_create_command() { fn ticking_uv_tiles_creates_a_uv_tile_project() { for (tick, expected) in [(false, Vec::::new()), (true, vec![1002])] { let mut h = harness(); - h.state_mut().ui.new_project.file = Some(mesh_file(&format!("udim-{tick}"), TILE_1002_QUAD)); + let dir = TempDir::new("new-project-udim"); + h.state_mut().ui.new_project.file = Some(mesh_file(&dir, TILE_1002_QUAD)); h.state_mut().ui.new_project.resolution = 128; h.run_steps(2); if tick { h.get_by_role_and_label(Role::CheckBox, "Use UV Tile workflow").click(); h.run_steps(3); - assert!(!disabled(&h, Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles")); + assert!(!disabled(&h, Role::RadioButton, "Keep UV tiles together per material")); } h.get_by_role_and_label(Role::CheckBox, "Import cameras").click(); h.run_steps(2); @@ -286,3 +337,51 @@ fn picking_a_template_sets_its_resolution_and_normal_map_format() { assert!(h.query_by_value("DirectX").is_some(), "the template's normal map format"); assert_eq!(h.state().ui.new_project.resolution, 128); } + +#[test] +fn create_asks_before_discarding_edits_made_after_the_form_opened() { + let dir = TempDir::new("new-project-unsaved"); + let path = dir.join("tiles.obj"); + let mut h = harness(); + h.state_mut().ui.new_project.file = Some(path.display().to_string()); + h.state_mut().ui.new_project.resolution = 128; + h.state_mut().run("layer.add.paint", serde_json::Value::Null).unwrap(); + h.run_steps(3); + + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + + assert!(h.query_by_label("Unsaved changes").is_some()); + assert_eq!(h.state().session.doc.project.name, "Open"); + + h.get_by_role_and_label(Role::Button, "Don't save").click(); + h.run_steps(3); + + assert!(h.state().ui.windows.new_project); + assert!(h.state().session.modified, "a failed replacement keeps the old project dirty"); + assert_eq!(h.state().session.doc.project.name, "Open"); + + std::fs::write(path, TILE_1002_QUAD).unwrap(); + h.get_by_role_and_label(Role::Button, "Create").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Button, "Don't save").click(); + h.run_steps(3); + + assert_eq!(h.state().session.doc.project.name, "tiles"); + assert!(!h.state().ui.windows.new_project); +} + +#[test] +fn a_layout_that_closes_new_project_releases_the_selected_mesh() { + let mut h = harness(); + let bytes = std::sync::Arc::new(vec![0; 1024 * 1024]); + let buffer = std::sync::Arc::downgrade(&bytes); + let ui = &mut h.state_mut().ui; + ui.new_project.file = Some("reset.obj".into()); + ui.new_project.file_bytes = Some(bytes); + + ui.adopt_layout(texturecraft_ui_egui::UiState::default()); + + assert!(!ui.windows.new_project); + assert!(buffer.upgrade().is_none()); +} diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index 819a5468..f24e6b46 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -165,6 +165,7 @@ fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { click(&mut harness, view_2d_center); assert_eq!(harness.state().session.tool.path, path); + assert!(harness.state().toasts.iter().any(|t| t.text == "Finish or cancel the path first; it is in the 3D view"), "the click says why it was ignored"); assert_eq!(harness.state().session.doc.project, before.project); assert_eq!(harness.state().session.doc.pixels.layers, before.pixels.layers); assert_eq!(harness.state().session.history_labels(), history); @@ -202,3 +203,123 @@ fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { assert_eq!(path(&h).points, before); assert!(!path_sublayers(&h).is_empty(), "the path is still there"); } + +/// A split view over a sphere with the Path tool, plus the centres of the 3D and the 2D view +fn split_harness() -> (AppHarness<'static>, Pos2, Pos2) { + let mut session = + texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(4); + let view_3d = harness.state().viewport_rect; + let center_3d = view_3d.center(); + let center_2d = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + (harness, center_3d, center_2d) +} + +#[test] +fn clicking_the_2d_view_keeps_points_placed_in_3d_and_says_why() { + let (mut h, center_3d, center_2d) = split_harness(); + click(&mut h, center_3d); + click(&mut h, center_3d + egui::vec2(40.0, 0.0)); + let path = h.state().session.tool.path.clone(); + assert_eq!((path.points.len(), path.uv), (2, false)); + assert!(h.state().toasts.is_empty()); + + click(&mut h, center_2d); + + assert_eq!(h.state().session.tool.path, path, "the placed points stay"); + assert!(h.state().toasts.iter().any(|t| t.text == "Finish or cancel the path first; it is in the 3D view")); + + // Placing in the same view still works afterwards + click(&mut h, center_3d + egui::vec2(0.0, 40.0)); + assert_eq!(h.state().session.tool.path.points.len(), 3); +} + +#[test] +fn clicking_the_3d_view_keeps_points_placed_in_2d_and_says_why() { + let (mut h, center_3d, center_2d) = split_harness(); + click(&mut h, center_2d); + click(&mut h, center_2d + egui::vec2(40.0, 0.0)); + let path = h.state().session.tool.path.clone(); + assert_eq!((path.points.len(), path.uv), (2, true)); + + click(&mut h, center_3d); + + assert_eq!(h.state().session.tool.path, path, "the placed points stay"); + assert!(h.state().toasts.iter().any(|t| t.text == "Finish or cancel the path first; it is in the 2D view")); +} + +#[test] +fn an_empty_path_can_start_in_either_view() { + let (mut h, center_3d, center_2d) = split_harness(); + click(&mut h, center_3d); + assert_eq!((h.state().session.tool.path.points.len(), h.state().session.tool.path.uv), (1, false)); + h.state_mut().session.cancel_path(); + click(&mut h, center_2d); + assert_eq!((h.state().session.tool.path.points.len(), h.state().session.tool.path.uv), (1, true)); + assert!(h.state().toasts.is_empty()); +} + +/// A primary click with Shift held, in two frames like `click` +fn shift_click(h: &mut AppHarness<'_>, at: Pos2) { + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::SHIFT)); + for pressed in [true, false] { + let events = &mut h.input_mut().events; + events.push(Event::PointerMoved(at)); + events.push(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::SHIFT }); + h.step(); + } + h.input_mut().events.push(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +#[test] +fn shift_click_places_a_corner_point_in_one_undo_step() { + let mut h = harness(); + click(&mut h, A); + shift_click(&mut h, B); + click(&mut h, C); + assert_eq!(h.state().session.tool.path.points.len(), 3); + assert_eq!(h.state().session.tool.path.corner_flags(), vec![false, true, false]); + + // Shift+click on the curve inserts a corner there + shift_click(&mut h, A.lerp(B, 0.5)); + assert_eq!(h.state().session.tool.path.points.len(), 4); + assert_eq!(h.state().session.tool.path.corner_flags(), vec![false, true, true, false]); + + // Undo takes the inserted corner back, as a single step + h.state_mut().session.undo().unwrap(); + assert_eq!(h.state().session.tool.path.corner_flags(), vec![false, true, false]); +} + +#[test] +fn corner_button_toggles_the_selected_point_and_is_off_without_one() { + let mut h = harness(); + let button = "Corner point (Shift+click places one)"; + for at in [A, B, C] { + click(&mut h, at); + } + + // The last placed point is selected + h.get_all_by_label(button).next().unwrap().scroll_to_me(); + h.run_steps(30); + assert!(!h.get_all_by_label(button).next().unwrap().accesskit_node().is_disabled()); + h.get_all_by_label(button).next().unwrap().click(); + h.run_steps(2); + assert_eq!(h.state().session.tool.path.corner_flags(), vec![false, false, true]); + + h.get_all_by_label(button).next().unwrap().click(); + h.run_steps(2); + assert!(h.state().session.tool.path.corner_flags().is_empty()); + + // With no point selected the button is disabled + h.state_mut().session.tool.path.selected = None; + h.run_steps(2); + assert!(h.get_all_by_label(button).next().unwrap().accesskit_node().is_disabled()); +} diff --git a/crates/ui-egui/tests/it/polygon_fill.rs b/crates/ui-egui/tests/it/polygon_fill.rs index d362c1a8..ab50cb53 100644 --- a/crates/ui-egui/tests/it/polygon_fill.rs +++ b/crates/ui-egui/tests/it/polygon_fill.rs @@ -107,6 +107,23 @@ fn a_new_press_after_release_does_not_resume_the_previous_box() { assert_eq!(history(&harness).len(), history_after_drag.len() + 1, "only the new click records a step"); } +#[test] +fn the_symmetry_toggle_is_offered_for_polygon_fill_and_a_symmetric_click_is_one_step() { + use egui_kittest::kittest::Queryable; + + let mut harness = polygon_fill_app(); + harness.get_by_label("Symmetry settings"); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert!(harness.state().session.tool.brush.symmetry.any(), "the toggle turns mirroring on for the fill"); + + let center = harness.state().viewport_rect.center(); + let before = history(&harness).len(); + click(&mut harness, center); + assert_eq!(history(&harness).len(), before + 1, "the fill and its mirror copies are one undo step"); + assert_eq!(history(&harness).last().map(String::as_str), Some("Polygon fill")); +} + #[test] #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] fn polygon_fill_snapshots() { diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index ef11d0f2..1371e05b 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -9,8 +9,7 @@ use texturecraft_engine::Session; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::file_dialogs::{Answer, Request}; -mod temp_dir; -use temp_dir::TempDir; +use super::temp_dir::TempDir; const QUAD: &str = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n"; const TRIANGLE: &str = "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n"; @@ -136,7 +135,7 @@ fn every_setting_has_an_info_icon_and_the_window_ends_with_a_note() { let icons: Vec<_> = h.get_all_by_label(egui_phosphor::regular::INFO).collect(); let tip = "Green channel convention of normal maps: OpenGL (Y+) or DirectX (Y-). Imported and exported normal maps follow it."; - assert!(h.query_by_label("Please note: Changing any of these settings will cause all channels to be recomputed.").is_some(), "the note above the buttons"); + assert!(h.query_by_label("Changing the mesh or normal format can recalculate texture channels.").is_some(), "the note above the buttons"); assert_eq!( icons.len(), 13, @@ -169,9 +168,9 @@ fn the_window_follows_the_reference_layout() { "PROJECT SETTINGS", "Compute tangent space per fragment", "UV Tile settings (UDIMs)", - "You can't change UV Tile settings once a project has been created.", + "Change the UV tiles of a texture set in Texture Set Settings", "Use UV Tile workflow", - "Convert UV Tiles into individual Texture Sets (legacy)", + "Use a separate texture set for each tile", "Import settings", "Import cameras", "Preserve stroke positions on mesh", @@ -188,8 +187,8 @@ fn the_window_follows_the_reference_layout() { for (role, label) in [ (Role::CheckBox, "Compute tangent space per fragment"), (Role::CheckBox, "Use UV Tile workflow"), - (Role::RadioButton, "Preserve UV Tile layout per material and enable painting across tiles"), - (Role::RadioButton, "Convert UV Tiles into individual Texture Sets (legacy)"), + (Role::RadioButton, "Keep UV tiles together per material"), + (Role::RadioButton, "Use a separate texture set for each tile"), (Role::CheckBox, "Import cameras"), (Role::CheckBox, "Auto-unwrap"), (Role::Button, "Auto-unwrap options"), @@ -284,6 +283,9 @@ fn a_delayed_selection_does_not_change_a_window_reopened_after_layout_reset() { let context = harness.ctx.clone(); texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.resetUi"); + harness.run_steps(2); + harness.get_by_label("Reset").click(); + harness.run_steps(2); open_window(&mut harness); assert!(harness.state().ui.windows.project_config.as_ref().is_some_and(|config| config.mesh.is_none())); @@ -627,7 +629,7 @@ fn uv_tiles_are_shown_read_only() { assert!(h.query_by_label("UV Tile settings (UDIMs)").is_some()); hover_uv_tile_box(&mut h); assert!(h.query_by_label_contains("No UV tiles").is_some(), "a project without UV tiles"); - assert!(h.query_by_label("You can't change UV Tile settings once a project has been created.").is_some()); + assert!(h.query_by_label("Change the UV tiles of a texture set in Texture Set Settings").is_some()); click(&mut h, Role::Button, "Cancel"); diff --git a/crates/ui-egui/tests/it/reference_order.rs b/crates/ui-egui/tests/it/reference_order.rs new file mode 100644 index 00000000..2afce36d --- /dev/null +++ b/crates/ui-egui/tests/it/reference_order.rs @@ -0,0 +1,194 @@ +//! The order of the menus, the tool shelf and the right bar, and what is enabled with no project open, +//! follow the reference app's measured layout. Items TextureCraft has no equivalent of are absent. + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_engine::Session; +use texturecraft_ui_egui::{TextureCraftApp, menus}; + +fn harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + harness +} + +fn buttons_in(harness: &Harness<'static, TextureCraftApp>, x: std::ops::Range) -> Vec<(f32, String, bool)> { + let mut found: Vec<(f32, String, bool)> = harness + .get_all_by_role(Role::Button) + .filter(|button| x.contains(&button.rect().min.x)) + .filter_map(|button| { + let node = button.accesskit_node(); + node.label().map(|label| (button.rect().min.y, label.to_string(), node.is_disabled())) + }) + .collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found +} + +fn named<'a>(found: &'a [(f32, String, bool)], name: &str) -> Option<&'a (f32, String, bool)> { + found.iter().find(|(_, label, _)| label == name || label.starts_with(&format!("{name} ("))) +} + +#[test] +fn every_menu_lists_its_items_in_the_reference_order() { + // Items the reference has and TextureCraft lacks are absent; TextureCraft's own sit where they fit + let expected = [ + "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...", + ]; + let actual: Vec = menus::TOP + .iter() + .map(|top| { + let items: Vec = menus::CATALOG + .iter() + .filter(|item| item.menu == *top) + .map(|item| match item.sub { + Some(sub) => format!("{sub} > {}", item.label), + None => item.label.to_string(), + }) + .collect(); + format!("{top}: {}", items.join(" | ")) + }) + .collect(); + for (expected, actual) in expected.iter().zip(&actual) { + assert_eq!(expected, actual); + } + assert_eq!(menus::TOP, ["File", "Edit", "Mode", "Window", "Viewport", "Help"], "the reference's top menus, minus the scripting ones"); +} + +#[test] +fn the_tool_shelf_keeps_the_reference_order() { + let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let shelf = buttons_in(&harness, 0.0..60.0); + let order = ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Material picker", "Geometry mask"]; + let row_positions: Vec = order.iter().map(|name| named(&shelf, name).unwrap_or_else(|| panic!("{name} on the shelf: {shelf:?}")).0).collect(); + + assert!(row_positions.windows(2).all(|pair| pair[0] < pair[1]), "{row_positions:?}"); +} + +#[test] +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 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:?}"); +} + +#[test] +fn the_blank_screen_enables_what_the_reference_enables() { + let harness = harness(Session::closed().unwrap()); + let shelf = buttons_in(&harness, 0.0..60.0); + for name in ["Paint", "Eraser", "Path", "Projection", "Polygon fill", "Smudge", "Clone", "Material picker", "Geometry mask"] { + 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"] { + assert!(!named(&bar, name).unwrap().2, "{name} on the right bar stays enabled"); + } + + // Top bar: layout stays on; camera type and the three modes are greyed, Painting shown as the current mode + let top = buttons_in(&harness, 600.0..1562.0); + let on = |name: &str| !named(&top, name).unwrap_or_else(|| panic!("{name}: {top:?}")).2; + + assert!(on("3D/2D views"), "the layout selector works without a project"); + assert!(!on("Perspective") && !on("Painting") && !on("Bake Mesh Maps") && !on("Rendering (path traced)")); + + let painting = + harness.get_all_by_role(Role::Button).find(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("Painting"))).unwrap(); + + assert_eq!(painting.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "Painting is the shown mode"); +} + +#[test] +fn the_blank_screen_menus_match_the_measured_enabled_states() { + let harness = harness(Session::closed().unwrap()); + let app = harness.state(); + let disabled = [ + "file.close", + "file.save", + "file.saveAs", + "file.saveCopy", + "file.removeUnused", + "ui.export", + "file.exportMesh", + "edit.undo", + "edit.redo", + "ui.projectConfig", + "file.reimportMesh", + "ui.mode.bake", + "ui.mode.paint", + "ui.mode.render", + "viewport.displayMaterial", + "viewport.nextChannel", + "viewport.previousChannel", + "viewport.nextMeshMap", + "viewport.previousMeshMap", + "viewport.quickMask", + "viewport.quickMask.edit", + "viewport.quickMask.invert", + ]; + for id in disabled { + assert!(!menus::enabled(app, id), "{id} is disabled on the blank screen"); + } + let enabled = [ + "ui.newProject", + "file.open", + "project.sample", + "ui.quit", + "ui.settings", + "ui.view.assets", + "ui.view.layers", + "ui.view.properties", + "ui.view.textureSetList", + "ui.view.textureSetSettings", + "ui.view.display", + "ui.view.history", + "ui.view.log", + "ui.view.shader", + "ui.hideUi", + "ui.resetUi", + "ui.layout.save", + "ui.layout.load", + "viewport.frame", + "ui.help.docs", + "ui.help.shortcuts", + "ui.help.bug", + "ui.about", + ]; + for id in enabled { + assert!(menus::enabled(app, id), "{id} is enabled on the blank screen"); + } + for id in ["ui.view.bakeSettings", "ui.view.bakeMaps", "ui.view.meshMapBakers"] { + assert!(!menus::enabled(app, id), "{id} belongs to Baking mode"); + } +} + +#[test] +fn opening_a_project_enables_the_same_items() { + let harness = harness(texturecraft_engine::sample_session(256, 64).unwrap()); + let app = harness.state(); + for id in [ + "file.close", + "file.save", + "file.saveAs", + "file.saveCopy", + "ui.export", + "file.exportMesh", + "ui.projectConfig", + "ui.mode.bake", + "ui.mode.paint", + "ui.mode.render", + "viewport.displayMaterial", + "viewport.quickMask", + ] { + assert!(menus::enabled(app, id), "{id} is enabled with a project"); + } +} diff --git a/crates/ui-egui/tests/it/rename_anchor.rs b/crates/ui-egui/tests/it/rename_anchor.rs new file mode 100644 index 00000000..f8ee1763 --- /dev/null +++ b/crates/ui-egui/tests/it/rename_anchor.rs @@ -0,0 +1,260 @@ +//! Renaming an effect row and mask anchor points, driven through the interface: the row's Rename action, Undo and Redo, +//! Save and Open, and the Add effect menu and Source picker that link a fill on a higher layer to an anchor in a mask. + +use std::path::{Path, PathBuf}; + +use egui::accesskit::Role; +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::file_dialogs::Answer; + +const BLACK: [f32; 3] = [0.0; 3]; +const WHITE: [f32; 3] = [1.0; 3]; + +fn id(v: &Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +fn harness_for(session: Session) -> Harness<'static, TextureCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + + // English, so a first-run locale does not change the queried labels + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + h +} + +/// A path in a new temporary folder, named after the test. +fn temp_file(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("texturecraft-rename-anchor-{test}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join("project.tcraft") +} + +fn save_to(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { + let path = file.to_path_buf(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![path.clone()])))); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.saveAs"); + h.run_steps(3); + assert!(file.exists(), "Save as wrote the project"); + assert!(!h.state().session.modified, "the project counts as saved"); +} + +fn reopen(h: &mut Harness<'_, TextureCraftApp>, file: &Path) { + let path = file.to_path_buf(); + h.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![path.clone()])))); + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, "file.open"); + h.run_steps(3); + assert_eq!(h.state().session.path.as_deref(), Some(file.display().to_string().as_str()), "the saved project is open"); +} + +fn effect_name(h: &Harness<'_, TextureCraftApp>, effect: u64) -> String { + h.state().session.doc.project.effect(LayerId(effect)).unwrap().1.name.clone() +} + +/// A fill layer with one effect named "Effect A", selected, in the running interface. +fn effect_harness() -> (Harness<'static, TextureCraftApp>, u64) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = id(&texturecraft_engine::execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + let effect = id( + &texturecraft_engine::execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), + "effect", + ); + texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer})).unwrap(); + (harness_for(session), effect) +} + +/// Choose Rename effect from the row's context menu and type `text` over the old name. +fn rename_from_the_menu(h: &mut Harness<'_, TextureCraftApp>, old: &str, text: &str) { + h.get_by_label(old).click_secondary(); + h.run_steps(2); + h.get_by_label("Rename effect").click(); + h.run_steps(3); + assert!(h.state().ui.rename.is_some(), "the editor is open"); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(3); +} + +#[test] +fn renaming_an_effect_row_undoes_redoes_and_survives_save_and_reopen() { + let (mut h, effect) = effect_harness(); + rename_from_the_menu(&mut h, "Effect A", "Pitted rust"); + h.key_press(Key::Enter); + h.run_steps(3); + assert!(h.state().ui.rename.is_none(), "Enter closes the editor"); + assert_eq!(effect_name(&h, effect), "Pitted rust"); + assert!(h.query_by_label("Pitted rust").is_some(), "the row shows the new name"); + assert!(h.query_by_label("Effect A").is_none(), "the old name is gone from the row"); + + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run_steps(3); + assert_eq!(effect_name(&h, effect), "Effect A", "Ctrl+Z restores the old name"); + assert!(h.query_by_label("Effect A").is_some(), "the row shows the old name again"); + + h.key_press_modifiers(Modifiers::COMMAND, Key::Y); + h.run_steps(3); + assert_eq!(effect_name(&h, effect), "Pitted rust", "Ctrl+Y redoes the rename"); + assert!(h.query_by_label("Pitted rust").is_some()); + + let file = temp_file("rename"); + save_to(&mut h, &file); + + // Change the open project, so the reopen has to bring the saved name back + h.state_mut().run("effect.set", json!({"effect": effect, "name": "Unsaved name"})); + h.state_mut().session.modified = false; + reopen(&mut h, &file); + assert_eq!(effect_name(&h, effect), "Pitted rust", "the reopened project keeps the name"); + let layer = h.state().session.doc.project.effect(LayerId(effect)).unwrap().0; + h.state_mut().run("layer.select", json!({"layer": layer.0})); + h.run_steps(3); + assert!(h.query_by_label("Pitted rust").is_some(), "the reopened stack shows the name"); + std::fs::remove_dir_all(file.parent().unwrap()).unwrap(); +} + +#[test] +fn escape_in_the_effect_editor_keeps_the_name() { + let (mut h, effect) = effect_harness(); + let history = h.state().session.history_labels().len(); + rename_from_the_menu(&mut h, "Effect A", "Never applied"); + h.key_press(Key::Escape); + h.run_steps(3); + assert!(h.state().ui.rename.is_none(), "Escape closes the editor"); + assert_eq!(effect_name(&h, effect), "Effect A"); + assert_eq!(h.state().session.history_labels().len(), history, "nothing was added to the history"); +} + +/// Composited base color at the middle texel of the sphere's texture. +fn base_color(s: &mut Session) -> [f32; 3] { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, 128, 128) +} + +fn close(a: [f32; 3], b: [f32; 3]) -> bool { + (0..3).all(|i| (a[i] - b[i]).abs() < 2e-3) +} + +/// A black layer "Low" whose mask is a 0.4 fill: it shows at 0.5 * 0.6 over the default base color. +fn low_layer(s: &mut Session) -> u64 { + let low = id(&texturecraft_engine::execute(s, "layer.add.fill", &json!({"color": BLACK})).unwrap(), "layer"); + texturecraft_engine::execute(s, "layer.rename", &json!({"layer": low, "name": "Low"})).unwrap(); + texturecraft_engine::execute(s, "mask.add.black", &Value::Null).unwrap(); + texturecraft_engine::execute(s, "effect.add.fill", &json!({"value": 0.4})).unwrap(); + low +} + +/// A white layer with a black mask, selected on its mask. +fn high_layer(s: &mut Session) -> u64 { + let high = id(&texturecraft_engine::execute(s, "layer.add.fill", &json!({"color": WHITE})).unwrap(), "layer"); + texturecraft_engine::execute(s, "mask.add.black", &Value::Null).unwrap(); + high +} + +fn sphere_session() -> Session { + Session::new_project("anchors", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap() +} + +fn mask_anchor_of(h: &Harness<'_, TextureCraftApp>, layer: u64) -> Option { + let layer = h.state().session.doc.project.layer(LayerId(layer)).unwrap(); + layer.mask.iter().flat_map(|m| m.effects.iter()).find(|e| matches!(e.kind, EffectKind::Anchor)).map(|e| e.id.0) +} + +fn reader_source(h: &Harness<'_, TextureCraftApp>, reader: u64) -> Source { + let layer = h.state().session.doc.project.layer(LayerId(reader)).unwrap(); + let effect = layer.mask.as_ref().unwrap().effects.iter().find(|e| matches!(e.kind, EffectKind::Fill { .. })).expect("the mask has a fill"); + let EffectKind::Fill { source, .. } = &effect.kind else { unreachable!() }; + source.clone() +} + +#[test] +fn a_fill_on_a_higher_layer_reads_a_mask_anchor_added_in_the_interface() { + let mut session = sphere_session(); + let low = low_layer(&mut session); + let mut h = harness_for(session); + + // The wand adds to the mask, since the mask's fill is the selected target of the Low layer + assert!(matches!(h.state().session.target, StackTarget::Effect(_))); + h.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + h.run_steps(3); + assert!(h.query_by_label("Add to the mask").is_some(), "the menu offers the mask"); + h.get_by_label("Add anchor point").click(); + h.run_steps(3); + let anchor = mask_anchor_of(&h, low).expect("the anchor point is in the mask of Low"); + assert!(h.state().session.doc.project.layer(LayerId(low)).unwrap().content_effects.is_empty(), "the anchor point is not on the layer content"); + + // A higher layer with a mask fill, added through the same menu + let high = high_layer(&mut h.state_mut().session); + h.run_steps(3); + h.get_by_label(egui_phosphor::regular::MAGIC_WAND).click(); + h.run_steps(3); + h.get_by_label("Add fill").click(); + h.run_steps(3); + assert!(matches!(reader_source(&h, high), Source::Uniform(_)), "a new fill starts as a uniform value"); + + // The Anchor points tab lists the mask anchor of the layer below + h.get_by_role_and_label(Role::ComboBox, "Grayscale").scroll_to_me(); + h.run_steps(30); + h.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + h.run_steps(3); + h.get_by_role_and_label(Role::Tab, "Anchor points").click(); + h.run_steps(3); + + let label = format!("Low / mask / {}", effect_name(&h, anchor)); + h.get_by_role_and_label(Role::Button, &label).click(); + h.run_steps(3); + + let Source::Anchor { anchor: read, .. } = reader_source(&h, high) else { panic!("the fill reads an anchor: {:?}", reader_source(&h, high)) }; + assert_eq!(read.0, anchor, "the fill reads the anchor of Low"); + + // The higher layer shows the mask value recorded at the anchor: 0.4 + let low_shown = 0.5 * 0.6; + let expected = low_shown + (1.0 - low_shown) * 0.4; + assert!(close(base_color(&mut h.state_mut().session), [expected; 3]), "{:?}", base_color(&mut h.state_mut().session)); + + // The engine alone gives the same result for the same stack + let mut reference = sphere_session(); + low_layer(&mut reference); + let ref_anchor = id(&texturecraft_engine::execute(&mut reference, "effect.add.anchor", &json!({"target": "mask"})).unwrap(), "effect"); + high_layer(&mut reference); + texturecraft_engine::execute(&mut reference, "effect.add.fill", &json!({"anchor": ref_anchor})).unwrap(); + assert!(close(base_color(&mut h.state_mut().session), base_color(&mut reference))); + + // Save and reopen keep the link and the result + let file = temp_file("anchor"); + save_to(&mut h, &file); + + // Unlink the fill in the open project, so the reopen has to bring the saved link back + let fill = h + .state() + .session + .doc + .project + .layer(LayerId(high)) + .unwrap() + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find(|e| matches!(e.kind, EffectKind::Fill { .. })) + .unwrap() + .id + .0; + h.state_mut().run("effect.set", json!({"effect": fill, "value": 1.0})); + assert!(matches!(reader_source(&h, high), Source::Uniform(_))); + h.state_mut().session.modified = false; + reopen(&mut h, &file); + assert_eq!(mask_anchor_of(&h, low), Some(anchor), "the anchor point is still in the mask"); + let Source::Anchor { anchor: read, .. } = reader_source(&h, high) else { panic!("the reopened fill reads an anchor") }; + assert_eq!(read.0, anchor, "the reopened fill still reads that anchor"); + assert!(close(base_color(&mut h.state_mut().session), [expected; 3]), "{:?}", base_color(&mut h.state_mut().session)); + std::fs::remove_dir_all(file.parent().unwrap()).unwrap(); +} diff --git a/crates/ui-egui/tests/it/reset_ui.rs b/crates/ui-egui/tests/it/reset_ui.rs new file mode 100644 index 00000000..759f7e5e --- /dev/null +++ b/crates/ui-egui/tests/it/reset_ui.rs @@ -0,0 +1,126 @@ +//! Window ▸ Reset panel layout puts back only the panels; Reset UI asks before it resets the view too. + +use egui::Key; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::{Mode, ViewLayout}; + +/// An app with the Assets panel closed, a changed view split, zoom, wireframe and mode. +fn changed_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let ui = &mut h.state_mut().ui; + ui.dock.close(Panel::Assets); + ui.layout = ViewLayout::Only3D; + ui.uv_zoom = 2.5; + ui.wireframe_3d = true; + ui.mode = Mode::Rendering; + h.run_steps(2); + h +} + +fn invoke(h: &mut Harness<'_, TextureCraftApp>, id: &str) { + let ctx = h.ctx.clone(); + texturecraft_ui_egui::menus::invoke(h.state_mut(), &ctx, id); + h.run_steps(2); +} + +fn view_kept(h: &Harness<'_, TextureCraftApp>) -> bool { + let ui = &h.state().ui; + ui.layout == ViewLayout::Only3D && ui.uv_zoom == 2.5 && ui.wireframe_3d && ui.mode == Mode::Rendering +} + +#[test] +fn reset_panel_layout_restores_the_panels_and_keeps_the_view() { + let mut h = changed_app(); + assert!(!h.state().ui.dock.is_open(Panel::Assets)); + invoke(&mut h, "ui.resetPanelLayout"); + assert!(h.state().ui.dock.is_open(Panel::Assets), "the closed panel is back"); + assert!(view_kept(&h), "view split, zoom, wireframe and mode stay"); + assert!(!h.state().ui.windows.confirm_reset_ui, "no question for the panel reset"); +} + +#[test] +fn reset_ui_asks_first_and_cancel_changes_nothing() { + let mut h = changed_app(); + invoke(&mut h, "ui.resetUi"); + assert!(!h.state().ui.dock.is_open(Panel::Assets), "nothing is reset before the answer"); + assert!(view_kept(&h)); + h.get_by_label("Cancel").click(); + h.run_steps(2); + assert!(!h.state().ui.windows.confirm_reset_ui); + assert!(!h.state().ui.dock.is_open(Panel::Assets)); + assert!(view_kept(&h)); +} + +#[test] +fn reset_ui_ok_resets_everything_as_before() { + let mut h = changed_app(); + invoke(&mut h, "ui.resetUi"); + h.get_by_label("Reset").click(); + h.run_steps(2); + let ui = &h.state().ui; + assert!(!ui.windows.confirm_reset_ui); + assert!(ui.dock.is_open(Panel::Assets)); + assert_eq!((ui.layout, ui.uv_zoom, ui.wireframe_3d, ui.mode), (ViewLayout::Split, 1.0, false, Mode::Painting)); +} + +#[test] +fn reset_ui_escape_keeps_everything_and_enter_resets() { + let mut h = changed_app(); + invoke(&mut h, "ui.resetUi"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(!h.state().ui.windows.confirm_reset_ui); + assert!(view_kept(&h) && !h.state().ui.dock.is_open(Panel::Assets)); + + invoke(&mut h, "ui.resetUi"); + h.key_press(Key::Enter); + h.run_steps(2); + assert!(!h.state().ui.windows.confirm_reset_ui); + assert!(h.state().ui.dock.is_open(Panel::Assets)); + assert_eq!(h.state().ui.layout, ViewLayout::Split); +} + +#[test] +fn the_menu_invoke_command_asks_first_like_a_click() { + let mut h = changed_app(); + let ctx = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &ctx, "ui.menu.invoke", &serde_json::json!({"id": "ui.resetUi"})); + h.run_steps(2); + assert!(reply.get("error").is_none(), "{reply}"); + assert!(h.state().ui.windows.confirm_reset_ui, "the question is open"); + assert!(!h.state().ui.dock.is_open(Panel::Assets), "nothing is reset before the answer"); + assert!(view_kept(&h)); +} + +#[test] +fn the_ui_reset_control_command_resets_without_asking() { + let mut h = changed_app(); + let ctx = h.ctx.clone(); + let reply = texturecraft_ui_egui::control::handle(h.state_mut(), &ctx, "ui.reset", &serde_json::Value::Null); + h.run_steps(2); + assert!(reply.get("error").is_none(), "{reply}"); + let ui = &h.state().ui; + assert!(!ui.windows.confirm_reset_ui, "no question for a script"); + assert!(ui.dock.is_open(Panel::Assets)); + assert_eq!((ui.layout, ui.uv_zoom, ui.wireframe_3d, ui.mode), (ViewLayout::Split, 1.0, false, Mode::Painting)); +} + +#[test] +fn escape_cancels_the_question_even_when_a_shortcut_binds_it() { + let mut h = changed_app(); + h.state_mut().ui.keymap.insert("ui.hideUi".into(), "Escape".into()); + h.run_steps(2); + invoke(&mut h, "ui.resetUi"); + assert!(h.state().ui.windows.confirm_reset_ui); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(!h.state().ui.windows.confirm_reset_ui, "Escape closed the question"); + assert!(!h.state().ui.hide_ui, "and did not run the command bound to it"); + assert!(view_kept(&h) && !h.state().ui.dock.is_open(Panel::Assets)); +} diff --git a/crates/ui-egui/tests/it/shelf_click.rs b/crates/ui-egui/tests/it/shelf_click.rs new file mode 100644 index 00000000..bc11cfdb --- /dev/null +++ b/crates/ui-egui/tests/it/shelf_click.rs @@ -0,0 +1,78 @@ +//! A click on a simple shelf material sets the brush's material and adds no layer; a click on a smart material changes nothing + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::materials::{brush_values, find}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The shelf's Materials and Smart materials types +const MATERIALS_TYPE: usize = 0; +const SMART_TYPE: usize = 1; + +/// The sample project with the shelf on type `tab`, filtered to `label` +fn shelf(tab: usize, label: &str) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1920.0, 1032.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.shelf_tab = tab; + harness.state_mut().ui.shelf_filter = label.to_lowercase(); + harness.run_steps(4); + harness +} + +fn stack_sizes(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.state().session.doc.project.texture_sets.iter().map(|set| set.stack.len()).collect() +} + +#[test] +fn a_click_on_a_simple_material_sets_the_brush_material_and_adds_no_layer() { + let label = find("gold_polished").unwrap().label; + let mut harness = shelf(MATERIALS_TYPE, label); + let (stacks, history, values) = (stack_sizes(&harness), harness.state().session.history_labels(), harness.state().session.tool.values.clone()); + assert_ne!(values[&texturecraft_engine::core::Channel::Metallic], [1.0; 3], "the brush starts non-metallic"); + + harness.get_all_by_label(label).next().unwrap().click(); + harness.run_steps(3); + + let app = harness.state(); + assert_eq!(stack_sizes(&harness), stacks, "no layer"); + assert_eq!(app.session.history_labels(), history, "no history entry"); + for (channel, value) in brush_values("gold_polished").unwrap() { + assert_eq!(app.session.tool.values[&channel], value, "{channel:?}"); + } +} + +#[test] +fn a_click_on_a_smart_material_adds_no_layer_and_leaves_the_brush() { + let label = find("iron_rusted").unwrap().label; + let mut harness = shelf(SMART_TYPE, label); + let (stacks, history, tool) = (stack_sizes(&harness), harness.state().session.history_labels(), harness.state().session.tool.clone()); + + harness.get_all_by_label(label).next().unwrap().click(); + harness.run_steps(3); + + let app = harness.state(); + assert_eq!(stack_sizes(&harness), stacks, "no layer"); + assert_eq!(app.session.history_labels(), history, "no history entry"); + assert_eq!(serde_json::to_value(&app.session.tool).unwrap(), serde_json::to_value(&tool).unwrap(), "the brush is untouched"); +} + +#[test] +fn clicking_a_saved_material_loads_it_above_the_selected_layer() { + let mut harness = shelf(SMART_TYPE, "SavedFixture"); + let layer = harness.state().session.selected_layer().unwrap(); + let bytes = harness.state().session.smart_material_bytes(layer, "Saved fixture").unwrap(); + let file = std::env::temp_dir().join(format!("SavedFixture-{}.tcmat", std::process::id())); + std::fs::write(&file, bytes).unwrap(); + harness.state_mut().library = Some(vec![file.clone()]); + harness.state_mut().ui.shelf_path = vec!["user".into()]; + harness.run_steps(3); + let before = stack_sizes(&harness); + + harness.get_by_label_contains("SavedFixture-").click(); + harness.run_steps(3); + std::fs::remove_file(file).unwrap(); + + let ts = harness.state().session.ts(); + assert_eq!(stack_sizes(&harness)[ts], before[ts] + 1); + assert_ne!(harness.state().session.selected_layer(), Some(layer)); +} diff --git a/crates/ui-egui/tests/it/shelf_drop.rs b/crates/ui-egui/tests/it/shelf_drop.rs index db784edf..56e57f62 100644 --- a/crates/ui-egui/tests/it/shelf_drop.rs +++ b/crates/ui-egui/tests/it/shelf_drop.rs @@ -310,3 +310,43 @@ fn image_drop_menu_snapshots() { assert!(matches!(harness.state().session.target, texturecraft_engine::StackTarget::Effect(_))); harness.render().unwrap().save(directory.join("image-drop-mask.png")).unwrap(); } + +/// The names of the Ball's top-level layers, bottom to top +fn ball_stack_names(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let project = &harness.state().session.doc.project; + project.texture_sets[0].stack.iter().map(|id| project.layer(*id).unwrap().name.clone()).collect() +} + +#[test] +fn a_material_dropped_on_the_view_becomes_a_fill_layer_at_the_top_whatever_is_selected() { + let mut harness = sample_app(); + let bottom = harness.state().session.doc.project.texture_sets[0].stack[0]; + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.select", &serde_json::json!({"layer": bottom.0})).unwrap(); + harness.run_steps(2); + let before = ball_stack_names(&harness); + + let ball = point_over(&harness, Some(0)); + drop_asset(&mut harness, Asset::Material("copper"), ball); + + let after = ball_stack_names(&harness); + assert_eq!(after.len(), before.len() + 1); + assert_eq!(after.last().map(String::as_str), Some("Copper"), "the new layer is on top: {after:?}"); + let app = harness.state(); + let layer = app.session.doc.project.layer(*app.session.doc.project.texture_sets[0].stack.last().unwrap()).unwrap(); + assert!(matches!(layer.kind, texturecraft_engine::core::LayerKind::Fill(_))); + assert!(layer.mask.is_none(), "no mask"); +} + +#[test] +fn a_material_dropped_on_a_layer_row_goes_directly_below_that_row() { + let mut harness = sample_app(); + let before = ball_stack_names(&harness); + let row_name = before.last().unwrap().clone(); + let row = harness.get_by_label(&row_name).rect().center(); + + drop_asset(&mut harness, Asset::Material("copper"), row); + + let mut expected = before.clone(); + expected.insert(before.len() - 1, "Copper".into()); + assert_eq!(ball_stack_names(&harness), expected, "below the dropped-on row, which stays on top"); +} diff --git a/crates/ui-egui/tests/it/shift_lines_3d.rs b/crates/ui-egui/tests/it/shift_lines_3d.rs new file mode 100644 index 00000000..2c009a9b --- /dev/null +++ b/crates/ui-egui/tests/it/shift_lines_3d.rs @@ -0,0 +1,139 @@ +//! Shift+click in the 3D view paints a straight line from the model point where the last stroke ended, also after the camera moved + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::Tool; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// How far the camera turns between the stroke and the Shift+click (radians) +const ORBIT: f32 = 0.5; + +/// Alpha a texel needs to count as painted +const PAINTED_ALPHA: f32 = 0.05; + +/// Search step and reach when looking for a pixel that shows the model (viewport pixels) +const SEARCH_STEP: f32 = 6.0; +const SEARCH_REACH: f32 = 300.0; + +/// The sample project with only the 3D view and the Paint tool +fn view_3d_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.state_mut().session.tool.tool = Tool::Paint; + harness.run_steps(4); + harness +} + +/// The screen position, in the window, of the model pixel nearest `near` (viewport pixels from the view's corner) +fn model_pixel_near(harness: &Harness<'_, TextureCraftApp>, near: Vec2) -> Pos2 { + let app = harness.state(); + let steps = (SEARCH_REACH / SEARCH_STEP) as i32; + let mut candidates: Vec = (-steps..=steps).flat_map(|x| (-steps..=steps).map(move |y| near + Vec2::new(x as f32, y as f32) * SEARCH_STEP)).collect(); + candidates.sort_by(|a, b| a.distance(near).total_cmp(&b.distance(near))); + let hit = candidates.into_iter().find(|point| app.session.pick(*point, app.session.viewport).is_some()).expect("the model is in view"); + pos2(app.viewport_rect.left() + hit.x, app.viewport_rect.top() + hit.y) +} + +/// A primary click at `pos`, with Shift held when `shift` is set +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, shift: bool) { + let modifiers = if shift { Modifiers::SHIFT } else { Modifiers::NONE }; + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// The selected layer's base color alpha, row by row, with the texture width +fn alpha(harness: &Harness<'_, TextureCraftApp>) -> (Vec, u32) { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return (vec![0.0; (width * height) as usize], width) }; + let texels = (0..height).flat_map(|y| (0..width).map(move |x| (x, y))); + (texels.map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).collect(), width) +} + +/// The alpha-weighted centre of `paint`, in texels +fn centre(paint: &[f32], width: u32) -> Vec2 { + let (sum, total) = paint.iter().enumerate().fold((Vec2::ZERO, 0.0), |(sum, total), (index, value)| { + let texel = Vec2::new((index as u32 % width) as f32, (index as u32 / width) as f32); + (sum + texel * *value, total + value) + }); + assert!(total > 0.0, "something was painted"); + sum / total +} + +/// The stored line anchor +fn anchor(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness.state().last_paint_point +} + +/// A fresh app and a click on the model; returns it with the click position and the dab's centre in texels +fn after_first_click() -> (Harness<'static, TextureCraftApp>, Pos2, Vec2) { + let mut harness = view_3d_app(); + let first = model_pixel_near(&harness, harness.state().session.viewport * 0.5); + let (blank, width) = alpha(&harness); + assert!(blank.iter().all(|alpha| *alpha == 0.0), "the layer starts empty"); + let app = harness.state(); + let local = Vec2::new(first.x - app.viewport_rect.left(), first.y - app.viewport_rect.top()); + assert_eq!(app.session.texture_set_at(local, app.session.viewport), Some(app.session.ts()), "the click lands on the active texture set"); + click(&mut harness, first, false); + let (dab, _) = alpha(&harness); + let dab_centre = centre(&dab, width); + (harness, first, dab_centre) +} + +#[test] +fn the_line_starts_at_the_old_model_point_after_orbiting() { + let (mut harness, _, dab_centre) = after_first_click(); + harness.state_mut().session.undo().unwrap(); + let (blank, width) = alpha(&harness); + assert!(blank.iter().all(|alpha| *alpha == 0.0), "undo removed the first dab"); + + harness.state_mut().session.camera.orbit(ORBIT, 0.0); + harness.run_steps(2); + let end = model_pixel_near(&harness, harness.state().session.viewport * 0.5 + Vec2::new(40.0, 20.0)); + click(&mut harness, end, true); + + let (line, _) = alpha(&harness); + let index = dab_centre.y.round() as usize * width as usize + dab_centre.x.round() as usize; + assert!(line[index] > PAINTED_ALPHA, "the line is painted at the old model point {dab_centre}"); +} + +#[test] +fn the_anchor_is_the_model_point_of_the_stroke_end() { + let (harness, first, _) = after_first_click(); + let app = harness.state(); + let local = Vec2::new(first.x - app.viewport_rect.left(), first.y - app.viewport_rect.top()); + let expected = app.session.pick(local, app.session.viewport).unwrap().pos; + let stored = anchor(&harness).and_then(|point| point.position_for(&app.session)).expect("an anchor after a stroke"); + assert!(stored.distance(expected) < 1e-4, "{stored} vs {expected}"); +} + +#[test] +fn switching_the_texture_set_drops_the_anchor() { + let (mut harness, _, _) = after_first_click(); + harness.state_mut().run("textureSet.select", json!({"ts": 1})); + harness.run_steps(2); + let session = &harness.state().session; + assert!(anchor(&harness).and_then(|point| point.position_for(session)).is_none()); +} + +#[test] +fn opening_another_project_drops_the_anchor() { + let (mut harness, _, _) = after_first_click(); + harness.state_mut().run("project.new", json!({"mesh": "sphere", "resolution": 256})).unwrap(); + harness.run_steps(2); + let session = &harness.state().session; + assert!(anchor(&harness).and_then(|point| point.position_for(session)).is_none()); +} diff --git a/crates/ui-egui/tests/it/shortcut_gestures.rs b/crates/ui-egui/tests/it/shortcut_gestures.rs new file mode 100644 index 00000000..4f900746 --- /dev/null +++ b/crates/ui-egui/tests/it/shortcut_gestures.rs @@ -0,0 +1,31 @@ +//! The shortcut window's fixed list names the mouse gestures and hold keys of the painting tools. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; + +#[test] +fn the_gesture_grid_of_the_shortcut_window_lists_the_stencil_clone_line_and_path_gestures() { + let mut h = Harness::builder() + .with_size(egui::vec2(700.0, 900.0)) + .with_context_setup(texturecraft_ui_egui::theme::install) + .build_ui(texturecraft_ui_egui::keymap::fixed_gestures_grid); + h.run_steps(3); + for text in [ + "Shift + LMB", + "Paint a straight line from where the last stroke ended", + "S + LMB drag", + "Projection: rotate the stencil", + "S + RMB drag", + "S + MMB drag", + "V + LMB", + "Clone: pick the point to copy from", + "Path: add a point; on the curve it inserts one", + "Path: close it (needs 3 points)", + "Path: apply it with the brush", + "Path: remove the selected or last point", + "Path: cancel it", + "Shift + RMB drag", + ] { + assert!(h.query_by_label(text).is_some(), "the overview lacks {text}"); + } +} diff --git a/crates/ui-egui/tests/it/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index bffac25b..e8a8f492 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -104,3 +104,26 @@ fn a_pasted_image_counts_as_the_paste_shortcut() { h.run_steps(3); assert!(h.state().session.doc.project.layers.len() > before, "the paste ran layer.paste"); } + +#[test] +fn a_command_without_a_default_key_runs_from_the_key_it_is_bound_to() { + let mut h = harness(); + let before = h.state().session.doc.project.layers.len(); + h.event(press(Key::F7, Modifiers::NONE, false)); + h.run_steps(2); + assert_eq!(h.state().session.doc.project.layers.len(), before, "F7 is free"); + h.state_mut().ui.keymap.insert("layer.add.fill".into(), "F7".into()); + h.run_steps(2); + h.event(press(Key::F7, Modifiers::NONE, false)); + h.run_steps(2); + assert_eq!(h.state().session.doc.project.layers.len(), before + 1, "F7 added a fill layer"); +} + +#[test] +fn the_shortcut_editor_lists_a_command_without_a_key_and_hides_one_that_needs_a_parameter() { + let mut h = harness(); + h.state_mut().ui.windows.shortcuts = true; + h.run_steps(4); + assert!(h.query_by_label("Toggle layer visibility").is_some(), "Toggle layer visibility is listed"); + assert!(h.query_by_label("Select texture set").is_none(), "Select texture set needs a texture set"); +} diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs new file mode 100644 index 00000000..63826cd1 --- /dev/null +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -0,0 +1,96 @@ +//! The Smudge panel shows which channels a smudge drags and shares their on/off flags with the Material tab + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, Tool, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::PropsTab; + +fn harness() -> Harness<'static, TextureCraftApp> { + let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + run(&mut harness, "tool.smudge", Value::Null); + harness +} + +fn run(harness: &mut Harness<'_, TextureCraftApp>, command: &str, params: Value) { + execute(&mut harness.state_mut().session, command, ¶ms).unwrap(); + harness.run_steps(4); +} + +/// The channel chips drawn in the open Properties panel +fn chip_is_on(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> bool { + let chips: Vec<_> = harness.get_all_by_role_and_label(Role::Button, channel.short()).collect(); + assert_eq!(chips.len(), 1, "one {} chip is drawn", channel.short()); + chips[0].accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +/// Channels whose chip is on, in the order of `Channel::ALL` +fn chips_on(harness: &Harness<'_, TextureCraftApp>) -> Vec { + Channel::ALL + .iter() + .copied() + .filter(|channel| harness.query_all_by_role_and_label(Role::Button, channel.short()).next().is_some() && chip_is_on(harness, *channel)) + .collect() +} + +fn enabled(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let tool = &harness.state().session.tool; + Channel::ALL.iter().copied().filter(|channel| tool.enabled.contains(channel)).collect() +} + +#[test] +fn smudge_panel_shows_the_channels_the_material_has_on() { + let mut harness = harness(); + assert_eq!(harness.state().session.tool.tool, Tool::Smudge); + assert!(harness.query_by_label("Channels dragged").is_some()); + assert_eq!(chips_on(&harness), enabled(&harness)); + for channel in [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Normal, Channel::Height] { + assert!(chip_is_on(&harness, channel), "{channel:?} is on by default"); + } + + run(&mut harness, "tool.material", json!({"channel": "roughness", "enabled": false})); + + assert_eq!(chips_on(&harness), enabled(&harness)); + assert!(!chip_is_on(&harness, Channel::Roughness)); +} + +#[test] +fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() { + let mut harness = harness(); + + harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + harness.run_steps(4); + assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic)); + assert!(!chip_is_on(&harness, Channel::Metallic)); + + harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + harness.run_steps(4); + assert!(harness.state().session.tool.enabled.contains(&Channel::Metallic)); + assert!(chip_is_on(&harness, Channel::Metallic)); +} + +#[test] +fn material_tab_and_smudge_panel_stay_in_sync() { + let mut harness = harness(); + harness.state_mut().ui.props_tab = PropsTab::Material; + harness.run_steps(4); + + // Both the Smudge panel and the Material tab draw a chip per channel + let chips = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).count(); + assert_eq!(chips, 2, "Smudge panel and Material tab"); + + let first = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).next().unwrap(); + first.click(); + harness.run_steps(4); + + assert!(!harness.state().session.tool.enabled.contains(&Channel::Height)); + for chip in harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()) { + assert_ne!(chip.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "both chips show height off"); + } +} diff --git a/crates/ui-egui/tests/it/snapped_lines.rs b/crates/ui-egui/tests/it/snapped_lines.rs new file mode 100644 index 00000000..44a37b86 --- /dev/null +++ b/crates/ui-egui/tests/it/snapped_lines.rs @@ -0,0 +1,180 @@ +//! Ctrl+Shift+click paints a straight line from the last stroke with its angle snapped to 15 degree steps + +use egui::{Event, Modifiers, PointerButton, Pos2, Vec2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// Where the first, plain click lands in the 2D view +const FIRST_2D: Pos2 = pos2(700.0, 420.0); + +/// Length of the test lines in points +const LINE_LENGTH: f32 = 160.0; + +/// An angle 7 degrees past a step: it snaps back to 15 degrees, not on to 30 +const CLICK_DEGREES: f32 = 22.0; + +/// The step it snaps to +const SNAPPED_DEGREES: f32 = 15.0; + +/// A line must differ at least this much from the unsnapped one (share of the snapped line's alpha) +const MIN_DIFFERENCE: f32 = 0.05; + +/// The snapped line may differ at most this much from the reference (share of its alpha) +const MAX_DIFFERENCE: f32 = 0.01; + +fn app(layout: ViewLayout) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = layout; + harness.run_steps(4); + harness +} + +fn ctrl_shift() -> Modifiers { + Modifiers::COMMAND.plus(Modifiers::SHIFT) +} + +/// A primary click at `pos` with `modifiers` held +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2, modifiers: Modifiers) { + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(1); +} + +/// The point `length` away from `from` at `degrees` on screen +fn away(from: Pos2, degrees: f32, length: f32) -> Pos2 { + from + Vec2::angled(degrees.to_radians()) * length +} + +/// The selected layer's base color alpha in every texture set, set after set +fn alpha(harness: &mut Harness<'_, TextureCraftApp>) -> Vec { + let sets = harness.state().session.doc.project.texture_sets.len(); + let mut all = Vec::new(); + for set in 0..sets { + harness.state_mut().run("textureSet.select", json!({"ts": set})); + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[set].size(); + let layer = session.selected_layer().expect("a selected layer"); + let image = session.doc.pixels.layer(layer, Channel::BaseColor); + all.extend( + (0..height) + .flat_map(|y| (0..width).map(move |x| (x, y))) + .map(|(x, y)| image.and_then(|image| image.get(x, y).get(3).copied()).unwrap_or(0) as f32 / 65535.0), + ); + } + harness.state_mut().run("textureSet.select", json!({"ts": 0})); + all +} + +/// Total alpha painted between two snapshots +fn painted(before: &[f32], after: &[f32]) -> Vec { + after.iter().zip(before).map(|(after, before)| (after - before).max(0.0)).collect() +} + +/// Sum of the absolute differences of two paints +fn difference(first: &[f32], second: &[f32]) -> f32 { + first.iter().zip(second).map(|(first, second)| (first - second).abs()).sum() +} + +/// A plain click at `first`, then a click at `second` with `modifiers`; the paint the second click added +fn line_paint(layout: ViewLayout, first: Pos2, second: Pos2, modifiers: Modifiers) -> Vec { + let mut harness = app(layout); + click(&mut harness, first, Modifiers::NONE); + let before = alpha(&mut harness); + click(&mut harness, second, modifiers); + painted(&before, &alpha(&mut harness)) +} + +/// Ctrl+Shift+click paints the line Shift+click paints to the end snapped to 15 degrees, and not the straight one to the click +fn assert_snaps(layout: ViewLayout, first: Pos2) { + let clicked = away(first, CLICK_DEGREES, LINE_LENGTH); + let snapped_end = away(first, SNAPPED_DEGREES, LINE_LENGTH); + + let snapped = line_paint(layout, first, clicked, ctrl_shift()); + let reference = line_paint(layout, first, snapped_end, Modifiers::SHIFT); + let unsnapped = line_paint(layout, first, clicked, Modifiers::SHIFT); + + let total: f32 = reference.iter().sum(); + assert!(total > 1.0, "the reference line painted: {total}"); + assert!(difference(&snapped, &reference) < total * MAX_DIFFERENCE, "Ctrl+Shift+click ends on the 15 degree line: {}", difference(&snapped, &reference)); + assert!( + difference(&unsnapped, &reference) > total * MIN_DIFFERENCE, + "Shift+click without Ctrl keeps the clicked angle: {}", + difference(&unsnapped, &reference) + ); +} + +#[test] +fn ctrl_shift_click_snaps_the_line_to_15_degrees_in_the_2d_view() { + assert_snaps(ViewLayout::Only2D, FIRST_2D); +} + +#[test] +fn ctrl_shift_click_snaps_the_line_to_15_degrees_in_the_3d_view() { + let center = app(ViewLayout::Only3D).state().viewport_rect.center() - Vec2::new(80.0, 40.0); + assert_snaps(ViewLayout::Only3D, center); +} + +#[test] +fn ctrl_shift_click_snaps_to_negative_angles_in_the_2d_view() { + let first = pos2(700.0, 560.0); + let clicked = away(first, -CLICK_DEGREES, LINE_LENGTH); + let snapped = line_paint(ViewLayout::Only2D, first, clicked, ctrl_shift()); + let reference = line_paint(ViewLayout::Only2D, first, away(first, -SNAPPED_DEGREES, LINE_LENGTH), Modifiers::SHIFT); + let total: f32 = reference.iter().sum(); + assert!(total > 1.0, "the reference line painted: {total}"); + assert!(difference(&snapped, &reference) < total * MAX_DIFFERENCE); +} + +#[test] +fn ctrl_shift_click_without_a_previous_stroke_paints_a_dot_like_a_click() { + let mut harness = app(ViewLayout::Only2D); + let blank = alpha(&mut harness); + click(&mut harness, FIRST_2D, ctrl_shift()); + let dot = painted(&blank, &alpha(&mut harness)); + + let mut reference = app(ViewLayout::Only2D); + click(&mut reference, FIRST_2D, Modifiers::NONE); + let plain = painted(&blank, &alpha(&mut reference)); + assert!(plain.iter().sum::() > 1.0); + assert!(difference(&dot, &plain) < plain.iter().sum::() * MAX_DIFFERENCE); +} + +#[test] +fn ctrl_shift_click_paints_instead_of_changing_the_brush() { + let mut harness = app(ViewLayout::Only2D); + let (brush, steps) = (harness.state().session.tool.brush.clone(), harness.state().session.history_labels().len()); + click(&mut harness, FIRST_2D, ctrl_shift()); + assert_eq!(harness.state().session.history_labels().len(), steps + 1, "the click painted"); + assert_eq!(harness.state().session.tool.brush.size, brush.size); + assert_eq!(harness.state().session.tool.brush.flow, brush.flow); +} + +#[test] +fn ctrl_shift_right_drag_still_changes_the_brush() { + let mut harness = app(ViewLayout::Only3D); + let size = harness.state().session.tool.brush.size; + let from = harness.state().viewport_rect.center(); + let modifiers = ctrl_shift(); + harness.event(Event::ModifiersChanged(modifiers)); + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Secondary, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + Vec2::new(20.0 * step as f32, 0.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + Vec2::new(80.0, 0.0), button: PointerButton::Secondary, pressed: false, modifiers }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(3); + assert!(harness.state().session.tool.brush.size > size, "a Ctrl+Shift right drag to the right enlarges the brush"); +} diff --git a/crates/ui-egui/tests/it/start_window.rs b/crates/ui-egui/tests/it/start_window.rs deleted file mode 100644 index 9c5415b4..00000000 --- a/crates/ui-egui/tests/it/start_window.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! The start window: New project opens its dialog, Continue keeps the open project, and the -//! startup choice is a setting. - -use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; -use texturecraft_ui_egui::TextureCraftApp; - -fn harness() -> Harness<'static, TextureCraftApp> { - let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); - h.state_mut().ui.windows.start = true; - h.run_steps(3); - h -} - -#[test] -fn start_window_choices() { - let mut h = harness(); - h.get_by_label("New project...").click(); - h.run_steps(3); - assert!(!h.state().ui.windows.start && h.state().ui.windows.new_project, "New project opens its dialog"); - - let mut h = harness(); - h.get_by_label("Show at startup").click(); - h.get_by_label("Continue with the sample project").click(); - h.run_steps(3); - assert!(!h.state().ui.windows.start && !h.state().ui.windows.new_project); - assert!(!h.state().ui.prefs.start_window, "unticked: not shown next time"); - assert_eq!(h.state().session.doc.project.texture_sets.len(), 2, "the sample stays open"); -} diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs new file mode 100644 index 00000000..c746d213 --- /dev/null +++ b/crates/ui-egui/tests/it/stencil.rs @@ -0,0 +1,174 @@ +//! The Projection tool's stencil: an Assets image dropped on its slot, position fields and a reset in the tool panel, +//! S + Shift + left-drag to turn it in snapped steps, and the 2D view saying that projection paints in the 3D view + +use egui::accesskit::Role; +use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::json; +use texturecraft_engine::Tool; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; +use texturecraft_ui_egui::state::ViewLayout; + +/// The sample project with the Projection tool equipped, and an imported image's resource name +fn projection_app() -> (Harness<'static, TextureCraftApp>, String) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("logo.png", png).unwrap(); + session.tool.tool = Tool::Projection; + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(4); + (harness, name) +} + +/// The number field beside a uniquely labelled slider +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +} + +/// Type a complete value in the number field beside a uniquely labelled slider +fn set_number(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + let length = number_field(harness, label).value().unwrap().len(); + number_field(harness, label).focus(); + harness.run_steps(2); + harness.key_press(Key::End); + harness.run_steps(1); + for _ in 0..length { + harness.key_press(Key::Backspace); + harness.run_steps(1); + } + number_field(harness, label).type_text(value); + harness.run_steps(1); + harness.key_press(Key::Enter); + harness.run_steps(2); +} + +/// A point on the UV square in the 2D-only layout +const FIRST_DRAG: Pos2 = egui::pos2(700.0, 420.0); + +fn history(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} + +fn shows_text(harness: &Harness<'_, TextureCraftApp>, text: &str) -> bool { + harness.output().shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(found) if found.galley.text() == text)) +} + +/// Drag with the left button from `from` by `by` in a few moves, holding `keys` and `modifiers` +fn drag_holding(harness: &mut Harness<'_, TextureCraftApp>, keys: &[Key], modifiers: Modifiers, from: Pos2, by: egui::Vec2) { + harness.event(Event::ModifiersChanged(modifiers)); + for key in keys { + harness.event(Event::Key { key: *key, physical_key: Some(*key), pressed: true, repeat: false, modifiers }); + } + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + by * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(Event::PointerButton { pos: from + by, button: PointerButton::Primary, pressed: false, modifiers }); + for key in keys { + harness.event(Event::Key { key: *key, physical_key: Some(*key), pressed: false, repeat: false, modifiers }); + } + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(3); +} + +#[test] +fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { + let (mut harness, name) = projection_app(); + assert!(harness.state().session.tool.stencil.is_none()); + + let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into() }); + harness.hover_at(slot); + harness.run_steps(2); + harness.event(Event::PointerButton { pos: slot, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.stencil.as_ref().map(|stencil| stencil.image.as_str()), Some(name.as_str())); +} + +#[test] +fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { + let (mut harness, name) = projection_app(); + texturecraft_engine::execute( + &mut harness.state_mut().session, + "tool.stencil", + &json!({"image": name, "center": [0.5, -0.25], "scale": 2.0, "rotation": 90.0, "opacity": 0.3, "tile": true}), + ) + .unwrap(); + harness.run_steps(3); + + // Typing in a position field moves the stencil + set_number(&mut harness, "Position X", "-0.75"); + let moved = harness.state().session.tool.stencil.clone().unwrap(); + assert_eq!(moved.center, [-0.75, -0.25], "only X changed"); + harness.get_by_label("Position Y"); + + harness.get_by_label("Reset stencil").scroll_to_me(); + harness.run_steps(3); + harness.get_by_label("Reset stencil").click(); + harness.run_steps(3); + let reset = harness.state().session.tool.stencil.clone().unwrap(); + assert_eq!((reset.center, reset.scale, reset.rotation), ([0.0, 0.0], 0.8, 0.0)); + assert_eq!((reset.image.as_str(), reset.opacity, reset.tile), (name.as_str(), 0.3, true), "image, opacity and tiling stay"); +} + +#[test] +fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { + let (mut harness, name) = projection_app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + harness.run_steps(2); + let from = harness.state().viewport_rect.center(); + let before = harness.state().session.tool.stencil.clone().unwrap(); + let steps = history(&harness); + + drag_holding(&mut harness, &[Key::S], Modifiers::SHIFT, from, vec2(100.0, -40.0)); + + let turned = harness.state().session.tool.stencil.clone().unwrap(); + assert_ne!(turned.rotation, before.rotation, "it turned"); + assert_eq!(turned.rotation % 15.0, 0.0, "a snapped turn lands on a multiple of 15 degrees: {}", turned.rotation); + assert_eq!(turned.center, before.center, "a turn does not move it"); + assert_eq!(history(&harness), steps, "nothing painted"); + + // Without Shift the left-drag turns it freely, and still does not paint + drag_holding(&mut harness, &[Key::S], Modifiers::NONE, from, vec2(30.0, 0.0)); + let free = harness.state().session.tool.stencil.clone().unwrap(); + assert_ne!(free.rotation % 15.0, 0.0, "a free turn is not snapped: {}", free.rotation); + assert_eq!(free.center, turned.center); + assert_eq!(history(&harness), steps); +} + +#[test] +fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { + let (mut harness, name) = projection_app(); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + let from = FIRST_DRAG; + let steps = history(&harness); + + // Without a stencil + assert!(shows_text(&harness, "Projection paints in the 3D view")); + drag_holding(&mut harness, &[], Modifiers::NONE, from, vec2(60.0, 0.0)); + assert_eq!(history(&harness), steps, "no stencil: nothing painted"); + + // With a stencil + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + harness.run_steps(2); + assert!(shows_text(&harness, "Projection paints in the 3D view")); + drag_holding(&mut harness, &[], Modifiers::NONE, from, vec2(60.0, 0.0)); + assert_eq!(history(&harness), steps, "with a stencil: nothing painted"); + + // Other tools paint in the 2D view and show no hint + harness.state_mut().session.tool.tool = Tool::Paint; + harness.run_steps(2); + assert!(!shows_text(&harness, "Projection paints in the 3D view")); + drag_holding(&mut harness, &[], Modifiers::NONE, from, vec2(60.0, 0.0)); + assert!(history(&harness) > steps, "the paint tool paints there"); +} diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 2d6181be..620300a1 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -317,3 +317,93 @@ fn ctrl_drag_on_a_symmetry_handle_only_adjusts_the_brush() { assert_eq!(after.symmetry, before.symmetry, "adjusting the brush must not also move symmetry"); assert_eq!(harness.state().session.history_labels(), history); } + +/// A point in the 3D view that lies on the model, with the surface point there (the pointer is not at the mesh's center so the picked offset is non-trivial) +fn point_on_model(harness: &Harness<'_, TextureCraftApp>) -> (Pos2, Vec3) { + let rect = harness.state().viewport_rect; + let viewport = harness.state().session.viewport; + let center = rect.center(); + for step in 0..40 { + let at = center + egui::vec2(step as f32 * 7.0 - 100.0, step as f32 * 3.0 - 40.0); + let local = texturecraft_engine::geom::glam::Vec2::new(at.x - rect.left(), at.y - rect.top()); + if let Some(hit) = harness.state().session.pick(local, viewport) { + return (at, hit.pos); + } + } + panic!("no model under the view"); +} + +fn model_center(harness: &Harness<'_, TextureCraftApp>) -> Vec3 { + let (lo, hi) = harness.state().session.mesh.bounds(); + (lo + hi) * 0.5 +} + +#[test] +fn the_center_button_puts_one_plane_back_in_the_middle_of_the_model() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryX": true, "symmetryY": true, "symmetryOffset": [0.1, 0.2, 0.0]})).unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let history = harness.state().session.history_labels(); + + harness.get_by_label("Center Y").click(); + harness.run_steps(2); + + assert_eq!(harness.state().session.tool.brush.symmetry.offset, [0.1, 0.0, 0.0], "only the Y plane moved to the middle"); + harness.get_by_label("Center X").click(); + harness.run_steps(2); + assert_eq!(harness.state().session.tool.brush.symmetry.offset, [0.0; 3]); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn pick_point_puts_the_planes_through_the_clicked_point_without_painting() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryX": true, "symmetryY": true})).unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let history = harness.state().session.history_labels(); + harness.get_by_label("Pick point").click(); + harness.run_steps(2); + assert!(harness.state().picking_symmetry_plane); + + let (at, hit) = point_on_model(&harness); + click_at(&mut harness, at); + + let center = model_center(&harness); + let offset = harness.state().session.tool.brush.symmetry.offset; + assert_eq!(offset[0], hit.x - center.x, "the X plane passes through the clicked point"); + assert_eq!(offset[1], hit.y - center.y, "the Y plane passes through the clicked point"); + assert_eq!(offset[2], 0.0, "Z has no plane, so it stays"); + assert!(!harness.state().picking_symmetry_plane, "one click ends picking"); + assert_eq!(harness.state().session.history_labels(), history, "the click paints nothing"); + assert!(!harness.state().session.stroke_active()); +} + +#[test] +fn escape_cancels_picking_the_symmetry_point() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryX": true})).unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_label("Pick point").click(); + harness.run_steps(2); + assert!(harness.state().picking_symmetry_plane); + + harness.key_press(egui::Key::Escape); + harness.run_steps(2); + + assert!(!harness.state().picking_symmetry_plane); + assert_eq!(harness.state().session.tool.brush.symmetry.offset, [0.0; 3]); +} + +#[test] +fn the_smudge_tool_offers_the_symmetry_toggle() { + let mut harness = app_harness(); + harness.state_mut().session.tool.tool = Tool::Smudge; + harness.run_steps(2); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false]), "the toggle mirrors the smudge on X"); +} diff --git a/crates/ui-egui/tests/it/symmetry_2d.rs b/crates/ui-egui/tests/it/symmetry_2d.rs new file mode 100644 index 00000000..29025dcd --- /dev/null +++ b/crates/ui-egui/tests/it/symmetry_2d.rs @@ -0,0 +1,66 @@ +//! A click in the 2D view paints the symmetry copies too + +use egui::{Event, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +/// A click on the sample's texture in the 2D view +const CLICK: Pos2 = pos2(700.0, 420.0); + +/// The sample project with only the 2D view, at 1600 x 960 +fn uv_view_app() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(4); + harness +} + +/// A primary click at `pos` +fn click(harness: &mut Harness<'_, TextureCraftApp>, pos: Pos2) { + harness.hover_at(pos); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// The base color alpha the selected layer holds, summed over the texture +fn painted(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let session = &harness.state().session; + let (width, height) = session.doc.project.texture_sets[session.ts()].size(); + let layer = session.selected_layer().expect("a selected layer"); + let Some(image) = session.doc.pixels.layer(layer, Channel::BaseColor) else { return 0.0 }; + (0..height).flat_map(|y| (0..width).map(move |x| (x, y))).map(|(x, y)| image.get(x, y)[3] as f32 / 65535.0).sum() +} + +/// What one click paints with the symmetry settings `brush` +fn click_paints(brush: serde_json::Value) -> f32 { + let mut harness = uv_view_app(); + harness.state_mut().run("tool.brush", brush); + harness.run_steps(2); + let before = painted(&harness); + click(&mut harness, CLICK); + painted(&harness) - before +} + +#[test] +fn a_click_in_the_2d_view_paints_the_mirrored_dab_too() { + let single = click_paints(json!({"symmetryOn": false})); + let mirrored = click_paints(json!({"symmetryOn": true, "symmetryX": true})); + + assert!(single > 1.0, "the dab itself paints: {single}"); + assert!(mirrored > single * 1.5, "the mirrored copy adds a second dab: {mirrored} against {single}"); +} + +#[test] +fn radial_copies_add_dabs_in_the_2d_view() { + let single = click_paints(json!({"symmetryOn": false})); + let radial = click_paints(json!({"symmetryOn": true, "symmetryRadial": 4, "symmetryAxis": "y"})); + + assert!(radial > single * 2.0, "three more dabs: {radial} against {single}"); +} diff --git a/crates/ui-egui/tests/it/project_config/temp_dir.rs b/crates/ui-egui/tests/it/temp_dir.rs similarity index 66% rename from crates/ui-egui/tests/it/project_config/temp_dir.rs rename to crates/ui-egui/tests/it/temp_dir.rs index 1c3ab71d..1f112493 100644 --- a/crates/ui-egui/tests/it/project_config/temp_dir.rs +++ b/crates/ui-egui/tests/it/temp_dir.rs @@ -1,12 +1,16 @@ use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; /// A test folder removed when its owner drops pub(super) struct TempDir(PathBuf); impl TempDir { pub(super) fn new(test: &str) -> Self { - let path = std::env::temp_dir().join(format!("texturecraft-project-config-{test}-{}", std::process::id())); - std::fs::create_dir_all(&path).unwrap(); + static NEXT_ID: AtomicU64 = AtomicU64::new(0); + + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!("texturecraft-{test}-{}-{id}", std::process::id())); + std::fs::create_dir(&path).unwrap(); Self(path) } diff --git a/crates/ui-egui/tests/it/template_invert.rs b/crates/ui-egui/tests/it/template_invert.rs new file mode 100644 index 00000000..748d5035 --- /dev/null +++ b/crates/ui-egui/tests/it/template_invert.rs @@ -0,0 +1,71 @@ +//! Export dialog › Output templates: each output channel has an Invert toggle that is saved in the template. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef}; +use texturecraft_ui_egui::TextureCraftApp; + +const TEMPLATE: &str = "Packed test"; + +mod library; + +use library::Library; + +fn harness() -> (Harness<'static, TextureCraftApp>, Library) { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + + // The user's template library is a folder; use a temporary one, not the real one + let dir = std::env::temp_dir().join(format!("texturecraft-template-invert-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + h.state_mut().session.load_export_presets(dir.clone()); + h.run_steps(4); + (h, Library(dir)) +} + +/// The channel toggles of the open dialog (the dialog sits left of the properties panel, which has its own Invert controls) +fn toggles<'h>(h: &'h Harness<'_, TextureCraftApp>) -> Vec> { + h.get_all_by_label("Invert").filter(|n| n.rect().max.x < DIALOG_RIGHT_EDGE).collect() +} + +const DIALOG_RIGHT_EDGE: f32 = 1200.0; + +fn template() -> ExportPreset { + let ch = |channel| SourceRef::Channel { channel, component: 0 }; + ExportPreset { + name: TEMPLATE.into(), + maps: vec![MapSpec { + file: "$mesh_$textureSet_Packed".into(), + format: FileFormat::Png, + bit_depth: 8, + channels: vec![(Dest::R, ch(Channel::Roughness)), (Dest::G, ch(Channel::Metallic)), (Dest::B, SourceRef::Constant(0.5))], + inverted: Vec::new(), + }], + } +} + +#[test] +fn invert_toggle_changes_the_saved_template() { + let (mut h, _library) = harness(); + let app = h.state_mut(); + app.run("export.preset.save", json!({ "preset": serde_json::to_value(template()).unwrap() })).expect("save template"); + app.ui.export.preset = TEMPLATE.into(); + app.ui.export.tab = 1; + app.ui.windows.export = true; + h.run_steps(4); + + let saved = |h: &Harness<'_, TextureCraftApp>| h.state().session.export_preset(TEMPLATE).unwrap().maps[0].inverted.clone(); + assert!(saved(&h).is_empty()); + + // One Invert toggle per channel: R, G, B + assert_eq!(toggles(&h).len(), 3); + toggles(&h)[1].click(); + h.run_steps(4); + assert_eq!(saved(&h), vec![Dest::G], "the second channel (G) is inverted"); + toggles(&h)[1].click(); + h.run_steps(4); + assert!(saved(&h).is_empty(), "a second click turns it off"); +} diff --git a/crates/ui-egui/tests/it/template_invert/library.rs b/crates/ui-egui/tests/it/template_invert/library.rs new file mode 100644 index 00000000..e8f4b9cc --- /dev/null +++ b/crates/ui-egui/tests/it/template_invert/library.rs @@ -0,0 +1,8 @@ +/// A temporary library folder removed when the test ends, including failures +pub(super) struct Library(pub(super) std::path::PathBuf); + +impl Drop for Library { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} diff --git a/crates/ui-egui/tests/it/tile_generator_panel.rs b/crates/ui-egui/tests/it/tile_generator_panel.rs new file mode 100644 index 00000000..40bfaa04 --- /dev/null +++ b/crates/ui-egui/tests/it/tile_generator_panel.rs @@ -0,0 +1,298 @@ +//! The pattern panel and the fill source picker: a mask fill picks the Tile Generator and its settings edit it + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::json; +use texturecraft_engine::core::{EffectKind, LayerId, Procedural, ProceduralKind, Source, TileGenerator}; +use texturecraft_engine::{ViewMode, execute}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::theme::Brightness; + +/// The sample session with an anchor point on a fill layer, and above it a fill layer whose black mask holds a uniform mask fill, selected +fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + session.camera.pitch = 0.5; + execute(&mut session, "layer.add.fill", &json!({"height": 0.6})).unwrap(); + execute(&mut session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(); + let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + let effect = execute(&mut session, "effect.add.fill", &json!({"value": 1.0})).unwrap()["effect"].as_u64().unwrap(); + session.view = ViewMode::Mask(LayerId(layer)); + session.update(); + let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.close(Panel::Layers); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + (harness, LayerId(effect)) +} + +fn source(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Source { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Fill { source, .. } => source.clone(), + _ => panic!("expected a mask fill"), + } +} + +fn pattern(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Procedural { + match source(harness, effect) { + Source::Procedural { pattern, .. } => pattern, + other => panic!("expected a pattern, the fill reads {other:?}"), + } +} + +/// Opens the mask fill's source picker from its Grayscale slot and clicks the tile labelled `tile` +fn pick(harness: &mut Harness<'_, TextureCraftApp>, tile: &str) { + harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_label(tile).click(); + harness.run_steps(3); +} + +/// Where a slider's track is grabbed, from its label's left end and bottom, and how far it is dragged (points) +const TRACK_GRAB_INSET: f32 = 20.0; +const TRACK_BELOW_LABEL: f32 = 10.0; +const DRAG_DISTANCE: f32 = 120.0; + +/// How long `settle` gives the render worker: 40 rounds of 50 ms, two seconds +const SETTLE_ROUNDS: usize = 40; +const SETTLE_WAIT: std::time::Duration = std::time::Duration::from_millis(50); +const FRAMES_PER_ROUND: usize = 3; + +/// Runs frames until the thumbnails rendered off the UI thread arrive +fn settle(harness: &mut Harness<'_, TextureCraftApp>) { + for _ in 0..SETTLE_ROUNDS { + harness.run_steps(FRAMES_PER_ROUND); + std::thread::sleep(SETTLE_WAIT); + } +} + +/// Drags the track under slider `label` to the right +fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + harness.get_by_label(label).scroll_to_me(); + harness.run_steps(3); + + // The track runs under the label: grab it near its left end and drag well to the right + let rect = harness.get_by_label(label).rect(); + let start = egui::pos2(rect.left() + TRACK_GRAB_INSET, rect.bottom() + TRACK_BELOW_LABEL); + let end = start + egui::vec2(DRAG_DISTANCE, 0.0); + harness.drag_at(start); + harness.run_steps(2); + harness.hover_at(end); + harness.run_steps(2); + harness.drop_at(end); + harness.run_steps(3); +} + +#[test] +fn the_picker_sets_a_mask_fill_to_the_tile_generator_and_back_to_a_value() { + let (mut harness, effect) = harness(false); + pick(&mut harness, "Tile Generator"); + assert_eq!(pattern(&harness, effect).kind, ProceduralKind::TileGenerator); + + pick(&mut harness, "Uniform value"); + assert!(matches!(source(&harness, effect), Source::Uniform(_))); +} + +#[test] +fn the_anchor_points_tab_picks_an_anchor() { + let (mut harness, effect) = harness(false); + harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + harness.run_steps(3); + harness.get_by_label("Anchor points").click(); + harness.run_steps(3); + + // An anchor tile is labelled " / ", as the anchors below a layer are listed + let project = &harness.state().session.doc.project; + let owner = project.layers.values().find(|layer| layer.content_effects.iter().any(|effect| effect.name == "Height")).unwrap(); + let label = format!("{} / Height", owner.name); + harness.get_by_role_and_label(Role::Button, &label).click(); + harness.run_steps(3); + assert!(source(&harness, effect).anchor().is_some()); +} + +/// An anchor in a mask records the mask's gray whatever the channel, so the slot names the mask +#[test] +fn the_slot_names_the_mask_for_an_anchor_in_a_mask() { + let mut session = texturecraft_engine::sample_session(512, 256).unwrap(); + session.active_set = 1; + let lower = execute(&mut session, "layer.add.fill", &json!({"name": "Lower"})).unwrap()["layer"].as_u64().unwrap(); + execute(&mut session, "mask.add.white", &json!({})).unwrap(); + let anchor = execute(&mut session, "effect.add.anchor", &json!({"layer": lower, "target": "mask", "name": "Wear"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + execute(&mut session, "effect.add.fill", &json!({"anchor": anchor})).unwrap(); + session.update(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 2400.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + + let slot = harness.get_by_role_and_label(Role::ComboBox, "Grayscale"); + + assert_eq!(slot.value().as_deref(), Some("Lower · Mask")); +} + +#[test] +fn an_amount_drag_is_one_undo_step_and_restore_defaults_puts_the_tiles_back() { + let (mut harness, effect) = harness(false); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.run_steps(3); + let history = harness.state().session.history_labels().len(); + + drag_slider(&mut harness, "X amount"); + let tile = pattern(&harness, effect).tile.unwrap(); + assert!(tile.amount[0] > TileGenerator::default().amount[0], "the drag adds columns: {:?}", tile.amount); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "one drag is one undo step"); + + harness.get_by_label("Restore defaults").scroll_to_me(); + harness.run_steps(2); + harness.get_by_label("Restore defaults").click(); + harness.run_steps(3); + assert_eq!(*pattern(&harness, effect).tile.unwrap(), TileGenerator::default()); +} + +/// The gray rows take a typed value, so they can be set without a pointer +#[test] +fn a_gray_value_typed_in_its_field_applies() { + let (mut harness, effect) = harness(false); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.run_steps(3); + + // A section's title can also be a control's label above it: the title is the last one + harness.get_all_by_label("Color").last().unwrap().scroll_to_me(); + harness.run_steps(12); + harness.get_all_by_label("Color").last().unwrap().click(); + harness.run_steps(6); + harness.get_by_label("Background").scroll_to_me(); + harness.run_steps(12); + let field = |harness: &Harness<'_, TextureCraftApp>| { + let row = harness.get_by_label("Background").rect().center().y; + harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap().rect().center() + }; + + let at = field(&harness); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + for key in [egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace] { + harness.key_press(key); + harness.run_steps(1); + } + for character in "0.5".chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(pattern(&harness, effect).tile.unwrap().background, 0.5); +} + +#[test] +fn typing_tile_contrast_then_clicking_invert_preserves_both_edits() { + let (mut harness, effect) = harness(false); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.run_steps(3); + let contrast = harness.get_by_label("Contrast"); + contrast.scroll_to_me(); + harness.run_steps(12); + let row = harness.get_by_label("Contrast").rect().center().y; + let at = harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap().rect().center(); + + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(2); + for key in [egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace] { + harness.key_press(key); + harness.run_steps(1); + } + for character in "0.5".chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } + harness.get_by_label("Invert").click(); + harness.run_steps(3); + + let edited = pattern(&harness, effect); + assert_eq!(edited.tile.unwrap().contrast, 0.5); + assert!(edited.invert); +} + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn tile_generator_snapshots() { + let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS")); + std::fs::create_dir_all(&directory).unwrap(); + let (mut harness, effect) = harness(true); + + // The picker over the slot, both tabs + harness.get_by_role_and_label(Role::ComboBox, "Grayscale").click(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("picker-resources.png")).unwrap(); + harness.get_by_label("Anchor points").click(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("picker-anchors.png")).unwrap(); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "procedural": "Tile Generator"})).unwrap(); + harness.state_mut().session.update(); + harness.run_steps(12); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("tile-panel-{name}.png"))).unwrap(); + } + harness.state_mut().ui.prefs.brightness = Brightness::Dark; + + // Open, the section also holds a menu labelled "Resolution": its title is the first one + harness.get_by_label("Resolution").click(); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("tile-resolution.png")).unwrap(); + harness.get_all_by_label("Resolution").next().unwrap().click(); + harness.run_steps(6); + + for (sections, name) in [(["Pattern", "Size"], "pattern-size"), (["Position", "Rotation"], "position-rotation")] { + for section in sections { + // A section's title can also be a control's label above it ("Position"): the title is the last one + harness.get_all_by_label(section).last().unwrap().scroll_to_me(); + + // The scroll animates: the title must be on screen before the click + harness.run_steps(12); + harness.get_all_by_label(section).last().unwrap().click(); + harness.run_steps(3); + } + harness.run_steps(6); + harness.render().unwrap().save(directory.join(format!("tile-sections-{name}.png"))).unwrap(); + } + harness.get_all_by_label("Color").last().unwrap().scroll_to_me(); + harness.run_steps(12); + harness.get_all_by_label("Color").last().unwrap().click(); + harness.run_steps(6); + harness.render().unwrap().save(directory.join("tile-sections-color.png")).unwrap(); + + // A changed pattern, in the 2D view + let edits = json!({"effect": effect.0, "tile": {"shape": "Disc", "amount": [8, 4], "offset": 0.5, "scaleRandom": 0.6, "luminanceRandom": 0.5}}); + execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap(); + harness.state_mut().session.update(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("tile-adjusted.png")).unwrap(); + + // An image as the mask fill's source: the slot names it over its projection + let mut png_bytes = Vec::new(); + image::RgbaImage::from_fn(8, 8, |x, y| image::Rgba([if (x + y) % 2 == 0 { 230 } else { 40 }; 4])) + .write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png) + .unwrap(); + let name = harness.state_mut().session.import_resource_bytes("checks.png", png_bytes).unwrap(); + execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "image": name})).unwrap(); + harness.state_mut().session.update(); + settle(&mut harness); + harness.render().unwrap().save(directory.join("mask-fill-image.png")).unwrap(); +} diff --git a/crates/ui-egui/tests/it/tool_availability.rs b/crates/ui-egui/tests/it/tool_availability.rs index 77fd888f..cc6d97ff 100644 --- a/crates/ui-egui/tests/it/tool_availability.rs +++ b/crates/ui-egui/tests/it/tool_availability.rs @@ -243,15 +243,17 @@ fn unavailable_effect_tools_hide_their_properties() { for path in [false, true] { let mut harness = app_harness(); let session = &mut harness.state_mut().session; - let layer = add_layer(session, "layer.add.paint"); + let mut layer = add_layer(session, "layer.add.paint"); select(session, layer, json!("content")); let (effect, usable, blocked) = if path { let result = execute(session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); (result["committed"]["effect"].as_u64().unwrap(), Tool::Path, Tool::Paint) } else { - execute(session, "mask.add.black", &json!({"layer": layer})).unwrap(); - let result = execute(session, "effect.add.paint", &json!({"layer": layer, "target": "mask"})).unwrap(); - (result["effect"].as_u64().unwrap(), Tool::Paint, Tool::Smudge) + // A paint sublayer in a fill layer takes brushes, but no paths + let fill = add_layer(session, "layer.add.fill"); + let result = execute(session, "effect.add.paint", &json!({"layer": fill, "target": "content"})).unwrap(); + layer = fill; + (result["effect"].as_u64().unwrap(), Tool::Paint, Tool::Path) }; select(session, layer, json!(effect)); session.tool.tool = usable; @@ -263,8 +265,24 @@ fn unavailable_effect_tools_hide_their_properties() { if let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS") { let directory = std::path::PathBuf::from(directory); std::fs::create_dir_all(&directory).unwrap(); - let name = if path { "unavailable-path-effect.png" } else { "unavailable-mask-paint-effect.png" }; + let name = if path { "unavailable-path-effect.png" } else { "unavailable-fill-paint-effect.png" }; harness.render().unwrap().save(directory.join(name)).unwrap(); } } } + +#[test] +fn clone_and_smudge_are_offered_for_a_layer_mask() { + let mut harness = app_harness(); + let session = &mut harness.state_mut().session; + let paint = add_layer(session, "layer.add.paint"); + execute(session, "mask.add.black", &json!({"layer": paint})).unwrap(); + select(session, paint, json!("mask")); + session.tool.tool = Tool::Smudge; + harness.run_steps(4); + + assert!(!shelf_button_disabled(&harness, "Smudge (5)")); + assert!(!shelf_button_disabled(&harness, "Clone (6)")); + assert!(shelf_button_selected(&harness, "Smudge (5)")); + assert!(shows_text(&harness, "Size"), "the brush controls stay in the top bar"); +} diff --git a/crates/ui-egui/tests/it/tool_settings_saved.rs b/crates/ui-egui/tests/it/tool_settings_saved.rs new file mode 100644 index 00000000..b5c5fd73 --- /dev/null +++ b/crates/ui-egui/tests/it/tool_settings_saved.rs @@ -0,0 +1,27 @@ +//! The app saves the brush and other tool settings with the UI state + +use egui_kittest::Harness; +use texturecraft_ui_egui::{TextureCraftApp, UiState}; + +mod memory_storage; + +use memory_storage::MemoryStorage; + +#[test] +fn saving_the_app_stores_the_current_brush_and_tool_settings() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(2); + let tool = &mut harness.state_mut().session.tool; + tool.brush.size = 0.37; + tool.brush.symmetry.z = true; + tool.smudge_strength = 0.9; + + let mut storage = MemoryStorage::default(); + eframe::App::save(harness.state_mut(), &mut storage); + + let saved = serde_json::from_str::(&storage.0["ui.json"]).expect("the UI state was saved"); + assert_eq!(saved.tool_settings.brush.size, 0.37); + assert!(saved.tool_settings.brush.symmetry.z); + assert_eq!(saved.tool_settings.smudge_strength, 0.9); +} diff --git a/crates/ui-egui/tests/it/tool_settings_saved/memory_storage.rs b/crates/ui-egui/tests/it/tool_settings_saved/memory_storage.rs new file mode 100644 index 00000000..dc70812f --- /dev/null +++ b/crates/ui-egui/tests/it/tool_settings_saved/memory_storage.rs @@ -0,0 +1,19 @@ +/// UI state storage for the tool-setting persistence test +#[derive(Default)] +pub(super) struct MemoryStorage(pub(super) std::collections::HashMap); + +impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} +} diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs new file mode 100644 index 00000000..da94ccda --- /dev/null +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -0,0 +1,85 @@ +//! Saving a layer's mask as a user smart mask from its context menu, and the shelf listing and applying it + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +const WINDOW: egui::Vec2 = egui::vec2(1920.0, 1032.0); +/// The Smart masks type's and the Smart materials type's positions in the shelf's type row (its table is crate-private) +const SMART_MASKS_TYPE: usize = 2; +const SMART_MATERIALS_TYPE: usize = 1; + +fn harness(prepare: impl FnOnce(&mut texturecraft_engine::Session)) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + prepare(&mut session); + let mut harness = Harness::builder().with_size(WINDOW).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + harness +} + +/// A new fill layer called `name`, with a mask of two effects when `masked` +fn add_layer(session: &mut texturecraft_engine::Session, name: &str, masked: bool) -> LayerId { + let layer = LayerId(execute(session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap()); + execute(session, "layer.rename", &json!({"layer": layer.0, "name": name})).unwrap(); + if masked { + execute(session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); + execute(session, "effect.add.generator", &json!({"layer": layer.0, "generator": "edgeWear"})).unwrap(); + execute(session, "effect.add.filter", &json!({"layer": layer.0, "target": "mask", "filter": "invert"})).unwrap(); + } + layer +} + +fn mask_effect_count(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> usize { + harness.state().session.doc.project.layer(layer).unwrap().mask.as_ref().map_or(0, |mask| mask.effects.len()) +} + +fn menu_item_disabled(name: &str) -> bool { + let mut harness = harness(|session| { + add_layer(session, "Plain layer", false); + add_layer(session, "Masked layer", true); + }); + harness.get_all_by_label(name).next().unwrap().click_secondary(); + harness.run_steps(3); + harness.get_all_by_label("Create smart mask").last().unwrap().accesskit_node().is_disabled() +} + +#[test] +fn create_smart_mask_is_in_the_menu_of_a_layer_with_a_mask() { + assert!(!menu_item_disabled("Masked layer"), "a mask can be saved"); +} + +#[test] +fn create_smart_mask_is_off_for_a_layer_without_a_mask() { + assert!(menu_item_disabled("Plain layer"), "there is no mask to save"); +} + +#[test] +fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected_layer() { + let mut saved = texturecraft_engine::sample_session(256, 64).unwrap(); + let source = add_layer(&mut saved, "Source", true); + let dir = std::env::temp_dir().join(format!("tc-ui-smart-mask-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("Stencil.tcmask"); + std::fs::write(&file, saved.smart_mask_bytes(source, "Stencil").unwrap()).unwrap(); + + let mut harness = harness(|_| {}); + let target = harness.state().session.selected_layer().unwrap(); + let before = mask_effect_count(&harness, target); + harness.state_mut().library = Some(vec![file.clone()]); + harness.state_mut().ui.shelf_path = vec!["user".into()]; + harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; + harness.run_steps(3); + assert!(harness.query_by_label_contains("Stencil").is_none(), "it is not a smart material"); + + harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; + harness.run_steps(3); + harness.get_by_label_contains("Stencil").click(); + harness.run_steps(3); + std::fs::remove_dir_all(&dir).unwrap(); + + assert_ne!(before, 2, "the layer did not already have the two effects"); + assert_eq!(mask_effect_count(&harness, target), 2, "the click replaces the selected layer's mask with the saved one"); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 4ab7803f..eab48e4e 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -23,14 +23,85 @@ fn select_map(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { harness.run_steps(3); } -fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { - h.run_steps(6); - let img = h.render().unwrap_or_else(|e| panic!("{name}: {e}")); +fn save(harness: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { + harness.run_steps(6); + let img = harness.render().unwrap_or_else(|e| panic!("{name}: {e}")); let path = dir.join(format!("{name}.png")); img.save(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); eprintln!("wrote {}", path.display()); } +#[test] +#[ignore] +fn empty_start_snapshot() { + 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::Session::closed().unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + save(&mut harness, &output_dir, "empty-start"); +} + +/// Closing rejects a same-frame capture, then releases both rendered view targets. +#[test] +#[ignore] +fn close_releases_view_targets_and_rejects_immediate_capture() { + let session = texturecraft_engine::Session::closed().unwrap(); + let mut harness = Harness::builder().with_size(egui::vec2(960.0, 640.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + + for mesh in ["cube", "plane"] { + assert!(harness.state_mut().run("project.new", serde_json::json!({"mesh": mesh, "resolution": 128})).is_some()); + harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Split; + harness.run_steps(4); + harness.render().unwrap(); + let render_state = harness.state().render_state.as_ref().unwrap().clone(); + let report = |stage: &str| { + render_state.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + if let Some(report) = render_state.device.generate_allocator_report() { + eprintln!( + "{mesh} {stage}: {} live GPU allocations, {} allocated bytes, {} reserved bytes", + report.allocations.len(), + report.total_allocated_bytes, + report.total_reserved_bytes + ); + } else { + eprintln!("{mesh} {stage}: allocator report unavailable on this backend"); + } + }; + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_some()); + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_2D).is_some()); + report("before close"); + let ctx = harness.ctx.clone(); + + let reply = texturecraft_ui_egui::control::handle(harness.state_mut(), &ctx, "command.run", &serde_json::json!({"id": "file.close"})); + + assert_eq!(reply["ok"], true); + assert!(texturecraft_ui_egui::control::screenshot(harness.state(), texturecraft_ui_egui::viewport::VIEW_3D).is_none()); + { + let renderer = render_state.renderer.read(); + let gpu = renderer.callback_resources.get::().unwrap(); + assert!( + gpu.renderer.read_view(&render_state.device, &render_state.queue, texturecraft_ui_egui::viewport::VIEW_3D).is_some(), + "the stale target still exists before the next UI frame" + ); + } + + harness.run_steps(2); + harness.render().unwrap(); + + { + let renderer = render_state.renderer.read(); + let gpu = renderer.callback_resources.get::().unwrap(); + for view in [texturecraft_ui_egui::viewport::VIEW_3D, texturecraft_ui_egui::viewport::VIEW_2D] { + assert!(gpu.renderer.read_view(&render_state.device, &render_state.queue, view).is_none()); + } + } + report("after close"); + } +} + /// Check the saved-brush controls without a GPU adapter #[test] #[ignore] @@ -757,3 +828,32 @@ fn mask_fill_image_snapshot() { assert!(harness.query_by_label("Projection").is_some(), "image projection is editable"); save(&mut harness, &output_dir, "mask-fill-image-selected"); } + +#[test] +#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"] +fn tile_generator_gradient_map_snapshot() { + use serde_json::json; + use texturecraft_engine::execute; + + 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 mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &json!({})).unwrap(); + execute( + &mut session, + "layer.fill.set", + &json!({"channel": "baseColor", "procedural": "Tile Generator", "tile": {"amount": [5, 3]}, "colors": ["#1d1745", "#4e80a0", "#f0bb75"]}), + ) + .unwrap(); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).wgpu().build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Properties); + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::ComboBox, "Base color").scroll_to_me(); + harness.run_steps(30); + + assert!(harness.query_by_label_contains("Add color").is_some()); + save(&mut harness, &output_dir, "tile-generator-gradient-map"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1ebe01d2..23bf09f3 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -18,6 +18,27 @@ effect's input), so an agent can pick its input range from the data. `effect.mov index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. +`layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer` +is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and +Ctrl+click do in the Layers panel. `layer.select {all: true}` (Ctrl+A with the pointer over the +Layers panel) selects every shown row of the active texture set: the folder rows and the layers +of open folders, not the layers of collapsed ones. `{layer, toggle: true}` on the only selected +layer leaves nothing selected. `layer.visible {layers, layer}` gives every listed layer the +opposite of `layer`'s visibility (the Layers panel's eye uses `{layer}` and acts on that layer +only). `layer.group` puts the new folder at the place and in the folder of the topmost selected +layer, the others in stack order; `layer.duplicate` puts the copies in one block above the +topmost selected layer. Without `layer`, `layer.remove`, `layer.duplicate`, +`layer.group` and `layer.visible` act on every selected layer; each of them and `layer.move +{layers, above | index}` also take an explicit `layers` list. `session.inspect` lists the +selection as `selectedLayers` (top row first). + +`mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the +texture set's resolution: black where the mesh does not cover the texture, with the orientation +of the exported textures (top row first). A UV-tiled set writes one file per tile, each at its +tile's size, with the tile number before the extension (`mask.1001.png`, `mask.1002.png`). The +result is `{files}`. A layer without an enabled mask is an error. The layer menu's Export mask to +file runs it; Copy mask to clipboard puts the same mask on the system clipboard as an 8-bit +grayscale image (the whole tile atlas for a UV-tiled set). `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus @@ -29,10 +50,30 @@ must be added separately with `effect.add.filter`. A successful replacement is o a rejected replacement changes nothing. `edit.undo {steps?}` and `edit.redo {steps?}` go back or forward several steps at once (as far -as the history reaches); `edit.history` lists the steps done and the undone ones, next first. +as the history reaches); `edit.history` lists the steps done and the undone ones, next first. Step names are English; a stroke is named by tool and layer (`Paint on Rust`, +`Clone on Rust`, `Erase mask of Rust`). Any command takes `merge: true` to fold its edit into the previous undo step when that step has the same label: a drag that applies a value on every frame stays one step. +A colour param is `[r, g, b]` in linear 0..1, or `"#rrggbb"` in sRGB, which is converted to +linear. The same digits are two different colours: `"#c8102e"` is `[0.578, 0.005, 0.027]`, while +`[0.784, 0.063, 0.180]` (its hex digits over 255) paints the lighter `#e54776`. Pass a colour from +a design tool or a brand guide as hex. A single number is a linear grey. +For a colour selection, `effect.set` accepts only linear `[r, g, b]` arrays in its `colors` list. + +`tool.cloneSource {uv: [u, v]}` (or `{x, y}` for a point on the mesh, or `{clear: true}`) sets the +Clone tool's source. The source belongs to the active texture set: selecting another texture set +(`textureSet.select`, or `layer.select` of a layer in another set) clears it. `tool.brush +{cloneAligned}` (default `true`) chooses how later strokes use it: aligned keeps the offset the +first stroke fixed, so the source moves along with the brush; `false` makes every stroke start +sampling at the source point. Changing `cloneAligned` forgets the offset of earlier strokes. +`tool.brush` takes the alpha's shared parameters next to `alpha`: `alphaSizeX` and `alphaSizeY` +(5..100, percent of the stamp the alpha fills, default 100), `alphaRoundness` (0..100, only for the +procedural Round alpha: 100 is a circle, 0 a square), `alphaContrast` (1..8, 1 leaves the values +alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). They apply to +procedural, library and imported alphas alike and are returned by `tool.brush` with the other +values. The alpha's rotation is the brush `angle`. + Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the changed fields; Restore Defaults resets the whole parameter section across all sets. @@ -66,6 +107,14 @@ if output size changes, or neutral values when no previous map exists. A running tile selection captured when its worker started. Sets with no checked tiles are skipped; their geometry still contributes to occlusion when baking other tiles. +`view.solo {layer?, ignoreMask?}` shows one layer alone in the viewport, as if the other layers +of its texture set were hidden (`layer` defaults to the selected layer, `layer: null` ends the +solo; `ignoreMask: true` draws the layer, and the folders around it, at full coverage; other +texture sets are unchanged). It changes only the view: nothing enters the undo history, the +project file or an export (`file.exportTextures` and the CLI export the whole stack, then the solo comes +back), and removing the soloed layer ends it. `session.inspect` reports it as `solo` +(`{layer, ignoreMask}` or `null`). + ## Control channel (desktop app) ```sh @@ -106,7 +155,8 @@ 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.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.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` | @@ -212,6 +262,8 @@ Through `command_run`, every `file.*` command but `file.close` and `file.removeU a `files` entry (`resource.import`, `material.save`, `material.load`, `textureSet.meshMap.import`, …), in both modes: use the workspace tools below. `resource.text` takes a font family, not a path: it reads only the system's font folders. +`file.close` leaves no project open: `session.inspect` then reports `projectOpen: false`, `command.list` marks every command but the project-independent ones as not enabled: the ones that open or create a project (`file.open`, `file.new`, `project.new`, `project.sample`), `project.inspect`, `viewport.frame`, `project.templates`, the `export.preset*` commands (`export.presets`, `export.preset.get`, `export.preset.save`, `export.preset.remove`) and the library and preset listings (`brush.preset.list`, `alpha.list`, `filter.list`, `material.list`, `mask.smart.list`, `text.fonts`), each still subject to its own enabled check. The rest are refused with "no project is open" until a project is opened or created. A `texturecraft --control` run starts with the sample project (an empty material ball with `--empty`); the app without `--control` starts with no project. + | Tool | Params | Notes | |---|---|---| | `session_inspect` | | The whole session as JSON | @@ -381,6 +433,46 @@ Maps are found by file name, case-insensitively, from the last known word in the In the app: File › Import PBR texture folder... or drop a folder, a `.zip` or several map files on the window. The dialog shows the maps found, lets you pick between candidates, set the normal convention and projection, and keep the material in the library (shelf › Materials). + +## Smart masks + +`mask.smart.list` lists the built-in smart masks and `mask.smart.apply {name, layer?}` replaces a +layer's mask with one. A user smart mask is a layer's mask saved as a `.tcmask` file (the `.tcraft` +container holding one layer with the mask): all effects with their parameters, painted pixels and the +images they read. + +| Command | Params | +|---|---| +| `mask.smart.create` | `{layer?, path, name?}`: save the layer's mask (an instance without its own mask saves its source's) to `path` (`.tcmask` is appended if missing, folders are made); `name` defaults to the layer's name. Returns `{path}` | +| `mask.smart.apply` | `{path, layer?}`: replace the layer's mask with the one in a `.tcmask` file (one undo step; images it needs are added to the project, painted pixels are fitted to the texture set) | + +In the app: right-click a layer > *Create smart mask* saves into the library folder next to the smart +materials (never over an earlier file), and the shelf lists it under *My smart masks* (Smart masks tab, +*Your assets*): click it or drop it on a layer. Like `material.save`, both forms with `path` are not +available through `command_run` on the MCP server, which rejects host paths. + +## Geometry decals + +`layer.add.decal {image, ...}` places an image as a decal and `layer.decal.set {layer? | effect?, ...}` edits +one (`command.list` shows every param). Three of them keep the image's look: + +- `keepProportions: true` keeps the image's aspect (the decal's current ratio when it shows no image). A + height (`size: 0.2`) sets the width; a `[w, h]` pair or no `size` sets the height from the width. It acts + in that call only and is not saved: the desktop Properties panel's "Keep proportions" box (on for every + decal) sends it with each Width or Height edit. +- `flipU` / `flipV`: mirror the image left to right / top to bottom inside the frame. They are saved with + the decal (`flip: [u, v]`, left out while both are false, so older projects load and save unchanged). + +`layer.add.decal {image, position?, normal?, up?, size?, rotation?, depth?, symmetry?, symmetryFlip?}` +places an image on the surface; `layer.decal.set` moves, resizes or turns it later. `symmetry` +(`x`, `y`, `z` or `off`) adds a mirrored copy on the other side of the mesh: the decal reflected +through the plane across the mesh center, perpendicular to that axis. The copy is part of the +decal, not a second layer, so it follows every later edit and is saved with the project. +`symmetryFlip` (`none`, `u`, `v`) additionally flips the copy's image (U swaps left and right, +V swaps top and bottom). `symmetryOffset` moves the mirror plane along the axis, in world units from the mesh center (default 0, kept within the mesh, as the brush symmetry's offset). With a copy on, each of the three params may be sent alone and keeps the others. +`session.inspect` shows the setting as `decal.symmetry` (`{axis: 0|1|2, flip, offset?}`, absent without +a copy). + ## Camera bookmarks Saved cameras (`Project.cameras`, stored in the `.tcraft` file) are the camera bookmarks. @@ -390,6 +482,24 @@ is at), `camera.select {index? | name?}` restores one, `camera.rename {index? | go to the first nine. Commands jump straight to the view; the desktop UI glides there over about a third of a second. +## Framing the view + +`viewport.frame {target?: "all" | "selection"}` points the camera at the bounding box of the whole mesh +(`"all"`, the default, F) or of the active texture set's geometry only (`"selection"`), keeping the +current angles. The orbit pivot (`camera.get` `target`) is the framed center, so `camera.orbit` and the +Alt+drag orbit turn around the object being painted even with a floor plane or other helper geometry in +the mesh. `viewport.frameSelection` (Shift+F) is the same as `target: "selection"`; a set with no triangles +frames the whole mesh. Both return the camera like `camera.get`. + +## Camera views and projection + +`camera.view {view}` looks at the mesh from one side (`front` from +Z, `back`, `left` from -X, +`right`, `top` and `bottom` at the orbit's ±89° pitch limit) and frames it; the projection stays. +`camera.view.front` … `camera.view.bottom` do the same without params (Viewport menu, no default +shortcut, bindable in Settings ▸ Keyboard). `camera.perspective` (F5) and `camera.orthographic` (F6) +change only the projection; position and rotation stay. None of them is an undo step. In the 3D +view, Alt+Shift+left drag orbits in 90° steps. + ## MaterialCraft materials A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is diff --git a/docs/features.md b/docs/features.md index 83f95eac..19b63553 100644 --- a/docs/features.md +++ b/docs/features.md @@ -6,21 +6,26 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Brushes** with size, flow, stroke opacity, spacing, hardness, angle and follow path; size, angle, flow and position jitter; tangent or camera alignment, angle fade, backface culling, lazy - mouse, X/Y/Z mirror and radial symmetry (copies paint the far side too) and pen pressure in the - 3D and 2D views (Windows Ink pens, and pens that send touch events in the browser, such as on + mouse, X/Y/Z mirror and radial symmetry (copies paint the far side too, and in the 2D view they land where the 3D + copies would) and pen pressure in the 3D and 2D views (Windows Ink pens, and pens that send touch events in the browser, such as on tablets; on Linux, macOS and desktop browsers a pen works as a mouse for now). Ctrl+drag in a view sets them on the fly: right-drag the size and hardness, left-drag the flow and angle. - **67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha. + **67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha. Every alpha has Parameters (Properties › Alpha): hardness, size X and Y, + roundness for the Round shape, contrast and invert, with Restore defaults. **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the stroke and keep the size. The Brush section's **Brush presets** popover (and the shelf) also keeps your own: save the current brush, click to use it, rename, replace or delete it. - **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the - stencil), polygon fill (triangle, UV island or the whole mesh), **path** and **lasso fill**, a - **particle brush**, **smudge**, **clone** (V + click sets the source), material picker, Shift+click - straight lines, and painting directly in the **2D UV view**. -- **Geometry decals:** drop an image on the surface, then move, scale and turn its frame; it stays - an editable fill layer. + stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a + **particle brush**, **smudge**, **clone** (V + click sets the source, marked in the 3D and 2D views; + an Aligned option keeps or restarts the offset per stroke), material picker, Shift+click straight + lines (Ctrl+Shift+click snaps them to 15 degree steps), and painting directly in the **2D UV view**. + Brush, symmetry and the other tool settings stay when you open another project and when you + restart the app. +- **Geometry decals:** drop an image on the surface, then move, scale and turn its frame, keep the image's proportions + while sizing it or flip it; it stays an editable fill layer. Mirror across X, Y or Z (optionally flipping the copy's image in U or V) + to place a copy on the opposite side of the mesh (move the mirror plane with Axis position); it follows the decal. - **Text** in any installed font (or the built-in ones), shaped for every script with kerning and ligatures, one or more lines: stamp it with the brush as its alpha, or place it as a decal in the tool's base color (Properties › Alpha › Text). @@ -36,7 +41,16 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA Normal map detail), per-channel opacity, visibility, color tags, drag-and-drop reordering, duplicate, group, flatten, cut, copy and paste across texture sets, and **geometry masks** that show a layer only on the mesh parts you pick (right-click a layer, or click parts with the - **Geometry mask** tool, 8). + **Geometry mask** tool, 8). **Solo layer** (right-click a layer, or Alt+click its eye) shows + one layer alone in the 3D and 2D views, optionally without its mask (Alt+Shift+click, or + **Solo layer without its mask**), to judge a material hidden behind a mask. It is only a view: + the document, the undo history, saving, exporting and baking never see it. +- **Several layers at once:** Shift+click a layer to select the rows from the last clicked one, + Ctrl+click (Cmd+click on macOS) to add or take out one layer, Ctrl+A (Cmd+A) with the pointer + over the Layers panel to select every shown row (folder rows and the layers of open folders). + The eye of a row always acts on that layer only. Delete, the trash button, duplicate + (Ctrl+D), group (Ctrl+G: the new folder takes the place and folder of the topmost selected layer; copies go in one block above it), the row menu and drag-and-drop then act on every selected layer, each + as one undo step. - **Filters and content effects** on any layer or mask: **31 filters** (HSL, levels, contrast/luminosity, color balance, gradient map, posterize, clamp, histogram scan, range and shift, invert, threshold, grayscale, replace color, edge detect, normal invert, baked lighting, @@ -59,21 +73,30 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA and offset, and the cylindrical axis in the fill's properties. Each channel takes its own image (a normal, roughness or height map, say): pick it in the channel's source menu, which also imports one, or drop it from the Assets panel onto the channel. A normal map image made for DirectX (Y down) is marked with **DirectX normal map** under it. + A color channel's procedural or anchor point takes a **gradient map** (*Gradient Map* in the + channel's source menu): up to 16 color stops, dark to light, color the pattern, or recolor + the stack below by its lightness, without touching the other channels. The **Gradient map** + filter does the same for a whole layer's content. Alt+click a material channel (of a fill or the brush) to keep that channel alone. - **72 materials** (metals from measured reflectance, car paint, brushed anisotropic steel, velvet, skin, wax, glass, ice, woods, bamboo, bark, stone, cobblestone, gravel, plaster, sand, mud, snow, bone, moss, plastics, fabric, linen, wool, leather, ceramic, rust, cork, paper), **21 smart materials** (rusted iron, worn paint, oxidized copper, bronze statue, weathered wood, mossy brick and stone, sun-faded paint…) and **24 smart masks**, all procedural, so they work at any - resolution. Drag them from the tabbed, searchable shelf onto the layer stack or straight onto - the model. + resolution. Drag them from the tabbed, searchable shelf onto the layer stack (below the row you + drop on) or straight onto the model (a new fill layer on top). A click on a simple material makes it + the brush's material: the next stroke paints its pattern (colour, metallic, roughness, height), + fixed to the surface and sized with the brush. A click on a smart material, which is several + layers, only highlights it; drag it to add its layers. - **Import resources:** *File › Import resources...* opens a window: *Add resources* (images and - materials), an optional name prefix and a usage per file (texture, environment and alpha also - light the scene or set the brush alpha), a filter by usage, *Remove selected resources*, then - *Import*. Not yet available: the colorlut and postfx usages and the "Your assets" target (shown - disabled). The browser imports images straight from its file picker. + materials), an optional name prefix and a role for each image. Environment images light the scene, + and alpha images become the brush alpha. Filter by role or remove selected rows before importing. + Failed rows stay in the dialog for retry. Color LUT, post effects and asset-library import are + unavailable. The browser imports images straight from its file picker. - **Your own library:** right-click a layer or folder, choose *Create smart material*, and it - appears under *My smart materials*, pixels and images included. + appears under *My smart materials*, pixels and images included. *Create smart mask* in the same + menu saves just the layer's mask (all its effects, painted pixels and images); it appears under + *My smart masks* and applies to any layer like a built-in smart mask. - **MaterialCraft materials:** *File › Import material*, a drop on the window, or MaterialCraft's *File › Send to TextureCraft* (it lands under *My smart materials*) adds a `.mcmat` portable material, or a `.mcraft` package, as a fill layer. Its exposed graph inputs (numbers, vectors, @@ -94,9 +117,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **Edit › Project Configuration...** (desktop) does the same from the 3D MESH section: *Select...* picks the file, *Reimport mesh* is ticked for you (or tick it alone to read the same file again), OK applies. *Import settings* decides whether painted strokes follow the surface (on by default), and PROJECT SETTINGS sets the project's normal map format and - lists its UV tiles (read only; Texture Set Settings changes them). Physical size and Color management - follow the New project window. -- **File › New project...** follows the reference app's window: BASIC SETTINGS (*Select...* a mesh file, + shows its UV tiles in the UV workflow tooltip. Edit the tiles in Texture Set Settings. + Physical size and color management show the same settings as New project. +- **File › New project...** opens a setup form with BASIC SETTINGS (*Select...* a mesh file, the project template, the document resolution; Create waits for a mesh) and ADVANCED SETTINGS (normal map format, *Use UV Tile workflow*, *Import cameras*, *Import baked maps*, physical size, color management). The project is named after the mesh file. Settings TextureCraft does not have yet @@ -132,7 +155,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with UV padding, size override and OpenGL or DirectX normals. -- **Output template editor:** build your own presets with per-channel packing and converted maps, +- **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, and share them as JSON. - **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 @@ -150,8 +173,14 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA light, environment importance sampling, displaced geometry, a denoiser and one-click PNG save, traced on the GPU (compute shaders, about 25× the CPU tracer, desktop and WebGPU) or on the CPU. -- View any channel, any baked mesh map, or a UV checker; Alt+drag to orbit, middle-drag to pan, - wheel to zoom, F to frame, M / C / B to cycle views. +- View any channel, any baked mesh map, or a UV checker; Alt+drag to orbit (Alt+Shift+drag in 90° + steps), middle-drag to pan, wheel to zoom, F to 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 + 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 + bottom views** that frame the mesh (Viewport menu; bind your own keys in Settings). - **3D and UV wireframes** that show the mesh's own polygons: quads and n-gons from OBJ, FBX, COLLADA, USD, Alembic and PLY files keep their edges, without the triangulation's diagonals. @@ -164,11 +193,11 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA strip, and Settings › Interface › System title bar for the system's frame instead. - **Dockable, tabbed and floating panels**, saved layouts, and panels that reopen where you closed them. -- A **start window** at launch: a new project, a project file, a recent project or the sample - (Settings › Interface › Start window). +- **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). -- A **shortcut editor** with conflict detection, and every shortcut shown in its tooltip. +- 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. - 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 8ef5389a..70d417f8 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -2,7 +2,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Each row is a menu item of the target menu layout with TextureCraft's command id; **live** means the id is implemented. Feature parity beyond menus is tracked in [`ROADMAP.md`](../ROADMAP.md). -**60 of 60 menu items live (100%).** +**73 of 73 menu items live (100%).** ## File @@ -14,7 +14,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Close | `file.close` | Ctrl+F4 | live | | Save | `file.save` | Ctrl+S | live | | Save as... | `file.saveAs` | Ctrl+Shift+S | live | -| Save a copy... | `file.saveCopy` | | live | +| More save options ▸ Save a copy... | `file.saveCopy` | | live | | Remove unused resources... | `file.removeUnused` | | live | | Import resources... | `resource.import` | | live | | Import MaterialX material... | `file.importMaterialX` | | live | @@ -60,7 +60,10 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Views ▸ Texture Set Settings | `ui.view.textureSetSettings` | | live | | Save UI Layout ▸ Save current layout... | `ui.layout.save` | | live | | Load UI Layout | `ui.layout.load` | | live | +| Layouts ▸ Save current layout as... | `ui.layout.saveAs` | | live | +| Layouts ▸ Manage layouts... | `ui.layout.manage` | | live | | Hide UI | `ui.hideUi` | Tab | live | +| Reset panel layout | `ui.resetPanelLayout` | | live | | Reset UI | `ui.resetUi` | | live | ## Viewport @@ -73,10 +76,20 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac | Display next mesh map | `viewport.nextMeshMap` | B | live | | Display previous mesh map | `viewport.previousMeshMap` | Shift+B | live | | UV checker | `ui.uvChecker` | | live | +| Frame texture set | `viewport.frameSelection` | Shift+F | live | | Show entire mesh | `viewport.frame` | F | live | +| Front view | `camera.view.front` | | live | +| Back view | `camera.view.back` | | live | +| Left view | `camera.view.left` | | live | +| Right view | `camera.view.right` | | live | +| Top view | `camera.view.top` | | live | +| Bottom view | `camera.view.bottom` | | live | +| Perspective | `camera.perspective` | F5 | live | +| Orthographic | `camera.orthographic` | F6 | live | | 3D/2D views | `ui.layout.split` | F1 | live | | 3D view only | `ui.layout.3d` | F2 | live | | 2D view only | `ui.layout.2d` | F3 | live | +| Navigation buttons | `ui.navButtons` | | live | | Enable quick mask | `viewport.quickMask` | Y | live | | Edit quick mask | `viewport.quickMask.edit` | U | live | | Invert quick mask | `viewport.quickMask.invert` | Ctrl+Shift+I | live | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 776e0b59..af4aec31 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -34,16 +34,19 @@ stable review references, not a complete inventory of the reference interface. | UI-04 | P1 | Fill sampling/filtering and UV wrap controls | **UI + source.** The reference fill panel exposes filtering and wrapping. TextureCraft's fill editor exposes projection, transforms and channel sources without those controls. No per-fill UI workaround was established | Set filtering and wrapping per fill, inspect the difference at a UV border, and retain the settings across save/reopen | | UI-05 | P2 | Physical-size fill scaling | **UI + source.** The reference Scale menu offers tiling or physical size. TextureCraft exposes dimensionless scale only | Give a pattern a physical size and show that it keeps that size on meshes with different dimensions | | UI-06 | P2 | Warp and per-UV-tile fill projection choices | **UI + source.** Both choices were visible in the reference projection menu. TextureCraft's ordinary fill picker has UV, tri-planar, planar, spherical and cylindrical choices; decals have a separate editor. A warp filter is a different operation | Exercise the two projection workflows on a multi-tile asset, with explicit controls, persistence and command inspection | -| UI-08 | P2 | Save a reusable user smart mask | **UI + source.** The reference mask menu has a smart-mask creation action. TextureCraft offers built-in smart masks and Create smart material, but no equivalent action for saving just the edited mask | Save a multi-effect mask, apply it to another layer/project, and retain its parameters and resource dependencies | -| UI-09 | P2 | Export/copy a mask bitmap from its context menu | **UI.** The reference exposes file and clipboard mask export; these actions are absent from TextureCraft's inspected menu. Previewing a mask is available, and is not a full-resolution bitmap-export check | Export the evaluated grayscale mask at its texture/tile resolution with explicit bit depth and orientation; test the file and clipboard paths | -| UI-10 | P1 | MaterialX output from the texture-export dialog | **UI + source + commands.** The dialog has no MaterialX option and `export_params` does not forward `materialX`. Command export with the OpenPBR preset successfully wrote `.mtlx` and maps | Enable MaterialX in the UI, preview the manifest and texture outputs, export, and validate the same result as the command route | +| UI-09 | P2 | Export/copy a mask bitmap from its context menu | **UI + source.** Both actions are now in the layer menu. File export writes a 16-bit grayscale PNG per tile; clipboard copy uses an 8-bit grayscale atlas. There is no bit-depth chooser | Repeat file and clipboard export in the native app, including a UV-tiled set; the engine and headless UI tests cover the values and menu paths | | UI-11 | P1 | Configurable project/display color-management workflow | **Source.** `DisplaySettings` provides fixed Linear/ACES-filmic tone mapping; export has fixed color spaces and metadata. There is no OCIO configuration/display/view model to expose in project or display settings | Select a configuration, working space and display/view transform; retain them; distinguish color channels from data maps through painting, preview and export | -UI-02 and UI-07 were findings at the assessed `62b2b13` revision and are no longer missing in +UI-02, UI-07 and UI-08 were findings at the assessed `62b2b13` revision and are no longer missing in the integrated source. Effect rows now have a Rename action and editor, and anchors can record intermediate mask values for higher layers. Engine and compositor regressions cover mask-anchor -consumption. The original UI task audit did not exercise these new controls; a live UI rename, -undo and save/reopen task remains to be repeated on the integrated build. +consumption. Right-click a layer > *Create smart mask* saves its mask (all effects, parameters, painted pixels and images) as a user smart mask that the shelf lists under *My smart masks*; engine tests cover applying it to another layer and a fresh project. The original UI task audit did not exercise these new controls. The rename and anchor controls are now covered +by interface tests (`crates/ui-egui/tests/it/rename_anchor.rs`): renaming an effect row from its +context menu, Undo and Redo of the rename, Escape, and Save as and Open keeping the name; adding an +anchor point to a mask from the Add effect menu, picking it as the Source of a fill in a higher +layer's mask, the resulting composite matching the engine-only result, and Save as and Open keeping +the link. These run in the headless test harness; a live run in the native app on the integrated +build is still not done. The relevant implementations are [layer rows, menus and fill/brush editors](../crates/ui-egui/src/dock.rs), [generator properties](../crates/ui-egui/src/generator_panel.rs), @@ -57,16 +60,14 @@ The relevant implementations are [layer rows, menus and fill/brush editors](../c | ID | Area | Observed limit | Next check | |---|---|---|---| | 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 | +| 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 | -File > Import resources (#638) is a window like the reference's: add files, an optional -name prefix and a usage per file, a filter by usage, Remove selected resources, and Import or -Cancel. Usages `texture` and `undefined` import an image resource, `environment` also lights the -scene with it, `alpha` also makes it the brush alpha. `colorlut` and `postfx` have no feature -behind them and are listed disabled, as is the target "library 'Your assets'" (that library holds -smart materials and brush presets, not images). The prefix goes in front of the resource's name, -because resources have no folders. Materials (`.tcmat`, `.mcmat`, `.mcraft`) can be added too and -load as smart materials. The browser build still imports images straight from its file picker. +File > Import resources ([#638](https://github.com/storytold/texturecraft/issues/638)) queues +images and materials for the open project. Images support a name prefix and a usage. Texture +and undefined usages store the image, while environment and alpha also apply it to the scene +or brush. Filter the list by usage or remove rows before importing. Color LUT, post effects +and asset-library import remain unavailable. The browser imports images straight from its file +picker. Broader properties/filter work remains tracked in [#433](https://github.com/storytold/texturecraft/issues/433). Its individual rows need checking @@ -115,9 +116,11 @@ built-in `udim_plane`, a uniform fill and a tile-1002 resolution override. - The 2D paint cursor was visible, and direct 2D painting worked. This does not reproduce the older cursor/painting reports on this setup. - Brush size/hardness and flow/angle gestures have a visible hint. Hardness is present under - Flow and opacity; Angle has its own section. Their absence must not be inferred from the initial - scrolled position. The broader precision/shortcut concerns in - [#545](https://github.com/storytold/texturecraft/issues/545) still need an input-device task test. + Alpha > Parameters; Angle has its own section. Their absence must not be inferred from the initial + scrolled position. The shortcut overview lists Shift+wheel and Ctrl+wheel (brush size, 3D and 2D + view), Ctrl+right-drag, Ctrl+left-drag and the fine mode (Ctrl+Shift+right-drag changes size and + hardness by a tenth). Pen precision in [#545](https://github.com/storytold/texturecraft/issues/545) + still needs an input-device task test. - The shelf displayed four columns at the larger size, with type controls and search. Do not treat every older shelf-layout request as a currently missing implementation. - A missing mask-thumbnail menu does not mean mask effects are unavailable: the layer-name menu