diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 69e0384b..23727788 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "44 2 * * *" push: branches: [release] workflow_dispatch: @@ -23,6 +27,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: texturecraft app-title: "TextureCraft" craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc diff --git a/Cargo.lock b/Cargo.lock index 384c4457..4831abd2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,7 +758,7 @@ dependencies = [ [[package]] name = "craft-dialogs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "block2 0.6.2", "objc2 0.6.5", @@ -771,12 +771,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "fixed_decimal", "icu_decimal", @@ -799,7 +799,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "egui", "serde", @@ -809,7 +809,7 @@ dependencies = [ [[package]] name = "craft-menu" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "craft-keymap", "craft-quit", @@ -822,7 +822,7 @@ dependencies = [ [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "dispatch2", "egui", @@ -833,7 +833,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -854,7 +854,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "chrono", "dunce", @@ -864,6 +864,7 @@ dependencies = [ "image", "log", "plist", + "rustix 1.1.5", "semver", "serde", "serde_json", @@ -880,7 +881,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=1b34eba41e62138fc2438d2734523b302840b45d#1b34eba41e62138fc2438d2734523b302840b45d" +source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b" dependencies = [ "egui", "objc2 0.6.5", @@ -2640,6 +2641,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -2858,6 +2868,16 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -4192,6 +4212,20 @@ dependencies = [ "web-sys", ] +[[package]] +name = "sysinfo" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + [[package]] name = "tar" version = "0.4.46" @@ -4226,7 +4260,7 @@ dependencies = [ [[package]] name = "texturecraft" -version = "0.3.1" +version = "0.6.1" dependencies = [ "craft-menu", "craft-update", @@ -4247,7 +4281,7 @@ dependencies = [ [[package]] name = "texturecraft-automation" -version = "0.3.1" +version = "0.6.1" dependencies = [ "base64 0.22.1", "cap-std", @@ -4268,7 +4302,7 @@ dependencies = [ [[package]] name = "texturecraft-bake" -version = "0.3.1" +version = "0.6.1" dependencies = [ "bytemuck", "rayon", @@ -4280,7 +4314,7 @@ dependencies = [ [[package]] name = "texturecraft-cli" -version = "0.3.1" +version = "0.6.1" dependencies = [ "image", "serde_json", @@ -4292,7 +4326,7 @@ dependencies = [ [[package]] name = "texturecraft-compose" -version = "0.3.1" +version = "0.6.1" dependencies = [ "half", "rayon", @@ -4303,7 +4337,7 @@ dependencies = [ [[package]] name = "texturecraft-core" -version = "0.3.1" +version = "0.6.1" dependencies = [ "serde", "serde_json", @@ -4312,7 +4346,7 @@ dependencies = [ [[package]] name = "texturecraft-engine" -version = "0.3.1" +version = "0.6.1" dependencies = [ "epaint_default_fonts", "image", @@ -4332,7 +4366,7 @@ dependencies = [ [[package]] name = "texturecraft-formats" -version = "0.3.1" +version = "0.6.1" dependencies = [ "base64 0.22.1", "exr", @@ -4345,6 +4379,7 @@ dependencies = [ "rayon", "serde", "serde_json", + "sysinfo", "texturecraft-compose", "texturecraft-core", "texturecraft-geom", @@ -4356,7 +4391,7 @@ dependencies = [ [[package]] name = "texturecraft-geom" -version = "0.3.1" +version = "0.6.1" dependencies = [ "glam 0.30.10", "mikktspace", @@ -4367,7 +4402,7 @@ dependencies = [ [[package]] name = "texturecraft-paint" -version = "0.3.1" +version = "0.6.1" dependencies = [ "epaint_default_fonts", "harfrust", @@ -4382,7 +4417,7 @@ dependencies = [ [[package]] name = "texturecraft-render" -version = "0.3.1" +version = "0.6.1" dependencies = [ "bytemuck", "half", @@ -4401,11 +4436,11 @@ dependencies = [ [[package]] name = "texturecraft-texel" -version = "0.3.1" +version = "0.6.1" [[package]] name = "texturecraft-ui-egui" -version = "0.3.1" +version = "0.6.1" dependencies = [ "base64 0.22.1", "craft-dialogs", @@ -4421,6 +4456,7 @@ dependencies = [ "image", "js-sys", "log", + "pollster 0.4.0", "rayon", "rfd", "serde", @@ -4438,7 +4474,7 @@ dependencies = [ [[package]] name = "texturecraft-web" -version = "0.3.1" +version = "0.6.1" dependencies = [ "eframe", "js-sys", @@ -5303,6 +5339,22 @@ dependencies = [ "web-sys", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -5312,6 +5364,12 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows" version = "0.62.2" @@ -5808,7 +5866,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.3.1" +version = "0.6.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 73a090c8..76f84caa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["vendor"] default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"] [workspace.package] -version = "0.3.1" +version = "0.6.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" @@ -32,6 +32,8 @@ serde_json = "1" glam = { version = "0.30", features = ["serde", "bytemuck"] } bytemuck = { version = "1", features = ["derive"] } rayon = "1" +# Free RAM, to size how much a project save holds in flight. +sysinfo = { version = "0.40", default-features = false, features = ["system"] } # Text alphas: shaping and glyph outlines, the versions egui's text layout already builds. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } @@ -63,19 +65,19 @@ getrandom = "0.3" rustix = { version = "1", default-features = false, features = ["std", "fs", "process"] } # Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs, # MIT OR Apache-2.0, pinned to one rev. -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["serde"] } +craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] } # 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 = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs). -craft-update = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs). -craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs). -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs). -craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d", features = ["egui"] } +craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] } # The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs). -craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "1b34eba41e62138fc2438d2734523b302840b45d" } +craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 4965c438..2deac956 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -121,16 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off -fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { +/// Preferences needed before opening the initial project or window, with legacy storage fallback. +fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { if let Some(ui) = ui_file.and_then(ui_state_store::read) { - return ui.prefs.system_title_bar; + return ui.prefs; } let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); - entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default() } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -197,7 +197,6 @@ fn main() { fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); - let session = initial_session(&args); // 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()))); @@ -206,7 +205,10 @@ fn main() { if let Some(file) = &ui_file { let _ = ui_state_store::FILE.set(file.clone()); } - let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); + let prefs = saved_prefs(ui_file.as_deref(), persistence_path.as_deref()); + prefs.apply_resource_limits(); + let session = initial_session(&args); + let title_bar = TitleBar::decide(prefs.system_title_bar); let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); @@ -331,27 +333,36 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + fn startup_preferences_use_ui_json_then_legacy_storage_then_defaults() { let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; + ui.prefs.project_open_limit_gib = 16; + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + let legacy = saved_prefs(None, Some(&ron_path)); + assert_eq!(legacy.system_title_bar, on); + assert_eq!(legacy.project_open_limit_gib, 16); ui.prefs.system_title_bar = !on; + ui.prefs.project_open_limit_gib = 32; std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); + + let current = saved_prefs(Some(&json_path), Some(&ron_path)); + assert_eq!(current.system_title_bar, !on, "ui.json comes first"); + assert_eq!(current.project_open_limit_gib, 32); } std::fs::write(&json_path, "not json").unwrap(); std::fs::write(&ron_path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); std::fs::remove_file(&json_path).unwrap(); std::fs::remove_file(&ron_path).unwrap(); - assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); } } diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index c61fce50..e390c239 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -85,7 +85,15 @@ impl Gpu { /// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels. pub fn render(&mut self, s: &mut Session, kind: ViewKind, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera) -> Option<(u32, u32, Vec)> { self.sync(s); - let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() }; + let frame = Frame { + view_id: 1, + size, + kind, + camera, + shade: shade(s), + visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + overlay: Vec::new(), + }; self.h.render(&frame) } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index d3ae712e..fe0bdb23 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1241,12 +1241,8 @@ impl<'a, 'b> Texel<'a, 'b> { signal }; - // A smooth step from black to white over 2 × softness around 1 − level - let threshold = 1.0 - generator.level.clamp(0.0, 1.0); - let softness = generator.softness.max(1e-3); - let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0); - let value = ramp * ramp * (3.0 - 2.0 * ramp); - if generator.invert { 1.0 - value } else { value } + // A smooth step from black to white over 2 × softness around 1 − level, then the offset + generator.shape(signal) } /// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend. diff --git a/crates/core/src/layer.rs b/crates/core/src/layer.rs index 37ce47e8..8e7c41e8 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -543,6 +543,9 @@ pub struct Generator { pub noise_amount: f32, pub noise_scale: f32, pub seed: u32, + /// Added to the finished mask value and clamped to 0..1 (−1..1; 0 = unchanged). + #[serde(default)] + pub offset: f32, /// Direction for `Position` / `Direction` generators (world space). pub direction: [f32; 3], pub invert: bool, @@ -565,7 +568,19 @@ impl Generator { GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }), _ => None, }; - Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail } + Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false, detail } + } + + /// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over + /// `softness`, inverted if asked, then shifted by `offset` (a non-finite offset counts as 0). + pub fn shape(&self, s: f32) -> f32 { + let th = 1.0 - self.level.clamp(0.0, 1.0); + let soft = self.softness.max(1e-3); + let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0); + let v = t * t * (3.0 - 2.0 * t); + let v = if self.invert { 1.0 - v } else { v }; + let offset = if self.offset.is_finite() { self.offset } else { 0.0 }; + (v + offset).clamp(0.0, 1.0) } } @@ -1065,6 +1080,30 @@ impl Effect { mod tests { use super::*; + #[test] + fn generator_offset_shifts_the_mask_value() { + let mut g = Generator::new(GeneratorKind::Position); + let base = g.shape(0.2); + assert!(base < 0.5); + g.offset = 0.3; + assert!((g.shape(0.2) - (base + 0.3)).abs() < 1e-6, "the offset is added"); + g.offset = 1.0; + assert_eq!(g.shape(0.2), 1.0, "and the result is clamped"); + g.offset = -1.0; + assert_eq!(g.shape(0.9), 0.0); + } + + #[test] + fn generator_non_finite_offset_counts_as_zero() { + let mut g = Generator::new(GeneratorKind::Position); + let base: Vec = [0.0, 0.2, 0.5, 0.9].iter().map(|&s| g.shape(s)).collect(); + for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { + g.offset = bad; + let got: Vec = [0.0, 0.2, 0.5, 0.9].iter().map(|&s| g.shape(s)).collect(); + assert_eq!(got, base, "offset {bad} behaves like 0"); + } + } + #[test] fn curvature_generators_saved_before_detail_sizes_load_without_them() { let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap(); diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 0ebfa070..2a83b3e1 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use texturecraft_paint::BrushSettings; -use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of}; +#[cfg(not(target_arch = "wasm32"))] +use texturecraft_paint::presets::with_stroke_of; +use texturecraft_paint::presets::{PRESETS, find_preset}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::tool_cmds::brush_json; diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 072f4071..d754fc70 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use texturecraft_core::{BlendMode, Channel, NormalFormat}; +use texturecraft_geom::glam::Vec3; use crate::{EngineError, Result, Session}; @@ -135,6 +136,14 @@ pub(crate) fn u64p(p: &Value, key: &str) -> Option { p.get(key).and_then(|v| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64))) } +/// A `[x, y, z]` param of finite numbers +pub(crate) fn vec3(params: &Value, key: &str) -> Option { + let [x, y, z] = params.get(key)?.as_array()?.as_slice() else { return None }; + let vector = Vec3::new(x.as_f64()? as f32, y.as_f64()? as f32, z.as_f64()? as f32); + + vector.is_finite().then_some(vector) +} + pub(crate) fn boolp(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_bool) } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index 85a62200..f1cecf11 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -5,7 +5,7 @@ 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 crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p}; +use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3}; use crate::tool_cmds::viewport_of; use crate::{Result, Session, StackTarget, cmd}; @@ -32,16 +32,6 @@ pub fn specs() -> Vec { ] } -/// A `[x, y, z]` param of finite numbers. -fn vec3(p: &Value, key: &str) -> Option { - let a = p.get(key)?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - match v.as_slice() { - [x, y, z] => Some(Vec3::new(*x, *y, *z)), - _ => None, - } -} - /// Resolve a viewport hit or explicit world position, using `texture_set` for explicit positions. /// Returns None when placement is optional and no position or viewport point is given. fn placement(session: &Session, command: &str, params: &Value, texture_set: usize, optional: bool) -> Result> { @@ -136,7 +126,7 @@ fn add(s: &mut Session, p: &Value) -> Result { // A decal dropped on another texture set goes there and selects it, as a dropped material does if ts != s.ts() { - crate::set_cmds::select_set(s, ts); + crate::set_cmds::select_set(s, ts)?; } let base = strp(p, "name") diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ae2f00b5..a728fd6c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -3,8 +3,8 @@ use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] -use texturecraft_core::PROJECT_EXT; -use texturecraft_core::{NormalFormat, Project, TextureSet}; +use texturecraft_core::{NormalFormat, PROJECT_EXT}; +use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 2db27946..233e9f4c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -71,7 +71,7 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value { /// A generator's settings, with its curvature mode and detail size weights when it has them. fn generator_json(generator: &Generator) -> Value { - let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert }); + let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert }); if let Some(detail) = &generator.detail { out["mode"] = json!(format!("{:?}", detail.mode)); out["sizes"] = json!(detail.weights); diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 747d7da1..36cd090c 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -168,6 +168,12 @@ fn group(s: &mut Session, p: &Value) -> Result { fn select(s: &mut Session, p: &Value) -> Result { 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()?; + } + s.active_set = ts; s.selected.insert(ts, id); s.target = match p.get("target") { @@ -184,6 +190,7 @@ fn select(s: &mut Session, p: &Value) -> Result { }, None => StackTarget::Content, }; + s.revision = s.revision.wrapping_add(1); Ok(json!({ "layer": id.0, "textureSet": ts })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4c68518a..a8ea034a 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -37,6 +37,7 @@ pub mod meshmap_import_cmds; mod orb_camera; pub mod orb_preview; pub mod painting; +mod path_draft; pub mod path_tool; mod polygon_fill; mod polygon_fill_drag; diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 7829efd2..36daf9a3 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -8,7 +8,9 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use texturecraft_core::{BakedMap, Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source}; -use texturecraft_formats::mcmat::{MCMAT_EXT, MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; +#[cfg(not(target_arch = "wasm32"))] +use texturecraft_formats::mcmat::MCMAT_EXT; +use texturecraft_formats::mcmat::{MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp}; use crate::materials::Place; diff --git a/crates/engine/src/mask_cmds.rs b/crates/engine/src/mask_cmds.rs index 9ff760f3..d47644de 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -49,7 +49,7 @@ pub fn specs() -> Vec { "Add generator", ["Layers", "Effects"], None, - "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", + "{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}", has_layer, add_generator ), @@ -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), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, 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), level?, softness?, noise?, noiseScale?, offset? (a mesh-map generator's), invert?, mode?, sizes?, 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)}", has_layer, set ), @@ -339,6 +339,9 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R if let Some(noise) = f32p(params, "noise") { generator.noise_amount = noise.clamp(0.0, 2.0); } + if let Some(offset) = f32p(params, "offset") { + generator.offset = offset.clamp(-1.0, 1.0); + } if let Some(noise_scale) = f32p(params, "noiseScale") { generator.noise_scale = noise_scale.clamp(0.01, 1000.0); } diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 06c5ba75..68792d5c 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -14,7 +14,9 @@ use serde_json::{Value, json}; use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source}; use texturecraft_formats::materialx_read::{Material, Value as Mtlx}; -use crate::commands::{CommandSpec, always, bad, strp}; +use crate::commands::{CommandSpec, always}; +#[cfg(not(target_arch = "wasm32"))] +use crate::commands::{bad, strp}; use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { diff --git a/crates/engine/src/path_draft.rs b/crates/engine/src/path_draft.rs new file mode 100644 index 00000000..6322a7dc --- /dev/null +++ b/crates/engine/src/path_draft.rs @@ -0,0 +1,13 @@ +//! A new Path tool path previewed in the document before it is applied + +use serde_json::Value; + +use crate::Document; + +/// A new path previewed in the document before it is applied +pub(crate) struct PathDraft { + /// The document before the preview + pub(crate) base: Document, + /// What painting the preview last reported (the commit's report when nothing changed since) + pub(crate) painted: Value, +} diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 150a103e..1607636c 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,56 +7,108 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_compose::{PaintTarget, PixelStore}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; -use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; +use crate::path_draft::PathDraft; use crate::session::{StackTarget, Tool}; use crate::tool_cmds::{points_param, set_tool, viewport_of}; -use crate::{EngineError, Result, Session, cmd}; +use crate::{Document, EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// The undo step that adds a new path +pub(crate) const NEW_PATH_LABEL: &str = "Path"; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; +/// A stored path's viewport is clamped to this range (pixels per side) before painting from it +const MIN_PAINT_VIEWPORT_PX: f32 = 16.0; +const MAX_PAINT_VIEWPORT_PX: f32 = 16384.0; +/// Sampling step of a 3D path's curve on the mesh for the views, in its paint viewport pixels +const SURFACE_STEP_PX: f32 = 4.0; const MIN_PROJECTIVE_W: f32 = 1e-6; +// Match the minimum world-space scale used by brush stamps +const MIN_BRUSH_SCALE: f32 = 1e-4; // Allow ray hits to differ slightly from transformed texel positions const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001; -/// The curve being edited with the Path tool. +/// The curve being edited with the Path tool #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PathState { - /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view). + /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view) pub points: Vec, - /// The points are texture coordinates (placed in the 2D view). + /// The points are texture coordinates (placed in the 2D view) pub uv: bool, - /// The curve loops back to its first point. + /// The curve loops back to its first point pub closed: bool, - /// A closed path fills its interior instead of stroking the curve. + /// A closed path fills its interior instead of stroking the curve pub fill: bool, - /// The stored path being edited: (path sublayer, index). Changes repaint it live. + /// The stored path being edited: (path sublayer, index). Changes repaint it live #[serde(default)] pub editing: Option<(LayerId, usize)>, - /// This edit has already repainted: later changes join its undo step, not an earlier edit's. + /// This edit has already repainted: later changes join its undo step, not an earlier edit's #[serde(default)] pub edited: bool, + /// The selected control point (drawn in the accent color; Backspace or Remove point removes it) + #[serde(default)] + pub selected: Option, } impl PathState { /// Append a control point; a point placed in the other view starts a new path. - pub fn push(&mut self, p: Vec3, uv: bool) { + pub fn push(&mut self, point: Vec3, uv: bool) { if uv != self.uv { self.points.clear(); self.uv = uv; } if self.points.len() < MAX_PATH_POINTS { - self.points.push(p); + self.points.push(point); + } + } + + /// 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 { + return None; + } + + self.points.insert(at, point); + 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) + } + + /// Empty the tool for the next path: no points, open, nothing selected or edited + pub fn clear(&mut self) { + self.points.clear(); + self.closed = false; + self.selected = None; + self.editing = None; + self.edited = false; + } + + /// Remove the selected control point, or the last one when none is selected + pub fn remove_selected(&mut self) { + 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.closed && self.points.len() < 3 { + self.closed = false; } } } @@ -116,31 +168,35 @@ 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"; if s.tool.tool != Tool::Path { set_tool(s, Tool::Path)?; } - let vp = viewport_of(s, p); + + let viewport = viewport_of(s, p); if boolp(p, "clear") == Some(true) { - s.tool.path.points.clear(); - s.tool.path.editing = None; + s.cancel_path(); } + let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { - (Some(pts), _) => Some(( - pts.iter() + (Some(pixels), _) => Some(( + pixels + .iter() .enumerate() - .map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) + .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(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), + (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.uv = uv; } @@ -151,19 +207,21 @@ fn path(s: &mut Session, p: &Value) -> Result { s.tool.path.fill = v; } s.revision = s.revision.wrapping_add(1); + let committed = if boolp(p, "commit") == Some(true) { - let r = s.commit_path(vp)?; + let report = s.commit_path(viewport)?; s.update(); - r + report } else { - if s.path_live()? { + if s.path_live_in_view(viewport)? { s.update(); } Value::Null }; - let st = &s.tool.path; - let editing = st.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); - Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "editing": editing, "committed": committed })) + + let path = &s.tool.path; + let editing = path.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); + Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed })) } /// The `effect` and `index` params naming a stored path, with the path. @@ -177,20 +235,25 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh Ok((eid, i, shape)) } +/// Finish any draft and load a stored path's geometry and paint settings for live editing fn edit_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.edit"; let (eid, index, shape) = path_ref(s, CMD, p)?; let paint = read_paint(&shape)?; + + s.finish_path()?; set_tool(s, Tool::Path)?; s.tool.brush = paint.brush; s.tool.values = paint.values; s.tool.enabled = paint.enabled; s.tool.mask_value = paint.mask_value; s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) }; + s.path_steps = Default::default(); s.target = StackTarget::Effect(eid); Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) } +/// Remove one stored curve and repaint its sublayer as an atomic document edit fn remove_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.remove"; let (eid, index, _) = path_ref(s, CMD, p)?; @@ -216,10 +279,46 @@ fn read_paint(shape: &PathShape) -> Result { Ok(paint) } -/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]). +/// 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, editing: None, edited: false } + PathState { points, 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) +fn changed_tiles(before: &PixelStore, after: &PixelStore, eid: LayerId) -> BTreeSet<(u32, u32)> { + let (before_images, after_images) = (sublayer_images(before, eid), sublayer_images(after, eid)); + let channels: BTreeSet> = before_images.keys().chain(after_images.keys()).copied().collect(); + + let mut tiles = BTreeSet::new(); + for channel in channels { + let (before_image, after_image) = (before_images.get(&channel), after_images.get(&channel)); + let Some(image) = before_image.or(after_image) else { continue }; + for ty in 0..image.tiles_y() { + for tx in 0..image.tiles_x() { + let same = match (before_image.and_then(|i| i.tile_handle(tx, ty)), after_image.and_then(|i| i.tile_handle(tx, ty))) { + (None, None) => true, + (Some(before_tile), Some(after_tile)) => Arc::ptr_eq(before_tile, after_tile), + _ => false, + }; + if !same { + tiles.insert((tx, ty)); + } + } + } + } + tiles +} + +/// Sublayer `eid`'s images by channel (None: its mask image) +fn sublayer_images(pixels: &PixelStore, eid: LayerId) -> BTreeMap, &TileImage> { + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, channel), image)| (Some(*channel), image)); + layers.chain(pixels.masks.get(&eid).map(|mask| (None, mask))).collect() +} + +/// The camera and viewport a stored path paints through (the views draw its curve the same way) +fn paint_view(shape: &PathShape, paint: &PathPaint) -> (OrbitCamera, Vec2) { + (paint.camera, Vec2::from_array(shape.viewport).max(Vec2::splat(MIN_PAINT_VIEWPORT_PX)).min(Vec2::splat(MAX_PAINT_VIEWPORT_PX))) } /// NDC (y up) to viewport pixels (origin top-left). @@ -235,10 +334,16 @@ impl Session { if path.uv { return path.points.iter().map(|p| Some(p.truncate())).collect(); } + let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect() } + /// The stored paths of path sublayer `eid` as Path tool states, for the views to draw + pub fn stored_path_states(&self, eid: LayerId) -> Vec { + self.paths(eid).unwrap_or_default().iter().map(state_of).collect() + } + /// The stored paths of path sublayer `eid` (None if it isn't one). pub fn paths(&self, eid: LayerId) -> Option<&[PathShape]> { match self.doc.project.effect(eid) { @@ -261,12 +366,36 @@ impl Session { } } - /// Store the Path tool's curve (a new path in the selected path sublayer, or in a new one; - /// or the path being edited) and repaint the sublayer, as one undo step. Clears the tool. + /// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool pub fn commit_path(&mut self, viewport: Vec2) -> Result { + if let Some((effect, index)) = self.tool.path.editing + && self.paths(effect).and_then(|paths| paths.get(index)).is_some_and(|stored| self.same_as_stored(stored)) + { + // Camera navigation alone must not replace the pixels the user just previewed + let mut report = match self.path_draft.take() { + Some(draft) => { + self.push_step(NEW_PATH_LABEL, draft.base, false); + draft.painted + } + None => json!({}), + }; + report["effect"] = json!(effect.0); + report["index"] = json!(index); + self.target = StackTarget::Effect(effect); + self.cancel_path(); + return Ok(report); + } + + if let Some(draft) = self.path_draft.take() { + // Changed settings paint again from the document before the preview + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + self.tool.path.editing = None; + } + let shape = self.path_shape(self.camera, viewport); let editing = self.tool.path.editing; - let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1)); + let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1)); let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| { let (eid, index) = match editing { Some(at) => at, @@ -274,49 +403,309 @@ impl Session { }; s.put_path(eid, index, shape) })?; + if let Some(eid) = out.get("effect").and_then(Value::as_u64) { self.target = StackTarget::Effect(LayerId(eid)); } - self.tool.path.points.clear(); - self.tool.path.editing = None; + self.tool.path.clear(); + Ok(out) } - /// While a stored path is edited, repaint its sublayer when the tool's points, brush or - /// material changed (orbiting or resizing the view alone doesn't), merged into one undo - /// step. Cheap when nothing changed; the UI calls it every frame. Returns whether it - /// repainted. + /// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame pub fn path_live(&mut self) -> Result { - let Some((eid, index)) = self.tool.path.editing else { return Ok(false) }; - let Some(stored) = self.paths(eid).and_then(|v| v.get(index)).cloned() else { - self.stop_path_edit(); - return Ok(false); + self.path_live_in_view(self.viewport) + } + + /// Compare curve and typed paint settings through the stored camera and viewport + fn same_as_stored(&self, stored: &PathShape) -> bool { + // 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) + && read_paint(¤t).is_ok_and(|current_paint| current_paint == paint) + }) + } + + /// Preview a command's points in its supplied viewport, or the UI's current viewport + fn path_live_in_view(&mut self, viewport: Vec2) -> Result { + let stored = match self.tool.path.editing { + Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() { + Some(shape) => Some((eid, index, shape)), + None => { + self.stop_path_edit(); + return Ok(false); + } + }, + None => None, }; + + if self.tool.tool != Tool::Path || self.stroke.is_some() { + return Ok(false); + } + + if self.tool.path.points.is_empty() { + if let Some((effect, index, _)) = stored { + 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.cancel_path(); + } + return Ok(true); + } + return Ok(false); + } + let path = &self.tool.path; - if self.tool.tool != Tool::Path || self.stroke.is_some() || path.points.is_empty() || (path.closed && path.fill && path.points.len() < 3) { + if path.closed && path.fill && path.points.len() < 3 { return Ok(false); } - // Typed comparison: the stored settings went through JSON (f64), maybe a save and load. - let unchanged = read_paint(&stored).is_ok_and(|p| { - let now = self.path_shape(p.camera, Vec2::from_array(stored.viewport)); - (&now.points, now.uv, now.closed, now.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) && read_paint(&now).is_ok_and(|n| n == p) - }); - if unchanged { + + let Some((eid, index, stored)) = stored else { return self.start_path_draft(viewport) }; + + if self.same_as_stored(&stored) { return Ok(false); } - let shape = self.path_shape(self.camera, self.viewport); - self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |s| s.put_path(eid, index, shape))?; - self.tool.path.edited = true; + + let shape = self.path_shape(self.camera, viewport); + let (painted, before) = self.repaint_path(eid, index, shape)?; + match &mut self.path_draft { + Some(draft) => draft.painted = painted, + 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.path_steps = steps; + self.tool.path.edited = true; + } + } Ok(true) } - /// Stop editing a stored path (its changes are already applied) and clear the tool. - pub fn stop_path_edit(&mut self) { - if self.tool.path.editing.take().is_some() { - self.tool.path.points.clear(); + /// Paint a new path's first preview where [`Session::commit_path`] would add it, keeping the document before it for apply and cancel + fn start_path_draft(&mut self, viewport: Vec2) -> Result { + let base = self.doc.clone(); + let shape = self.path_shape(self.camera, viewport); + let placed = self.path_effect().and_then(|eid| { + let index = self.paths(eid).map_or(0, <[_]>::len); + self.put_path(eid, index, shape).map(|painted| ((eid, index), painted)) + }); + match placed { + Ok((at, painted)) => { + // Placing a path is a new action: what was undone before can't be redone over it + self.redo.clear(); + self.tool.path.editing = Some(at); + self.changed_without_history(&base); + self.path_draft = Some(PathDraft { base, painted }); + Ok(true) + } + Err(e) => { + self.doc = base; + Err(e) + } } } + /// Remember the curve before a point change from a view, so undo steps back through those changes while the path is edited + pub fn path_checkpoint(&mut self) { + if !self.path_steps.0.last().is_some_and(|s| s.same_curve(&self.tool.path)) { + self.path_steps.0.push(self.tool.path.clone()); + // Each snapshot can contain thousands of points; bound point history like document history + let excess = self.path_steps.0.len().saturating_sub(crate::session::MAX_HISTORY); + self.path_steps.0.drain(..excess); + self.path_steps.1.clear(); + } + } + + /// Select a point without changing its geometry or clearing redo + pub fn select_path_point(&mut self, index: usize) { + self.tool.path.selected = (index < self.tool.path.points.len()).then_some(index); + } + + /// Append and select a point, checkpointing the curve before it changes + pub fn append_path_point(&mut self, point: Vec3, uv: bool) -> Option { + if !point.is_finite() || (self.tool.path.uv == uv && self.tool.path.points.len() >= MAX_PATH_POINTS) { + return None; + } + + // A click in the other view must not replace a committed path's coordinate space + if self.tool.path.editing.is_some() && self.path_draft.is_none() && self.tool.path.uv != uv { + return None; + } + + self.path_checkpoint(); + self.tool.path.push(point, uv); + self.tool.path.selected = self.tool.path.points.len().checked_sub(1); + self.tool.path.selected + } + + /// Insert and select a point as one undoable point edit + pub fn insert_path_point(&mut self, index: usize, point: Vec3) -> Option { + if !point.is_finite() || index > self.tool.path.points.len() || self.tool.path.points.len() >= MAX_PATH_POINTS { + return None; + } + + self.path_checkpoint(); + self.tool.path.insert(index, point) + } + + /// Move a point, checkpointing only the first actual movement in a drag + pub fn move_path_point(&mut self, index: usize, point: Vec3, begin_drag: bool) -> bool { + if !point.is_finite() || self.tool.path.points.get(index).is_none_or(|current| *current == point) { + return false; + } + + if begin_drag { + self.path_checkpoint(); + } + if let Some(current) = self.tool.path.points.get_mut(index) { + *current = point; + } + true + } + + /// Remove the selected point, or the last one, as one undoable point edit + pub fn remove_selected_path_point(&mut self) { + if self.tool.path.points.is_empty() { + return; + } + + self.path_checkpoint(); + self.tool.path.remove_selected(); + } + + /// 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 { + self.path_checkpoint(); + self.tool.path.closed = closed; + } + } + + /// Change whether a closed path fills its interior, with point undo + pub fn set_path_fill(&mut self, fill: bool) { + if self.tool.path.fill != fill { + self.path_checkpoint(); + self.tool.path.fill = fill; + } + } + + /// Whether [`Session::step_path`] would undo (`back`) or redo a point change + pub(crate) fn path_step_pending(&self, back: bool) -> bool { + let steps = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) + } + + /// Undo calls needed to move back through document history, including pending path operations. + /// With zero document steps, only an uncommitted draft is canceled; stored edits stay applied. + pub fn history_undo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 && self.path_draft.is_none() { + return 0; + } + + let (point_steps, clears_path) = self.path_steps_before_document(true); + let cancel_draft = self.path_draft.is_some() && !clears_path; + document_steps.saturating_add(point_steps).saturating_add(usize::from(cancel_draft)) + } + + /// Redo calls needed to move forward through document history, including pending point edits. + /// Unlike undo, document redo cancels any remaining draft in the same call. + pub fn history_redo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 { + return 0; + } + + document_steps.saturating_add(self.path_steps_before_document(false).0) + } + + /// Count pending point steps and whether their last step clears the path + fn path_steps_before_document(&self, back: bool) -> (usize, bool) { + if self.tool.tool != Tool::Path { + return (0, false); + } + + let states = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let mut steps = 0usize; + let mut current = &self.tool.path; + for state in states.iter().rev() { + if state.same_curve(current) { + continue; + } + + steps = steps.saturating_add(1); + + // Restoring an empty curve cancels the draft and clears point history in the same step + if state.points.is_empty() { + return (steps, true); + } + + current = state; + } + + (steps, false) + } + + /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history + pub(crate) fn step_path(&mut self, back: bool) -> Result { + if self.tool.tool != Tool::Path { + return Ok(false); + } + + // Skip no-change checkpoints without consuming history until the repaint succeeds + let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; + + let path = &mut self.tool.path; + let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() }); + if let Err(error) = self.path_live() { + self.tool.path = previous; + return Err(error); + } + + if self.tool.path.points.is_empty() { + self.stop_path_edit(); + } else { + let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; + from.truncate(index); + to.push(previous); + } + Ok(true) + } + + /// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes + pub fn finish_path(&mut self) -> Result<()> { + if self.path_draft.is_some() { + let viewport = self.viewport; + self.commit_path(viewport)?; + } + self.stop_path_edit(); + Ok(()) + } + + /// Cancel the Path tool's path: a new one's preview is removed, a stored one keeps its applied changes + pub fn cancel_path(&mut self) { + self.stop_path_edit(); + self.tool.path.clear(); + } + + /// Stop editing a stored path (its changes are already applied) and clear the tool; a new path's preview is removed + pub fn stop_path_edit(&mut self) { + if let Some(draft) = self.path_draft.take() { + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + } + if self.tool.path.editing.is_some() { + self.tool.path.clear(); + } + self.path_steps = Default::default(); + } + /// The selected path sublayer, or a new one on the selected layer's content or mask /// (whichever is selected). fn path_effect(&mut self) -> Result { @@ -346,6 +735,32 @@ impl Session { Ok(eid) } + /// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before + fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> { + let before = self.doc.clone(); + let painted = match self.put_path(eid, index, shape) { + Ok(v) => v, + Err(e) => { + self.doc = before; + return Err(e); + } + }; + + // Paths paint into the active set; a sublayer in another set recomposites in full + let project = &self.doc.project; + let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts); + if set == Some(self.ts()) { + // Content or mask, the sublayer's owner decides which sets redraw + let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid); + self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles); + } else { + self.invalidate_changed(&before); + } + self.revision = self.revision.wrapping_add(1); + self.modified = true; + Ok((painted, before)) + } + /// Replace path `index` of sublayer `eid` (append when out of range) and repaint the /// sublayer. Returns what painting that path reported, with the sublayer and index. fn put_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result { @@ -421,13 +836,41 @@ impl Session { fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; + let (camera, viewport) = paint_view(shape, &paint); self.tool.brush = paint.brush; self.tool.values = paint.values; self.tool.enabled = paint.enabled; self.tool.mask_value = paint.mask_value; - self.camera = paint.camera; + self.camera = camera; self.tool.path = state_of(shape); - self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0))) + 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) + pub fn path_surface(&self, points: &[Vec3], 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) + .into_iter() + .zip(&screen) + .map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect()) + .collect() + } + + /// [`Session::path_surface`] of a stored 3D path through the camera and viewport it paints with + pub fn stored_path_surface(&self, eid: LayerId, index: usize) -> Option>>> { + let shape = self.paths(eid)?.get(index)?; + if shape.uv { + return None; + } + + 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)) } /// Paint the Path tool's curve with the current brush (or fill it when closed and filled) @@ -452,74 +895,101 @@ impl Session { }) } - /// Fill the inside of `poly`: viewport pixels over the visible surface, or texture - /// coordinates. Returns the touched tiles. - fn lasso_fill(&mut self, poly: Vec, uv: bool, viewport: Vec2) -> Result { - let ts = self.ts(); - let (gbuf, mut canvas) = self.fill_canvas(ts)?; - let w = gbuf.width.max(1); + /// Fill the inside of `polygon` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles + fn lasso_fill(&mut self, polygon: Vec, uv: bool, viewport: Vec2) -> Result { + let texture_set = self.ts(); + let (uv_buffer, mut canvas) = self.fill_canvas(texture_set)?; + let width = uv_buffer.width.max(1); + if uv { - let lasso = Lasso::new(poly.iter().map(|p| *p * Vec2::new(w as f32, gbuf.height as f32)).collect()); - fill_coverage(&mut canvas, &gbuf, |i, _| lasso.coverage(Vec2::new((i as u32 % w) as f32 + 0.5, (i as u32 / w) as f32 + 0.5))); + let lasso = Lasso::new(polygon.iter().map(|point| *point * Vec2::new(width as f32, uv_buffer.height as f32)).collect()); + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { + lasso.coverage(Vec2::new((texel as u32 % width) as f32 + 0.5, (texel as u32 / width) as f32 + 0.5)) + }); } else { - let lasso = Lasso::new(poly); - let view_proj = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0)); - let inv = view_proj.inverse(); - let (cull, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh); + let lasso = Lasso::new(polygon); + let view_projection = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0)); + let inverse_view_projection = view_projection.inverse(); + let (mesh, bvh) = (&self.mesh, &self.bvh); + let brush = self.tool.brush.sanitized(); // A visible source inside the lasso can paint each symmetry copy - let (lo, hi) = mesh.bounds(); - let center = (lo + hi) * 0.5; - let inverses: Vec<_> = self.tool.brush.sanitized().symmetry.transforms().iter().map(|m| m.inverse()).collect(); + let (bounds_min, bounds_max) = mesh.bounds(); + let symmetry = brush.symmetry; + let symmetry_origin = symmetry.origin((bounds_min + bounds_max) * 0.5); + let inverses: Vec<_> = symmetry.transforms().iter().map(|transform| transform.inverse()).collect(); - fill_coverage(&mut canvas, &gbuf, |i, _| { - let Some(s) = gbuf.surface(mesh, i) else { return 0.0 }; + // Copies can leave the source surface, within the same depth allowed for brush stamps + let copy_depth = brush.size * (bounds_max - bounds_min).length().max(MIN_BRUSH_SCALE) * brush.depth; + let eye = self.camera.eye(); + let camera_distance = self.camera.distance.max(MIN_BRUSH_SCALE); + + // Bound the search using the farthest bounding-box corner; acceptance still uses the actual hit + let max_copy_depth = + if brush.screen_space { copy_depth * (bounds_min - eye).abs().max((bounds_max - eye).abs()).length() / camera_distance } else { copy_depth }; + + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { + let Some(surface) = uv_buffer.surface(mesh, texel) else { return 0.0 }; let mut best = 0.0f32; - for m in &inverses { - let pos = center + *m * (s.pos - center); - let c = view_proj * pos.extend(1.0); - if c.w <= MIN_PROJECTIVE_W { + for inverse in &inverses { + let position = symmetry_origin + *inverse * (surface.pos - symmetry_origin); + let clip = view_projection * position.extend(1.0); + if clip.w <= MIN_PROJECTIVE_W { continue; } - let ndc = Vec2::new(c.x, c.y) / c.w; - let a = lasso.coverage(to_pixels(ndc, viewport)); - if a <= best { + + let normalized_screen = Vec2::new(clip.x, clip.y) / clip.w; + let coverage = lasso.coverage(to_pixels(normalized_screen, viewport)); + if coverage <= best { continue; } // Use the source surface normal; a copy may face away from the camera - let o = inv * ndc.extend(0.0).extend(1.0); - let origin = o.truncate() / o.w; - let to = pos - origin; - let d = to.length(); - let Some(dir) = to.try_normalize() else { continue }; - let Some(hit) = - bvh.closest(origin, dir, d * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)).filter(|hit| hit.t >= d * (1.0 - RAY_HIT_RELATIVE_TOLERANCE)) - else { - continue; + let near_clip = inverse_view_projection * normalized_screen.extend(0.0).extend(1.0); + let origin = near_clip.truncate() / near_clip.w; + let to_surface = position - origin; + let distance = to_surface.length(); + let Some(direction) = to_surface.try_normalize() else { continue }; + let is_copy = *inverse != Mat3::IDENTITY; + let max_distance = distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE); + let search_depth = if is_copy { max_copy_depth } else { 0.0 }; + let Some(hit) = bvh.closest(origin, direction, max_distance + search_depth) else { continue }; + + // Keep identity copies exact and reject occluders beyond the bounded displacement + let off_surface = if !is_copy { + 0.0 + } else if brush.screen_space { + copy_depth * (origin + direction * hit.t).distance(eye) / camera_distance + } else { + copy_depth }; - - let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue }; - - if cull && source.nrm.dot(dir) >= 0.0 { + if hit.t < distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE) - off_surface || hit.t > max_distance + off_surface { continue; } - best = a; + let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue }; + + if brush.backface_culling && source.nrm.dot(direction) >= 0.0 { + continue; + } + + best = coverage; } best }); } + let tiles = canvas.dirty.len(); - self.commit_fill("Path fill", ts, &canvas)?; + self.commit_fill("Path fill", texture_set, &canvas)?; Ok(tiles) } } #[cfg(test)] mod tests { + use super::*; use serde_json::json; use crate::{Session, execute}; @@ -556,4 +1026,94 @@ mod tests { assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); } + + #[test] + fn point_insertion_and_removal_respect_boundaries() { + let mut path = PathState { points: vec![Vec3::ZERO, Vec3::X], ..Default::default() }; + + assert_eq!(path.insert(2, Vec3::Y), Some(2)); + assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X, Vec3::Y]); + assert_eq!(path.insert(4, Vec3::Z), None); + path.closed = true; + path.selected = Some(usize::MAX); + path.remove_selected(); + assert_eq!(path.points, vec![Vec3::ZERO, Vec3::X]); + assert!(!path.closed); + path.remove_selected(); + path.remove_selected(); + path.remove_selected(); + assert!(path.points.is_empty()); + assert_eq!(path.selected, None); + + path.points = vec![Vec3::ZERO; MAX_PATH_POINTS]; + assert_eq!(path.insert(MAX_PATH_POINTS, Vec3::X), None); + assert_eq!(path.points.len(), MAX_PATH_POINTS); + } + + #[test] + fn changed_tiles_include_mask_and_channel_creation_and_deletion() { + let effect = LayerId(7); + let mut before = PixelStore::default(); + let mut image = TileImage::new(192, 128, 1); + image.tile_mut(0, 0, &[1]).unwrap(); + before.masks.insert(effect, image.clone()); + before.layers.insert((effect, Channel::Roughness), image.clone()); + let mut after = before.clone(); + after.masks.get_mut(&effect).unwrap().set_tile(0, 0, None); + after.masks.get_mut(&effect).unwrap().tile_mut(2, 1, &[1]).unwrap(); + after.layers.remove(&(effect, Channel::Roughness)); + image.set_tile(0, 0, None); + image.tile_mut(1, 0, &[1]).unwrap(); + after.layers.insert((effect, Channel::Metallic), image); + + assert_eq!(changed_tiles(&before, &before.clone(), effect), BTreeSet::new()); + assert_eq!(changed_tiles(&before, &after, effect), BTreeSet::from([(0, 0), (1, 0), (2, 1)])); + assert_eq!(changed_tiles(&before, &after, LayerId(8)), BTreeSet::new()); + } + + #[test] + fn point_checkpoints_skip_noops_and_bound_retained_points() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:test", None, 128).unwrap(); + session.tool.tool = Tool::Path; + session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS]; + session.path_checkpoint(); + assert!(!session.path_step_pending(true)); + assert!(!session.step_path(true).unwrap()); + + for index in 0..crate::session::MAX_HISTORY + 10 { + session.path_checkpoint(); + session.tool.path.points[0].x = index as f32 + 1.0; + } + + assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY); + assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::(), crate::session::MAX_HISTORY * MAX_PATH_POINTS); + session.path_checkpoint(); + assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo"); + assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32); + } + + #[test] + fn stored_surface_uses_bounded_viewports_and_skips_uv_paths() { + let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let StackTarget::Effect(effect) = session.target else { panic!("path sublayer") }; + assert!(session.stored_path_surface(effect, 0).is_none()); + let shape = session.paths(effect).unwrap()[0].clone(); + let paint = read_paint(&shape).unwrap(); + let mut shape = shape; + shape.viewport = [-1.0, f32::MAX]; + assert_eq!(paint_view(&shape, &paint).1, Vec2::new(MIN_PAINT_VIEWPORT_PX, MAX_PAINT_VIEWPORT_PX)); + + let points = [Vec3::new(-0.2, 0.0, 1.0), Vec3::new(0.0, 0.2, 1.0), Vec3::new(0.2, 0.0, 1.0)]; + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + let surface = session.path_surface(&points, true, session.camera, Vec2::splat(400.0)); + assert_eq!(surface.len(), 3); + let first = surface.first().unwrap().first().unwrap().unwrap(); + let last = surface.last().unwrap().last().unwrap().unwrap(); + assert!(first.distance(last) < 1e-5, "the closed curve returns to its starting surface point"); + let off_mesh = session.path_surface(&[Vec3::new(10.0, 0.0, 0.0), Vec3::new(11.0, 0.0, 0.0)], false, session.camera, Vec2::splat(400.0)); + assert!(!off_mesh.is_empty()); + assert!(off_mesh.iter().flatten().all(Option::is_none)); + } } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 64ebec69..41bfacbb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -356,6 +356,10 @@ pub struct Session { pub(crate) painting_paths: bool, /// Pixels of the paths below the one being edited, so live edits skip repainting them. pub(crate) path_cache: Option, + /// A new path's live preview: the path becomes an undo step only when it is applied + pub(crate) path_draft: Option, + /// Point changes of the path being edited: (earlier states for undo, undone states for redo) + pub(crate) path_steps: (Vec, Vec), pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -374,8 +378,7 @@ pub struct Session { } impl Session { - /// A session for `project` on `mesh` (texture sets must reference mesh materials). The - /// UVs of UV-tiled sets are mapped into their tile atlas (see [`Session::source_mesh`]). + /// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`]) pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result { mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?; let source = Arc::new(mesh); @@ -413,6 +416,8 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_draft: None, + path_steps: Default::default(), path: None, modified: false, revision: 1, @@ -529,21 +534,43 @@ impl Session { self.record(label, before, false); } - /// A change from `before` to the current document: a new undo step `label`, or with - /// `merge` part of the previous one when it has the same label. + /// A change from `before`: a new undo step `label`, or with `merge` part of the previous one when it has the same label fn record(&mut self, label: &str, before: Document, merge: bool) { + self.invalidate_changed(&before); + self.push_step(label, before, merge); + } + + /// [`Session::record`] for a change whose tiles the caller already marked for recompositing + pub(crate) fn push_step(&mut self, label: &str, before: Document, merge: bool) { + // Another change during a new path's preview makes the path its own step first + if !self.painting_paths + && let Some(draft) = self.path_draft.take() + { + self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base)); + } + + // Point changes of an edited path undo only until another step lands + if !self.painting_paths { + self.path_steps = Default::default(); + } + self.modified = true; self.revision = self.revision.wrapping_add(1); - self.invalidate_changed(&before); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); - if self.undo.len() > MAX_HISTORY { - self.undo.remove(0); - } } + let over = self.undo.len().saturating_sub(MAX_HISTORY); + self.undo.drain(..over); self.redo.clear(); } + /// A change from `other` to the current document that is not an undo step (a path preview) + pub(crate) fn changed_without_history(&mut self, other: &Document) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + self.invalidate_changed(other); + } + /// Mark dirty every texture set whose composite differs between `other` and the current /// document (after an edit, undo or redo). pub(crate) fn invalidate_changed(&mut self, other: &Document) { @@ -620,18 +647,32 @@ impl Session { } } + /// Whether a point edit, an uncommitted path preview, or a document edit can be undone pub fn can_undo(&self) -> bool { - !self.undo.is_empty() + !self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true) } + + /// Whether a point edit or document edit can be restored pub fn can_redo(&self) -> bool { - !self.redo.is_empty() + !self.redo.is_empty() || self.path_step_pending(false) } + + /// Label of the next undo action, giving an active path's point edits and preview priority pub fn undo_label(&self) -> Option<&str> { + if self.path_draft.is_some() || self.path_step_pending(true) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.undo.last().map(|(l, _)| l.as_str()) } + + /// Label of the next redo action, giving an active path's point history priority pub fn redo_label(&self) -> Option<&str> { + if self.path_step_pending(false) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. pub fn redo_labels(&self) -> Vec { self.redo.iter().rev().map(|(l, _)| l.clone()).collect() @@ -640,10 +681,23 @@ impl Session { self.undo.iter().map(|(l, _)| l.clone()).collect() } + /// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order pub fn undo(&mut self) -> Result { // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); self.end_polygon_fill_box(); + + // While a path is edited, undo steps back through its point changes first + if self.step_path(true)? { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // A path being placed isn't a step yet: undo removes it + if self.path_draft.is_some() { + self.stop_path_edit(); + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + self.stop_path_edit(); let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; @@ -654,10 +708,16 @@ impl Session { Ok(label) } + /// Restore a point edit and its pixels before considering document redo pub fn redo(&mut self) -> Result { // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); self.end_polygon_fill_box(); + + if self.step_path(false)? { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + self.stop_path_edit(); let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 3f394e23..a0bf6b6d 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -79,16 +79,23 @@ fn select(s: &mut Session, p: &Value) -> Result { .map(|index| index as usize) .filter(|index| *index < s.set_count()) .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; - select_set(s, ts); + select_set(s, ts)?; Ok(json!({ "ts": ts })) } /// Make texture set `ts` the active one, on its content stack -pub(crate) fn select_set(s: &mut Session, ts: usize) { +pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { s.cancel_stroke(); + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); + Ok(()) } fn resolution(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index fbc4705b..7f39bd2a 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -25,6 +25,7 @@ pub fn specs() -> Vec { /// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; /// Families tried, in order, when no font is asked for. +#[cfg(not(target_arch = "wasm32"))] const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]; /// Largest font file read. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 6134c9d5..6a390866 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -4,9 +4,9 @@ use serde_json::{Value, json}; use texturecraft_core::Channel; use texturecraft_geom::glam::Vec2; -use texturecraft_paint::{Alignment, BrushAlpha, alphas}; +use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas}; -use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3}; use crate::fill_hit_test::FillHitTest; use crate::fill_mode::FillMode; use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; @@ -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?, symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), 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)}, 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}}", always, brush ), @@ -128,126 +128,159 @@ fn select(s: &mut Session, p: &Value) -> Result { set_tool(s, t) } -/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers. -fn brush(s: &mut Session, p: &Value) -> Result { - let b = &mut s.tool.brush; - let pct = |k: &str| f32p(p, k).map(|v| v / 100.0); - if let Some(v) = pct("size") { - b.size = v * 0.25; +/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers +fn brush(session: &mut Session, params: &Value) -> Result { + let mut settings = session.tool.brush.clone(); + let percent = |key: &str| f32p(params, key).map(|value| value / 100.0); + + if let Some(value) = percent("size") { + settings.size = value * 0.25; } - if let Some(v) = pct("minSize") { - b.min_size = v; + if let Some(value) = percent("minSize") { + settings.min_size = value; } - if let Some(v) = pct("flow") { - b.flow = v; + + if let Some(value) = percent("flow") { + settings.flow = value; } - if let Some(v) = pct("opacity") { - b.opacity = v; + if let Some(value) = percent("opacity") { + settings.opacity = value; } - if let Some(v) = pct("spacing") { - b.spacing = v; + if let Some(value) = percent("spacing") { + settings.spacing = value; } - if let Some(v) = pct("hardness") { - b.hardness = v; + if let Some(value) = percent("hardness") { + settings.hardness = value; } - if let Some(v) = f32p(p, "angle") { - b.angle = v; + + if let Some(value) = f32p(params, "angle") { + settings.angle = value; } - if let Some(v) = boolp(p, "followPath") { - b.follow_path = v; + if let Some(value) = boolp(params, "followPath") { + settings.follow_path = value; } - if let Some(a) = strp(p, "alignment") { - b.alignment = match a { + if let Some(alignment) = strp(params, "alignment") { + settings.alignment = match alignment { "camera" => Alignment::Camera, "tangent" | "uv" => Alignment::Tangent, other => return Err(bad("tool.brush", format!("unknown alignment `{other}`"))), }; } - if let Some(v) = f32p(p, "lazy") { - b.lazy = v; + + if let Some(value) = f32p(params, "lazy") { + settings.lazy = value; } - for (k, slot) in [("jitterSize", &mut b.jitter_size), ("jitterAngle", &mut b.jitter_angle), ("jitterFlow", &mut b.jitter_flow)] { - if let Some(v) = f32p(p, k) { - *slot = v / 100.0; + + for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] { + if let Some(value) = f32p(params, key) { + *slot = value / 100.0; } } - if let Some(v) = f32p(p, "jitterPosition") { - b.jitter_position = v / 100.0; + if let Some(value) = f32p(params, "jitterPosition") { + settings.jitter_position = value / 100.0; } - let alpha = p.get("alpha"); - if let Some(a) = strp(p, "alpha") { - b.alpha = BrushAlpha::parse(a).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{a}`")))?; - (b.alpha_image, b.alpha_library) = (None, None); - } else if let Some(name) = alpha.and_then(|a| a.get("image")).and_then(Value::as_str) { - if !s.images.contains_key(name) { + + let alpha = params.get("alpha"); + if let Some(alpha_name) = strp(params, "alpha") { + settings.alpha = BrushAlpha::parse(alpha_name).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{alpha_name}`")))?; + (settings.alpha_image, settings.alpha_library) = (None, None); + } else if let Some(name) = alpha.and_then(|alpha| alpha.get("image")).and_then(Value::as_str) { + if !session.images.contains_key(name) { return Err(bad("tool.brush", format!("no image resource `{name}` (import it first)"))); } - (b.alpha_image, b.alpha_library) = (Some(name.to_string()), None); - } else if let Some(id) = alpha.and_then(|a| a.get("library")).and_then(Value::as_str) { - let a = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?; - // Render it now rather than on the first stamp. - a.image(); - (b.alpha_image, b.alpha_library) = (None, Some(a.id.clone())); + + (settings.alpha_image, settings.alpha_library) = (Some(name.to_string()), None); + } else if let Some(id) = alpha.and_then(|alpha| alpha.get("library")).and_then(Value::as_str) { + let alpha = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?; + + // Render it now rather than on the first stamp + alpha.image(); + (settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone())); } - if let Some(v) = boolp(p, "backfaceCulling") { - b.backface_culling = v; + + if let Some(value) = boolp(params, "backfaceCulling") { + settings.backface_culling = value; } - for (k, slot) in [("symmetryX", &mut b.symmetry.x), ("symmetryY", &mut b.symmetry.y), ("symmetryZ", &mut b.symmetry.z)] { - if let Some(v) = boolp(p, k) { - *slot = v; + + if let Some(value) = boolp(params, "symmetryOn") { + settings.symmetry.enabled = value; + } + + for (key, slot) in [("symmetryX", &mut settings.symmetry.x), ("symmetryY", &mut settings.symmetry.y), ("symmetryZ", &mut settings.symmetry.z)] { + if let Some(value) = boolp(params, key) { + *slot = value; } } - if let Some(v) = f32p(p, "symmetryRadial") { - b.symmetry.radial = v.clamp(0.0, 32.0) as u8; + + if let Some(value) = f32p(params, "symmetryRadial") { + settings.symmetry.radial = value.clamp(0.0, f32::from(MAX_RADIAL_COPIES)) as u8; } - if let Some(a) = strp(p, "symmetryAxis") { - b.symmetry.axis = match a.to_ascii_lowercase().as_str() { + + if let Some(axis) = strp(params, "symmetryAxis") { + settings.symmetry.axis = match axis.to_ascii_lowercase().as_str() { "x" => 0, "y" => 1, "z" => 2, - _ => return Err(bad("tool.brush", format!("unknown symmetry axis `{a}` (x, y or z)"))), + _ => return Err(bad("tool.brush", format!("unknown symmetry axis `{axis}` (x, y or z)"))), }; } - if let Some(v) = boolp(p, "screenSpace") { - b.screen_space = v; + + if let Some(value) = f32p(params, "symmetryAngleSpan") { + settings.symmetry.angle_span = value; } - if let Some(q) = p.get("particles") { - let pt = &mut b.particles; - pt.enabled = boolp(q, "enabled").unwrap_or(pt.enabled); - pt.count = f32p(q, "count").map_or(pt.count, |v| v as u32); - pt.lifetime = f32p(q, "lifetime").map_or(pt.lifetime, |v| v as u32); - pt.gravity = f32p(q, "gravity").unwrap_or(pt.gravity); + + if params.get("symmetryOffset").is_some() { + settings.symmetry.offset = vec3(params, "symmetryOffset").ok_or_else(|| bad("tool.brush", "`symmetryOffset` must be [x, y, z]"))?.to_array(); } - *b = b.sanitized(); - if let Some(v) = f32p(p, "smudgeStrength") { - s.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0); + + if let Some(value) = boolp(params, "screenSpace") { + settings.screen_space = value; } - if let Some(v) = strp(p, "cloneSource") { - s.tool.clone_from = match v { + + if let Some(particle_params) = params.get("particles") { + let particles = &mut settings.particles; + particles.enabled = boolp(particle_params, "enabled").unwrap_or(particles.enabled); + particles.count = f32p(particle_params, "count").map_or(particles.count, |value| value as u32); + particles.lifetime = f32p(particle_params, "lifetime").map_or(particles.lifetime, |value| value as u32); + particles.gravity = f32p(particle_params, "gravity").unwrap_or(particles.gravity); + } + + let clone_from = if let Some(value) = strp(params, "cloneSource") { + match value { "composite" => CloneFrom::Composite, "layer" => CloneFrom::Layer, other => return Err(bad("tool.brush", format!("unknown clone source `{other}`: use composite or layer"))), - }; + } + } else { + session.tool.clone_from + }; + + session.tool.brush = settings.sanitized(); + session.tool.clone_from = clone_from; + if let Some(value) = f32p(params, "smudgeStrength") { + session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0); } - s.revision = s.revision.wrapping_add(1); - Ok(brush_json(s)) + + session.revision = session.revision.wrapping_add(1); + Ok(brush_json(session)) } -pub(crate) fn brush_json(s: &Session) -> Value { - let b = &s.tool.brush; +pub(crate) fn brush_json(session: &Session) -> Value { + let settings = &session.tool.brush; json!({ - "size": b.size / 0.25 * 100.0, "minSize": b.min_size * 100.0, "flow": b.flow * 100.0, "opacity": b.opacity * 100.0, - "spacing": b.spacing * 100.0, "hardness": b.hardness * 100.0, "angle": b.angle, "followPath": b.follow_path, - "alignment": format!("{:?}", b.alignment).to_lowercase(), "lazy": b.lazy, - "alpha": match (&b.alpha_image, &b.alpha_library) { + "size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0, + "spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path, + "alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy, + "alpha": match (&settings.alpha_image, &settings.alpha_library) { (Some(name), _) => json!({ "image": name }), (None, Some(id)) => json!({ "library": id }), - (None, None) => json!(b.alpha.label()), + (None, None) => json!(settings.alpha.label()), }, - "backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z], - "radialSymmetry": { "copies": b.symmetry.radial, "axis": (["x", "y", "z"].get(b.symmetry.axis as usize)) }, - "smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles, - "cloneSource": if s.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, + "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, + "cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, }) } diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 43d22bfa..e6157332 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -17,6 +17,7 @@ mod materialx; mod materialx_import; mod meshmap_import; mod painter_gaps; +mod path_perf; mod path_tool; mod perf; mod polygon_fill; @@ -26,3 +27,5 @@ mod thumbs; mod tools; mod udim; mod uv_strokes; + +mod symmetry; diff --git a/crates/engine/tests/it/path_perf.rs b/crates/engine/tests/it/path_perf.rs new file mode 100644 index 00000000..ac09c302 --- /dev/null +++ b/crates/engine/tests/it/path_perf.rs @@ -0,0 +1,115 @@ +//! Path preview timings and a repeatable memory soak (release, --ignored --nocapture). + +use std::time::{Duration, Instant}; + +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_engine::geom::glam::Vec2; + +/// Sort a nonempty timing sample in place and report its middle value in milliseconds +fn median_ms(samples: &mut [Duration]) -> f64 { + samples.sort_unstable(); + samples[samples.len() / 2].as_secs_f64() * 1_000.0 +} + +/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes +#[test] +#[ignore = "release benchmark: two texture resolutions and brush sizes"] +fn path_preview_timings() { + for resolution in [2048, 4096] { + let mut session = texturecraft_engine::sample_session(resolution, 64).unwrap(); + session.viewport = Vec2::splat(400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + for size in [4, 20] { + execute(&mut session, "tool.brush", &json!({"size": size})).unwrap(); + execute(&mut session, "tool.path", &json!({"points": [[150, 210], [175, 180], [200, 210], [225, 180], [250, 210]]})).unwrap(); + session.update(); + let original = session.tool.path.points[2]; + let (mut paint, mut composite, mut full) = (Vec::new(), Vec::new(), Vec::new()); + let mut dirty_tiles = Vec::new(); + + for step in 0..20 { + let point = original + texturecraft_engine::geom::glam::Vec3::Y * (step as f32 + 1.0) * 0.001; + assert!(session.move_path_point(2, point, step == 0)); + let started = Instant::now(); + assert!(session.path_live().unwrap()); + paint.push(started.elapsed()); + dirty_tiles.push(session.pending_tiles()); + let started = Instant::now(); + session.update(); + composite.push(started.elapsed()); + // The same document with full invalidation isolates the compositor saving + if step < 3 { + for cache in &mut session.caches { + cache.invalidate_all(); + } + let started = Instant::now(); + session.update(); + full.push(started.elapsed()); + } + } + + println!( + "path {resolution}px brush={size}: paint {:.2} ms, dirty composite {:.2} ms, full composite {:.2} ms; dirty tiles {:?}", + median_ms(&mut paint), + median_ms(&mut composite), + median_ms(&mut full), + dirty_tiles + ); + session.cancel_path(); + session.update(); + } + } +} + +/// Observe resident memory without treating allocator-retained pages as a leak +#[cfg(target_os = "linux")] +fn resident_kib() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap() +} + +/// Check that repeated canceled previews release tile buffers and leave no document history +#[cfg(target_os = "linux")] +#[test] +#[ignore = "release memory soak: 1,000 edits across 100 canceled previews"] +fn path_preview_memory_soak() { + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + + let mut session = Session::new_project("Path soak", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); + session.viewport = Vec2::splat(400.0); + session.update(); + let history = session.history_labels().len(); + let mut resident = Vec::new(); + + for cycle in 0..100 { + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.35, 0.45], [0.5, 0.5], [0.65, 0.45], [0.8, 0.5]]})).unwrap(); + for step in 0..10 { + let point = texturecraft_engine::geom::glam::Vec3::new(0.5, 0.5 + (step as f32 + 1.0) * 0.002, 0.0); + session.move_path_point(2, point, true); + assert!(session.path_live().unwrap()); + session.update(); + } + let preview_tiles: Vec<_> = session + .doc + .pixels + .layers + .values() + .flat_map(|image| image.allocated().map(|(x, y)| std::sync::Arc::downgrade(image.tile_handle(x, y).unwrap()))) + .collect(); + assert!(!preview_tiles.is_empty()); + session.cancel_path(); + session.update(); + assert!(preview_tiles.iter().all(|tile| tile.upgrade().is_none()), "canceled previews release their painted tile buffers"); + assert_eq!(session.history_labels().len(), history, "canceled previews retain no document history"); + if (cycle + 1) % 10 == 0 { + resident.push(resident_kib()); + } + } + + println!("path soak VmRSS KiB after each 100 edits: {resident:?}"); + // RSS is an observation, not a portable leak assertion: allocators can retain freed pages +} diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs index b053e979..bb4ea764 100644 --- a/crates/engine/tests/it/path_tool.rs +++ b/crates/engine/tests/it/path_tool.rs @@ -37,7 +37,7 @@ fn path_stroke_paints_along_the_curve() { let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); assert_eq!(r["points"], 3); assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path); - assert!(!red_at(&s, 200.0, 180.0), "nothing painted before commit"); + assert!(red_at(&s, 200.0, 180.0), "the path is previewed before it is applied"); let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}"); assert_eq!(r["points"], 0, "commit clears the path"); @@ -46,11 +46,11 @@ fn path_stroke_paints_along_the_curve() { } assert!(!red_at(&s, 200.0, 240.0), "below the curve"); assert!(!red_at(&s, 200.0, 130.0), "above the curve"); - // One undo step. + // One undo step execute(&mut s, "edit.undo", &Value::Null).unwrap(); s.update(); assert!(!red_at(&s, 200.0, 180.0)); - // Errors: no points, points off the mesh. + // Errors: no points, points off the mesh assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err()); assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err()); } @@ -278,3 +278,434 @@ fn each_path_and_each_edit_of_one_is_its_own_undo_step() { s.update(); assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit"); } + +/// The pixels of every path sublayer of the selected layer, comparable +fn path_pixels(s: &Session) -> Vec { + let ids: Vec = path_sublayers(s).into_iter().map(|(id, _)| id).collect(); + let mut v: Vec = s.doc.pixels.layers.iter().filter(|((id, _), _)| ids.contains(&id.0)).map(|(k, img)| format!("{k:?}{img:?}")).collect(); + v.sort(); + v +} + +#[test] +fn placing_points_previews_the_path_with_no_undo_step_until_it_is_applied() { + let points = json!([[140, 210], [200, 180], [260, 210]]); + let mut direct = session(primitives::sphere(1.0, 48, 24)); + execute(&mut direct, "tool.path", &json!({"points": points, "commit": true})).unwrap(); + + let mut s = session(primitives::sphere(1.0, 48, 24)); + let start = s.history_labels(); + execute(&mut s, "tool.path", &json!({"points": [[140, 280], [260, 280]]})).unwrap(); + assert!(red_at(&s, 200.0, 280.0)); + execute(&mut s, "tool.path", &json!({"points": points})).unwrap(); + assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 280.0), "the preview follows the points"); + assert_eq!(s.history_labels(), start, "no undo step while placing"); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert_eq!(s.history_labels().len(), start.len() + 1, "applying is one undo step"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(path_pixels(&s), path_pixels(&direct), "the same pixels as applying without a preview"); + + // Cancelling removes the preview + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(red_at(&s, 200.0, 250.0)); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0) && red_at(&s, 200.0, 180.0)); + assert_eq!(s.history_labels().len(), start.len() + 1); +} + +#[test] +fn undo_while_placing_removes_the_preview_only() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0), "the preview is gone"); + assert!(red_at(&s, 200.0, 180.0), "the applied path stays"); + assert_eq!(s.history_labels().len(), steps); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none()); +} + +#[test] +fn another_change_while_placing_makes_the_path_its_own_step_first() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let labels = s.history_labels(); + assert_eq!(labels.len(), steps + 2); + assert_eq!(labels.get(steps).map(String::as_str), Some("Path")); + // Undoing the other change keeps the path; undoing again removes it + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 180.0)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 180.0)); +} + +#[test] +fn editing_another_path_while_placing_applies_the_new_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 2)], "the new path was applied"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(s.tool.path.editing, Some((texturecraft_engine::core::LayerId(eid), 0))); +} + +#[test] +fn the_next_path_starts_open_after_a_closed_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "closed": true, "commit": true})).unwrap(); + assert!(!s.tool.path.closed, "applying a closed path leaves the tool open for the next one"); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]], "closed": true})).unwrap(); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + assert!(!s.tool.path.closed, "cancelling does too"); +} + +/// A short path's repaint marks under 1/N of a 1024-texel set's 256 tiles +const SHORT_PATH_TILE_SHARE_DIVISOR: usize = 4; + +/// Move the middle point of the Path tool's curve down to viewport row `y` and repaint, returning the (dirty, all) tile counts +fn move_middle_point(s: &mut Session, y: f32) -> (usize, usize) { + s.tool.path.points[1] = s.pick(Vec2::new(200.0, y), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len()) +} + +#[test] +fn moving_a_point_recomposites_only_the_paths_tiles() { + // 1024 texels: 256 tiles, so a short path covers few of them + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:test", None, 1024).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + (s.camera.yaw, s.camera.pitch) = (0.0, 0.0); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + s.update(); + + let (dirty, all) = move_middle_point(&mut s, 190.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "a new path: {dirty} of {all} tiles to recomposite"); + s.update(); + + let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": r["committed"]["effect"], "index": 0})).unwrap(); + s.update(); + // Another row than the applied one, so the edit changes the path + let (dirty, all) = move_middle_point(&mut s, 200.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "an applied path being edited: {dirty} of {all} tiles to recomposite"); +} + +#[test] +fn another_change_ends_the_point_undo_of_an_edited_path() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = texturecraft_engine::core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 0})).unwrap(); + s.path_checkpoint(); + s.tool.path.points[1] = s.pick(Vec2::new(200.0, 230.0), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + let moved: Vec<[f32; 3]> = s.tool.path.points.iter().map(|p| p.to_array()).collect(); + let layers = s.doc.project.layers.len(); + + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layers.len(), layers, "undo removes the new layer"); + assert_eq!(s.paths(eid).unwrap()[0].points, moved, "the path keeps its moved point"); +} + +#[test] +fn placing_a_path_ends_redo() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.can_redo()); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(!s.can_redo(), "redo would throw the path being placed away"); +} + +#[test] +fn switching_texture_sets_applies_the_path_being_placed() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]]})).unwrap(); + + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1); + assert_eq!(s.undo_label(), Some("Path")); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none(), "the path no longer paints into the other set"); +} + +#[test] +fn applying_after_orbit_preserves_preview_pixels_and_storage() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + let preview = session.doc.clone(); + let steps = session.history_labels().len(); + session.camera.yaw += 0.6; + session.viewport = Vec2::new(600.0, 400.0); + assert!(!session.path_live().unwrap()); + + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + + assert_eq!(session.doc.project, preview.project, "apply must keep the preview's camera and viewport"); + assert_eq!(session.doc.pixels.layers, preview.pixels.layers, "apply must keep the preview pixels"); + for (key, image) in &preview.pixels.layers { + for (x, y) in image.allocated() { + assert!(std::sync::Arc::ptr_eq(image.tile_handle(x, y).unwrap(), session.doc.pixels.layers[key].tile_handle(x, y).unwrap())); + } + } + assert_eq!(session.history_labels().len(), steps + 1); +} + +#[test] +fn applying_an_unchanged_stored_path_after_orbit_adds_no_history() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let before = session.doc.clone(); + let history = session.history_labels(); + session.camera.yaw += 0.6; + assert!(!session.path_live().unwrap()); + + execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); + + assert_eq!(session.history_labels(), history, "accepting an unchanged path is not an edit"); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert!(session.tool.path.editing.is_none()); +} + +#[test] +fn removing_the_final_preview_point_removes_its_pixels() { + let mut session = session(wall()); + let before = session.doc.clone(); + let history = session.history_labels(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]]})).unwrap(); + assert!(!path_sublayers(&session).is_empty()); + + session.path_checkpoint(); + session.tool.path.remove_selected(); + assert!(session.path_live().unwrap()); + session.update(); + + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.history_labels(), history); + assert!(session.tool.path.editing.is_none()); +} + +#[test] +fn preview_uses_the_commands_explicit_viewport() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + let params = json!({"points": [[170, 210], [200, 180], [230, 210]], "viewport": [400, 600]}); + execute(&mut session, "tool.path", ¶ms).unwrap(); + let preview = path_pixels(&session); + let (effect, index) = session.tool.path.editing.unwrap(); + + let mut direct = self::session(primitives::sphere(1.0, 48, 24)); + let mut params = params; + params["commit"] = json!(true); + execute(&mut direct, "tool.path", ¶ms).unwrap(); + + assert_eq!(session.paths(effect).unwrap()[index].viewport, [400.0, 600.0]); + assert_eq!(preview, path_pixels(&direct)); +} + +/// An opposite-view placement must preserve the stored curve, painted pixels and point redo +#[test] +fn stored_paths_ignore_point_placement_from_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let params = + if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true}) } else { json!({"points": [[140, 210], [260, 210]], "commit": true}) }; + let report = execute(&mut session, "tool.path", ¶ms).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let (effect, index) = session.tool.path.editing.unwrap(); + let uv_point = Vec3::new(0.5, 0.6, 0.0); + let world_point = session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos; + assert_eq!(session.append_path_point(if uv { uv_point } else { world_point }, uv), Some(2)); + session.path_live().unwrap(); + let extended = session.tool.path.points.clone(); + session.undo().unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + + let placed = session.append_path_point(if uv { world_point } else { uv_point }, !uv); + session.path_live().unwrap(); + + assert_eq!(session.paths(effect).unwrap()[index].uv, uv, "the stored path must keep its coordinate space"); + assert_eq!(placed, None); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.doc.pixels.masks, before.pixels.masks); + assert_eq!(session.history_labels(), history); + assert!(session.can_redo(), "ignored placement must preserve point redo"); + + session.redo().unwrap(); + assert_eq!(session.tool.path.points, extended); + } +} + +/// A new, uncommitted curve can still switch views and cancel without changing the document +#[test] +fn draft_paths_can_switch_to_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let before = session.doc.clone(); + let history = session.history_labels(); + let params = if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]}) } else { json!({"points": [[140, 210], [260, 210]]}) }; + execute(&mut session, "tool.path", ¶ms).unwrap(); + let point = if uv { session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos } else { Vec3::new(0.5, 0.6, 0.0) }; + + assert_eq!(session.append_path_point(point, !uv), Some(0)); + session.path_live().unwrap(); + + assert_eq!(session.tool.path.points, vec![point]); + assert_eq!(session.tool.path.uv, !uv); + assert_eq!(session.history_labels(), history); + session.cancel_path(); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + } +} + +/// Headless history commands must restore geometry and pixels before any frame or subsequent edit +#[test] +fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + let original_pixels = session.doc.pixels.clone(); + let history = session.history_labels().len(); + session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0)); + session.path_live().unwrap(); + let inserted = session.tool.path.points.clone(); + let inserted_pixels = session.doc.pixels.clone(); + session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true); + session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + let moved_pixels = session.doc.pixels.clone(); + session.remove_selected_path_point(); + session.path_live().unwrap(); + let removed = session.tool.path.points.clone(); + let removed_pixels = session.doc.pixels.clone(); + + for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] { + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); + } + + session.select_path_point(0); + assert!(session.can_redo(), "selection must preserve point redo"); + for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] { + execute(&mut session, "edit.redo", &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); + } + assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels"); +} + +/// A bad path above the edited one must not consume undo or redo when repainting fails +#[test] +fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() { + use texturecraft_engine::core::{EffectKind, LayerId}; + + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let effect = LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); + let paint = session.paths(effect).unwrap()[1].paint.clone(); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + + for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] { + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = Value::Null; + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = (session.history_labels(), session.redo_labels()); + + let error = execute(&mut session, command, &Value::Null).unwrap_err(); + + assert!(error.to_string().contains("unreadable path settings"), "{error}"); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!((session.history_labels(), session.redo_labels()), history); + + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = paint.clone(); + execute(&mut session, command, &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected, "the failed step remains available"); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + } +} + +/// Point history repaints an uncommitted preview without creating document undo steps +#[test] +fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() { + let mut session = session(wall()); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let before = session.doc.clone(); + let history = session.history_labels(); + session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true); + session.path_live().unwrap(); + let one_point = session.doc.clone(); + session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true); + session.path_live().unwrap(); + let two_points = session.doc.clone(); + + for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] { + execute(&mut session, command, &Value::Null).unwrap(); + + assert_eq!(session.doc.project, expected.project); + assert_eq!(session.doc.pixels.layers, expected.pixels.layers); + assert_eq!(session.history_labels(), history); + } + assert!(session.tool.path.points.is_empty()); + assert!(session.tool.path.editing.is_none()); +} + +#[test] +fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() { + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.5, 0.5]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let before = session.doc.clone(); + + session.remove_selected_path_point(); + assert!(session.path_live().unwrap()); + + assert!(session.paths(effect).unwrap().is_empty()); + assert!(session.doc.pixels.layers.keys().all(|(id, _)| *id != effect)); + assert!(session.tool.path.editing.is_none()); + session.undo().unwrap(); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); +} diff --git a/crates/engine/tests/it/symmetry.rs b/crates/engine/tests/it/symmetry.rs new file mode 100644 index 00000000..6beb03cc --- /dev/null +++ b/crates/engine/tests/it/symmetry.rs @@ -0,0 +1,283 @@ +//! Symmetry around a moved plane or axis, driven through engine commands the way agents paint + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; +use texturecraft_engine::geom::{Mesh, primitives}; +use texturecraft_engine::{Session, execute}; + +const TEXTURE_SIZE: f32 = 256.0; +const VIEWPORT: f32 = 400.0; + +fn session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "builtin:test", None, TEXTURE_SIZE as u32).unwrap(); + session.viewport = Vec2::splat(VIEWPORT); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + session +} + +/// A 2×2 wall in the XY plane facing the camera (+Z) +fn wall() -> Mesh { + let mut mesh = primitives::plane(2.0, 8); + for point in &mut mesh.positions { + *point = Vec3::new(point.x, -point.z, 0.0); + } + mesh.normals.iter_mut().for_each(|normal| *normal = Vec3::Z); + mesh.tangents.iter_mut().for_each(|tangent| *tangent = Vec4::new(1.0, 0.0, 0.0, 1.0)); + mesh +} + +/// Viewport pixel of world `point` +fn screen(session: &Session, point: Vec3) -> Vec2 { + let ndc = session.camera.project(point, 1.0).unwrap(); + Vec2::new((ndc.x * 0.5 + 0.5) * VIEWPORT, (0.5 - ndc.y * 0.5) * VIEWPORT) +} + +/// Is the surface at world `point` painted red? +fn red_at(session: &Session, point: Vec3) -> bool { + let hit = session.pick(screen(session, point), session.viewport).unwrap(); + let color = session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +/// Where a viewport pixel lands on the mesh +fn surface(session: &Session, x: f32, y: f32) -> Vec3 { + session.pick(Vec2::new(x, y), session.viewport).unwrap().pos +} + +#[test] +fn a_moved_mirror_plane_paints_the_copy_at_the_mirrored_point() { + let mut session = session(wall()); + let reply = execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]})).unwrap(); + + // Right of the view's center, on the wall + let stroke = surface(&session, 300.0, 200.0); + execute(&mut session, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap(); + session.update(); + + let mirrored = Vec3::new(0.5 - stroke.x, stroke.y, stroke.z); + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, mirrored), "its copy across x = 0.25"); + assert!(!red_at(&session, Vec3::new(-stroke.x, stroke.y, stroke.z)), "nothing across the mesh center"); + assert_eq!(reply["symmetryOffset"], json!([0.25, 0.0, 0.0]), "agents read the offset back"); +} + +#[test] +fn radial_copies_turn_around_the_moved_axis() { + let mut session = session(wall()); + let axis = Vec3::new(0.2, -0.1, 0.0); + execute(&mut session, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "z", "symmetryOffset": axis.to_array()})).unwrap(); + + // Up and right of the view's center, on the wall + let stroke = surface(&session, 290.0, 160.0); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + // Half a turn around Z through the moved axis + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, axis * 2.0 - stroke), "its copy half a turn around the moved axis"); + assert!(!red_at(&session, Vec3::new(-stroke.x, -stroke.y, 0.0)), "nothing around the mesh center"); +} + +#[test] +fn a_closed_path_fill_mirrors_around_the_moved_plane() { + let mut session = session(wall()); + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [-0.2, 0.0, 0.0]})).unwrap(); + + // A small square right of the view's center, on the wall + let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + let inside = surface(&session, 265.0, 200.0); + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, Vec3::new(-0.4 - inside.x, inside.y, 0.0)), "its copy across x = -0.2"); + assert!(!red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), "nothing across the mesh center"); +} + +#[test] +fn a_closed_path_fill_reaches_a_curved_copy_across_a_moved_plane() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + + // Occlusion must still protect the rear surface when normal-based culling is disabled + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0], "backfaceCulling": false})).unwrap(); + let inside = surface(&session, 185.0, 200.0); + let mirrored_x = 0.2 - inside.x; + let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt()); + + let square = json!([[175, 190], [195, 190], [195, 210], [175, 210]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, copy), "its copy where the sphere curves away across x = 0.1"); + + session.camera.yaw = std::f32::consts::PI; + assert!(!red_at(&session, Vec3::new(copy.x, copy.y, -copy.z)), "the hidden back of the copy stays clean"); + assert!(!red_at(&session, Vec3::new(inside.x, inside.y, -inside.z)), "the hidden back of the source stays clean"); +} + +#[test] +fn a_closed_path_fill_reaches_a_copy_in_front_of_the_source_surface() { + for ortho in [false, true] { + for screen_space in [false, true] { + let mut session = session(primitives::sphere(1.0, 48, 24)); + session.camera.ortho = ortho; + execute(&mut session, "tool.brush", &json!({"size": 10, "screenSpace": screen_space, "symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})) + .unwrap(); + let inside = surface(&session, 235.0, 200.0); + let mirrored_x = 0.2 - inside.x; + let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt()); + assert!(copy.z > inside.z + 0.01, "the copy must be nearer the camera than its source"); + + let square = json!([[225, 190], [245, 190], [245, 210], [225, 210]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, copy), "the ray must reach the source: ortho={ortho}, screen_space={screen_space}"); + } + } +} + +#[test] +fn screen_space_fill_copy_depth_is_limited_at_the_source_hit() { + // The source hit allows about 0.071 world units; the search bound allows about 0.122 + for (displacement, painted) in [(-0.074, false), (0.068, true), (0.1, false)] { + let mut session = session(wall()); + session.camera.ortho = true; + session.camera.distance = 1.0; + execute( + &mut session, + "tool.brush", + &json!({"size": 10, "screenSpace": true, "symmetryRadial": 2, "symmetryAxis": "y", "symmetryOffset": [0.0, 0.0, displacement * 0.5]}), + ) + .unwrap(); + let inside = surface(&session, 265.0, 200.0); + + let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert_eq!(red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), painted, "source displacement {displacement}"); + } +} + +/// How much redder than green a texel must be to count as painted (faded edges included) +const PAINTED_TINT: f32 = 0.05; + +/// Texels tinted red in the top and bottom half of the texture +fn painted_halves(session: &Session) -> (usize, usize) { + let painted = |x: u32, y: u32| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }; + let half = TEXTURE_SIZE as u32 / 2; + let count = |rows: std::ops::Range| rows.flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| painted(x, y)).count(); + (count(0..half), count(half..TEXTURE_SIZE as u32)) +} + +#[test] +fn a_mirror_copy_paints_exactly_where_its_stroke_does() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.brush", &json!({"size": 4, "symmetryY": true})).unwrap(); + + // From the middle of the view to past the ball's right edge, above center, where it fades out; the copy below must fade the same way + let points: Vec = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect(); + execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + + let (stroke, copy) = painted_halves(&session); + assert!(stroke > 0); + // Within 4%: the ball's texture layout is not exactly symmetric texel for texel + assert!(stroke.abs_diff(copy) * 25 <= stroke, "stroke {stroke} texels, copy {copy}"); +} + +#[test] +fn a_copy_paints_on_a_curved_mesh_across_a_moved_plane() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})).unwrap(); + + // Left of the view's center; across x = 0.1 its copy lands where the ball curves away a little more + let stroke = surface(&session, 185.0, 200.0); + execute(&mut session, "tool.stroke", &json!({"points": [[185, 200]]})).unwrap(); + session.update(); + + let mirrored_x = 0.2 - stroke.x; + let on_ball = Vec3::new(mirrored_x, stroke.y, (1.0 - mirrored_x * mirrored_x - stroke.y * stroke.y).sqrt()); + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, on_ball), "its copy on the ball across x = 0.1"); +} + +#[test] +fn symmetry_offsets_require_exactly_three_finite_numbers() { + let mut session = session(wall()); + let invalid = [json!([1, 2, 3, null]), json!([null, 1, 2, 3]), json!([1, "bad", 2, 3]), json!([1, 2, 3, 1e100]), json!([1, 2]), json!([1, 2, 1e100])]; + + for offset in invalid { + let result = execute(&mut session, "tool.brush", &json!({"symmetryOffset": offset})); + + assert!(result.is_err(), "accepted malformed offset: {offset}"); + } +} + +#[test] +fn invalid_brush_settings_leave_the_tool_unchanged() { + let mut session = session(wall()); + let before = session.tool.clone(); + let revision = session.revision; + + for invalid in [ + json!({"size": 20, "symmetryOn": false, "symmetryOffset": [1, 2]}), + json!({"size": 20, "symmetryAxis": "bad"}), + json!({"symmetryOffset": [0.2, 0, 0], "smudgeStrength": 70, "cloneSource": "bad"}), + ] { + let result = execute(&mut session, "tool.brush", &invalid); + + assert!(result.is_err()); + assert_eq!(session.tool, before, "a rejected partial update must not change the tool"); + assert_eq!(session.revision, revision); + } +} + +#[test] +fn symmetry_commands_report_effective_limits_and_keep_updates_out_of_history() { + let mut session = session(wall()); + let history = session.history_labels(); + + for (span, expected) in [(-20.0, 0.0), (120.0, 120.0), (500.0, 360.0)] { + let reply = execute(&mut session, "tool.brush", &json!({"symmetryAngleSpan": span, "symmetryOffset": [1e30, -1e30, 0.25]})).unwrap(); + + assert_eq!(reply["symmetryAngleSpan"], json!(expected)); + assert_eq!(reply["symmetryOffset"], json!([1e6, -1e6, 0.25])); + assert_eq!(session.tool.brush, session.tool.brush.sanitized()); + } + assert_eq!(session.history_labels(), history); +} + +#[test] +fn disabling_symmetry_paints_only_the_source_and_keeps_the_settings() { + for radial in [false, true] { + let mut session = session(wall()); + execute(&mut session, "tool.brush", &json!({"symmetryX": !radial, "symmetryRadial": if radial { 2 } else { 0 }, "symmetryAxis": "z"})).unwrap(); + let settings = session.tool.brush.symmetry; + let stroke = surface(&session, 290.0, 160.0); + let copy = if radial { -stroke } else { Vec3::new(-stroke.x, stroke.y, stroke.z) }; + + execute(&mut session, "tool.brush", &json!({"symmetryOn": false})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + assert!(red_at(&session, stroke)); + assert!(!red_at(&session, copy), "disabled symmetry must not paint its copy"); + assert_eq!(session.tool.brush.symmetry, texturecraft_engine::paint::Symmetry { enabled: false, ..settings }); + + execute(&mut session, "tool.brush", &json!({"symmetryOn": true})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + assert!(red_at(&session, copy), "enabling symmetry restores its copies"); + assert_eq!(session.tool.brush.symmetry, settings); + } +} diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs index b564698b..afadf0b3 100644 --- a/crates/engine/tests/it/tools.rs +++ b/crates/engine/tests/it/tools.rs @@ -181,6 +181,32 @@ fn quick_mask_limits_painting() { assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); } +/// How much redder than green a texel must be to count as painted (faded edges included) +const PAINTED_TINT: f32 = 0.05; + +/// Separate painted runs down texture column `x` (base color tinted red) +fn painted_runs(session: &Session, x: u32) -> usize { + let painted = |y: u32| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }; + (0..RES as u32).filter(|&y| painted(y) && (y == 0 || !painted(y - 1))).count() +} + +#[test] +fn a_stroke_to_the_edge_of_the_mesh_fades_without_breaking_into_dots() { + let mut session = session(); + paint_red(&mut session, 4.0); + // From the middle of the view to past the ball's right edge, above center + let points: Vec = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect(); + execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + + // The stroke crosses each texture column once, also where the surface turns away from the camera + let broken: Vec = (0..RES as u32).filter(|&x| painted_runs(&session, x) > 1).collect(); + assert!(broken.is_empty(), "columns with gaps: {broken:?}"); +} + #[test] fn swap_mask_value_inverts_only_while_a_mask_is_the_target() { let mut session = session(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 4dd04032..22a17cd5 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -54,6 +54,84 @@ fn layers_masks_materials_and_bake() { assert_eq!(s.doc.project.walk(0).len(), 1, "back to the initial paint layer"); } +#[test] +fn generator_offset_is_settable_and_clamped() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "position", "offset": 0.25})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + let offset = |s: &Session| { + let layer = s.doc.project.layers.values().find(|l| l.mask.is_some()).unwrap(); + layer + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find_map(|e| match &e.kind { + texturecraft_engine::core::EffectKind::Generator(g) => Some(g.offset), + _ => None, + }) + .unwrap() + }; + assert_eq!(offset(&s), 0.25); + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": 5.0})).unwrap(); + assert_eq!(offset(&s), 1.0, "clamped to 1"); +} + +fn generator_offset_of(s: &Session) -> f32 { + let layer = s.doc.project.layers.values().find(|l| l.mask.is_some()).unwrap(); + layer + .mask + .as_ref() + .unwrap() + .effects + .iter() + .find_map(|e| match &e.kind { + texturecraft_engine::core::EffectKind::Generator(g) => Some(g.offset), + _ => None, + }) + .unwrap() +} + +#[test] +fn generator_offset_survives_save_and_reopen_and_undo_restores_it() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "position", "offset": 0.25})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": -0.6})).unwrap(); + assert_eq!(generator_offset_of(&s), -0.6); + + let path = std::env::temp_dir().join(format!("tc-generator-offset-{}.tcraft", std::process::id())); + let path = path.to_str().unwrap(); + execute(&mut s, "file.saveCopy", &json!({"path": path})).unwrap(); + let reopened = texturecraft_engine::file_cmds::open_path(path); + let _ = std::fs::remove_file(path); + assert_eq!(generator_offset_of(&reopened.unwrap()), -0.6, "the offset is saved and read back"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(generator_offset_of(&s), 0.25, "undo restores the previous offset"); +} + +#[test] +fn generator_offset_works_alongside_curvature_mode_and_sizes() { + let mut s = session(); + execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + execute(&mut s, "mask.add.black", &Value::Null).unwrap(); + let r = execute(&mut s, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities", "offset": 0.5})).unwrap(); + let eff = r["effect"].as_u64().unwrap(); + assert_eq!(generator_offset_of(&s), 0.5); + + execute(&mut s, "effect.set", &json!({"effect": eff, "offset": -0.5, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap(); + assert_eq!(generator_offset_of(&s), -0.5); + let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string(); + assert!(inspect.contains(r#""offset":-0.5"#) && inspect.contains(r#""mode":"Cavities""#), "{inspect}"); + assert!(inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}"); +} + #[test] fn layer_rename_and_undo() { let mut s = session(); diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index cb0fa8c5..7b458a53 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -27,3 +27,6 @@ serde_json = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true } base64 = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +sysinfo = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index a52e80a5..9c0580fe 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -128,6 +128,8 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result>; pub fn load_project_bytes(bytes: &[u8]) -> Result; pub fn save_project(path: &Path, pf: &ProjectFile) -> Result<()>; // native, atomic pub fn load_project(path: &Path) -> Result; // native +pub fn set_project_open_limit_gib(limit_gib: u32); // subsequent loads, minimum 1 GiB +pub fn project_open_limit_gib() -> u32; ``` `.tcraft` layout (zip, deflate): @@ -152,8 +154,25 @@ maps retain their working atlas layout. Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`), checks every tile against its texture set's resolution and component count, rejects repeated or -out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the -total decompressed size at 8 GiB. +out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total +decompressed project data is limited to 8 GiB by default. Settings › Project › Max project size on +open changes this limit, in GiB, independently of the save CPU and RAM preferences. Each load keeps +the limit it started with; individual resource, mesh, image and entry-count limits still apply. +The limit counts file data, including binary headers and tile coordinates, rather than peak process +memory. Saves and autosaves are not refused by this open limit; raise it to reopen a larger project. + +Opening checks the sum of all declared ZIP payload sizes before decompression, including unknown +entries, and checks actual reads against the same limit independently. Overlapping ZIP entries are +rejected. ZIP indexing is restricted to the final 32 MiB with a 64 MiB read allowance before the +100,000-entry limit can be checked. Baked-map dimensions must agree with the entry size; float data +is read in bounded chunks with fallible allocation. Nested archives are not recursively extracted +by the project reader. Subsequent image and mesh decoding has separate format-specific limits; +the project-open limit is not a combined budget for those decoded assets or the application's heap. + +Native saves compress entries in parallel within the configured CPU allowance and an estimated +in-flight byte budget. Stored resources and entries larger than that budget stream directly into +the destination without a whole-entry temporary buffer. The save RAM percentage is an estimate, +excluding compressor, allocator and project-snapshot overhead; it is not a peak process memory cap. Unreadable bake settings fall back to defaults field by field while readable settings and project content are retained. Legacy baked-map filenames remain readable; unsupported baked-map types are diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index d504072a..6e57432e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -47,14 +47,19 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; -pub use project_file::{BakePaintData, ProjectFile, load_project_bytes, sanitize_resource_name, save_project_bytes}; +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, +}; #[cfg(not(target_arch = "wasm32"))] pub use export::write_files; #[cfg(not(target_arch = "wasm32"))] pub use mesh_import::{import_mesh, read_mesh_file}; #[cfg(not(target_arch = "wasm32"))] -pub use project_file::{load_project, save_project}; +pub use project_file::{ + DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, load_project, save_project, save_ram_budget, set_save_resources, +}; #[derive(Debug, thiserror::Error)] pub enum FormatError { diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 44277208..2f284704 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -36,10 +36,14 @@ fn read_inner(bytes: &[u8]) -> Result { let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default(); - let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), Some(Vec::new()), Vec::new()); + let any_uvs = models.iter().any(|m| !m.mesh.indices.is_empty() && m.mesh.texcoords.len() == (m.mesh.positions.len() / 3) * 2); + let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), any_uvs.then(Vec::new), Vec::new()); let mut partial_uvs = false; for model in &models { let mesh = &model.mesh; + if mesh.indices.is_empty() { + continue; + } let vertex_count = mesh.positions.len() / 3; check_vertices(raw.positions.len().saturating_add(vertex_count))?; @@ -56,14 +60,14 @@ fn read_inner(bytes: &[u8]) -> Result { } else { normals = None; } - if mesh.texcoords.len() == vertex_count * 2 { - if let Some(v) = &mut uvs { + if let Some(v) = &mut uvs { + if mesh.texcoords.len() == vertex_count * 2 { // OBJ UVs have their origin bottom-left v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); + } else { + v.extend(std::iter::repeat_n(Vec2::ZERO, vertex_count)); + partial_uvs = true; } - } else { - partial_uvs |= vertex_count > 0 && !mesh.indices.is_empty(); - uvs = None; } // `v x y z r g b`: objects without colors are white @@ -94,8 +98,8 @@ fn read_inner(bytes: &[u8]) -> Result { } } - if partial_uvs && models.iter().any(|model| !model.mesh.texcoords.is_empty()) { - raw.warnings.push("some objects have no UVs; the whole mesh was unwrapped automatically".into()); + if partial_uvs { + raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } raw.normals = normals; diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index fd45cc87..e55f8eae 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -235,6 +235,33 @@ fn obj_without_uvs_or_normals_is_completed() { assert!(n0.len() > 1 && n0.iter().all(|n| (*n - n0[0]).length() < 1e-5)); } +#[test] +fn obj_with_some_objects_having_uvs_preserves_uvs_without_full_unwrap() { + let obj = "o Body +v 0 0 0 +v 1 0 0 +v 1 1 0 +vt 0 0 +vt 1 0 +vt 1 1 +f 1/1 2/2 3/3 +o Helper +v 2 0 0 +v 3 0 0 +v 3 1 0 +f 4 5 6 +"; + let im = import_mesh_bytes("character.obj", obj.as_bytes()).unwrap(); + assert!(!im.report.uvs_generated); + assert_eq!(im.mesh.uvs[0], Vec2::new(0.0, 1.0)); + assert_eq!(im.mesh.uvs[1], Vec2::new(1.0, 1.0)); + assert_eq!(im.mesh.uvs[2], Vec2::new(1.0, 0.0)); + assert_eq!(im.mesh.uvs[3], Vec2::ZERO); + assert_eq!(im.mesh.uvs[4], Vec2::ZERO); + assert_eq!(im.mesh.uvs[5], Vec2::ZERO); + assert!(im.report.warnings.iter().any(|w| w.contains("some objects have no UVs"))); +} + #[test] fn polygons_keep_their_edges_for_the_wireframe() { // An OBJ quad and pentagon (with UVs, so no unwrap splits them), a triangle, and a PLY quad. diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs new file mode 100644 index 00000000..7e0238e0 --- /dev/null +++ b/crates/formats/src/project_file/entries.rs @@ -0,0 +1,294 @@ +//! Writing the zip entries of a project file. +//! +//! Compressing the baked maps dominates a save (deflate level 6 over gigabytes of `f32`), and every +//! entry is independent, so on native targets the entries are compressed on several threads. Each +//! worker builds a one-entry zip in memory with the same options the serial writer uses; the writing +//! thread copies those entries into the real file in the original order with +//! [`ZipWriter::raw_copy_file`]. The compressed bytes of every entry and the entry order are +//! therefore the same as in a serial save. +//! +//! Workers share an estimated byte budget for entries started but not yet written. Stored entries +//! and entries larger than that budget stream directly into the destination, without a whole-entry +//! buffer. The estimate excludes allocator and compressor overhead; it is not a process memory cap. + +use std::io::{Seek, Write}; + +use zip::ZipWriter; +use zip::write::SimpleFileOptions; + +use super::zip_err; +use crate::Result; + +/// Produces the uncompressed bytes of one entry into the zip writer. +pub(super) type Body<'a> = Box std::io::Result<()> + Send + 'a>; + +pub(super) struct Entry<'a> { + pub name: String, + pub options: SimpleFileOptions, + /// Estimated entry size in bytes, based on its uncompressed payload. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub weight: u64, + pub body: Body<'a>, +} + +/// How much of the machine a save may use. Native targets only; the browser saves on one thread. +#[cfg(not(target_arch = "wasm32"))] +mod limits { + use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; + + /// Cores a save leaves to the UI (an autosave runs while the user keeps painting). + static RESERVED_CORES: AtomicUsize = AtomicUsize::new(DEFAULT_RESERVED_CORES); + /// Share of the available RAM, in percent, that entries in flight may hold. + static RAM_PERCENT: AtomicU8 = AtomicU8::new(DEFAULT_RAM_PERCENT); + + pub const DEFAULT_RESERVED_CORES: usize = 1; + pub const DEFAULT_RAM_PERCENT: u8 = 50; + + pub fn set(reserved_cores: usize, ram_percent: u8) { + RESERVED_CORES.store(reserved_cores, Ordering::Relaxed); + RAM_PERCENT.store(ram_percent.clamp(1, 100), Ordering::Relaxed); + } + + pub fn get() -> (usize, u8) { + (RESERVED_CORES.load(Ordering::Relaxed), RAM_PERCENT.load(Ordering::Relaxed)) + } + + /// RAM the system can give out now, in bytes (the total when the system does not say it; 8 GiB + /// when the system tells nothing). + pub fn available_ram() -> u64 { + let Ok(mut sys) = sysinfo::System::new() else { return 8 << 30 }; + sys.refresh_memory(); + match sys.available_memory() { + 0 => sys.total_memory(), + n => n, + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +pub use limits::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES}; + +/// Set what saves may use: cores left to the UI (any number; at least one worker always runs) and +/// the percentage (1 to 100) of available RAM used as the estimated in-flight entry budget. +#[cfg(not(target_arch = "wasm32"))] +pub fn set_save_resources(reserved_cores: usize, ram_percent: u8) { + limits::set(reserved_cores, ram_percent); +} + +/// Logical CPUs and currently available RAM in bytes, using the same readings as project saves. +#[cfg(not(target_arch = "wasm32"))] +pub fn available_save_resources() -> (usize, u64) { + let cores = std::thread::available_parallelism().map_or(1, usize::from); + (cores, limits::available_ram()) +} + +/// Estimated in-flight entry budget, shared by the save planner and the Settings readout. +#[cfg(not(target_arch = "wasm32"))] +pub fn save_ram_budget(available_ram_bytes: u64, ram_percent: u8) -> u64 { + u64::try_from(u128::from(available_ram_bytes) * u128::from(ram_percent.clamp(1, 100)) / 100).unwrap_or(u64::MAX) +} + +/// Worker threads and in-flight byte budget for a save of `entries` entries. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn plan(cpus: usize, reserved_cores: usize, entries: usize, available_ram: u64, ram_percent: u8) -> (usize, u64) { + let workers = cpus.saturating_sub(reserved_cores).max(1).min(entries); + (workers, save_ram_budget(available_ram, ram_percent)) +} + +/// Write `entries` in order: in parallel where threads exist, else one after the other. +pub(super) fn write_entries(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + #[cfg(not(target_arch = "wasm32"))] + { + let (cores, available_ram_bytes) = available_save_resources(); + let (reserved_cores, ram_percent) = limits::get(); + let (workers, budget) = plan(cores, reserved_cores, entries.len(), available_ram_bytes, ram_percent); + if workers > 1 { + return parallel::write(zip, entries, workers, budget); + } + } + write_serial(zip, entries) +} + +/// One entry after the other straight into `zip`. +pub(super) fn write_serial(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + for e in entries { + zip.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(zip)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) mod parallel { + use std::collections::BTreeMap; + use std::io::{Cursor, Seek, Write}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::{Condvar, Mutex, MutexGuard}; + + use zip::{CompressionMethod, ZipArchive, ZipWriter}; + + use super::Entry; + use crate::project_file::zip_err; + use crate::{FormatError, Result}; + + struct State { + /// Next entry to start. + next: usize, + /// Estimated bytes of the entries started and not yet written. + in_flight: u64, + /// Finished entries (one-entry zips) waiting for their turn. + ready: BTreeMap>>, + /// The writer failed: start nothing more. + stop: bool, + } + + fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait<'a>(cv: &Condvar, g: MutexGuard<'a, State>) -> MutexGuard<'a, State> { + cv.wait(g).unwrap_or_else(|e| e.into_inner()) + } + + /// Compress one entry into a zip of its own. + fn compress(e: Entry<'_>) -> Result> { + let mut z = ZipWriter::new(Cursor::new(Vec::new())); + z.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(&mut z)?; + Ok(z.finish().map_err(zip_err)?.into_inner()) + } + + fn worker(slots: &[Mutex>>], weights: &[u64], budget: u64, state: &Mutex, cv: &Condvar) { + loop { + let entry_index = { + let mut state_guard = lock(state); + loop { + if state_guard.stop || state_guard.next >= slots.len() { + return; + } + + let weight = weights.get(state_guard.next).copied().unwrap_or(0); + + // Oversized entries stream separately, so every queued weight fits the budget + if state_guard.in_flight <= budget.saturating_sub(weight) { + let entry_index = state_guard.next; + state_guard.next += 1; + state_guard.in_flight = state_guard.in_flight.saturating_add(weight); + break entry_index; + } + state_guard = wait(cv, state_guard); + } + }; + let entry = slots.get(entry_index).and_then(|slot| lock(slot).take()); + let result = match entry { + Some(entry) => catch_unwind(AssertUnwindSafe(|| compress(entry))) + .unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))), + None => Err(FormatError::Invalid("project entry missing".into())), + }; + + lock(state).ready.insert(entry_index, result); + cv.notify_all(); + } + } + + /// Copy the compressed entry of a one-entry zip into `zip` without recompressing. + fn copy_entry(zip: &mut ZipWriter, bytes: Vec) -> Result<()> { + let mut a = ZipArchive::new(Cursor::new(bytes)).map_err(zip_err)?; + let f = a.by_index_raw(0).map_err(zip_err)?; + zip.raw_copy_file(f).map_err(zip_err) + } + + fn streams_directly(entry: &Entry<'_>, budget: u64) -> bool { + let stored_options = entry.options.compression_method(CompressionMethod::Stored); + entry.options == stored_options || entry.weight > budget + } + + pub(in crate::project_file) fn write(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + if workers == 0 { + return super::write_serial(zip, entries); + } + + let mut remaining = entries.into_iter().peekable(); + while let Some(entry) = remaining.next() { + // Storing bytes gains nothing from a worker; oversized entries must not get a whole-entry buffer + if streams_directly(&entry, budget) { + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; + continue; + } + + let mut batch = vec![entry]; + while remaining.peek().is_some_and(|entry| !streams_directly(entry, budget)) { + if let Some(entry) = remaining.next() { + batch.push(entry); + } + } + + // Finish the workers before direct compression, keeping the CPU allowance shared + write_buffered(zip, batch, workers, budget)?; + } + + Ok(()) + } + + fn write_buffered(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + if entries.len() == 1 { + return super::write_serial(zip, entries); + } + + let weights: Vec = entries.iter().map(|entry| entry.weight).collect(); + let slots: Vec>>> = entries.into_iter().map(|entry| Mutex::new(Some(entry))).collect(); + let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); + let cv = Condvar::new(); + std::thread::scope(|scope| { + let mut started = 0; + for _ in 0..workers.min(slots.len()) { + // If thread creation fails, the workers already started drain the queue + if std::thread::Builder::new().spawn_scoped(scope, || worker(&slots, &weights, budget, &state, &cv)).is_ok() { + started += 1; + } + } + + let result = (|| -> Result<()> { + for (entry_index, weight) in weights.iter().enumerate() { + if started == 0 { + // If no workers started, stream directly into the destination + let entry = + slots.get(entry_index).and_then(|slot| lock(slot).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?; + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; + continue; + } + + let done = { + let mut state_guard = lock(&state); + loop { + if let Some(result) = state_guard.ready.remove(&entry_index) { + break result; + } + state_guard = wait(&cv, state_guard); + } + }; + let copied = done.and_then(|bytes| copy_entry(zip, bytes)); + + // Release the entry's share only once its bytes are gone + { + let mut state_guard = lock(&state); + state_guard.in_flight = state_guard.in_flight.saturating_sub(*weight); + } + cv.notify_all(); + copied?; + } + + Ok(()) + })(); + + if result.is_err() { + lock(&state).stop = true; + cv.notify_all(); + } + + result + }) + } +} diff --git a/crates/formats/src/project_file/load_budget.rs b/crates/formats/src/project_file/load_budget.rs new file mode 100644 index 00000000..284c4d64 --- /dev/null +++ b/crates/formats/src/project_file/load_budget.rs @@ -0,0 +1,68 @@ +/// Decompressed bytes accepted by one project load, fixed when the load starts. +pub(super) struct LoadBudget { + limit_bytes: u64, + used_bytes: u64, +} + +impl LoadBudget { + pub(super) fn new(limit_bytes: u64) -> Self { + Self { limit_bytes, used_bytes: 0 } + } + + pub(super) fn remaining(&self) -> u64 { + self.limit_bytes - self.used_bytes + } + + /// Reserve bytes before retaining decoded data so entries share one allocation budget. + pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> { + if bytes > self.remaining() { + return Err(format!( + "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", + self.limit_bytes, + self.limit_bytes as f64 / (1u64 << 30) as f64, + )); + } + + self.used_bytes += bytes; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::LoadBudget; + + #[test] + fn entries_share_the_limit_and_the_exact_boundary_is_allowed() { + let mut budget = LoadBudget::new(10); + + budget.take(4).unwrap(); + budget.take(6).unwrap(); + let error = budget.take(1).unwrap_err(); + + assert_eq!(budget.remaining(), 0); + assert!(error.contains("10 bytes"), "{error}"); + assert!(error.contains("Settings > Project"), "{error}"); + } + + #[test] + fn a_rejected_entry_does_not_consume_the_remaining_budget() { + let mut budget = LoadBudget::new(10); + budget.take(4).unwrap(); + + assert!(budget.take(7).is_err()); + + assert_eq!(budget.remaining(), 6); + assert!(budget.take(6).is_ok()); + } + + #[test] + fn accounting_cannot_wrap_at_the_integer_boundary() { + let mut budget = LoadBudget::new(u64::MAX); + budget.take(u64::MAX).unwrap(); + + assert!(budget.take(1).is_err()); + assert!(budget.take(0).is_ok()); + assert_eq!(budget.remaining(), 0); + } +} diff --git a/crates/formats/src/project_file/metadata_reader.rs b/crates/formats/src/project_file/metadata_reader.rs new file mode 100644 index 00000000..7e82825c --- /dev/null +++ b/crates/formats/src/project_file/metadata_reader.rs @@ -0,0 +1,81 @@ +use std::cell::Cell; +use std::io::{self, Read, Seek, SeekFrom}; + +/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access. +pub(super) struct MetadataReader<'a, R> { + reader: R, + metadata_only: &'a Cell, + metadata_start: u64, + remaining_bytes: u64, + position: u64, +} + +impl<'a, R: Read + Seek> MetadataReader<'a, R> { + pub(super) fn new(mut reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> io::Result { + let end = reader.seek(SeekFrom::End(0))?; + Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end }) + } +} + +impl Read for MetadataReader<'_, R> { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if bytes.is_empty() { + return Ok(0); + } + + let metadata_only = self.metadata_only.get(); + if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit")); + } + + let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() }; + let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?; + self.position = self.position.saturating_add(read as u64); + if metadata_only { + self.remaining_bytes -= read as u64; + } + + Ok(read) + } +} + +impl Seek for MetadataReader<'_, R> { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.position = self.reader.seek(position)?; + Ok(self.position) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn indexing_cannot_read_payloads_outside_the_metadata_window() { + let metadata_only = Cell::new(true); + let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap(); + reader.seek(SeekFrom::Start(91)).unwrap(); + + assert!(reader.read(&mut [0; 1]).is_err()); + reader.seek(SeekFrom::Start(92)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + + metadata_only.set(false); + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 100]).unwrap(); + } + + #[test] + fn repeated_metadata_scans_share_one_read_allowance() { + let metadata_only = Cell::new(true); + let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap(); + for _ in 0..2 { + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + } + reader.seek(SeekFrom::Start(0)).unwrap(); + + assert!(reader.read(&mut [0; 1]).is_err()); + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 0e1db163..8390220a 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -18,6 +18,7 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). +use std::cell::Cell; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; @@ -28,18 +29,30 @@ use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; +use self::entries::Entry; +use self::load_budget::LoadBudget; +use self::metadata_reader::MetadataReader; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; +mod entries; +mod load_budget; +mod metadata_reader; +mod project_open_limit; +#[cfg(not(target_arch = "wasm32"))] +pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources}; +pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; + const KIND: &str = "project file"; const MAGIC: &[u8; 4] = b"TCTX"; /// Version of the `.bin` layout. const BIN_VERSION: u32 = 1; +const BIN_HEADER_BYTES: usize = 24; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; const MAX_RESOURCE: u64 = 512 << 20; const MAX_ENTRIES: usize = 100_000; -/// Total decompressed bytes accepted from one project file (zip-bomb guard). -const MAX_TOTAL: u64 = 8 << 30; +/// Bound ZIP index parsing before the archive exposes its entry count. +const MAX_ZIP_METADATA_BYTES: u64 = 32 << 20; /// Largest image (texels) of a texture set or baked map: UV-tiled sets hold several tiles. const MAX_TEXELS: u64 = 1 << 28; @@ -156,21 +169,42 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -fn write_project(out: W, pf: &ProjectFile) -> Result<()> { - let mut zip = ZipWriter::new(out); +/// Floats converted to bytes at a time when a baked map streams into the compressor. +const BAKED_CHUNK: usize = 1 << 16; + +fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { + w.write_all(&header(res, h, comps, 0))?; + let mut buf = Vec::with_capacity(BAKED_CHUNK * 4); + for chunk in data.chunks(BAKED_CHUNK) { + buf.clear(); + buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); + w.write_all(&buf)?; + } + Ok(()) +} + +/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. +fn entries(pf: &ProjectFile) -> Result>> { let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; - zip.start_file("project.json", deflate).map_err(zip_err)?; - zip.write_all(&json)?; + let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }]; if let Some((ext, bytes)) = &pf.mesh { - zip.start_file(format!("mesh.{}", sanitize_ext(ext)), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: format!("mesh.{}", sanitize_ext(ext)), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } let mut used = HashSet::new(); for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) { - zip.start_file(unique_entry_name(dir, name, &mut used), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name(dir, name, &mut used), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } for ((texture_set, target), map) in &pf.bake_paint { if map.width == 0 || map.height == 0 || map.values.len() as u64 != u64::from(map.width) * u64::from(map.height) { @@ -180,23 +214,29 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { BakePaintTarget::Cage => "cage", BakePaintTarget::Skew => "skew", }; - zip.start_file(format!("bake_paint/{texture_set}_{target_name}.bin"), deflate).map_err(zip_err)?; - zip.write_all(&header(map.width, map.height, 1, 0))?; - for value in &map.values { - zip.write_all(&value.to_le_bytes())?; - } + out.push(Entry { + name: format!("bake_paint/{texture_set}_{target_name}.bin"), + options: deflate, + weight: map.values.len() as u64 * 4, + body: Box::new(move |w| write_baked(w, map.width, map.height, 1, &map.values)), + }); } let mut layers: Vec<_> = pf.pixels.layers.iter().collect(); layers.sort_by_key(|(k, _)| **k); for ((id, c), img) in layers { - zip.start_file(format!("pixels/layer_{}_{}.bin", id.0, c.id()), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { + name: format!("pixels/layer_{}_{}.bin", id.0, c.id()), + options: deflate, + weight, + body: Box::new(move |mut w| write_tiles(&mut w, img)), + }); } let mut masks: Vec<_> = pf.pixels.masks.iter().collect(); masks.sort_by_key(|(k, _)| **k); for (id, img) in masks { - zip.start_file(format!("pixels/mask_{}.bin", id.0), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) }); } for (ts, maps) in &pf.baked { let r = maps.resolution; @@ -206,21 +246,33 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { if h == 0 || data.len() != (r as usize) * (h as usize) * m.components() { continue; } - zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).map_err(zip_err)?; - zip.write_all(&header(r, h, m.components(), 0))?; - let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); - zip.write_all(&bytes)?; + let comps = m.components(); + out.push(Entry { + name: format!("baked/{ts}_{}.bin", m.id()), + options: deflate, + weight: data.len() as u64 * 4, + body: Box::new(move |w| write_baked(w, r, h, comps, data)), + }); } } if let Some(png) = &pf.thumbnail { - zip.start_file("thumbnail.png", stored).map_err(zip_err)?; - zip.write_all(png)?; + out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) }); } used.clear(); for (name, bytes) in &pf.resources { - zip.start_file(unique_entry_name("resources", name, &mut used), stored).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name("resources", name, &mut used), + options: stored, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } + Ok(out) +} + +fn write_project(out: W, pf: &ProjectFile) -> Result<()> { + let mut zip = ZipWriter::new(out); + entries::write_entries(&mut zip, entries(pf)?)?; zip.finish().map_err(zip_err)?; Ok(()) } @@ -238,29 +290,37 @@ pub fn load_project(path: &std::path::Path) -> Result { crate::guard(KIND, || load(std::io::BufReader::new(file))) } -/// Counts decompressed bytes against [`MAX_TOTAL`]. -struct Budget(u64); - -impl Budget { - fn take(&mut self, n: u64) -> Result<()> { - self.0 = self.0.saturating_add(n); - if self.0 > MAX_TOTAL { - return Err(FormatError::TooLarge(format!("project file decompresses to more than {MAX_TOTAL} bytes"))); - } - Ok(()) - } -} - -fn read_all(r: &mut impl Read, cap: u64, budget: &mut Budget, what: &str) -> Result> { +fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &str) -> Result> { let mut out = Vec::new(); - r.take(cap.saturating_add(1)).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?; + + // Read at most one byte beyond either limit to detect overflow without a full entry allocation + let read_limit = cap.min(budget.remaining()).saturating_add(1); + reader.take(read_limit).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?; if out.len() as u64 > cap { return Err(FormatError::TooLarge(format!("{what} is larger than {cap} bytes"))); } - budget.take(out.len() as u64)?; + + budget.take(out.len() as u64).map_err(FormatError::TooLarge)?; Ok(out) } +/// Decode bounded chunks so a false header cannot allocate an entire missing map. +fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result> { + let mut values = Vec::new(); + let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4]; + let mut remaining = count; + while remaining > 0 { + let chunk_values = BAKED_CHUNK.min(remaining); + let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?; + read_exact(reader, chunk, what)?; + values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?; + values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes))); + remaining -= chunk_values; + } + + Ok(values) +} + fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> { r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}"))) } @@ -271,7 +331,7 @@ fn u32_at(b: &[u8], i: usize) -> u32 { /// Read and check a `.bin` header: returns (width, height, comps, count). fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> { - let mut h = [0u8; 24]; + let mut h = [0u8; BIN_HEADER_BYTES]; read_exact(r, &mut h, what)?; if h.get(..4) != Some(MAGIC.as_slice()) { return Err(malformed(KIND, format!("{what}: bad magic"))); @@ -293,7 +353,8 @@ fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { } } -fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut Budget, what: &str) -> Result { +fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result { + budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; let (width, height, stored_components, count) = read_header(reader, what)?; if (width, height) != size || stored_components != components { return Err(malformed( @@ -310,6 +371,7 @@ fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budge let mut bytes = vec![0u8; TILE_AREA * components * 2]; let mut position_bytes = [0u8; 8]; for _ in 0..count { + budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?; read_exact(reader, &mut position_bytes, what)?; let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { @@ -317,7 +379,6 @@ fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budge } read_exact(reader, &mut bytes, what)?; - budget.take(bytes.len() as u64)?; let data: Vec = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect(); image.set_tile(tx, ty, Some(Arc::new(data))); } @@ -328,19 +389,25 @@ fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budge } /// A baked map: (width, height, data). -fn read_baked(reader: &mut impl Read, components: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec)> { +fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec)> { + budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; let (width, height, stored_components, _) = read_header(reader, what)?; if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); } - let value_count = (width as usize) * (height as usize) * components; - budget.take(value_count as u64 * 4)?; - let mut bytes = vec![0u8; value_count * 4]; - read_exact(reader, &mut bytes, what)?; + let value_count = u64::from(width) * u64::from(height) * components as u64; + let payload_bytes = value_count * 4; + if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes { + return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map"))); + } + + budget.take(payload_bytes).map_err(FormatError::TooLarge)?; + let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?; + let data = read_f32s(reader, value_count, what)?; expect_end(reader, what)?; - Ok((width, height, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect())) + Ok((width, height, data)) } /// Texture set holding a paint layer, a content effect or a mask effect id. @@ -350,12 +417,44 @@ fn texture_set_of(project: &Project, id: LayerId) -> Option { } fn load(reader: R) -> Result { - let mut zip = ZipArchive::new(reader).map_err(zip_err)?; + let limit_bytes = u64::from(project_open_limit_gib()) << 30; + load_with_budget(reader, LoadBudget::new(limit_bytes)) +} + +fn check_archive(zip: &mut ZipArchive, limit_bytes: u64) -> Result<()> { if zip.len() > MAX_ENTRIES { return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); } - let mut budget = Budget(0); + // Count every declared payload, including ignored entries, before any decompression + let mut declared_budget = LoadBudget::new(limit_bytes); + for index in 0..zip.len() { + let entry = zip.by_index_raw(index).map_err(zip_err)?; + declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?; + } + + // Shared compressed ranges can amplify one payload into many apparent files + if zip.has_overlapping_entries().map_err(zip_err)? { + return Err(malformed(KIND, "overlapping ZIP entries are not supported")); + } + + Ok(()) +} + +fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> Result>> { + let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?; + // Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset + let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; + let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?; + metadata_only.set(false); + Ok(archive) +} + +fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result { + let metadata_only = Cell::new(true); + let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?; + check_archive(&mut zip, budget.remaining())?; + let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; #[derive(serde::Deserialize)] struct Version { @@ -388,6 +487,7 @@ fn load(reader: R) -> Result { for i in 0..zip.len() { let mut f = zip.by_index(i).map_err(zip_err)?; + let declared_bytes = f.size(); let name = f.name().map_err(zip_err)?.into_owned(); let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size()); if name == "thumbnail.png" { @@ -421,7 +521,7 @@ fn load(reader: R) -> Result { "skew" => BakePaintTarget::Skew, _ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))), }; - let (width, height, values) = read_baked(&mut f, 1, &mut budget, &name)?; + let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?; pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values }); } else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) { let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; @@ -453,7 +553,7 @@ fn load(reader: R) -> Result { continue; } - let (res, height, data) = read_baked(&mut f, m.components(), &mut budget, &name)?; + let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?; let maps = pf.baked.entry(ts).or_default(); if maps.maps.is_empty() { maps.resolution = res; diff --git a/crates/formats/src/project_file/project_open_limit.rs b/crates/formats/src/project_file/project_open_limit.rs new file mode 100644 index 00000000..3926da27 --- /dev/null +++ b/crates/formats/src/project_file/project_open_limit.rs @@ -0,0 +1,41 @@ +use std::sync::atomic::{AtomicU32, Ordering}; + +/// Default maximum decompressed project size, in GiB. +pub const DEFAULT_PROJECT_OPEN_LIMIT_GIB: u32 = 8; + +static PROJECT_OPEN_LIMIT_GIB: AtomicU32 = AtomicU32::new(DEFAULT_PROJECT_OPEN_LIMIT_GIB); + +/// Set the limit for subsequent project loads, in GiB; zero is clamped to one GiB. +/// An in-progress load keeps the limit it started with. Individual entry limits still apply. +pub fn set_project_open_limit_gib(limit_gib: u32) { + PROJECT_OPEN_LIMIT_GIB.store(limit_gib.max(1), Ordering::Relaxed); +} + +/// Maximum decompressed project size accepted by subsequent loads, in GiB. +pub fn project_open_limit_gib() -> u32 { + PROJECT_OPEN_LIMIT_GIB.load(Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_file::load_budget::LoadBudget; + + #[test] + fn preferences_apply_to_new_loads_in_gib_without_disabling_existing_guards() { + set_project_open_limit_gib(8); + let mut active_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30); + + set_project_open_limit_gib(16); + let mut next_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30); + + assert!(active_load.take(9 << 30).is_err()); + assert!(next_load.take(9 << 30).is_ok()); + + set_project_open_limit_gib(0); + assert_eq!(project_open_limit_gib(), 1); + set_project_open_limit_gib(u32::MAX); + assert_eq!(u64::from(project_open_limit_gib()) << 30, 4_611_686_017_353_646_080); + set_project_open_limit_gib(DEFAULT_PROJECT_OPEN_LIMIT_GIB); + } +} diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 7f756554..93a58a9a 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -228,6 +228,145 @@ fn duplicate_entry_names_are_made_unique_on_save() { assert_eq!(res, vec![vec![3], vec![4]]); } +/// Every entry of a zip in file order: (name, method, crc, sizes, the compressed bytes as stored). +/// The zip headers around them (version fields, zip64 size placeholders) are not part of this: +/// copying an entry between zips rewrites them. +#[allow(clippy::type_complexity)] +fn payloads(zip: &[u8]) -> Vec<(String, CompressionMethod, u32, u64, u64, Vec)> { + let mut a = ZipArchive::new(Cursor::new(zip)).unwrap(); + (0..a.len()) + .map(|i| { + let mut f = a.by_index_raw(i).unwrap(); + let mut raw = Vec::new(); + f.read_to_end(&mut raw).unwrap(); + (f.name().unwrap().into_owned(), f.compression(), f.crc32(), f.size(), f.compressed_size(), raw) + }) + .collect() +} + +/// A project with several baked maps and pixel layers, big enough that entries stream in chunks. +fn big_sample() -> ProjectFile { + let mut s = sample(); + let mut x = 12345u32; + let mut noise = |n: usize| -> Vec { + (0..n) + .map(|i| { + x = x.wrapping_mul(1664525).wrapping_add(1013904223); + (i as f32 * 0.001).sin() * 0.5 + 0.5 + (x >> 24) as f32 * 1e-4 + }) + .collect() + }; + let r = 300usize; + let maps = [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature, BakedMap::Position] + .into_iter() + .map(|m| (m, Arc::new(noise(r * r * m.components())))) + .collect(); + s.pf.baked.insert(1, BakedMaps { resolution: r as u32, maps }); + s.pf.mesh = Some(("obj".into(), noise(5000).iter().map(|v| (v * 200.0) as u8).collect())); + s.pf +} + +fn serial_bytes(pf: &ProjectFile) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::write_serial(&mut zip, entries(pf).unwrap()).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[cfg(not(target_arch = "wasm32"))] +fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::parallel::write(&mut zip, entries(pf).unwrap(), workers, budget).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn save_plan_follows_the_reserved_cores_and_the_ram_share() { + // No cap of 8 workers any more, only the entry count and the cores. + assert_eq!(entries::plan(64, 1, 100, 1000, 50), (63, 500)); + assert_eq!(entries::plan(64, 1, 20, 1000, 50).0, 20); + // 0 reserved uses every core; more reserved than cores still leaves one worker. + assert_eq!(entries::plan(16, 0, 100, 1000, 100), (16, 1000)); + assert_eq!(entries::plan(4, 9, 100, 1000, 100).0, 1); + assert_eq!(entries::plan(1, 0, 100, 1000, 100).0, 1); + // The share is of the RAM given, clamped to 1..=100 percent, and never overflows. + assert_eq!(entries::plan(2, 1, 5, 1000, 0).1, 10); + assert_eq!(entries::plan(2, 1, 5, 1000, 250).1, 1000); + assert_eq!(entries::plan(2, 1, 5, u64::MAX, 100).1, u64::MAX); + assert_eq!(entries::plan(2, 1, 5, u64::MAX, 50).1, u64::MAX / 2); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_with_any_reserved_cores_and_ram_share_matches_serial() { + let pf = big_sample(); + let want = payloads(&serial_bytes(&pf)); + let n = want.len(); + // (cpus, reserved cores, available RAM, percent): none reserved, all reserved, a tiny and a huge share. + for (cpus, reserved, ram, percent) in [(8, 0, 1u64 << 40, 100u8), (8, 1, 1 << 40, 50), (8, 99, 1 << 40, 50), (16, 0, 1000, 1), (6, 1, u64::MAX, 100)] { + let (workers, budget) = entries::plan(cpus, reserved, n, ram, percent); + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{cpus} cpus, {reserved} reserved, {ram} bytes at {percent}%"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The setting is read by the public save; extreme values still save the same entries. + for (reserved, percent) in [(0, 100), (1000, 1), (1, 50)] { + set_save_resources(reserved, percent); + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want, "{reserved} reserved, {percent}%"); + } + set_save_resources(DEFAULT_RESERVED_CORES, DEFAULT_RAM_PERCENT); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_writes_the_same_entries_as_serial() { + let pf = big_sample(); + let serial = serial_bytes(&pf); + let want = payloads(&serial); + assert!(want.len() > 10); + for (workers, budget) in [(0, 1), (2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{workers} workers, budget {budget}"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The public entry point (threads chosen by the machine) agrees too, and loads back. + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want); + assert_same(&pf, &load_project_bytes(&serial).unwrap()); +} + +/// The files written before entries were compressed in parallel: each entry written in one go. +fn reference_one_shot(pf: &ProjectFile) -> Vec { + let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file("project.json", deflate).unwrap(); + zip.write_all(&serde_json::to_vec_pretty(&pf.project).unwrap()).unwrap(); + for (ts, maps) in &pf.baked { + for (m, data) in &maps.maps { + zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).unwrap(); + zip.write_all(&header(maps.resolution, maps.height(*m), m.components(), 0)).unwrap(); + let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); + zip.write_all(&bytes).unwrap(); + } + } + zip.finish().unwrap().into_inner() +} + +/// Streaming a baked map into the compressor in chunks may place deflate block boundaries a few +/// bytes differently than one big write, so the stored bytes can differ slightly; what the entry +/// holds (name, method, CRC, size) must not, and the compressed size stays within 0.01%. +#[test] +fn baked_entries_hold_what_the_one_shot_writer_wrote() { + let mut pf = big_sample(); + (pf.mesh, pf.high_poly, pf.cage, pf.bake_paint, pf.thumbnail, pf.resources) = (None, vec![], None, BTreeMap::new(), None, BTreeMap::new()); + pf.pixels = PixelStore::default(); + let (new, old) = (payloads(&save_project_bytes(&pf).unwrap()), payloads(&reference_one_shot(&pf))); + assert_eq!(new.len(), old.len()); + for (n, o) in new.iter().zip(&old) { + assert_eq!((&n.0, n.1, n.2, n.3), (&o.0, o.1, o.2, o.3)); + assert!(n.4.abs_diff(o.4) <= 64 + o.4 / 10_000, "{}: {} vs {}", n.0, n.4, o.4); + } +} + #[test] fn bake_model_options_survive_the_project_archive() { use texturecraft_core::{BackfaceMode, CageType, HeightNormalization}; @@ -346,6 +485,125 @@ fn recovery_defaults_unreadable_bake_blocks() { } } +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_failing_entry_is_an_error_not_a_hang() { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for fail_at in [0usize, 3, 9] { + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| { + if i == fail_at { + return Err(std::io::Error::other("boom")); + } + if i == 5 && fail_at == 9 { + panic!("worker panic"); + } + w.write_all(&[i as u8; 100]) + }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + assert!(entries::parallel::write(&mut zip, list, 4, 25).is_err(), "fail at {fail_at}"); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_late_failing_entry_after_good_ones_is_its_own_error() { + // Only the last entry fails and nothing panics, so the error must come from that entry. + for (workers, budget) in [(4usize, 25u64), (4, u64::MAX), (2, 1)] { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| if i == 9 { Err(std::io::Error::other("late boom")) } else { w.write_all(&[i as u8; 100]) }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + let res = entries::parallel::write(&mut zip, list, workers, budget); + let _ = tx.send(res.map_err(|e| matches!(&e, FormatError::Io(io) if io.to_string() == "late boom"))); + }); + let res = + rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap_or_else(|e| panic!("save did not finish ({e}): {workers} workers, budget {budget}")); + assert_eq!(res, Err(true), "{workers} workers, budget {budget}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn assert_entry_streams_to_destination(method: CompressionMethod, budget: u64) { + use std::sync::atomic::{AtomicBool, Ordering}; + + let path = std::env::temp_dir().join(format!("texturecraft-entry-streaming-{}-{method:?}.zip", std::process::id())); + let destination = std::fs::File::create(&path).unwrap(); + let observed_destination = destination.try_clone().unwrap(); + let reached_destination = AtomicBool::new(false); + let mut random = 12345u32; + let payload: Vec = (0..131_072) + .map(|_| { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + random as u8 + }) + .collect(); + let compressed = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let mut list: Vec> = (0..2) + .map(|index| Entry { name: format!("before{index}"), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[7; 128])) }) + .collect(); + list.push(Entry { + name: "target".into(), + options: SimpleFileOptions::default().compression_method(method), + weight: payload.len() as u64, + body: Box::new(|writer| { + let before_bytes = observed_destination.metadata()?.len(); + writer.write_all(&payload)?; + writer.flush()?; + reached_destination.store(observed_destination.metadata()?.len() > before_bytes, Ordering::Relaxed); + Ok(()) + }), + }); + list.push(Entry { name: "after".into(), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[9; 128])) }); + let mut writer = ZipWriter::new(destination); + + let result = entries::parallel::write(&mut writer, list, 4, budget); + drop(writer.finish().unwrap()); + drop(observed_destination); + let bytes = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + + result.unwrap(); + assert!(reached_destination.load(Ordering::Relaxed), "{method:?} was buffered instead of streamed"); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + let names: Vec<_> = (0..archive.len()).map(|index| archive.by_index(index).unwrap().name().unwrap().into_owned()).collect(); + assert_eq!(names, ["before0", "before1", "target", "after"]); + let mut actual = Vec::new(); + archive.by_name("target").unwrap().read_to_end(&mut actual).unwrap(); + assert_eq!(actual, payload); + let mut after = Vec::new(); + archive.by_name("after").unwrap().read_to_end(&mut after).unwrap(); + assert_eq!(after, [9; 128]); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn stored_entries_reach_the_destination_during_their_body() { + assert_entry_streams_to_destination(CompressionMethod::Stored, 1 << 20); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn over_budget_entries_reach_the_destination_during_their_body() { + assert_entry_streams_to_destination(CompressionMethod::Deflated, 4096); +} + #[test] fn recovery_skips_unsupported_baked_map_entries() { let expected = sample().pf; @@ -407,3 +665,196 @@ fn recovery_does_not_accept_unrelated_json_errors() { let error = load_project_bytes(&bytes).unwrap_err(); assert!(error.to_string().contains("duplicate field"), "{error}"); } + +#[test] +fn project_open_limit_counts_every_loaded_entry_kind() { + let paint = sample().paint; + let baked = [header(16, 16, 1, 0), vec![0; 16 * 16 * 4]].concat(); + let entries = [ + ("resources/test.bin".to_string(), vec![1; 1024]), + ("mesh.obj".to_string(), vec![2; 1024]), + ("highpoly/test.obj".to_string(), vec![3; 1024]), + ("cage/test.obj".to_string(), vec![4; 1024]), + ("thumbnail.png".to_string(), vec![5; 1024]), + (format!("pixels/layer_{}_baseColor.bin", paint.0), tile_bin(128, 4, &[(0, 0)])), + (format!("pixels/mask_{}.bin", paint.0), tile_bin(128, 2, &[(0, 0)])), + ("baked/0_ambientOcclusion.bin".to_string(), baked.clone()), + ("bake_paint/0_skew.bin".to_string(), baked), + ]; + + for (name, data) in entries { + let bytes = zip_with(&[(&name, data)]); + let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum(); + + let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap(); + let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err(); + let raised_limit = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes + 1)).unwrap(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{name}: {error}"); + assert!(error.to_string().contains(&format!("{} bytes", total_bytes - 1)), "{name}: {error}"); + assert_same(&accepted, &raised_limit); + } +} + +#[test] +fn project_open_limit_is_shared_across_the_whole_archive() { + let project = sample().pf; + let bytes = serial_bytes(&project); + let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum(); + + let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap(); + let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err(); + + assert_same(&project, &accepted); + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); +} + +#[test] +fn entry_reads_stop_at_the_smaller_of_the_entry_and_project_limits() { + for (entry_limit, project_limit, expected_read) in [(8, 100, 9), (100, 8, 9)] { + let mut reader = Cursor::new(vec![1; 1000]); + let mut budget = LoadBudget::new(project_limit); + + let error = read_all(&mut reader, entry_limit, &mut budget, "resource").unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); + assert_eq!(reader.position(), expected_read); + } +} + +#[test] +fn oversized_baked_data_is_rejected_before_reading_its_payload() { + let mut reader = Cursor::new(header(16, 16, 1, 0)); + let mut budget = LoadBudget::new(BIN_HEADER_BYTES as u64 + 16 * 16 * 4 - 1); + + let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64 + 16 * 16 * 4, 1, &mut budget, "baked map").unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "the size guard must run before the truncated read: {error}"); + assert_eq!(reader.position(), BIN_HEADER_BYTES as u64); +} + +#[test] +fn archive_preflight_counts_ignored_entries_and_allows_the_exact_limit() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for name in ["project.json", "unknown/future-data"] { + writer.start_file(name, options).unwrap(); + writer.write_all(&[0; 16]).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + + check_archive(&mut archive, 32).unwrap(); + let error = check_archive(&mut archive, 31).unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); +} + +#[test] +fn overlapping_archive_entries_are_rejected_before_decompression() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default()).unwrap(); + writer.write_all(&[0; 16]).unwrap(); + writer.shallow_copy_file("resource", "copy").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + + let error = check_archive(&mut archive, 32).unwrap_err(); + + assert!(error.to_string().contains("overlapping ZIP entries"), "{error}"); +} + +#[test] +fn actual_decompression_is_bounded_even_when_the_declared_size_is_small() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Deflated)).unwrap(); + writer.write_all(&vec![0; 1 << 20]).unwrap(); + let mut bytes = writer.finish().unwrap().into_inner(); + let directory = ZipArchive::new(Cursor::new(&bytes)).unwrap().central_directory_start() as usize; + // The central header stores the uncompressed size at byte 24 + bytes.get_mut(directory + 24..directory + 28).unwrap().copy_from_slice(&1u32.to_le_bytes()); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + check_archive(&mut archive, 1024).unwrap(); + let mut entry = archive.by_index(0).unwrap(); + let mut budget = LoadBudget::new(1024); + + let error = read_all(&mut entry, MAX_RESOURCE, &mut budget, "resource").unwrap_err(); + + assert!( + matches!(error, FormatError::TooLarge(_)) || error.to_string().contains("larger than its declared uncompressed size"), + "actual bytes must be bounded independently of ZIP sizes: {error}" + ); +} + +#[test] +fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() { + let mut reader = Cursor::new(header(1024, 1024, 3, 0)); + let mut budget = LoadBudget::new(16 << 20); + + let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64, 3, &mut budget, "baked map").unwrap_err(); + + assert!(error.to_string().contains("24 bytes for a 1024×1024×3 map"), "{error}"); + assert_eq!(budget.remaining(), (16 << 20) - BIN_HEADER_BYTES as u64); + assert_eq!(reader.position(), BIN_HEADER_BYTES as u64); +} + +#[test] +fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() { + let values: Vec = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect(); + let bytes: Vec = values.iter().flat_map(|bits| bits.to_le_bytes()).collect(); + let mut reader = Cursor::new(bytes); + + let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap(); + + assert_eq!(decoded.into_iter().map(f32::to_bits).collect::>(), values); + assert_eq!(reader.position(), (values.len() * 4) as u64); +} + +#[test] +fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); + writer.write_all(&vec![7; 1 << 20]).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let metadata_only = Cell::new(true); + + let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap(); + let mut first_byte = [0; 1]; + archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap(); + + assert_eq!(first_byte, [7]); + assert!(!metadata_only.get()); + + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap(); + writer.write_all(&[7]).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let metadata_only = Cell::new(true); + + assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err()); + assert!(metadata_only.get(), "failed indexing must not enable payload access"); +} + +#[test] +fn zip64_entry_counts_remain_supported_and_bounded() { + for count in [65_536, MAX_ENTRIES + 1] { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for index in 0..count { + writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let metadata_only = Cell::new(true); + + let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap(); + let result = check_archive(&mut archive, 0); + + assert_eq!(archive.len(), count); + if count <= MAX_ENTRIES { + result.unwrap(); + } else { + assert!(matches!(result, Err(FormatError::TooLarge(_))), "{result:?}"); + } + } +} diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 61313d57..5bb3f911 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -130,33 +130,82 @@ pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { t * t * (3.0 - 2.0 * t) } -/// Mirror and radial symmetry through the mesh center. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +/// Largest symmetry offset kept from a command or a file (world units), far beyond any mesh +const MAX_SYMMETRY_OFFSET: f32 = 1.0e6; + +/// Mirror and radial symmetry through the mesh center, optionally moved by `offset` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Symmetry { + /// The toolbar's Symmetry toggle: off keeps the settings below but paints no copies + #[serde(default = "enabled_by_default")] + pub enabled: bool, pub x: bool, pub y: bool, pub z: bool, - /// Radial symmetry: copies spread evenly around `axis` (0 or 1: off; at most 32). + /// Radial copies around `axis`, spread over `angle_span` (0 or 1: off; at most [`MAX_RADIAL_COPIES`]) #[serde(default)] pub radial: u8, - /// Axis of radial symmetry: 0 = X, 1 = Y, 2 = Z. + /// Axis of radial symmetry (0 = X, 1 = Y, 2 = Z), independent of the mirror axes #[serde(default = "radial_axis")] pub axis: u8, + /// Where the mirror planes and the radial axis cross, relative to the mesh center (world units) + #[serde(default)] + pub offset: [f32; 3], + /// Degrees the radial copies spread over: a full turn spaces them evenly, less puts the first and last copy at its ends + #[serde(default = "full_turn")] + pub angle_span: f32, +} + +fn enabled_by_default() -> bool { + true } fn radial_axis() -> u8 { 1 } +fn full_turn() -> f32 { + FULL_TURN_DEGREES +} + +/// [`Symmetry::angle_span`] of a full turn +pub const FULL_TURN_DEGREES: f32 = 360.0; + +/// Most radial copies a brush paints +pub const MAX_RADIAL_COPIES: u8 = 32; + +/// [`Symmetry::axis`] of the last axis, Z +const LAST_AXIS: u8 = 2; + impl Default for Symmetry { fn default() -> Self { - Symmetry { x: false, y: false, z: false, radial: 0, axis: radial_axis() } + Symmetry { enabled: enabled_by_default(), x: false, y: false, z: false, radial: 0, axis: radial_axis(), offset: [0.0; 3], angle_span: full_turn() } } } impl Symmetry { + /// Whether symmetry is on with an axis to mirror on or radial copies pub fn any(&self) -> bool { - self.x || self.y || self.z || self.radial > 1 + self.enabled && (self.x || self.y || self.z || self.radial > 1) + } + + /// Whether radial symmetry is on (see [`Symmetry::radial_on`] for whether it paints copies) + pub fn radial_mode(&self) -> bool { + self.enabled && self.radial > 1 + } + + /// Whether radial copies are painted: with no angle to spread over they would all land on the stroke + pub fn radial_on(&self) -> bool { + self.radial_mode() && self.angle_span > 0.0 + } + + /// Rotation (radians) of radial copy number `copy` (0 = the stroke itself) around the axis + pub fn radial_angle(&self, copy: u8) -> f32 { + if self.angle_span >= FULL_TURN_DEGREES { + f32::from(copy) * std::f32::consts::TAU / f32::from(self.radial.max(1)) + } else { + f32::from(copy) * self.angle_span.to_radians() / f32::from(self.radial.saturating_sub(1).max(1)) + } } /// Mirror scales in stroke order, including identity, without allocating @@ -172,26 +221,39 @@ impl Symmetry { Vec3::NEG_ONE, ] .into_iter() - .filter(|sign| (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z)) + .filter(|sign| *sign == Vec3::ONE || (self.enabled && (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z))) } - /// Linear maps (through the mesh center) taking a point to each of its symmetry copies, - /// the identity first. Mirrors come first, then radial rotations of the point and its mirrors. + /// The point the mirror planes and the radial axis pass through, for a mesh centered at `center` + pub fn origin(&self, center: Vec3) -> Vec3 { + center + Vec3::from(self.offset) + } + + /// [`Symmetry::axis`] as an index (0 = X, 1 = Y, 2 = Z), out-of-range values read as Z + pub fn axis_index(&self) -> usize { + usize::from(self.axis.min(LAST_AXIS)) + } + + /// Axis of radial symmetry as a unit vector + pub fn radial_axis(&self) -> Vec3 { + [Vec3::X, Vec3::Y, Vec3::Z][self.axis_index()] + } + + /// Linear maps `m` taking a point to its copies as `origin + m * (p - origin)`: identity, mirrors, then their radial turns pub fn transforms(&self) -> Vec { - let mut out: Vec = self.mirror_signs().map(Mat3::from_diagonal).collect(); + let mut maps: Vec = self.mirror_signs().map(Mat3::from_diagonal).collect(); - if self.radial > 1 { - let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(self.axis as usize).copied().unwrap_or(Vec3::Y); - let base = out.clone(); - out.reserve(base.len().saturating_mul(usize::from(self.radial - 1))); + if self.radial_on() { + let mirrors = maps.clone(); + maps.reserve(mirrors.len().saturating_mul(usize::from(self.radial - 1))); - for k in 1..self.radial { - let r = Mat3::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(self.radial)); - out.extend(base.iter().map(|m| r * *m)); + for copy in 1..self.radial { + let turn = Mat3::from_axis_angle(self.radial_axis(), self.radial_angle(copy)); + maps.extend(mirrors.iter().map(|mirror| turn * *mirror)); } } - out + maps } } @@ -291,30 +353,37 @@ impl Default for BrushSettings { } impl BrushSettings { - /// Clamp every value into its valid range (input from UI, CLI or agents). + /// Clamp every value into its valid range (input from UI, CLI or agents) pub fn sanitized(&self) -> BrushSettings { - let f = |v: f32, lo: f32, hi: f32, d: f32| if v.is_finite() { v.clamp(lo, hi) } else { d }; + let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default }; + BrushSettings { - size: f(self.size, 0.0005, 0.5, 0.02), - min_size: f(self.min_size, 0.0, 1.0, 0.05), - flow: f(self.flow, 0.0, 1.0, 1.0), - opacity: f(self.opacity, 0.0, 1.0, 1.0), - spacing: f(self.spacing, 0.01, 10.0, 0.1), - hardness: f(self.hardness, 0.0, 0.999, 0.5), - angle: f(self.angle, -360.0, 360.0, 0.0), - angle_fade: (f(self.angle_fade.0, 0.0, 90.0, 70.0), f(self.angle_fade.1, 0.0, 90.0, 85.0)), - lazy: f(self.lazy, 0.0, 500.0, 0.0), - jitter_size: f(self.jitter_size, 0.0, 1.0, 0.0), - jitter_angle: f(self.jitter_angle, 0.0, 1.0, 0.0), - jitter_flow: f(self.jitter_flow, 0.0, 1.0, 0.0), - jitter_position: f(self.jitter_position, 0.0, 4.0, 0.0), - depth: f(self.depth, 0.05, 4.0, 1.0), - symmetry: Symmetry { radial: self.symmetry.radial.min(32), axis: self.symmetry.axis.min(2), ..self.symmetry }, + size: clamp_finite(self.size, 0.0005, 0.5, 0.02), + min_size: clamp_finite(self.min_size, 0.0, 1.0, 0.05), + flow: clamp_finite(self.flow, 0.0, 1.0, 1.0), + opacity: clamp_finite(self.opacity, 0.0, 1.0, 1.0), + spacing: clamp_finite(self.spacing, 0.01, 10.0, 0.1), + hardness: clamp_finite(self.hardness, 0.0, 0.999, 0.5), + angle: clamp_finite(self.angle, -360.0, 360.0, 0.0), + angle_fade: (clamp_finite(self.angle_fade.0, 0.0, 90.0, 70.0), clamp_finite(self.angle_fade.1, 0.0, 90.0, 85.0)), + lazy: clamp_finite(self.lazy, 0.0, 500.0, 0.0), + jitter_size: clamp_finite(self.jitter_size, 0.0, 1.0, 0.0), + jitter_angle: clamp_finite(self.jitter_angle, 0.0, 1.0, 0.0), + 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), + symmetry: Symmetry { + radial: self.symmetry.radial.min(MAX_RADIAL_COPIES), + axis: self.symmetry.axis.min(LAST_AXIS), + offset: self.symmetry.offset.map(|value| clamp_finite(value, -MAX_SYMMETRY_OFFSET, MAX_SYMMETRY_OFFSET, 0.0)), + angle_span: clamp_finite(self.symmetry.angle_span, 0.0, FULL_TURN_DEGREES, FULL_TURN_DEGREES), + ..self.symmetry + }, particles: Particles { enabled: self.particles.enabled, count: self.particles.count.clamp(1, 16), lifetime: self.particles.lifetime.clamp(1, 128), - gravity: f(self.particles.gravity, 0.0, 2.0, 1.0), + gravity: clamp_finite(self.particles.gravity, 0.0, 2.0, 1.0), }, ..self.clone() } diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 307ccd7f..88e68e1d 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -19,14 +19,16 @@ pub mod path; pub mod pickup; pub mod presets; pub mod raster; +pub mod stamp_source; pub mod stroke; pub mod text; pub mod visibility; -pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; +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}; +pub use path::{Lasso, spline, spline_segments}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; +pub use stamp_source::StampSource; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; pub use visibility::{EyeDepth, screen_point}; diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index 2bdb122f..51c3d53c 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -97,7 +97,7 @@ mod tests { hardness: 0.5, depth: 1.0, seed: 3, - copy: false, + source: None, }; let particles = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; diff --git a/crates/paint/src/path.rs b/crates/paint/src/path.rs index fe483ee0..6614857b 100644 --- a/crates/paint/src/path.rs +++ b/crates/paint/src/path.rs @@ -6,30 +6,44 @@ use texturecraft_geom::glam::Vec2; /// Most samples per curve segment. const MAX_SEGMENT_SAMPLES: f32 = 1024.0; -/// A Catmull-Rom spline through `points`, sampled about every `step` units. Closed curves wrap -/// back to the first point; the result starts at the first point. +/// 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 { - let n = points.len(); - if n < 2 { - return points.to_vec(); + let mut out: Vec = points.first().copied().into_iter().collect(); + for segment in segment_samples(points, closed, step) { + out.extend(segment); } - let at = |i: isize| { + out +} + +/// [`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() +} + +/// 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> + '_ { + 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 step = if step.is_finite() && step > 1e-6 { step } else { 1.0 }; - let segments = if closed { n } else { n - 1 } as isize; - let mut out = vec![at(0)]; - for s in 0..segments { + let segments = if n < 2 { + 0 + } else if closed { + n + } else { + n - 1 + } as isize; + (0..segments).map(move |s| { let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2)); let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize; - for j in 1..=k { + (1..=k).map(move |j| { let t = j as f32 / k as f32; let (t2, t3) = (t * t, t * t * t); - out.push(0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)); - } - } - out + 0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3) + }) + }) } /// A closed polygon's coverage: 1 inside, 0 outside, a one-unit ramp across the edge. diff --git a/crates/paint/src/raster.rs b/crates/paint/src/raster.rs index f53fd7fc..b033538b 100644 --- a/crates/paint/src/raster.rs +++ b/crates/paint/src/raster.rs @@ -82,6 +82,28 @@ impl StrokeCanvas { } } +/// Most a texel's eye distance may exceed the nearest surface in its 3×3 pixel neighbourhood, in pixels along the surface +const NEIGHBOUR_REACH: f32 = 1.5; + +/// Facing (cosine) below which the allowance stops growing +const MIN_FACING: f32 = 0.05; + +/// Height of the view in normalized device coordinates (−1 to 1) +const NDC_HEIGHT: f32 = 2.0; + +/// How far toward the eye to test a texel turned `facing` away: at grazing angles the neighbouring pixels of the same surface are much nearer, and the depth test would speckle +fn grazing_allowance(depth: &EyeDepth, point: Vec3, facing: f32, pixels_per_unit: f32) -> f32 { + // Back faces get none, so painting with culling off doesn't reach through thin parts + if facing <= 0.0 { + return 0.0; + } + + let clip_w = (depth.view_proj * point.extend(1.0)).w.max(0.0); + let world_per_pixel = clip_w * NDC_HEIGHT / pixels_per_unit; + let facing = facing.clamp(MIN_FACING, 1.0); + world_per_pixel * NEIGHBOUR_REACH * (1.0 - facing * facing).sqrt() / facing +} + /// What the rasterizer reads. pub struct RasterCtx<'a> { pub mesh: &'a Mesh, @@ -103,28 +125,37 @@ fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { } /// Accumulate `stamps` into `canvas` ("over": `m = a + m·(1 − a)`). -pub fn rasterize(canvas: &mut StrokeCanvas, ctx: &RasterCtx, stamps: &[Stamp]) { - let (w, h) = (ctx.gbuf.width, ctx.gbuf.height); - canvas.fit(ctx.gbuf); - let fade_lo = ctx.angle_fade.1.to_radians().cos(); - let fade_hi = ctx.angle_fade.0.to_radians().cos(); - let mut tris = Vec::new(); - for s in stamps { - if s.radius.is_nan() || s.radius <= 0.0 || !s.center.is_finite() { +pub fn rasterize(canvas: &mut StrokeCanvas, context: &RasterCtx, stamps: &[Stamp]) { + let (width, height) = (context.gbuf.width, context.gbuf.height); + canvas.fit(context.gbuf); + let fade_lo = context.angle_fade.1.to_radians().cos(); + let fade_hi = context.angle_fade.0.to_radians().cos(); + + // The camera scale is shared by every candidate texel in this batch + let pixels_per_unit = context.depth.map_or(1.0, |depth| { + let ndc_per_unit = depth.view_proj.row(1).truncate().length(); + (depth.height as f32 * ndc_per_unit).max(f32::EPSILON) + }); + let mut triangles = Vec::new(); + for stamp in stamps { + if stamp.radius.is_nan() || stamp.radius <= 0.0 || !stamp.center.is_finite() { continue; } - let ext = Vec3::splat(s.radius * s.depth.max(1.0) * 1.42); - tris.clear(); - ctx.bvh.query_box(s.center - ext, s.center + ext, |t| tris.push(t)); - // Each texel belongs to one triangle, so triangles scan independently (in parallel for - // large stamps); stamp alphas combine commutatively, so the order does not matter. - let scan = |&t: &u32| scan_triangle(ctx, s, t, w, h, fade_lo, fade_hi); - let parts: Vec = if tris.len() > 16 { tris.par_iter().filter_map(scan).collect() } else { tris.iter().filter_map(scan).collect() }; - // The stamp center in texels: the footprint texel nearest to it on the surface. + + let extent = Vec3::splat(stamp.radius * stamp.depth.max(1.0) * 1.42); + triangles.clear(); + context.bvh.query_box(stamp.center - extent, stamp.center + extent, |triangle| triangles.push(triangle)); + + // Each texel belongs to one triangle, so large stamps can scan triangles in parallel + let scan = |&triangle: &u32| scan_triangle(context, stamp, triangle, width, height, fade_lo, fade_hi, pixels_per_unit); + let parts: Vec = + if triangles.len() > 16 { triangles.par_iter().filter_map(scan).collect() } else { triangles.iter().filter_map(scan).collect() }; + + // The footprint texel nearest the stamp center supplies the pickup's center let mut center = ([0.0f32; 2], f32::MAX); - for (texels, c) in parts { - if c.1 < center.1 { - center = c; + for (texels, nearest) in parts { + if nearest.1 < center.1 { + center = nearest; } canvas.texels.extend(texels); } @@ -136,69 +167,91 @@ pub fn rasterize(canvas: &mut StrokeCanvas, ctx: &RasterCtx, stamps: &[Stamp]) { type TriTexels = (Vec<(u32, u32, f32)>, ([f32; 2], f32)); #[allow(clippy::too_many_arguments)] -fn scan_triangle(ctx: &RasterCtx, s: &Stamp, t: u32, w: u32, h: u32, fade_lo: f32, fade_hi: f32) -> Option { - if ctx.mesh.material_of(t as usize) != Some(ctx.material) { +fn scan_triangle( + context: &RasterCtx, + stamp: &Stamp, + triangle: u32, + width: u32, + height: u32, + fade_lo: f32, + fade_hi: f32, + pixels_per_unit: f32, +) -> Option { + if context.mesh.material_of(triangle as usize) != Some(context.material) { return None; } - let [a, b, c] = ctx.mesh.tri(t as usize)?; - let (ua, ub, uc) = (ctx.mesh.uvs.get(a)?, ctx.mesh.uvs.get(b)?, ctx.mesh.uvs.get(c)?); - let (pa, pb, pc) = (ctx.mesh.positions.get(a)?, ctx.mesh.positions.get(b)?, ctx.mesh.positions.get(c)?); - let (na, nb, nc) = (ctx.mesh.normals.get(a)?, ctx.mesh.normals.get(b)?, ctx.mesh.normals.get(c)?); - let x0 = (ua.x.min(ub.x).min(uc.x) * w as f32).floor().max(0.0) as u32; - let x1 = ((ua.x.max(ub.x).max(uc.x) * w as f32).ceil().max(0.0) as u32).min(w); - let y0 = (ua.y.min(ub.y).min(uc.y) * h as f32).floor().max(0.0) as u32; - let y1 = ((ua.y.max(ub.y).max(uc.y) * h as f32).ceil().max(0.0) as u32).min(h); - // Stamp radius in texels on this triangle: texel area over world area. - let uv_area = (*ub - *ua).perp_dot(*uc - *ua).abs() * w as f32 * h as f32; - let world_area = (*pb - *pa).cross(*pc - *pa).length(); - let shape = ctx.shape.at_radius(s.radius * (uv_area / world_area).sqrt()); + + let [first, second, third] = context.mesh.tri(triangle as usize)?; + let (uv_a, uv_b, uv_c) = (context.mesh.uvs.get(first)?, context.mesh.uvs.get(second)?, context.mesh.uvs.get(third)?); + let (position_a, position_b, position_c) = (context.mesh.positions.get(first)?, context.mesh.positions.get(second)?, context.mesh.positions.get(third)?); + let (normal_a, normal_b, normal_c) = (context.mesh.normals.get(first)?, context.mesh.normals.get(second)?, context.mesh.normals.get(third)?); + let x0 = (uv_a.x.min(uv_b.x).min(uv_c.x) * width as f32).floor().max(0.0) as u32; + let x1 = ((uv_a.x.max(uv_b.x).max(uv_c.x) * width as f32).ceil().max(0.0) as u32).min(width); + let y0 = (uv_a.y.min(uv_b.y).min(uv_c.y) * height as f32).floor().max(0.0) as u32; + let y1 = ((uv_a.y.max(uv_b.y).max(uv_c.y) * height as f32).ceil().max(0.0) as u32).min(height); + + // Stamp radius in texels on this triangle: texel area over world area + let uv_area = (*uv_b - *uv_a).perp_dot(*uv_c - *uv_a).abs() * width as f32 * height as f32; + let world_area = (*position_b - *position_a).cross(*position_c - *position_a).length(); + let shape = context.shape.at_radius(stamp.radius * (uv_area / world_area).sqrt()); + let mut texels = Vec::new(); let mut center = ([0.0f32; 2], f32::MAX); + for y in y0..y1 { for x in x0..x1 { - let i = (y * w + x) as usize; - if ctx.gbuf.tri.get(i).copied().unwrap_or(NO_TRI) != t { + let texel = (y * width + x) as usize; + if context.gbuf.tri.get(texel).copied().unwrap_or(NO_TRI) != triangle { continue; } - let Some([b1, b2]) = ctx.gbuf.bary.get(i).copied() else { continue }; + + let Some([b1, b2]) = context.gbuf.bary.get(texel).copied() else { continue }; let b0 = 1.0 - b1 - b2; - let p = *pa * b0 + *pb * b1 + *pc * b2; - let d = p - s.center; - let lx = d.dot(s.tangent) / s.radius; - let ly = d.dot(s.bitangent) / s.radius; - if lx * lx + ly * ly > 2.0 { + let position = *position_a * b0 + *position_b * b1 + *position_c * b2; + let offset = position - stamp.center; + let local_x = offset.dot(stamp.tangent) / stamp.radius; + let local_y = offset.dot(stamp.bitangent) / stamp.radius; + if local_x * local_x + local_y * local_y > 2.0 { continue; } - if d.dot(s.normal).abs() > s.radius * s.depth { + + if offset.dot(stamp.normal).abs() > stamp.radius * stamp.depth { continue; } - let dist = d.length_squared(); - if dist < center.1 { - center = ([x as f32 + 0.5, y as f32 + 0.5], dist); + + let distance_squared = offset.length_squared(); + if distance_squared < center.1 { + center = ([x as f32 + 0.5, y as f32 + 0.5], distance_squared); } - let n = (*na * b0 + *nb * b1 + *nc * b2).try_normalize().unwrap_or(s.normal); - let to_eye = (ctx.eye - p).try_normalize().unwrap_or(n); - let facing = n.dot(to_eye); - // Symmetry copies paint where the camera may not see (the back of the model). - let culled = ctx.backface_culling && !s.copy; - if culled && facing <= 0.0 { + + let normal = (*normal_a * b0 + *normal_b * b1 + *normal_c * b2).try_normalize().unwrap_or(stamp.normal); + if normal.dot(stamp.normal) <= 0.0 { continue; } - if n.dot(s.normal) <= 0.0 { + + // Allow half the stamp depth when the mirrored point is off an asymmetric surface + let (seen, seen_normal) = stamp.source.map_or((position, normal), |source| (source.point(position), source.direction(normal))); + let off_surface = if stamp.source.is_some() { stamp.radius * stamp.depth } else { 0.0 }; + let to_eye = (context.eye - seen).try_normalize().unwrap_or(seen_normal); + let facing = seen_normal.dot(to_eye); + if context.backface_culling && facing <= 0.0 { continue; } - if let Some(depth) = ctx.depth.filter(|_| !s.copy) - && !depth.visible(p) + + if let Some(depth) = context.depth + && !depth.visible(seen + to_eye * (grazing_allowance(depth, seen, facing, pixels_per_unit) + off_surface)) { continue; } - let fade = if culled { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 }; - let a = shape.sample(lx, ly, s.hardness, s.seed) * s.flow * fade; - if a > 0.0 { - texels.push((x, y, a)); + + let fade = if context.backface_culling { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 }; + let alpha = shape.sample(local_x, local_y, stamp.hardness, stamp.seed) * stamp.flow * fade; + if alpha > 0.0 { + texels.push((x, y, alpha)); } } } + (center.1 < f32::MAX || !texels.is_empty()).then_some((texels, center)) } @@ -257,7 +310,7 @@ mod tests { hardness: 0.9, depth: 1.0, seed: 0, - copy: false, + source: None, }; rasterize(&mut canvas, &ctx, &[st]); // Plane is 2 units over 128 texels: radius 0.25 = 16 texels around the center (64, 64). diff --git a/crates/paint/src/stamp_source.rs b/crates/paint/src/stamp_source.rs new file mode 100644 index 00000000..5f56e435 --- /dev/null +++ b/crates/paint/src/stamp_source.rs @@ -0,0 +1,24 @@ +//! Where a symmetry copy of a stamp comes from + +use texturecraft_geom::glam::{Mat3, Vec3}; + +/// The map from a symmetry copy back to its source stamp: a copy paints where its source would be painted +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StampSource { + /// The point the symmetry maps turn and mirror about + pub origin: Vec3, + /// The inverse of the copy's linear map (mirrors and turns, so its transpose) + pub to_source: Mat3, +} + +impl StampSource { + /// The source's point for a point of the copy + pub fn point(&self, copy_point: Vec3) -> Vec3 { + self.origin + self.to_source * (copy_point - self.origin) + } + + /// The source's direction for a direction of the copy + pub fn direction(&self, copy_direction: Vec3) -> Vec3 { + self.to_source * copy_direction + } +} diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index 6aacb737..9cc3972b 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -1,11 +1,12 @@ //! From pointer samples to stamps: picking, lazy mouse, spacing along the surface, stamp //! frames, jitter and symmetry. -use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::glam::{Mat3, Quat, Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, surface_at}; use texturecraft_texel::noise::pcg3d; use crate::brush::{Alignment, BrushSettings}; +use crate::stamp_source::StampSource; /// Scene access for picking. pub struct PickCtx<'a> { @@ -37,7 +38,20 @@ pub fn pick(ctx: &PickCtx, screen: Vec2) -> Option { Some(SurfaceHit { pos: s.pos, nrm: s.nrm, tri: hit.tri, uv: s.uv, material: ctx.mesh.material_of(hit.tri as usize).unwrap_or(0), screen }) } -/// One brush dab in world space. +/// Random channels of a stamp's jitters (each draws its own number from the stamp's seed) +const JITTER_ANGLE: u32 = 1; +const JITTER_SIZE: u32 = 2; +const JITTER_ACROSS: u32 = 3; +const JITTER_ALONG: u32 = 4; +const JITTER_FLOW: u32 = 5; + +/// Full angle jitter turns a stamp this far either way (degrees) +const HALF_TURN_DEGREES: f32 = 180.0; + +/// Smallest size jitter leaves a stamp, as a fraction of its radius +const MIN_JITTERED_SIZE: f32 = 0.05; + +/// One brush dab in world space #[derive(Clone, Copy, Debug, PartialEq)] pub struct Stamp { pub center: Vec3, @@ -47,12 +61,12 @@ pub struct Stamp { pub radius: f32, pub flow: f32, pub hardness: f32, - /// Half-depth of the stamp volume relative to the radius. + /// Half-depth of the stamp volume relative to the radius pub depth: f32, - /// Varies procedural alphas per stamp. + /// Varies procedural alphas per stamp pub seed: u32, - /// A symmetry copy: it paints where symmetry puts it, whether the camera sees that or not. - pub copy: bool, + /// A symmetry copy's way back to its source: it paints where the source would, mirrored + pub source: Option, } /// An in-progress stroke. @@ -168,66 +182,87 @@ impl Stroke { self.last = Some(hit); } + /// The next stamp at `hit`: oriented to the surface or the camera, then jittered fn stamp(&mut self, ctx: &PickCtx, hit: &SurfaceHit, radius: f32) -> Stamp { - let s = &self.settings; - let n = self.count; + let settings = &self.settings; + let seed = self.count; self.count = self.count.wrapping_add(1); - let jitter = |k: u32, amount: f32| if amount > 0.0 { (rand01(n, k) * 2.0 - 1.0) * amount } else { 0.0 }; - let normal = match s.alignment { + let jitter = |channel: u32, amount: f32| if amount > 0.0 { (rand01(seed, channel) * 2.0 - 1.0) * amount } else { 0.0 }; + + // Frame: the normal, and an up direction from the camera or the stroke's path + let normal = match settings.alignment { Alignment::Tangent => hit.nrm, Alignment::Camera => -ctx.camera.forward(), }; - let cam_up = { - let f = ctx.camera.forward(); - let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); - right.cross(f) + let camera_up = { + let forward = ctx.camera.forward(); + let right = forward.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + right.cross(forward) }; - let up_src = if s.follow_path { self.last_dir.unwrap_or(cam_up) } else { cam_up }; - let up = (up_src - normal * normal.dot(up_src)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); - let tangent0 = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); - let angle = (s.angle + jitter(1, s.jitter_angle) * 180.0).to_radians(); - let q = Quat::from_axis_angle(normal, angle); - let tangent = q * tangent0; + let up_source = if settings.follow_path { self.last_dir.unwrap_or(camera_up) } else { camera_up }; + let up = (up_source - normal * normal.dot(up_source)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + let unturned_tangent = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + + // Jitter: angle, size, position and flow + let angle = (settings.angle + jitter(JITTER_ANGLE, settings.jitter_angle) * HALF_TURN_DEGREES).to_radians(); + let turn = Quat::from_axis_angle(normal, angle); + let tangent = turn * unturned_tangent; let bitangent = normal.cross(tangent); - let r = radius * (1.0 + jitter(2, s.jitter_size)).max(0.05); - let offset = (tangent * jitter(3, 1.0) + bitangent * jitter(4, 1.0)) * s.jitter_position * radius; - let flow = (s.flow * (1.0 - jitter(5, s.jitter_flow).abs())).clamp(0.0, 1.0); - Stamp { center: hit.pos + offset, normal, tangent, bitangent, radius: r, flow, hardness: s.hardness, depth: s.depth, seed: n, copy: false } + let jittered_radius = radius * (1.0 + jitter(JITTER_SIZE, settings.jitter_size)).max(MIN_JITTERED_SIZE); + let offset = (tangent * jitter(JITTER_ACROSS, 1.0) + bitangent * jitter(JITTER_ALONG, 1.0)) * settings.jitter_position * radius; + let flow = (settings.flow * (1.0 - jitter(JITTER_FLOW, settings.jitter_flow).abs())).clamp(0.0, 1.0); + + Stamp { + center: hit.pos + offset, + normal, + tangent, + bitangent, + radius: jittered_radius, + flow, + hardness: settings.hardness, + depth: settings.depth, + seed, + source: None, + } } - /// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and - /// its mirrors. - fn mirrors(&self, s: &Stamp) -> Vec { - let sym = self.settings.symmetry; - if !sym.any() { + /// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and its mirrors + fn mirrors(&self, stamp: &Stamp) -> Vec { + let symmetry = self.settings.symmetry; + if !symmetry.any() { return Vec::new(); } - let mut out = Vec::new(); - for sign in sym.mirror_signs().skip(1) { - let normal = s.normal * sign; - let tangent = s.tangent * sign; - out.push(Stamp { center: self.center + (s.center - self.center) * sign, normal, tangent, bitangent: normal.cross(tangent), copy: true, ..*s }); + let origin = symmetry.origin(self.center); + let mut copies = Vec::new(); + let mut maps = Vec::new(); + for sign in symmetry.mirror_signs().skip(1) { + let normal = stamp.normal * sign; + let tangent = stamp.tangent * sign; + let map = Mat3::from_diagonal(sign); + let source = Some(StampSource { origin, to_source: map.transpose() }); + copies.push(Stamp { center: origin + (stamp.center - origin) * sign, normal, tangent, bitangent: normal.cross(tangent), source, ..*stamp }); + maps.push(map); } - if sym.radial > 1 { - let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(sym.axis as usize).copied().unwrap_or(Vec3::Y); - let base: Vec = std::iter::once(*s).chain(out.iter().copied()).collect(); + if symmetry.radial_on() { + let axis = symmetry.radial_axis(); + let to_turn: Vec<(Stamp, Mat3)> = std::iter::once((*stamp, Mat3::IDENTITY)).chain(copies.iter().copied().zip(maps)).collect(); - for k in 1..sym.radial { - let q = Quat::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(sym.radial)); - out.extend(base.iter().map(|b| Stamp { - center: self.center + q * (b.center - self.center), - normal: q * b.normal, - tangent: q * b.tangent, - bitangent: q * b.bitangent, - copy: true, - ..*b + for copy in 1..symmetry.radial { + let turn = Quat::from_axis_angle(axis, symmetry.radial_angle(copy)); + copies.extend(to_turn.iter().map(|(base, map)| Stamp { + center: origin + turn * (base.center - origin), + normal: turn * base.normal, + tangent: turn * base.tangent, + bitangent: turn * base.bitangent, + source: Some(StampSource { origin, to_source: (Mat3::from_quat(turn) * *map).transpose() }), + ..*base })); } } - out + copies } pub fn last_hit(&self) -> Option { @@ -296,6 +331,61 @@ mod tests { assert_eq!(s.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 8); } + #[test] + fn symmetry_mirrors_about_the_moved_plane() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry.x = true; + settings.symmetry.offset = [0.25, 0.0, 0.0]; + let mut stroke = Stroke::new(&settings, &mesh); + let stamps = stroke.add(&ctx, Vec2::new(250.0, 200.0), 1.0); + assert_eq!(stamps.len(), 2, "one stamp and its copy"); + let (painted, copy) = (stamps[0], stamps[1]); + + // Mirrored about x = 0.25 instead of the mesh center (x = 0) + assert!((painted.center.x + copy.center.x - 0.5).abs() < 1e-4, "{} {}", painted.center, copy.center); + assert!((painted.center.y - copy.center.y).abs() < 1e-4 && (painted.center.z - copy.center.z).abs() < 1e-4); + } + + #[test] + fn default_symmetry_copies_match_the_mesh_centered_formula_bit_for_bit() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry = crate::brush::Symmetry { x: true, y: true, radial: 3, axis: 1, ..settings.symmetry }; + let mut stroke = Stroke::new(&settings, &mesh); + let stamps = stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0); + + // Copies as painting computed them before the plane could move: mirrors, then radial turns of each + let (lo, hi) = mesh.bounds(); + let center = (lo + hi) * 0.5; + let source = stamps[0].center; + let mirrored = [Vec3::new(-1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, 1.0), Vec3::new(-1.0, -1.0, 1.0)].map(|sign| center + (source - center) * sign); + let to_turn: Vec = std::iter::once(source).chain(mirrored).collect(); + let turned = (1..3u8).flat_map(|copy| { + let turn = Quat::from_axis_angle(Vec3::Y, f32::from(copy) * std::f32::consts::TAU / 3.0); + to_turn.iter().map(move |point| center + turn * (*point - center)).collect::>() + }); + let expected: Vec = mirrored.into_iter().chain(turned).collect(); + + let copies: Vec = stamps[1..].iter().map(|stamp| stamp.center).collect(); + assert_eq!(copies, expected); + } + + #[test] + fn a_zero_angle_span_paints_no_radial_copies() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry.radial = 6; + settings.symmetry.angle_span = 0.0; + let mut stroke = Stroke::new(&settings, &mesh); + + // Six copies with no angle between them would all paint over the stroke + assert_eq!(stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 1); + } + #[test] fn radial_symmetry_spreads_copies_around_the_axis() { let (m, b, c) = ctx_parts(); diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 775fc026..601e097e 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -113,6 +113,11 @@ pub struct GpuTracer { env: Option, materials: Option, acc: Option, + /// Keep the preceding size so motion/full-resolution switches can reuse allocations. + spare_acc: Option, + /// How many sets of accumulation buffers were allocated (for tests). + #[cfg(test)] + acc_allocations: u32, scene: Option, bind: Option, samples: u32, @@ -309,6 +314,9 @@ impl GpuTracer { env: None, materials: None, acc: None, + spare_acc: None, + #[cfg(test)] + acc_allocations: 0, scene: None, bind: None, samples: 0, @@ -323,6 +331,7 @@ impl GpuTracer { /// Free the scene and accumulation memory, keeping the compiled pipelines. pub fn release(&mut self) { (self.geometry, self.env, self.materials, self.acc, self.scene, self.bind) = (None, None, None, None, None, None); + self.spare_acc = None; self.samples = 0; } @@ -498,24 +507,42 @@ impl GpuTracer { Ok(true) } - /// Start over at `width × height` (the accumulation buffers are cleared or reallocated). + /// Start over at `width × height`, keeping the active render intact if allocation fails. pub fn reset(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, width: u32, height: u32) -> Result<(), String> { - let (w, h) = (width.clamp(1, 8192), height.clamp(1, 8192)); - self.samples = 0; - if let Some(a) = self.acc.as_ref().filter(|a| (a.width, a.height) == (w, h)) { - for b in &a.acc { - encoder.clear_buffer(b, 0, None); + let (width, height) = (width.clamp(1, 8192), height.clamp(1, 8192)); + let bytes = u64::from(width) * u64::from(height) * 16; + let limits = device.limits(); + + // Reject unsupported sizes before invalidating the displayed render + if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit")); + } + + if let Some(accumulation) = self.acc.as_ref().filter(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { + for buffer in &accumulation.acc { + encoder.clear_buffer(buffer, 0, None); } + + self.samples = 0; return Ok(()); } - self.acc = None; - self.bind = None; - let bytes = u64::from(w) * u64::from(h) * 16; - let limits = device.limits(); - if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err(format!("a {w}×{h} render exceeds this GPU's buffer limit")); + + // Reused buffers must not retain samples from the previous view + if let Some(spare) = self.spare_acc.take_if(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { + for buffer in spare.acc.iter().chain(&spare.illum) { + encoder.clear_buffer(buffer, 0, None); + } + + self.spare_acc = self.acc.replace(spare); + self.bind = None; + self.samples = 0; + return Ok(()); } - let buf = |label| { + + // Retire the obsolete spare before allocating, but keep the active render until success + self.spare_acc = None; + + let create_buffer = |label| { device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size: bytes, @@ -523,12 +550,20 @@ impl GpuTracer { mapped_at_creation: false, }) }; - self.acc = Some(scoped(device, "GPU path tracing: accumulation buffers", || Accum { - width: w, - height: h, - acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(buf), - illum: ["tc_illum_a", "tc_illum_b"].map(buf), - })?); + let accumulation = scoped(device, "GPU path tracing: accumulation buffers", || Accum { + width, + height, + acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(create_buffer), + illum: ["tc_illum_a", "tc_illum_b"].map(create_buffer), + })?; + self.spare_acc = self.acc.replace(accumulation); + self.bind = None; + self.samples = 0; + #[cfg(test)] + { + self.acc_allocations += 1; + } + Ok(()) } @@ -800,22 +835,87 @@ mod tests { /// The radiance accumulation, read back. fn accumulation(h: &Headless, t: &GpuTracer) -> Vec<[f32; 4]> { - let acc = t.acc.as_ref().unwrap(); - let bytes = acc.width as u64 * acc.height as u64 * 16; - let staging = h.device.create_buffer(&wgpu::BufferDescriptor { + read_buffer(h, &t.acc.as_ref().unwrap().acc[0]) + } + + /// Read a completed buffer to check its contents across resets and reuse. + fn read_buffer(headless: &Headless, buffer: &wgpu::Buffer) -> Vec<[f32; 4]> { + let bytes = buffer.size(); + let staging = headless.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: bytes, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false, }); - let mut enc = h.device.create_command_encoder(&Default::default()); - enc.copy_buffer_to_buffer(&acc.acc[0], 0, &staging, 0, bytes); - h.queue.submit([enc.finish()]); + let mut encoder = headless.device.create_command_encoder(&Default::default()); + encoder.copy_buffer_to_buffer(buffer, 0, &staging, 0, bytes); + headless.queue.submit([encoder.finish()]); staging.slice(..).map_async(wgpu::MapMode::Read, |_| {}); - h.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + headless.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).unwrap(); + bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec() } + /// Two cached sizes reuse cleared buffers, and leaving Rendering mode releases both. + #[test] + fn switching_between_two_sizes_reuses_the_accumulation_buffers() { + let Some((headless, mut tracer)) = gpu() else { return }; + + for (width, height) in [(64, 48), (32, 24), (64, 48), (32, 24), (64, 48)] { + let mut encoder = headless.device.create_command_encoder(&Default::default()); + tracer.reset(&headless.device, &mut encoder, width, height).unwrap(); + headless.queue.submit([encoder.finish()]); + + let accumulation = tracer.acc.as_ref().unwrap(); + assert_eq!((accumulation.width, accumulation.height), (width, height)); + assert_eq!(tracer.samples(), 0); + for buffer in accumulation.acc.iter().chain(&accumulation.illum) { + assert!(read_buffer(&headless, buffer).iter().all(|pixel| *pixel == [0.0; 4]), "reused buffers must be cleared"); + + // Leave nonzero contents to detect stale pixels on the next reuse + let pixels = vec![[1.0f32; 4]; (width * height) as usize]; + headless.queue.write_buffer(buffer, 0, bytemuck::cast_slice(&pixels)); + } + tracer.samples = 7; + } + + assert_eq!(tracer.acc_allocations, 2, "two sizes, two allocations, however often it switches"); + let mut encoder = headless.device.create_command_encoder(&Default::default()); + tracer.reset(&headless.device, &mut encoder, 16, 16).unwrap(); + headless.queue.submit([encoder.finish()]); + assert_eq!(tracer.acc_allocations, 3, "a third size allocates (and drops the oldest set)"); + + tracer.release(); + assert!(tracer.acc.is_none() && tracer.spare_acc.is_none(), "leaving Rendering mode frees both sizes"); + } + + /// Rejecting an oversized render preserves the image and lets tracing continue. + #[test] + fn failed_reset_retains_the_active_render() { + let Some((mut headless, mut tracer)) = gpu() else { return }; + let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); + let camera = camera(); + let settings = TraceSettings::default(); + let display = TraceDisplay::from_display(&Default::default()); + tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera, &settings, &display, [32, 24], 2).unwrap(); + let before = accumulation(&headless, &tracer); + + let mut encoder = headless.device.create_command_encoder(&Default::default()); + let error = tracer.reset(&headless.device, &mut encoder, 8192, 8192).unwrap_err(); + + assert!(error.contains("exceeds this GPU's buffer limit")); + assert!(tracer.acc.is_some(), "a rejected resize must keep the active buffers"); + assert!(tracer.bind.is_some(), "a rejected resize must keep the active bindings"); + assert_eq!(tracer.samples(), 2, "a rejected resize must keep the accumulated samples"); + assert_eq!(accumulation(&headless, &tracer), before); + assert!(tracer.pass(&headless.device, &headless.queue, &mut encoder, &camera, &settings, 1)); + let output = GpuTracer::output_texture(&headless.device, 32, 24); + assert!(tracer.resolve(&headless.device, &headless.queue, &mut encoder, &display, &output.create_view(&Default::default()))); + headless.queue.submit([encoder.finish()]); + assert!(crate::readback::Readback::blocking(&headless.device, &headless.queue, &output).is_some()); + assert_eq!(tracer.samples(), 3); + } + const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])]; #[test] diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index bb0967c7..649d9988 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -24,6 +24,7 @@ pub mod headless; mod high_poly_gpu; pub mod ibl; pub mod mesh_maps; +pub mod overlay_quad; pub mod readback; pub mod renderer; pub mod set_highlight; @@ -32,6 +33,7 @@ pub mod trace; mod uv_seam_gpu; pub use bake_visualization::BakeVisualization; +pub use overlay_quad::OverlayQuad; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/overlay_quad.rs b/crates/render/src/overlay_quad.rs new file mode 100644 index 00000000..c813bb42 --- /dev/null +++ b/crates/render/src/overlay_quad.rs @@ -0,0 +1,11 @@ +//! See-through quads drawn into the 3D view and hidden where the mesh is in front (the symmetry plane and lines) + +use texturecraft_geom::glam::Vec3; + +/// A flat quad with its corners in order, in a screen color (linear RGB) and opacity +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OverlayQuad { + pub corners: [Vec3; 4], + pub color: [f32; 3], + pub opacity: f32, +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ad2bc2bf..1636f1ad 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -35,6 +35,7 @@ use crate::cage_gpu::CageGpu; use crate::gpu_trace::{Checked, checked}; use crate::high_poly_gpu::HighPolyGpu; use crate::ibl; +use crate::overlay_quad::OverlayQuad; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; use crate::uv_seam_gpu::UvSeamGpu; @@ -289,6 +290,8 @@ pub struct Frame { pub shade: Shade, /// Visibility per texture set. pub visible: Vec, + /// See-through quads in the 3D view, hidden behind the mesh + pub overlay: Vec, } struct Tex { @@ -499,6 +502,9 @@ struct ViewTargets { behind: Option, blit_buf: wgpu::Buffer, blit_bg: wgpu::BindGroup, + /// The frame's overlay triangles and how many vertices of the buffer they use + overlay: Option, + overlay_vertices: u32, /// Set by [`Renderer::prepare`]: the view has content to blit. ready: bool, } @@ -535,6 +541,7 @@ pub struct Renderer { uv_pipeline: wgpu::RenderPipeline, wire_pipeline: wgpu::RenderPipeline, wire3d_pipeline: wgpu::RenderPipeline, + overlay_pipeline: wgpu::RenderPipeline, /// The highlighted set's mesh edges, wider and in the highlight color highlight_pipeline: wgpu::RenderPipeline, /// Bake mode: the high poly, the cage's faces and wireframe, the low poly's UV seams @@ -997,6 +1004,8 @@ impl Renderer { let uv_seam_pipeline = pipeline(device, "tc_uv_seam", &layout, &module, "vs_wire3d", &vertex_layout, hdr_target("fs_wire_uv_seam", blend), MSAA, wire3d_depth.clone()); let bg_pipeline = pipeline(device, "tc_bg", &background_layout, &module, "vs_bg", &[], hdr_target("fs_bg", None), MSAA, always()); + let overlay_pipeline = + pipeline(device, "tc_overlay", &background_layout, &module, "vs_overlay", &vertex_layout, hdr_target("fs_overlay", blend), MSAA, wire3d_depth); let blit_pipeline = pipeline(device, "tc_blit", &blit_layout, &util_module, "vs_blit", &[], Some(("fs_blit", target_format, None)), 1, None); let post_pipeline = pipeline(device, "tc_post", &effect_layout, &post_module, "vs_full", &[], Some(("fs_post", COLOR_FORMAT, None)), 1, None); let bloom_pipelines = [("fs_bloom_pre", None), ("fs_bloom_down", None), ("fs_bloom_up", Some(ADDITIVE))].map(|(fragment_entry_point, blend)| { @@ -1121,6 +1130,7 @@ impl Renderer { uv_pipeline, wire_pipeline, wire3d_pipeline, + overlay_pipeline, highlight_pipeline, bake_high_pipeline, cage_pipeline, @@ -1675,6 +1685,8 @@ impl Renderer { behind: None, blit_buf, blit_bg, + overlay: None, + overlay_vertices: 0, ready: false, } } @@ -1938,6 +1950,7 @@ impl Renderer { let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post)); + upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev)); v.ready = true; v.history = Some((frame.clone(), rev)); v.samples = sample; @@ -2160,6 +2173,15 @@ impl Renderer { if let Some(bake) = bake { self.draw_bake(&mut pass, mesh, frame, bake); } + + // Overlay quads last, so the mesh's depth hides what is behind it + if uv_set.is_none() + && let Some(overlay) = targets.overlay.as_ref().filter(|_| targets.overlay_vertices > 0) + { + pass.set_pipeline(&self.overlay_pipeline); + pass.set_vertex_buffer(0, overlay.slice(..)); + pass.draw(0..targets.overlay_vertices, 0..1); + } } /// Bake mode's high poly, UV seams and cages over the low poly `low_poly` @@ -2261,6 +2283,51 @@ fn drawable_ranges<'a>( }) } +/// A quad's two triangles, as corner indices +const QUAD_TRIANGLES: [usize; 6] = [0, 1, 2, 0, 2, 3]; + +/// Write `quads` into the view's overlay buffer, colors divided by the exposure only (undoing ACES makes saturated colors overshoot) +fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTargets, quads: &[OverlayQuad], exposure_ev: Option) { + view.overlay_vertices = 0; + let Some(vertex_count) = quads.len().checked_mul(QUAD_TRIANGLES.len()).and_then(|count| u32::try_from(count).ok()) else { + log::warn!("Symmetry overlay has too many vertices; hide the intersection or use a simpler mesh"); + return; + }; + + // A valid imported mesh can produce more intersection vertices than the GPU accepts + let byte_count = u64::from(vertex_count) * std::mem::size_of::() as u64; + if byte_count > device.limits().max_buffer_size { + log::warn!("Symmetry overlay exceeds the GPU buffer limit; hide the intersection or use a simpler mesh"); + return; + } + + if vertex_count == 0 { + return; + } + + let vertices: Vec = quads + .iter() + .flat_map(|quad| { + let [r, g, b] = exposure_ev.map_or(quad.color, |exposure_ev| crate::set_highlight::scene_color_showing(quad.color, exposure_ev, false)); + let vertex = |corner: Vec3| Vertex { pos: corner.to_array(), nrm: [0.0; 3], tan: [r, g, b, quad.opacity], uv: [0.0; 2] }; + QUAD_TRIANGLES.map(|corner| vertex(quad.corners[corner])) + }) + .collect(); + let bytes: &[u8] = bytemuck::cast_slice(&vertices); + if view.overlay.as_ref().is_none_or(|buffer| buffer.size() < bytes.len() as u64) { + view.overlay = Some(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_overlay"), + size: bytes.len() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + if let Some(buffer) = &view.overlay { + queue.write_buffer(buffer, 0, bytes); + view.overlay_vertices = vertex_count; + } +} + /// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { let Some(highlight) = shade.highlight else { return [0.0; 4] }; @@ -2282,6 +2349,23 @@ mod tests { use super::*; use crate::headless::Headless; + #[test] + fn oversized_overlays_leave_the_view_usable() { + let Ok(mut headless) = Headless::new() else { return }; + let limit = headless.device.limits().max_buffer_size as usize; + let count = limit / (QUAD_TRIANGLES.len() * std::mem::size_of::()) + 1; + let quad = OverlayQuad { corners: [Vec3::ZERO; 4], color: [1.0, 0.0, 0.0], opacity: 0.5 }; + let quads = vec![quad; count]; + let view = headless.renderer.targets(&headless.device, 1, [32, 32], false, false, false).unwrap(); + upload_overlay(&headless.device, &headless.queue, view, &[quad], None); + + upload_overlay(&headless.device, &headless.queue, view, &quads, None); + + assert_eq!(view.overlay_vertices, 0, "skip overlays beyond the device limit"); + upload_overlay(&headless.device, &headless.queue, view, &[quad], None); + assert_eq!(view.overlay_vertices, 6, "the next frame can draw its overlay"); + } + /// A headless renderer with one 256² texture set, and the base color slot's full-size /// texture handed over as WebGPU would: allocated, with its verdict still to come. fn awaiting() -> Option<(Headless, std::sync::mpsc::Sender>)> { diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs index 878968c1..cc29879e 100644 --- a/crates/render/src/set_highlight.rs +++ b/crates/render/src/set_highlight.rs @@ -17,17 +17,22 @@ pub struct SetHighlight { impl SetHighlight { /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { - let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); - - self.color.map(|screen| { - let screen = screen.max(0.0); - let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; - - exposed / exposure - }) + scene_color_showing(self.color, exposure_ev, aces) } } +/// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as `screen` (linear RGB) +pub(crate) fn scene_color_showing(screen: [f32; 3], exposure_ev: f32, aces: bool) -> [f32; 3] { + let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); + + screen.map(|screen| { + let screen = screen.max(0.0); + let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; + + exposed / exposure + }) +} + /// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input fn inverse_aces(screen: f32) -> f32 { let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen); diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 863d6eae..23c4bd64 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -682,6 +682,26 @@ fn fs_wire3d(i: VOut) -> @location(0) vec4 { return vec4(0.35, 0.35, 0.35, 0.45); } +// How far overlay quads move toward the eye, as a fraction of their distance (as the wireframe does) +const OVERLAY_TOWARD_EYE: f32 = 0.002; + +// See-through overlay quads (the symmetry plane and the lines on the mesh): the color comes in the tangent slot, nudged toward the eye like the wireframe so lines on the surface win the depth test +@vertex +fn vs_overlay(v: VIn) -> VOut { + var o: VOut; + o.wpos = v.pos; + o.nrm = v.nrm; + o.tan = v.tan; + o.uv = v.uv; + o.clip = g.view_proj * vec4(v.pos + (g.eye.xyz - v.pos) * OVERLAY_TOWARD_EYE, 1.0); + return o; +} + +@fragment +fn fs_overlay(i: VOut) -> @location(0) vec4 { + return i.tan; +} + // The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel @vertex fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut { diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a823a031..36a1c087 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -66,6 +66,9 @@ pub struct TraceScene { pub lens: Option<[f32; 2]>, } +/// Width of the built-in environments traced (texels). +const ENV_SIZE: u32 = 1024; + impl TraceScene { pub fn new(mesh: Arc, bvh: Arc, sets: Vec, env: Arc, env_rotation: f32) -> TraceScene { let mut tri_set = vec![usize::MAX; mesh.triangle_count()]; @@ -114,13 +117,24 @@ impl TraceScene { /// The scene as `display` shows it: the imported environment `env_image` (when the display /// names a resource and it decodes) or the built-in one, its rotation and the shading mode. pub fn for_display(mesh: Arc, bvh: Arc, sets: Vec, display: &DisplaySettings, env_image: Option<&ImageRes>) -> TraceScene { + TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(TraceScene::display_env(display, env_image))) + } + + /// The environment [`TraceScene::for_display`] traces under (building it takes a while: a + /// caller that rebuilds scenes often keeps it and passes it to [`TraceScene::for_display_env`]). + pub fn display_env(display: &DisplaySettings, env_image: Option<&ImageRes>) -> EnvImage { let imported = env_image.and_then(|i| EnvImage::from_rgba(i.width, i.height, &i.rgba, i.srgb)); - let env = imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, 1024)); - let mut scene = TraceScene::new(mesh, bvh, sets, Arc::new(env), display.env_rotation.to_radians()); + imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, ENV_SIZE)) + } + + /// [`TraceScene::for_display`] under `env`, from [`TraceScene::display_env`] of the same display. + pub fn for_display_env(mesh: Arc, bvh: Arc, sets: Vec, display: &DisplaySettings, env: Arc) -> TraceScene { + let mut scene = TraceScene::new(mesh, bvh, sets, env, display.env_rotation.to_radians()); scene.spec_gloss = display.spec_gloss; scene.set_scatter(display.scatter_color, display.scatter_radius); scene.ior = display.ior; scene.lens = display.dof.enabled.then_some([display.dof.focus_distance, display.dof.aperture]); + scene } diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 84a6e0e2..3b5b3938 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -59,7 +59,8 @@ fn setup() -> Option<(Headless, Frame)> { let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); cam.frame(lo, hi); - let frame = Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true] }; + let frame = + Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true], overlay: Vec::new() }; Some((h, frame)) } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index fdc45c70..46f84fd7 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -55,4 +55,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } +# Fallible setup of the exact GPU device used by rendering regression tests. +pollster = "0.4" image = { workspace = true } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 0260d65c..b95788d3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -73,6 +73,7 @@ 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, p: &Value) -> Value { + app.ui.prefs.apply_resource_limits(); match method { "ping" => ok(json!("pong")), "ui.resize" => { @@ -178,6 +179,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & match serde_json::from_value(cur) { Ok(ui) => { app.ui = ui; + app.ui.prefs.apply_resource_limits(); ok(Value::Null) } Err(e) => err(format!("invalid UI state: {e}")), diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index d32fe0e6..15371d22 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1612,30 +1612,10 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { brush.particles = defaults.particles; } - let lazy_fields = |settings: &BrushSettings| (settings.lazy, settings.symmetry); - if section_with_reset(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, lazy_fields(brush) == lazy_fields(&defaults), |ui| { + if section_with_reset(ui, "sec_lazy", tr("Lazy mouse"), false, brush.lazy == defaults.lazy, |ui| { slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); - ui.horizontal(|ui| { - ui.checkbox(&mut brush.symmetry.x, tr("Mirror X")); - ui.checkbox(&mut brush.symmetry.y, tr("Mirror Y")); - ui.checkbox(&mut brush.symmetry.z, tr("Mirror Z")); - }); - - let mut copies = f32::from(brush.symmetry.radial); - if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() { - brush.symmetry.radial = copies as u8; - } - - ui.add_enabled_ui(brush.symmetry.radial > 1, |ui| { - ui.horizontal(|ui| { - ui.label(tr("Radial axis")); - for (axis_index, name) in ["X", "Y", "Z"].into_iter().enumerate() { - ui.selectable_value(&mut brush.symmetry.axis, axis_index as u8, name); - } - }); - }); }) { - (brush.lazy, brush.symmetry) = lazy_fields(&defaults); + brush.lazy = defaults.lazy; } *brush = brush.sanitized(); @@ -2421,17 +2401,18 @@ fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generat } }); - let (mut level, mut softness, mut noise, mut noise_scale, mut invert) = - (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.invert); + let (mut level, mut softness, mut noise, mut noise_scale, mut offset, mut invert) = + (generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset, generator.invert); let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2); let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2); let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2); let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1); + let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2); let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false); - if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(invert_edit) { + if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit).or(invert_edit) { app.run( "effect.set", - json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "invert": invert, "merge": merge}), + json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "invert": invert, "merge": merge}), ); } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 0dcbdaa2..5bebfd98 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -133,9 +133,7 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; let column = split( @@ -147,20 +145,13 @@ pub fn default_workspace() -> Workspace { let root = split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); + for panel in Panel::ALL { if let Some(rect) = panel.float_rect() { - let location = Location { - floating: Some(rect), - anchor: None, - placement: Placement::Tab { before: None }, - size: None, - stack: None, - sibling: Vec::new(), - group: None, - }; - workspace.hidden.push((panel, location)); + workspace.hidden.push((panel, floating_location(rect))); } } + for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { workspace.hidden.push(( panel, @@ -175,9 +166,15 @@ pub fn default_workspace() -> Workspace { }, )); } + workspace } +/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`) +fn floating_location(rect: [f32; 4]) -> Location { + Location { floating: Some(rect), anchor: None, placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None } +} + /// craft-ui's checks plus the viewport's: a saved or hand-edited file cannot hide, float, group /// or collapse it. pub fn validate(workspace: &Workspace) -> Result<(), String> { @@ -344,6 +341,13 @@ impl Dock { } } + /// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`) + pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) { + self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel); + self.workspace.hidden.push((panel, floating_location(rect))); + self.focus(panel); + } + /// One change from the dock area's gestures. A change that is rejected leaves the layout as /// it was. fn apply(&mut self, action: Action) { @@ -415,57 +419,70 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tk: tokens }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens }); + crate::rail_popup::hand_drag_to_dock(&context, area_id()); + + // After the dock, which records the viewport the popup reaches into, and before a changed layout returns early + crate::rail_popup::show(app, &context); + #[cfg(not(target_arch = "wasm32"))] crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); if let Some(error) = &output.error { log::warn!("docking: {error}"); } + // A layout changed by a panel takes priority over gestures from the old layout if app.ui.dock.workspace.layout != layout { craft_ui::docking::cancel_drag::(&context, area_id()); return; } + for action in output.actions { app.ui.dock.apply(action); } } -/// The panels' contents, names and limits for the dock area. +/// The panels' contents, names and limits for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, - tk: Tokens, + tokens: Tokens, +} + +/// Room between a panel's edges and its contents +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) { + 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), + Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), + Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), + Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), + Panel::TextureSetList => crate::dock::texture_set_list(app, ui), + 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, + Panel::History => crate::windows::history(app, ui), + Panel::Log => crate::windows::log(app, ui), + Panel::Viewport => {} + }); } impl DockContent for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { let app = &mut *self.app; if *panel == Panel::Viewport { - ui.painter().rect_filled(ui.max_rect(), 0.0, self.tk.viewport); + crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); + ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); crate::viewport::central(app, ui); return; } - egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), - Panel::Assets => crate::shelf::body(app, ui), - Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), - Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), - Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), - Panel::TextureSetList => crate::dock::texture_set_list(app, ui), - Panel::Layers => crate::dock::layers(app, ui), - Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), - Panel::Properties => crate::dock::properties(app, ui), - // The other panels scroll their own lists. - Panel::Display => { - egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, false]).show(ui, |ui| crate::windows::display(app, ui)).inner - } - Panel::Shader => { - egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, false]).show(ui, |ui| crate::windows::shader(app, ui)).inner - } - Panel::History => crate::windows::history(app, ui), - Panel::Log => crate::windows::log(app, ui), - Panel::Viewport => {} - }); + + panel_body(app, ui, *panel); } fn logical_label(&self, panel: &Panel) -> String { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index aabb2571..95373f3d 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -451,7 +451,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "ذاكرة الطبقات: {mb} ميغابايت"), ("Layers", "الطبقات"), ("Lazy mouse", "الفأرة الكسولة (Lazy mouse)"), - ("Lazy mouse and symmetry", "الفأرة الكسولة والتناظر"), ("Lazy mouse distance", "مسافة الفأرة الكسولة"), ("Leather grain", "حبيبات جلدية"), ("Lens size: how quickly things blur away from the focus distance", "حجم العدسة: سرعة تمويه العناصر البعيدة عن مسافة التركيز"), @@ -498,9 +497,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "درجات الإضاءة المتوسطة"), ("Minimum", "الحد الأدنى"), ("Minimum size (%)", "الحد الأدنى للحجم (%)"), - ("Mirror X", "مرآة X"), - ("Mirror Y", "مرآة Y"), - ("Mirror Z", "مرآة Z"), ("Missing (bake to create)", "مفقود (اخبز للإنشاء)"), ("Mixed AO", "انسداد محيطي مختلط"), ("Mode", "النمط"), @@ -582,7 +578,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "ارسم على المجسم لتعديل هذا القناع. استخدم قيمة القناع في لسان تبويب المادة للتدرج الرمادي.", ), - ("Paint the path with the brush (Enter)", "رسم المسار بالفرشاة (Enter)"), ("Paint with the current tool", "الرسم بالأداة الحالية"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -601,7 +596,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "لصق الطبقة (الطبقات)"), ("Path", "مسار"), ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "المسار: النقر يضيف نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "المسار: النقر يضيف نقطة، والنقر على المنحنى يُدرج نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي", + ), ("Pattern scale", "مقياس النمط"), ("Perlin noise", "ضوضاء بيرلن (Perlin)"), ("Pick focus in the viewport", "اختر نقطة التركيز في منفذ العرض"), @@ -628,8 +626,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "ربع"), ("Quick mask", "قناع سريع"), ("Quit", "إنهاء"), - ("Radial axis", "المحور الدائري"), - ("Radial copies", "نُسخ دائرية"), ("Radius (texels at 2K)", "نصف القطر (تكسل بدقة 2K)"), ("RENDERING", "التصيير"), ("Range", "النطاق"), @@ -648,8 +644,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "إزالة الطبقة"), ("Remove layer(s)", "إزالة الطبقة (الطبقات)"), ("Remove mask", "إزالة القناع"), + ("Remove point", "إزالة النقطة"), ("Remove resource", "إزالة المورد"), - ("Remove the path (Esc)", "إزالة المسار (Esc)"), ("Remove the shortcut", "إزالة الاختصار"), ("Remove this output", "إزالة هذا المخرج"), ("Remove unused resources...", "إزالة الموارد غير المستخدمة..."), @@ -767,8 +763,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "استعيان فرعي 8×8"), ("Subsurface scattering", "تشتت تحت السطح (SSS)"), ("Subtract", "طرح"), - ("Symmetry (X)", "تناظر (X)"), - ("Symmetry (Y)", "تناظر (Y)"), ("Tangent | Wrap", "مماس | التفاف"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "تنعيم حواف زمني (يحسّن العرض ثلاثي الأبعاد أثناء ثباته)"), ("Texture Sets", "مجموعات الخامات"), @@ -1067,6 +1061,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Angle span", "مدى الزاوية"), + ("Axis position", "موضع المحور"), + ("Count", "العدد"), + ("Display", "العرض"), + ("Hide while painting", "إخفاء أثناء الرسم"), + ("Manipulator size", "حجم أداة التحريك"), + ("Mirror symmetry", "تناظر مرآوي"), + ("Radial settings", "إعدادات التناظر الدائري"), + ("Radial symmetry", "تناظر دائري"), + ("Show axis", "إظهار المحور"), + ("Show axis position manipulator", "إظهار أداة تحريك موضع المحور"), + ("Show cursor", "إظهار المؤشر"), + ("Show intersection", "إظهار التقاطع"), + ("Show plane", "إظهار المستوى"), + ("Symmetry", "التناظر"), + ("Symmetry color display", "لون عرض التناظر"), + ("Symmetry settings", "إعدادات التناظر"), + ("Type", "النوع"), ("Advanced settings", "إعدادات متقدمة"), ("Import baked maps", "استيراد خرائط مخبوزة"), ("Name each file after its texture set, like Body_normal.png", "سمِّ كل ملف باسم مجموعة الخامات الخاصة به، مثل Body_normal.png"), @@ -1109,4 +1121,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"), ("The file dialog couldn't be shown: {error}", "تعذر عرض نافذة الملفات: {error}"), ("The project changed while the dialog was open, so nothing was done", "تغيّر المشروع أثناء فتح النافذة، لذا لم يُنفَّذ أي إجراء"), + ("Cores kept for the UI", "أنوية محجوزة للواجهة"), + ("Max RAM while saving", "أقصى ذاكرة عند الحفظ"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "يستخدم الحفظ الأنوية الأخرى وحدًا أقصى بهذه النسبة من الذاكرة الحرة. يعمل نواة واحدة على الأقل دائمًا.", + ), + ("Max project size on open", "الحد الأقصى لحجم المشروع عند الفتح"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 12858d1e..0f7e7c35 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -478,7 +478,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Ebenenspeicher: {mb} MB"), ("Layers", "Ebenen"), ("Lazy mouse", "Lazy Mouse"), - ("Lazy mouse and symmetry", "Lazy Mouse und Symmetrie"), ("Lazy mouse distance", "Lazy-Mouse-Distanz"), ("Leather grain", "Ledernarbung"), ("Lens size: how quickly things blur away from the focus distance", "Linsengröße: wie schnell Objekte außerhalb der Fokusdistanz unscharf werden"), @@ -525,9 +524,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Mitteltöne"), ("Minimum", "Minimum"), ("Minimum size (%)", "Mindestgröße (%)"), - ("Mirror X", "Spiegeln X"), - ("Mirror Y", "Spiegeln Y"), - ("Mirror Z", "Spiegeln Z"), ("Missing (bake to create)", "Fehlt (zum Erstellen backen)"), ("Mixed AO", "Gemischte AO"), ("Mode", "Modus"), @@ -615,7 +611,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Auf das Mesh malen, um diese Maske zu bearbeiten. Für Grau den Maskenwert im Tab Material verwenden.", ), - ("Paint the path with the brush (Enter)", "Pfad mit dem Pinsel malen (Eingabe)"), ("Paint with the current tool", "Mit dem aktuellen Werkzeug malen"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -638,8 +633,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Pfad"), ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Pfad: Klicken fügt einen Punkt hinzu, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Pfad: Klicken fügt einen Punkt hinzu, Klicken auf die Kurve fügt einen ein, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", ), ("Pattern scale", "Musterskalierung"), ("Perlin noise", "Perlin-Rauschen"), @@ -667,8 +662,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Viertel"), ("Quick mask", "Schnellmaske"), ("Quit", "Beenden"), - ("Radial axis", "Radiale Achse"), - ("Radial copies", "Radiale Kopien"), ("Radius (texels at 2K)", "Radius (Texel bei 2K)"), ("RENDERING", "RENDERING"), ("Range", "Bereich"), @@ -687,8 +680,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Ebene entfernen"), ("Remove layer(s)", "Ebene(n) entfernen"), ("Remove mask", "Maske entfernen"), + ("Remove point", "Punkt entfernen"), ("Remove resource", "Ressource entfernen"), - ("Remove the path (Esc)", "Pfad entfernen (Esc)"), ("Remove the shortcut", "Tastenkürzel entfernen"), ("Remove this output", "Diese Ausgabe entfernen"), ("Remove unused resources...", "Unbenutzte Ressourcen entfernen..."), @@ -806,8 +799,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Subsampling 8x8"), ("Subsurface scattering", "Subsurface Scattering"), ("Subtract", "Subtrahieren"), - ("Symmetry (X)", "Symmetrie (X)"), - ("Symmetry (Y)", "Symmetrie (Y)"), ("Tangent | Wrap", "Tangente | Umhüllen"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Temporale Kantenglättung (verfeinert die 3D-Ansicht im Stillstand)"), ("Texture Sets", "Textursets"), @@ -1110,6 +1101,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Angle span", "Winkelbereich"), + ("Axis position", "Achsenposition"), + ("Count", "Anzahl"), + ("Display", "Anzeige"), + ("Hide while painting", "Beim Malen ausblenden"), + ("Manipulator size", "Manipulatorgröße"), + ("Mirror symmetry", "Spiegelsymmetrie"), + ("Radial settings", "Radial-Einstellungen"), + ("Radial symmetry", "Radialsymmetrie"), + ("Show axis", "Achse anzeigen"), + ("Show axis position manipulator", "Manipulator für die Achsenposition anzeigen"), + ("Show cursor", "Cursor anzeigen"), + ("Show intersection", "Schnittlinie anzeigen"), + ("Show plane", "Ebene anzeigen"), + ("Symmetry", "Symmetrie"), + ("Symmetry color display", "Anzeigefarbe der Symmetrie"), + ("Symmetry settings", "Symmetrie-Einstellungen"), + ("Type", "Typ"), ("Advanced settings", "Erweiterte Einstellungen"), ("Import baked maps", "Gebackene Maps importieren"), ("Name each file after its texture set, like Body_normal.png", "Benennen Sie jede Datei nach ihrem Texturset, z. B. Body_normal.png"), @@ -1158,4 +1167,15 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Das Projekt hat sich geändert, während der Dialog geöffnet war, daher wurde nichts ausgeführt", ), + ("Cores kept for the UI", "Für die Oberfläche reservierte Kerne"), + ("Max RAM while saving", "Max. RAM beim Speichern"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Das Speichern nutzt die übrigen Kerne und höchstens diesen Anteil des freien RAMs. Mindestens ein Kern arbeitet immer.", + ), + ("Max project size on open", "Max. Projektgröße beim Öffnen"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 92120ff4..b5361801 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -469,7 +469,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memoria de capas: {mb} MB"), ("Layers", "Capas"), ("Lazy mouse", "Ratón perezoso"), - ("Lazy mouse and symmetry", "Ratón perezoso y simetría"), ("Lazy mouse distance", "Distancia del ratón perezoso"), ("Leather grain", "Grano de cuero"), ("Lens size: how quickly things blur away from the focus distance", "Tamaño de la lente: lo rápido que se desenfoca todo fuera de la distancia de enfoque"), @@ -516,9 +515,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Medios tonos"), ("Minimum", "Mínimo"), ("Minimum size (%)", "Tamaño mínimo (%)"), - ("Mirror X", "Reflejar X"), - ("Mirror Y", "Reflejar Y"), - ("Mirror Z", "Reflejar Z"), ("Missing (bake to create)", "Falta (hornear para crear)"), ("Mixed AO", "AO mixta"), ("Mode", "Modo"), @@ -606,7 +602,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinta sobre la malla para editar esta máscara. Usa el valor de máscara de la pestaña Material para el gris.", ), - ("Paint the path with the brush (Enter)", "Pintar el trazado con el pincel (Intro)"), ("Paint with the current tool", "Pintar con la herramienta actual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -628,7 +623,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Pegar capa(s)"), ("Path", "Trazado"), ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Trazado: clic añade un punto, arrastrar lo mueve, Intro aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Trazado: clic añade un punto, clic en la curva inserta uno, arrastrar lo mueve, Intro aplica, Esc cancela", + ), ("Pattern scale", "Escala del patrón"), ("Perlin noise", "Ruido Perlin"), ("Pick focus in the viewport", "Elegir el enfoque en la ventana gráfica"), @@ -655,8 +653,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Cuarto"), ("Quick mask", "Máscara rápida"), ("Quit", "Salir"), - ("Radial axis", "Eje radial"), - ("Radial copies", "Copias radiales"), ("Radius (texels at 2K)", "Radio (téxeles a 2K)"), ("RENDERING", "RENDERIZADO"), ("Range", "Rango"), @@ -675,8 +671,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Eliminar capa"), ("Remove layer(s)", "Eliminar capa(s)"), ("Remove mask", "Quitar máscara"), + ("Remove point", "Quitar punto"), ("Remove resource", "Quitar recurso"), - ("Remove the path (Esc)", "Quitar el trazado (Esc)"), ("Remove the shortcut", "Quitar el atajo"), ("Remove this output", "Quitar esta salida"), ("Remove unused resources...", "Quitar recursos no usados..."), @@ -794,8 +790,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Submuestreo 8x8"), ("Subsurface scattering", "Dispersión subsuperficial"), ("Subtract", "Restar"), - ("Symmetry (X)", "Simetría (X)"), - ("Symmetry (Y)", "Simetría (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antialiasing temporal (refina la vista 3D mientras está quieta)"), ("Texture Sets", "Conjuntos de texturas"), @@ -1095,6 +1089,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Angle span", "Amplitud del ángulo"), + ("Axis position", "Posición del eje"), + ("Count", "Cantidad"), + ("Display", "Visualización"), + ("Hide while painting", "Ocultar al pintar"), + ("Manipulator size", "Tamaño del manipulador"), + ("Mirror symmetry", "Simetría de espejo"), + ("Radial settings", "Ajustes radiales"), + ("Radial symmetry", "Simetría radial"), + ("Show axis", "Mostrar eje"), + ("Show axis position manipulator", "Mostrar manipulador de posición del eje"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar intersección"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetría"), + ("Symmetry color display", "Color de visualización de simetría"), + ("Symmetry settings", "Ajustes de simetría"), + ("Type", "Tipo"), ("Advanced settings", "Ajustes avanzados"), ("Import baked maps", "Importar mapas horneados"), ("Name each file after its texture set, like Body_normal.png", "Nombra cada archivo según su conjunto de texturas, p. ej. Body_normal.png"), @@ -1146,4 +1158,15 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "El proyecto cambió mientras el cuadro de diálogo estaba abierto, así que no se hizo nada", ), + ("Cores kept for the UI", "Núcleos reservados para la interfaz"), + ("Max RAM while saving", "RAM máx. al guardar"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Guardar usa los demás núcleos y como máximo esta parte de la RAM libre. Siempre trabaja al menos un núcleo.", + ), + ("Max project size on open", "Tamaño máximo al abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index e7fa9b1d..00b8c2af 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -481,7 +481,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Mémoire des calques : {mb} Mo"), ("Layers", "Calques"), ("Lazy mouse", "Stabilisateur"), - ("Lazy mouse and symmetry", "Stabilisateur et symétrie"), ("Lazy mouse distance", "Distance du stabilisateur"), ("Leather grain", "Grain de cuir"), ( @@ -531,9 +530,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Tons moyens"), ("Minimum", "Minimum"), ("Minimum size (%)", "Taille minimale (%)"), - ("Mirror X", "Miroir X"), - ("Mirror Y", "Miroir Y"), - ("Mirror Z", "Miroir Z"), ("Missing (bake to create)", "Manquante (précalculer pour la créer)"), ("Mixed AO", "AO mixte"), ("Mode", "Mode"), @@ -621,7 +617,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Peignez sur le maillage pour modifier ce masque. Utilisez la valeur de masque de l'onglet Matériau pour le gris.", ), - ("Paint the path with the brush (Enter)", "Peindre le tracé avec le pinceau (Enter)"), ("Paint with the current tool", "Peindre avec l'outil actuel"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -643,7 +638,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Coller le(s) calque(s)"), ("Path", "Tracé"), ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Tracé : cliquer ajoute un point, glisser le déplace, Enter applique, Esc annule"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracé : cliquer ajoute un point, cliquer sur la courbe en insère un, glisser le déplace, Enter applique, Esc annule", + ), ("Pattern scale", "Échelle du motif"), ("Perlin noise", "Bruit de Perlin"), ("Pick focus in the viewport", "Choisir la mise au point dans la fenêtre d'affichage"), @@ -670,8 +668,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Quart"), ("Quick mask", "Masque rapide"), ("Quit", "Quitter"), - ("Radial axis", "Axe radial"), - ("Radial copies", "Copies radiales"), ("Radius (texels at 2K)", "Rayon (texels en 2K)"), ("RENDERING", "RENDU"), ("Range", "Plage"), @@ -690,8 +686,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Supprimer le calque"), ("Remove layer(s)", "Supprimer le(s) calque(s)"), ("Remove mask", "Supprimer le masque"), + ("Remove point", "Retirer le point"), ("Remove resource", "Supprimer la ressource"), - ("Remove the path (Esc)", "Supprimer le tracé (Esc)"), ("Remove the shortcut", "Supprimer le raccourci"), ("Remove this output", "Supprimer cette sortie"), ("Remove unused resources...", "Supprimer les ressources inutilisées..."), @@ -812,8 +808,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Sous-échantillonnage 8x8"), ("Subsurface scattering", "Diffusion sous-surfacique"), ("Subtract", "Soustraction"), - ("Symmetry (X)", "Symétrie (X)"), - ("Symmetry (Y)", "Symétrie (Y)"), ("Tangent | Wrap", "Tangente | Enveloppe"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anticrénelage temporel (affine la vue 3D tant qu'elle est immobile)"), ("Texture Sets", "Ensembles de textures"), @@ -1119,6 +1113,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Angle span", "Amplitude d'angle"), + ("Axis position", "Position de l'axe"), + ("Count", "Nombre"), + ("Display", "Affichage"), + ("Hide while painting", "Masquer pendant la peinture"), + ("Manipulator size", "Taille du manipulateur"), + ("Mirror symmetry", "Symétrie miroir"), + ("Radial settings", "Paramètres radiaux"), + ("Radial symmetry", "Symétrie radiale"), + ("Show axis", "Afficher l'axe"), + ("Show axis position manipulator", "Afficher le manipulateur de position de l'axe"), + ("Show cursor", "Afficher le curseur"), + ("Show intersection", "Afficher l'intersection"), + ("Show plane", "Afficher le plan"), + ("Symmetry", "Symétrie"), + ("Symmetry color display", "Couleur d'affichage de la symétrie"), + ("Symmetry settings", "Paramètres de symétrie"), + ("Type", "Type"), ("Advanced settings", "Paramètres avancés"), ("Import baked maps", "Importer des cartes précalculées"), ("Name each file after its texture set, like Body_normal.png", "Nommez chaque fichier d'après son ensemble de textures, par ex. Body_normal.png"), @@ -1170,4 +1182,15 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Le projet a changé pendant que la boîte de dialogue était ouverte ; rien n'a été fait", ), + ("Cores kept for the UI", "Cœurs réservés à l'interface"), + ("Max RAM while saving", "RAM max. à l'enregistrement"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "L'enregistrement utilise les autres cœurs et au plus cette part de la RAM libre. Au moins un cœur travaille toujours.", + ), + ("Max project size on open", "Taille max. à l’ouverture"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 8bec1934..e067cf67 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -472,7 +472,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memoria livelli: {mb} MB"), ("Layers", "Livelli"), ("Lazy mouse", "Lazy mouse"), - ("Lazy mouse and symmetry", "Lazy mouse e simmetria"), ("Lazy mouse distance", "Distanza lazy mouse"), ("Leather grain", "Grana pelle"), ( @@ -522,9 +521,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Mezzitoni"), ("Minimum", "Minimo"), ("Minimum size (%)", "Dimensione minima (%)"), - ("Mirror X", "Specchia X"), - ("Mirror Y", "Specchia Y"), - ("Mirror Z", "Specchia Z"), ("Missing (bake to create)", "Mancante (esegui il bake per crearla)"), ("Mixed AO", "AO miscelata"), ("Mode", "Modalità"), @@ -612,7 +608,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Dipingi sulla mesh per modificare questa maschera. Usa il valore maschera della scheda Materiale per il grigio.", ), - ("Paint the path with the brush (Enter)", "Dipingi il tracciato con il pennello (Invio)"), ("Paint with the current tool", "Dipingi con lo strumento corrente"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -635,8 +630,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Tracciato"), ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Tracciato: clic aggiunge un punto, trascina lo sposta, Invio applica, Esc annulla", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracciato: clic aggiunge un punto, clic sulla curva ne inserisce uno, trascina lo sposta, Invio applica, Esc annulla", ), ("Pattern scale", "Scala motivo"), ("Perlin noise", "Rumore Perlin"), @@ -664,8 +659,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Un quarto"), ("Quick mask", "Maschera rapida"), ("Quit", "Esci"), - ("Radial axis", "Asse radiale"), - ("Radial copies", "Copie radiali"), ("Radius (texels at 2K)", "Raggio (texel a 2K)"), ("RENDERING", "RENDERING"), ("Range", "Intervallo"), @@ -684,8 +677,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Rimuovi livello"), ("Remove layer(s)", "Rimuovi livello/i"), ("Remove mask", "Rimuovi maschera"), + ("Remove point", "Rimuovi punto"), ("Remove resource", "Rimuovi risorsa"), - ("Remove the path (Esc)", "Rimuovi il tracciato (Esc)"), ("Remove the shortcut", "Rimuovi la scorciatoia"), ("Remove this output", "Rimuovi questo output"), ("Remove unused resources...", "Rimuovi risorse inutilizzate..."), @@ -803,8 +796,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Sottocampionamento 8x8"), ("Subsurface scattering", "Subsurface scattering"), ("Subtract", "Sottrai"), - ("Symmetry (X)", "Simmetria (X)"), - ("Symmetry (Y)", "Simmetria (Y)"), ("Tangent | Wrap", "Tangente | Avvolgi"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anti-aliasing temporale (affina la vista 3D quando è ferma)"), ("Texture Sets", "Set di texture"), @@ -1104,6 +1095,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Angle span", "Ampiezza angolo"), + ("Axis position", "Posizione asse"), + ("Count", "Numero"), + ("Display", "Visualizzazione"), + ("Hide while painting", "Nascondi durante la pittura"), + ("Manipulator size", "Dimensione manipolatore"), + ("Mirror symmetry", "Simmetria speculare"), + ("Radial settings", "Impostazioni radiali"), + ("Radial symmetry", "Simmetria radiale"), + ("Show axis", "Mostra asse"), + ("Show axis position manipulator", "Mostra manipolatore posizione asse"), + ("Show cursor", "Mostra cursore"), + ("Show intersection", "Mostra intersezione"), + ("Show plane", "Mostra piano"), + ("Symmetry", "Simmetria"), + ("Symmetry color display", "Colore di visualizzazione simmetria"), + ("Symmetry settings", "Impostazioni simmetria"), + ("Type", "Tipo"), ("Advanced settings", "Impostazioni avanzate"), ("Import baked maps", "Importa mappe bake"), ("Name each file after its texture set, like Body_normal.png", "Dai a ogni file il nome del suo set di texture, ad es. Body_normal.png"), @@ -1155,4 +1164,15 @@ pub const TABLE: &[(&str, &str)] = &[ "The project changed while the dialog was open, so nothing was done", "Il progetto è cambiato mentre la finestra di dialogo era aperta, quindi non è stato fatto nulla", ), + ("Cores kept for the UI", "Core riservati all'interfaccia"), + ("Max RAM while saving", "RAM max durante il salvataggio"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Il salvataggio usa gli altri core e al massimo questa quota della RAM libera. Almeno un core lavora sempre.", + ), + ("Max project size on open", "Dimensione massima all’apertura"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 90c28cab..0e60e132 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -463,7 +463,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "レイヤーメモリ: {mb} MB"), ("Layers", "レイヤー"), ("Lazy mouse", "レイジーマウス"), - ("Lazy mouse and symmetry", "レイジーマウスと対称"), ("Lazy mouse distance", "レイジーマウスの距離"), ("Leather grain", "革のシボ"), ("Lens size: how quickly things blur away from the focus distance", "レンズサイズ: フォーカス距離から離れるにつれてぼける速さ"), @@ -510,9 +509,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "中間調"), ("Minimum", "最小"), ("Minimum size (%)", "最小サイズ (%)"), - ("Mirror X", "ミラー X"), - ("Mirror Y", "ミラー Y"), - ("Mirror Z", "ミラー Z"), ("Missing (bake to create)", "なし (ベイクで作成)"), ("Mixed AO", "ミックスAO"), ("Mode", "モード"), @@ -600,7 +596,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "メッシュにペイントしてこのマスクを編集します。グレーには「マテリアル」タブのマスク値を使用します。", ), - ("Paint the path with the brush (Enter)", "ブラシでパスをペイント (Enter)"), ("Paint with the current tool", "現在のツールでペイント"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -619,7 +614,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "レイヤーを貼り付け"), ("Path", "パス"), ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "パス: クリックでポイントを追加、ドラッグで移動、Enterで適用、Escでキャンセル"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "パス: クリックでポイントを追加、カーブをクリックで挿入、ドラッグで移動、Enterで適用、Escでキャンセル", + ), ("Pattern scale", "パターンのスケール"), ("Perlin noise", "パーリンノイズ"), ("Pick focus in the viewport", "ビューポートでフォーカスを指定"), @@ -646,8 +644,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "クイックマスク"), ("Quit", "終了"), - ("Radial axis", "放射軸"), - ("Radial copies", "放射状コピー"), ("Radius (texels at 2K)", "半径 (2K時のテクセル)"), ("RENDERING", "レンダリング"), ("Range", "範囲"), @@ -666,8 +662,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "レイヤーを削除"), ("Remove layer(s)", "レイヤーを削除"), ("Remove mask", "マスクを削除"), + ("Remove point", "ポイントを削除"), ("Remove resource", "リソースを削除"), - ("Remove the path (Esc)", "パスを削除 (Esc)"), ("Remove the shortcut", "ショートカットを削除"), ("Remove this output", "この出力を削除"), ("Remove unused resources...", "未使用のリソースを削除..."), @@ -785,8 +781,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "サブサンプリング 8x8"), ("Subsurface scattering", "サブサーフェススキャタリング"), ("Subtract", "減算"), - ("Symmetry (X)", "対称 (X)"), - ("Symmetry (Y)", "対称 (Y)"), ("Tangent | Wrap", "タンジェント | ラップ"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "テンポラルアンチエイリアス (静止中に3Dビューを精細化)"), ("Texture Sets", "テクスチャセット"), @@ -1089,6 +1083,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Angle span", "角度範囲"), + ("Axis position", "軸の位置"), + ("Count", "数"), + ("Display", "表示"), + ("Hide while painting", "ペイント中は隠す"), + ("Manipulator size", "マニピュレーターのサイズ"), + ("Mirror symmetry", "ミラー対称"), + ("Radial settings", "放射の設定"), + ("Radial symmetry", "放射対称"), + ("Show axis", "軸を表示"), + ("Show axis position manipulator", "軸位置マニピュレーターを表示"), + ("Show cursor", "カーソルを表示"), + ("Show intersection", "交差部を表示"), + ("Show plane", "平面を表示"), + ("Symmetry", "対称"), + ("Symmetry color display", "対称の表示色"), + ("Symmetry settings", "対称の設定"), + ("Type", "種類"), ("Advanced settings", "詳細設定"), ("Import baked maps", "ベイク済みマップを読み込む"), ("Name each file after its texture set, like Body_normal.png", "各ファイル名をテクスチャセット名で始めてください(例: Body_normal.png)"), @@ -1137,4 +1149,15 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("The file dialog couldn't be shown: {error}", "ファイルダイアログを表示できませんでした: {error}"), ("The project changed while the dialog was open, so nothing was done", "ダイアログを開いている間にプロジェクトが変更されたため、何も実行されませんでした"), + ("Cores kept for the UI", "UI用に確保するコア数"), + ("Max RAM while saving", "保存時のRAM上限"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存は残りのコアと、空きRAMのこの割合までを使います。少なくとも1コアは常に動作します。", + ), + ("Max project size on open", "開くプロジェクトの最大サイズ"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index fd96c46d..7f80b6be 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -457,7 +457,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "레이어 메모리: {mb} MB"), ("Layers", "레이어"), ("Lazy mouse", "레이지 마우스"), - ("Lazy mouse and symmetry", "레이지 마우스 및 대칭"), ("Lazy mouse distance", "레이지 마우스 거리"), ("Leather grain", "가죽 결"), ("Lens size: how quickly things blur away from the focus distance", "렌즈 크기: 초점 거리에서 멀어질수록 얼마나 빠르게 흐려지는지 결정합니다"), @@ -504,9 +503,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "중간 영역"), ("Minimum", "최소"), ("Minimum size (%)", "최소 크기 (%)"), - ("Mirror X", "미러 X"), - ("Mirror Y", "미러 Y"), - ("Mirror Z", "미러 Z"), ("Missing (bake to create)", "없음 (베이크하여 생성)"), ("Mixed AO", "혼합 AO"), ("Mode", "모드"), @@ -591,7 +587,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "메시에 칠하여 이 마스크를 편집합니다. 회색은 머티리얼 탭의 마스크 값을 사용하세요.", ), - ("Paint the path with the brush (Enter)", "브러시로 패스를 칠합니다 (Enter)"), ("Paint with the current tool", "현재 도구로 페인팅"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -610,7 +605,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "레이어 붙여넣기"), ("Path", "패스"), ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "패스: 클릭으로 점 추가, 드래그로 이동, Enter로 적용, Esc로 취소"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "패스: 클릭으로 점 추가, 곡선 클릭으로 점 삽입, 드래그로 이동, Enter로 적용, Esc로 취소", + ), ("Pattern scale", "패턴 스케일"), ("Perlin noise", "펄린 노이즈"), ("Pick focus in the viewport", "뷰포트에서 초점 선택"), @@ -637,8 +635,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "퀵 마스크"), ("Quit", "종료"), - ("Radial axis", "방사형 축"), - ("Radial copies", "방사형 복사본"), ("Radius (texels at 2K)", "반경 (2K 기준 텍셀)"), ("RENDERING", "렌더링"), ("Range", "범위"), @@ -657,8 +653,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "레이어 제거"), ("Remove layer(s)", "레이어 제거"), ("Remove mask", "마스크 제거"), + ("Remove point", "점 제거"), ("Remove resource", "리소스 제거"), - ("Remove the path (Esc)", "패스를 제거합니다 (Esc)"), ("Remove the shortcut", "단축키를 제거합니다"), ("Remove this output", "이 출력을 제거합니다"), ("Remove unused resources...", "사용하지 않는 리소스 제거..."), @@ -776,8 +772,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "서브샘플링 8x8"), ("Subsurface scattering", "서브서피스 스캐터링"), ("Subtract", "빼기"), - ("Symmetry (X)", "대칭 (X)"), - ("Symmetry (Y)", "대칭 (Y)"), ("Tangent | Wrap", "탄젠트 | 랩"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "시간적 안티앨리어싱 (3D 뷰가 정지해 있을 때 품질을 높임)"), ("Texture Sets", "텍스처 세트"), @@ -1077,6 +1071,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Angle span", "각도 범위"), + ("Axis position", "축 위치"), + ("Count", "개수"), + ("Display", "표시"), + ("Hide while painting", "페인팅 중 숨기기"), + ("Manipulator size", "조작기 크기"), + ("Mirror symmetry", "미러 대칭"), + ("Radial settings", "방사형 설정"), + ("Radial symmetry", "방사형 대칭"), + ("Show axis", "축 표시"), + ("Show axis position manipulator", "축 위치 조작기 표시"), + ("Show cursor", "커서 표시"), + ("Show intersection", "교차선 표시"), + ("Show plane", "평면 표시"), + ("Symmetry", "대칭"), + ("Symmetry color display", "대칭 표시 색상"), + ("Symmetry settings", "대칭 설정"), + ("Type", "유형"), ("Advanced settings", "고급 설정"), ("Import baked maps", "베이크된 맵 가져오기"), ("Name each file after its texture set, like Body_normal.png", "각 파일 이름을 텍스처 세트 이름으로 시작하세요(예: Body_normal.png)"), @@ -1122,4 +1134,15 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"), ("The file dialog couldn't be shown: {error}", "파일 대화 상자를 표시할 수 없습니다: {error}"), ("The project changed while the dialog was open, so nothing was done", "대화 상자가 열려 있는 동안 프로젝트가 변경되어 아무 작업도 수행하지 않았습니다"), + ("Cores kept for the UI", "UI용으로 남겨 둘 코어"), + ("Max RAM while saving", "저장 시 최대 RAM"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "저장은 나머지 코어와 여유 RAM의 이 비율까지만 사용합니다. 최소 한 개의 코어는 항상 작동합니다.", + ), + ("Max project size on open", "열기 시 최대 프로젝트 크기"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 923b7fee..e5b023af 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -466,7 +466,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memória das camadas: {mb} MB"), ("Layers", "Camadas"), ("Lazy mouse", "Lazy mouse"), - ("Lazy mouse and symmetry", "Lazy mouse e simetria"), ("Lazy mouse distance", "Distância do lazy mouse"), ("Leather grain", "Grão de couro"), ("Lens size: how quickly things blur away from the focus distance", "Tamanho da lente: quão rápido os objetos desfocam fora da distância de foco"), @@ -513,9 +512,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Tons médios"), ("Minimum", "Mínimo"), ("Minimum size (%)", "Tamanho mínimo (%)"), - ("Mirror X", "Espelhar X"), - ("Mirror Y", "Espelhar Y"), - ("Mirror Z", "Espelhar Z"), ("Missing (bake to create)", "Ausente (faça o bake para criar)"), ("Mixed AO", "AO combinada"), ("Mode", "Modo"), @@ -603,7 +599,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinte na malha para editar esta máscara. Use o valor de máscara da aba Material para cinza.", ), - ("Paint the path with the brush (Enter)", "Pintar o caminho com o pincel (Enter)"), ("Paint with the current tool", "Pintar com a ferramenta atual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -625,7 +620,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Colar camada(s)"), ("Path", "Caminho"), ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Caminho: clicar adiciona um ponto, arrastar o move, Enter aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Caminho: clicar adiciona um ponto, clicar na curva insere um, arrastar o move, Enter aplica, Esc cancela", + ), ("Pattern scale", "Escala do padrão"), ("Perlin noise", "Ruído Perlin"), ("Pick focus in the viewport", "Escolher o foco na viewport"), @@ -652,8 +650,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Um quarto"), ("Quick mask", "Máscara rápida"), ("Quit", "Sair"), - ("Radial axis", "Eixo radial"), - ("Radial copies", "Cópias radiais"), ("Radius (texels at 2K)", "Raio (texels em 2K)"), ("RENDERING", "RENDERIZAÇÃO"), ("Range", "Intervalo"), @@ -672,8 +668,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Remover camada"), ("Remove layer(s)", "Remover camada(s)"), ("Remove mask", "Remover máscara"), + ("Remove point", "Remover ponto"), ("Remove resource", "Remover recurso"), - ("Remove the path (Esc)", "Remover o caminho (Esc)"), ("Remove the shortcut", "Remover o atalho"), ("Remove this output", "Remover esta saída"), ("Remove unused resources...", "Remover recursos não usados..."), @@ -791,8 +787,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Subamostragem 8x8"), ("Subsurface scattering", "Dispersão subsuperficial"), ("Subtract", "Subtração"), - ("Symmetry (X)", "Simetria (X)"), - ("Symmetry (Y)", "Simetria (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antisserrilhamento temporal (refina a vista 3D enquanto está parada)"), ("Texture Sets", "Conjuntos de texturas"), @@ -1092,6 +1086,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Angle span", "Amplitude do ângulo"), + ("Axis position", "Posição do eixo"), + ("Count", "Quantidade"), + ("Display", "Exibição"), + ("Hide while painting", "Ocultar ao pintar"), + ("Manipulator size", "Tamanho do manipulador"), + ("Mirror symmetry", "Simetria espelhada"), + ("Radial settings", "Configurações radiais"), + ("Radial symmetry", "Simetria radial"), + ("Show axis", "Mostrar eixo"), + ("Show axis position manipulator", "Mostrar manipulador da posição do eixo"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar interseção"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetria"), + ("Symmetry color display", "Cor de exibição da simetria"), + ("Symmetry settings", "Configurações de simetria"), + ("Type", "Tipo"), ("Advanced settings", "Configurações avançadas"), ("Import baked maps", "Importar mapas com bake"), ("Name each file after its texture set, like Body_normal.png", "Nomeie cada arquivo com o nome do seu conjunto de texturas, como Body_normal.png"), @@ -1140,4 +1152,15 @@ pub const TABLE: &[(&str, &str)] = &[ ), ("The file dialog couldn't be shown: {error}", "Não foi possível mostrar a caixa de diálogo de arquivos: {error}"), ("The project changed while the dialog was open, so nothing was done", "O projeto mudou enquanto a caixa de diálogo estava aberta, então nada foi feito"), + ("Cores kept for the UI", "Núcleos reservados para a interface"), + ("Max RAM while saving", "RAM máx. ao salvar"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Salvar usa os outros núcleos e no máximo esta parte da RAM livre. Pelo menos um núcleo sempre trabalha.", + ), + ("Max project size on open", "Tamanho máximo ao abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 47619f9e..ef4209e4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -421,7 +421,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "图层内存:{mb} MB"), ("Layers", "图层"), ("Lazy mouse", "平滑跟随"), - ("Lazy mouse and symmetry", "平滑跟随与对称"), ("Lazy mouse distance", "平滑跟随距离"), ("Leather grain", "皮革纹理"), ("Lens size: how quickly things blur away from the focus distance", "镜头大小:远离对焦距离时物体变模糊的速度"), @@ -468,9 +467,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "中间调"), ("Minimum", "最小值"), ("Minimum size (%)", "最小尺寸(%)"), - ("Mirror X", "镜像 X"), - ("Mirror Y", "镜像 Y"), - ("Mirror Z", "镜像 Z"), ("Missing (bake to create)", "缺失(烘焙以创建)"), ("Mixed AO", "混合 AO"), ("Mode", "模式"), @@ -549,7 +545,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paint chips", "掉漆"), ("Paint on the mesh to edit the layer content.", "在网格上绘画以编辑图层内容。"), ("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "在网格上绘画以编辑此遮罩。灰度请使用“材质”选项卡中的遮罩值。"), - ("Paint the path with the brush (Enter)", "用笔刷绘制路径(Enter)"), ("Paint with the current tool", "使用当前工具绘画"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -568,7 +563,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "粘贴图层"), ("Path", "路径"), ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "路径:单击添加点,拖动移动点,Enter 应用,Esc 取消"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "路径:单击添加点,单击曲线插入点,拖动移动点,Enter 应用,Esc 取消", + ), ("Pattern scale", "图案缩放"), ("Perlin noise", "柏林噪波"), ("Pick focus in the viewport", "在视口中拾取焦点"), @@ -595,8 +593,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "快速遮罩"), ("Quit", "退出"), - ("Radial axis", "径向轴"), - ("Radial copies", "径向副本"), ("Radius (texels at 2K)", "半径(2K 下的纹素数)"), ("RENDERING", "渲染"), ("Range", "范围"), @@ -615,8 +611,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "移除图层"), ("Remove layer(s)", "移除图层"), ("Remove mask", "移除遮罩"), + ("Remove point", "移除点"), ("Remove resource", "移除资源"), - ("Remove the path (Esc)", "移除路径(Esc)"), ("Remove the shortcut", "移除快捷键"), ("Remove this output", "移除此输出"), ("Remove unused resources...", "移除未使用的资源..."), @@ -734,8 +730,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "8x8 子采样"), ("Subsurface scattering", "次表面散射"), ("Subtract", "减去"), - ("Symmetry (X)", "对称(X)"), - ("Symmetry (Y)", "对称(Y)"), ("Tangent | Wrap", "切线 | 包裹"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "时间抗锯齿(在 3D 视图静止时逐步细化)"), ("Texture Sets", "纹理集"), @@ -1032,6 +1026,24 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Angle span", "角度范围"), + ("Axis position", "轴位置"), + ("Count", "数量"), + ("Display", "显示"), + ("Hide while painting", "绘制时隐藏"), + ("Manipulator size", "操纵器大小"), + ("Mirror symmetry", "镜像对称"), + ("Radial settings", "径向设置"), + ("Radial symmetry", "径向对称"), + ("Show axis", "显示轴"), + ("Show axis position manipulator", "显示轴位置操纵器"), + ("Show cursor", "显示光标"), + ("Show intersection", "显示交线"), + ("Show plane", "显示平面"), + ("Symmetry", "对称"), + ("Symmetry color display", "对称显示颜色"), + ("Symmetry settings", "对称设置"), + ("Type", "类型"), ("Advanced settings", "高级设置"), ("Import baked maps", "导入已烘焙贴图"), ("Name each file after its texture set, like Body_normal.png", "以纹理集名称为每个文件命名,例如 Body_normal.png"), @@ -1068,4 +1080,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"), ("The file dialog couldn't be shown: {error}", "无法显示文件对话框:{error}"), ("The project changed while the dialog was open, so nothing was done", "对话框打开期间项目已更改,因此未执行任何操作"), + ("Cores kept for the UI", "为界面保留的核心数"), + ("Max RAM while saving", "保存时的最大内存"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存使用其余核心,并最多占用这一比例的可用内存。至少始终有一个核心工作。", + ), + ("Max project size on open", "打开项目的大小上限"), + ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dc315a84..815ba793 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -34,11 +34,14 @@ pub mod menus; pub mod new_project_advanced; mod orb_shape; pub mod parity; +mod path_hit; +mod path_surface_cache; mod preview_image; mod preview_request; mod preview_worker; pub mod profile; pub mod properties_popup; +mod rail_popup; pub mod render_mode; mod resource_picker; mod resource_picker_item; @@ -47,6 +50,7 @@ pub mod shelf; pub mod shelf_preview; mod soft_box; pub mod state; +pub mod symmetry; pub mod theme; pub mod thumbs; pub mod titlebar; @@ -200,6 +204,7 @@ impl TextureCraftApp { ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + ui.prefs.apply_resource_limits(); let mut app = TextureCraftApp { camera_glide: None, @@ -270,7 +275,9 @@ impl TextureCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { - // Going to a saved camera glides there; the control channel and CLI jump straight away. + 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); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { Ok(v) => { @@ -654,6 +661,7 @@ impl eframe::App for TextureCraftApp { self.styled = Some(style); } self.step_camera_glide(ctx); + self.ui.prefs.apply_resource_limits(); control::poll(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); @@ -665,7 +673,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.poll_resize(ctx); self.poll_link_cooks(ctx); - // The library shelf rescans when the window comes back (MaterialCraft may have sent a material). + // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; @@ -688,9 +696,9 @@ impl eframe::App for TextureCraftApp { updates_ui::tick(self, ctx); self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); - // A stored path being edited repaints its sublayer as its points, brush or material change. + // The Path tool's curve repaints (a preview while placed) as its points, brush or material change if let Err(e) = self.session.path_live() { - self.session.stop_path_edit(); + self.session.cancel_path(); self.toast(e.to_string(), true); } profile::drive(self, ctx); @@ -716,7 +724,7 @@ impl eframe::App for TextureCraftApp { } let hide = self.ui.hide_ui; let tk = theme::Tokens::get(&ctx); - // The dock keeps the cards' gutter from the bars and rails around it. + // 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) }); windows::show(self, &ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index df5be69c..72d78b34 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -131,7 +131,7 @@ pub fn implemented(id: &str) -> bool { is_ui(id) || texturecraft_engine::find(id).is_some() } -/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). +/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`) pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { if !enabled(app, id) { return; @@ -142,15 +142,21 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { { return; } + if let Some(panel) = crate::docking::view_panel(id) { - app.ui.dock.toggle(panel); + if crate::rail_popup::is_rail_panel(panel) { + crate::rail_popup::toggle(app, panel); + } else { + app.ui.dock.toggle(panel); + } return; } + match id { "ui.newProject" => app.ui.windows.new_project = true, "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), - "ui.projectConfig" => app.ui.dock.focus(crate::docking::Panel::Display), + "ui.projectConfig" => crate::rail_popup::open(app, crate::docking::Panel::Display), "ui.settings" => app.ui.windows.settings = true, "ui.mode.bake" => app.ui.mode = Mode::Baking, "ui.mode.paint" => app.ui.mode = Mode::Painting, @@ -316,14 +322,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } + #[cfg(not(target_arch = "wasm32"))] if crate::updates_ui::blocks_input(app) { return; } - // The dispatcher reads Copy, Cut and Paste as their chords. A pasted image is Ctrl+V here, and - // Shift+Delete and Shift+Insert (Cut and Paste on Windows) are Ctrl+X and Ctrl+V unless - // something is bound to them. + // The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V + // Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V ctx.input_mut(|input| { let held = input.modifiers; let aliases: Vec<_> = input @@ -335,7 +341,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { input.events.extend(aliases); }); - // Escape closes an open popup first, before the Properties popup or the stroke + // Escape closes a dropdown before Properties, the rail popup, color picking or the stroke let popup_open = egui::Popup::is_any_open(ctx); let commands_to_invoke = ctx.input_mut(|input| { @@ -359,12 +365,13 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; + } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + 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.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); - app.session.tool.path.points.clear(); - app.session.tool.path.editing = None; + app.session.cancel_path(); } commands }); diff --git a/crates/ui-egui/src/path_hit.rs b/crates/ui-egui/src/path_hit.rs new file mode 100644 index 00000000..6b62f0f0 --- /dev/null +++ b/crates/ui-egui/src/path_hit.rs @@ -0,0 +1,17 @@ +//! What a pointer position in a view is over, for the Path tool + +use egui::Pos2; +use texturecraft_engine::core::LayerId; + +/// What a pointer position in a view is over, for the Path tool +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PathHit { + /// A control point of the path being edited + Point(usize), + /// The edited path's curve: the segment starting at this point, and the nearest screen position on it + Curve(usize, Pos2), + /// Another stored path of the selected layer: (path sublayer, index) + Stored(LayerId, usize), + /// Nothing of a path + Miss, +} diff --git a/crates/ui-egui/src/path_surface_cache.rs b/crates/ui-egui/src/path_surface_cache.rs new file mode 100644 index 00000000..9b216083 --- /dev/null +++ b/crates/ui-egui/src/path_surface_cache.rs @@ -0,0 +1,46 @@ +//! Sampled path curves retained only while the viewport uses them. + +use std::collections::HashMap; +use std::sync::Arc; + +use egui::cache::CacheTrait; +use texturecraft_engine::Session; +use texturecraft_engine::core::{LayerId, PathShape}; +use texturecraft_engine::geom::glam::Vec3; + +pub(crate) type SurfaceCurve = Arc>>>; + +#[derive(Default)] +pub(crate) struct PathSurfaceCache { + // Mesh, effect and path index identify entries; the flag records use during this pass + curves: HashMap<(u64, LayerId, usize), (PathShape, SurfaceCurve, bool)>, +} + +impl PathSurfaceCache { + /// Reuse an unchanged curve and retain it for this pass; UV or missing paths have no surface curve + pub(crate) fn get(&mut self, session: &Session, effect: LayerId, index: usize) -> Option { + let shape = session.paths(effect)?.get(index)?; + let key = (session.mesh_id, effect, index); + if let Some((cached_shape, surface, used)) = self.curves.get_mut(&key) + && cached_shape == shape + { + *used = true; + return Some(Arc::clone(surface)); + } + + let surface = Arc::new(session.stored_path_surface(effect, index)?); + self.curves.insert(key, (shape.clone(), Arc::clone(&surface), true)); + Some(surface) + } +} + +impl CacheTrait for PathSurfaceCache { + fn update(&mut self) { + // egui calls this even when paths stop drawing, so hidden or deleted paths release their buffers + self.curves.retain(|_, (_, _, used)| std::mem::take(used)); + } + + fn len(&self) -> usize { + self.curves.len() + } +} diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs new file mode 100644 index 00000000..afe85f1a --- /dev/null +++ b/crates/ui-egui/src/rail_popup.rs @@ -0,0 +1,240 @@ +//! The rail's panels open in a popup beside their rail icon, one at a time; dragging its title docks or floats the panel + +use egui::{Id, Pos2, Rect, RichText, Sense, Ui}; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::tr; +use crate::state::Mode; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The rail's panels, top to bottom, with their icons and Window ▸ Views ids +pub(crate) const RAIL_PANELS: [(Panel, &str, &str); 5] = [ + (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), + (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"), +]; + +/// The popup reaches this far into the viewport, so it covers the panels between the viewport and the rail +const VIEWPORT_OVERHANG: f32 = 48.0; + +/// Narrowest the popup gets, when the viewport is not left of the rail's column +const POPUP_MIN_WIDTH: f32 = 320.0; + +/// Settings panels' popups fit their contents up to this height, then scroll +const SETTINGS_MAX_HEIGHT: f32 = 640.0; + +/// History and Log fill their popup, so it has one height +const LIST_HEIGHT: f32 = 400.0; + +/// Gap between the popup and the rail +const RAIL_GAP: f32 = 4.0; + +/// Size of the close button in the popup's title row +const TITLE_BUTTON_SIZE: f32 = 22.0; + +/// The popup's area, whose rect egui remembers between frames +fn area_id() -> Id { + Id::unique("rail_popup") +} + +/// Where the rail drew its strip on this frame +fn strip_id() -> Id { + Id::unique("rail_popup_strip") +} + +/// Where the rail drew each panel's icon on this frame +fn icons_id() -> Id { + Id::unique("rail_popup_icons") +} + +/// The panel whose popup title a drag left, and the title's rect, until the dock takes the drag over +fn pending_drag_id() -> Id { + Id::unique("rail_popup_pending_drag") +} + +/// Where the dock drew the viewport on this frame +fn viewport_id() -> Id { + Id::unique("rail_popup_viewport") +} + +/// Whether `panel` opens from the rail rather than in the dock +pub(crate) fn is_rail_panel(panel: Panel) -> bool { + RAIL_PANELS.iter().any(|(rail_panel, _, _)| *rail_panel == panel) +} + +/// Whether the rail's open popup is visible in the current UI mode +pub(crate) fn is_visible(app: &TextureCraftApp) -> bool { + app.ui.rail_panel.is_some() && !app.ui.hide_ui && app.ui.mode != Mode::Baking +} + +/// Record the rail's strip before its icons, so the popup can line up with them +pub(crate) fn begin_rail(ctx: &egui::Context, strip: Rect) { + ctx.data_mut(|data| { + data.insert_temp(strip_id(), strip); + data.insert_temp(icons_id(), Vec::<(Panel, Rect)>::new()); + }); +} + +/// Record where the rail drew `panel`'s icon +pub(crate) fn remember_icon(ctx: &egui::Context, panel: Panel, icon: Rect) { + ctx.data_mut(|data| data.get_temp_mut_or_default::>(icons_id()).push((panel, icon))); +} + +/// Record where the dock drew the viewport, whose right edge the popup reaches past +pub(crate) fn remember_viewport(ctx: &egui::Context, viewport: Rect) { + ctx.data_mut(|data| data.insert_temp(viewport_id(), viewport)); +} + +/// A rail icon or its Window ▸ Views item: open `panel` in the popup in place of the one there, or close it +pub(crate) fn toggle(app: &mut TextureCraftApp, panel: Panel) { + // Bake mode has no rail, and a panel in the dock (which then has no rail icon) is toggled there + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.dock.toggle(panel); + return; + } + + app.ui.rail_panel = if app.ui.rail_panel == Some(panel) { None } else { Some(panel) }; +} + +/// Open `panel` from the rail: in its popup, or where it is in the dock (bake mode has no rail) +pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) { + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.dock.focus(panel); + } else { + app.ui.rail_panel = Some(panel); + } +} + +/// Hand a drag that left the popup's title to the dock, once the dock has drawn the panel it floated +pub(crate) fn hand_drag_to_dock(ctx: &egui::Context, dock_area: Id) { + let Some((panel, title)) = ctx.data(|data| data.get_temp::<(Panel, Rect)>(pending_drag_id())) else { return }; + + ctx.data_mut(|data| data.remove::<(Panel, Rect)>(pending_drag_id())); + if ctx.input(|input| input.pointer.primary_down()) { + craft_ui::docking::begin_drag(ctx, dock_area, panel, title); + } +} + +/// A rail popup and its dismissing press cannot start a paint stroke or move a decal +pub(crate) fn blocks_paint_input(app: &TextureCraftApp, ctx: &egui::Context) -> bool { + let closing_id = area_id().with("closing"); + let pointer_active = ctx.input(|input| input.pointer.any_down() || input.pointer.any_released()); + if !pointer_active { + ctx.data_mut(|data| data.remove::(closing_id)); + } + + // Both views must ignore the release, which would otherwise start a single-dab stroke + let closing = ctx.data(|data| data.get_temp::(closing_id)).unwrap_or(false); + + // A shortcut may open the panel during a stroke; let that existing stroke finish + !app.session.stroke_active() && (is_visible(app) || closing) +} + +/// Draw the open popup beside its icon; a press outside it closes it, as for a menu (Escape does too, in `menus.rs`) +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + // The dock has drawn both views, so a released dismissal must not suppress the next click + if !ctx.input(|input| input.pointer.any_down()) { + ctx.data_mut(|data| data.remove::(area_id().with("closing"))); + } + + let Some(panel) = app.ui.rail_panel else { return }; + + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.rail_panel = None; + return; + } + + let strip = ctx.data(|data| data.get_temp::(strip_id())).unwrap_or(Rect::NOTHING); + let icons = ctx.data(|data| data.get_temp::>(icons_id())).unwrap_or_default(); + let Some(icon) = icons.iter().find(|(icon_panel, _)| *icon_panel == panel).map(|(_, rect)| *rect) else { + app.ui.rail_panel = None; + return; + }; + + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + if closed_by_input(ctx, shown, strip) { + app.ui.rail_panel = None; + let held = ctx.input(|input| input.pointer.any_down()); + ctx.data_mut(|data| data.insert_temp(area_id().with("closing"), held)); + return; + } + + let tokens = Tokens::get(ctx); + let frame = egui::Frame::popup(&ctx.global_style()).fill(tokens.panel).stroke(egui::Stroke::new(1.0, tokens.accent)); + let (top_right, width) = placement(ctx, strip, icon); + let mut closed = false; + let mut dragged_from = None; + egui::Area::new(area_id()).order(egui::Order::Foreground).pivot(egui::Align2::RIGHT_TOP).fixed_pos(top_right).show(ctx, |ui| { + frame.show(ui, |ui| { + ui.set_width(width - frame.total_margin().sum().x); + let title_top = ui.cursor().top(); + (closed, dragged_from) = title_row(ui, &tokens, panel); + ui.separator(); + + // Keep the title, frame and body on screen even when the window is shorter than the usual popup + let title_height = ui.cursor().top() - title_top; + let body_height = (ctx.content_rect().height() - frame.total_margin().sum().y - title_height).max(0.0); + body(app, ui, panel, body_height); + }); + }); + + if closed { + app.ui.rail_panel = None; + } else if let Some(title) = dragged_from { + app.ui.rail_panel = None; + let rect = shown.unwrap_or(title); + app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]); + ctx.data_mut(|data| data.insert_temp(pending_drag_id(), (panel, title))); + } +} + +/// The popup's top right corner, beside the rail and level with its icon, and its width (egui keeps the area on screen) +fn placement(ctx: &egui::Context, strip: Rect, icon: Rect) -> (Pos2, f32) { + let right = strip.left() - RAIL_GAP; + let viewport = ctx.data(|data| data.get_temp::(viewport_id())); + let width = viewport.map_or(POPUP_MIN_WIDTH, |viewport| right - (viewport.right() - VIEWPORT_OVERHANG)).max(POPUP_MIN_WIDTH); + (Pos2::new(right, icon.top()), width) +} + +/// A press outside the popup and the rail, unless in one of the popup's own dropdowns +fn closed_by_input(ctx: &egui::Context, shown: Option, strip: Rect) -> bool { + let pressed_at = ctx.input(|input| input.pointer.press_origin().filter(|_| input.pointer.any_pressed())); + + // A press on the rail is left to its icons, which switch or close the popup themselves + let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at))); + outside && !egui::Popup::is_any_open(ctx) +} + +/// The panel's contents: History and Log at one height, the settings panels as tall as their contents up to a limit +fn body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel, available_height: f32) { + // A child Ui, so the height limits start below the title row instead of moving the cursor back up to it + ui.scope(|ui| { + if matches!(panel, Panel::History | Panel::Log) { + ui.set_height(LIST_HEIGHT.min(available_height)); + } else { + // The area's remembered size would otherwise cap the height + ui.set_max_height(SETTINGS_MAX_HEIGHT.min(available_height)); + } + + crate::docking::panel_body(app, ui, panel); + }); +} + +/// The panel's name, which drags like a tab, and a close button: whether it was clicked, and where a drag started +fn title_row(ui: &mut Ui, tokens: &Tokens, panel: Panel) -> (bool, Option) { + let row = ui.horizontal(|ui| { + ui.label(RichText::new(tr(panel.name())).strong().color(tokens.text_strong)); + ui.add_space((ui.available_width() - TITLE_BUTTON_SIZE).max(0.0)); + icon_button(ui, ic::X, tr("Close"), false, TITLE_BUTTON_SIZE) + }); + + let (row, close) = (row.response.rect, row.inner); + let title = Rect::from_min_max(row.min, egui::pos2(close.rect.left(), row.bottom())); + let drag = ui.interact(title, ui.scope_id().with("rail_popup_title"), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + (close.clicked(), drag.drag_started().then_some(title)) +} diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 80248a32..cef71ed1 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -14,9 +14,11 @@ use std::sync::{Mutex, PoisonError}; use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor}; use egui::{Color32, ColorImage, Rect, RichText, TextureHandle, TextureOptions, Ui, vec2}; +use texturecraft_engine::compose::ImageRes; use texturecraft_engine::geom::{Bvh, Mesh, OrbitCamera}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; +use texturecraft_render::ibl::EnvImage; use texturecraft_render::readback::Readback; use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer}; use texturecraft_render::{Renderer, wgpu}; @@ -25,6 +27,15 @@ use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; use crate::theme::Tokens; +mod frame_floor; +mod motion; +mod spp_control; +#[cfg(test)] +mod tests; + +use motion::Motion; +use spp_control::{SppControl, rescale_spp}; + /// A finished pass, ready to show. struct Frame { width: u32, @@ -132,9 +143,76 @@ struct GpuView { out_view: wgpu::TextureView, texture: egui::TextureId, status: Arc>, - /// Samples per pixel per frame: grows while frames are quick, halves when they are slow. + /// Samples per pixel per frame: grows while frames are quick, decreases when they are slow. spp: u32, + /// What steers `spp`. + spp_control: SppControl, read: Arc>, + /// An image of this render was resolved into `texture` at least once, so a restart keeps + /// showing it (the previous camera's frame) until the new samples replace it. + has_image: bool, + /// The egui texture of the last image traced at the smaller moving size, shown instead of + /// `texture` while the full-size render is too grainy (see [`holds_previous`]). + held: Option, + /// When `held` started being shown (egui time, seconds): a restart while it is up (a display + /// slider dragged) resets `started`, so the hold is timed from this instead. + held_since: f64, +} + +/// While the camera moves, the GPU render is traced at this fraction of the view size per axis +/// (the image is stretched to the view). A quarter of the pixels means about four times the samples +/// per pixel in the same frame time, so an orbit shows a smooth image instead of one or two noisy +/// samples; a faster GPU affords more samples (see `GpuView::spp`) at the same size. +const MOVING_SCALE: f32 = 0.5; + +/// Seconds without a camera change after which the render returns to the full view size. +const MOTION_SETTLE_S: f64 = 0.2; + +/// While textures load, new tiles are taken into the render at most this often (seconds). Each +/// time restarts the render, so taking them in every frame leaves it forever one or two samples +/// deep (raw noise) until loading ends; this lets about a third of a second of samples build up +/// between restarts, at the price of a little delay before a new tile shows. +const LOADING_RESTART_S: f64 = 0.35; + +/// Most samples per frame while textures load (see [`LOADING_RESTART_S`]). The frame time is +/// then the compositor's, not the tracer's, so the count is not steered by it: it stays where it +/// was, at most this (cheap at the smaller loading size). +const LOADING_MAX_SPP: u32 = 8; + +/// Whether textures are still loading: tiles wait to be composited, or composited ones to be +/// uploaded (the GPU render copies the uploaded display textures). +fn textures_loading(session: &texturecraft_engine::Session) -> bool { + session.pending_tiles() > 0 || session.caches.iter().any(|cache| !cache.upload.is_empty()) +} + +/// Whether changed textures are taken into the render now: always, except while loading, when at +/// most every [`LOADING_RESTART_S`]. +fn take_in_textures(loading: bool, now: f64, last_sync: f64) -> bool { + !loading || now - last_sync >= LOADING_RESTART_S +} + +/// When the render returns to full size after the camera stops, the soft image traced while it +/// moved stays on screen until the full-size render has this many samples (it starts from none, +/// and its first few samples are grainy)... +const SETTLE_HOLD_SAMPLES: u32 = 8; + +/// ...or for this many seconds at most, so a slow GPU never leaves the soft image up for long. +const SETTLE_HOLD_MAX_S: f64 = 0.5; + +/// Whether the image from before the view returned to full size is still shown: the full-size +/// render has `samples` samples after `elapsed` seconds. +fn holds_previous(samples: u32, elapsed: f64) -> bool { + samples < SETTLE_HOLD_SAMPLES && elapsed < SETTLE_HOLD_MAX_S +} + +/// Trace fewer pixels while the camera is moving, keeping tiny views at their original size. +fn traced_size(full: (u32, u32), moving: bool) -> (u32, u32) { + if !moving { + return full; + } + + let scale = |dimension: u32| ((dimension as f32 * MOVING_SCALE) as u32).clamp(16.min(dimension), dimension); + (scale(full.0), scale(full.1)) } /// The GPU tracer in egui's callback resources. @@ -144,6 +222,8 @@ struct TraceState { key: String, /// Samples in the resolved image (None: resolve again). resolved: Option, + /// When the tracer last took in changed textures (egui time, seconds). + last_sync: f64, } /// Traced geometry and the key of what it was built from. @@ -157,45 +237,75 @@ pub struct RenderView { /// Why the GPU tracer failed on the scene of this key (the CPU renders it instead). gpu_error: Option<(String, String)>, texture: Option, + motion: Motion, shown: Option<(u32, u32, Vec)>, samples: u32, elapsed: f64, /// The traced geometry (displaced or not) and what it was built from: changes to the display /// alone don't rebuild it. geometry: Mutex>, + /// The traced environment and what it was built from (see [`EnvKey`]): building one takes a + /// while, and the scene is rebuilt on every display change. + env: Mutex)>>, } +/// The display's environment name and its retained imported image (None: built-in). +type EnvKey = (String, Option>); + /// Viewport resolution of a CPU render (the web renders at half size: it has one thread). fn render_size(rect: Rect) -> (u32, u32) { let scale = if cfg!(target_arch = "wasm32") { 0.5 } else { 1.0 }; ((rect.width() * scale).max(16.0) as u32, (rect.height() * scale).max(16.0) as u32) } +/// Build a scene while retaining unchanged geometry and the decoded environment. fn trace_scene(app: &TextureCraftApp) -> TraceScene { - let s = &app.session; - let d = &s.doc.project.display; - let sets: Vec = s + let session = &app.session; + let display = &session.doc.project.display; + let sets: Vec = session .doc .project .texture_sets .iter() - .zip(&s.caches) - .map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() }) + .zip(&session.caches) + .map(|(set, cache)| TraceSet { material: set.material, composite: cache.composite.clone(), height_strength: set.atlas_height_strength() }) .collect(); - let env_image = d.environment_resource().and_then(|n| s.images.get(n)); - let revisions: Vec = s.caches.iter().map(|c| c.revision).collect(); - let strengths: Vec = sets.iter().map(|t| t.height_strength).collect(); - let key = format!("{}|{revisions:?}|{strengths:?}|{}", s.mesh_id, d.displacement); + let env_image = display.environment_resource().and_then(|n| session.images.get(n)); + + // Only displaced geometry depends on the composites (their heights) + let revisions: Vec = if display.displacement { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; + let strengths: Vec = sets.iter().map(|set| set.height_strength).collect(); + let key = format!("{}|{revisions:?}|{strengths:?}|{}", session.mesh_id, display.displacement); let mut cached = app.render.geometry.lock().unwrap_or_else(PoisonError::into_inner); let (mesh, bvh) = match cached.as_ref() { - Some((k, m, b)) if *k == key => (m.clone(), b.clone()), + Some((cached_key, mesh, bvh)) if *cached_key == key => (mesh.clone(), bvh.clone()), _ => { - let (m, b) = trace_geometry(&s.mesh, &s.bvh, &sets, d); - *cached = Some((key, m.clone(), b.clone())); - (m, b) + let (mesh, bvh) = trace_geometry(&session.mesh, &session.bvh, &sets, display); + *cached = Some((key, mesh.clone(), bvh.clone())); + (mesh, bvh) } }; - TraceScene::for_display(mesh, bvh, sets, d, env_image.map(|i| i.as_ref())) + drop(cached); + + let mut env_cached = app.render.env.lock().unwrap_or_else(PoisonError::into_inner); + let same_image = |source: &Option>| match (source, env_image) { + (Some(cached), Some(current)) => Arc::ptr_eq(cached, current), + (None, None) => true, + _ => false, + }; + let env = match env_cached.as_ref() { + Some(((name, source), environment)) if *name == display.environment && same_image(source) => environment.clone(), + _ => { + let environment = Arc::new(TraceScene::display_env(display, env_image.map(|image| image.as_ref()))); + + // Retaining the source prevents a later image from reusing its cached identity + let env_key = (display.environment.clone(), env_image.cloned()); + *env_cached = Some((env_key, environment.clone())); + environment + } + }; + + TraceScene::for_display_env(mesh, bvh, sets, display, env) } fn settings(app: &TextureCraftApp) -> TraceSettings { @@ -217,16 +327,26 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { } } -/// What the traced scene depends on. -fn scene_key(app: &TextureCraftApp) -> String { - let s = &app.session; - let revisions: Vec = s.caches.iter().map(|c| c.revision).collect(); - format!("{}|{revisions:?}|{:?}", s.mesh_id, s.doc.project.display) +/// What the traced scene depends on. `composites`: the texture-set composites too (their +/// revisions bump with every composited chunk, so while textures load this changes every frame). +fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { + let revisions: Vec = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; + let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength())).collect(); + + format!("{}|{revisions:?}|{sets:?}|{:?}", session.mesh_id, session.doc.project.display) } -/// What the render depends on; a change restarts it. -fn key(app: &TextureCraftApp, size: (u32, u32)) -> String { - format!("{}|{:?}|{size:?}|{:?}", scene_key(app), app.session.camera, app.ui.render) +/// [`scene_key`] of the GPU render. It takes texture changes in by copying the display textures +/// when their content changes (throttled while textures load, see [`take_in_textures`]), so the +/// composites only count when they displace the geometry. Restarting on every composited chunk +/// would rebuild the scene and reset the render every frame of a load. +fn gpu_scene_key(session: &texturecraft_engine::Session) -> String { + scene_key(session, session.doc.project.display.displacement) +} + +/// What the render of scene `scene_key` depends on; a change restarts it. +fn key(app: &TextureCraftApp, scene_key: &str, size: (u32, u32)) -> String { + format!("{scene_key}|{:?}|{size:?}|{:?}", app.session.camera, app.ui.render) } fn start(app: &TextureCraftApp, ctx: &egui::Context, key: String, size: (u32, u32)) -> Job { @@ -269,40 +389,53 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { overlay(app, ui, rect, on_gpu); } +/// Advance the CPU render and keep the last completed image visible during restarts. fn show_cpu(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { let ctx = ui.ctx().clone(); let size = render_size(rect); - let k = key(app, size); - if app.render.job.as_ref().is_none_or(|j| j.key != k) { - app.render.job = Some(start(app, &ctx, k, size)); + + // The CPU tracer reads the composites themselves: every change restarts it + let render_key = key(app, &scene_key(&app.session, true), size); + if app.render.job.as_ref().is_none_or(|job| job.key != render_key) { + app.render.job = Some(start(app, &ctx, render_key, size)); app.render.samples = 0; } + let now = ctx.input(|i| i.time); if let Some(job) = app.render.job.as_mut() { #[cfg(target_arch = "wasm32")] { - if let Some(f) = job.work.step_for(30.0) { - *job.latest.lock().unwrap_or_else(PoisonError::into_inner) = Some(f); + if let Some(frame) = job.work.step_for(30.0) { + *job.latest.lock().unwrap_or_else(PoisonError::into_inner) = Some(frame); } if job.work.tracer.samples < job.work.max_samples { ctx.request_repaint(); } } - if let Some(f) = job.latest.lock().unwrap_or_else(PoisonError::into_inner).take() { - let img = ColorImage::from_rgba_unmultiplied([f.width as usize, f.height as usize], &f.rgba); + if let Some(frame) = job.latest.lock().unwrap_or_else(PoisonError::into_inner).take() { + let image = ColorImage::from_rgba_unmultiplied([frame.width as usize, frame.height as usize], &frame.rgba); match app.render.texture.as_mut() { - Some(t) => t.set(img, TextureOptions::LINEAR), - None => app.render.texture = Some(ctx.load_texture("render-view", img, TextureOptions::LINEAR)), + Some(texture) => texture.set(image, TextureOptions::LINEAR), + None => app.render.texture = Some(ctx.load_texture("render-view", image, TextureOptions::LINEAR)), } - app.render.samples = f.samples; + app.render.samples = frame.samples; app.render.elapsed = now - job.started; - app.render.shown = Some((f.width, f.height, f.rgba)); + app.render.shown = Some((frame.width, frame.height, frame.rgba)); } } - let shown = app.render.texture.as_ref().filter(|_| app.render.samples > 0).map(TextureHandle::id); + + let shown = app.render.texture.as_ref().map(TextureHandle::id); paint(ui, rect, shown); } +/// Whether the view shows the render image rather than the "Starting render..." placeholder. +/// `has_image`: an earlier frame of this render is on screen. A restart (the camera moved) resets +/// the sample count to 0 but keeps that frame up, so orbiting doesn't flash the placeholder. +/// Only the very first frame, before anything was traced, has nothing to show. +fn show_image(has_image: bool, samples: u32) -> bool { + has_image || samples > 0 +} + /// The render, or a placeholder until its first samples. fn paint(ui: &Ui, rect: Rect, texture: Option) { let tk = Tokens::get(ui.ctx()); @@ -320,96 +453,165 @@ fn paint(ui: &Ui, rect: Rect, texture: Option) { /// Trace on the GPU; false when it can't (no compute shaders, or it failed on this scene). fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { - let Some(rs) = app.render_state.clone() else { return false }; - let scene_key = scene_key(app); - if !GpuTracer::supported(&rs.device) || app.render.gpu_error.as_ref().is_some_and(|(k, _)| *k == scene_key) { + let Some(render_state) = app.render_state.clone() else { return false }; + let scene_key = gpu_scene_key(&app.session); + if !GpuTracer::supported(&render_state.device) || app.render.gpu_error.as_ref().is_some_and(|(k, _)| *k == scene_key) { return false; } + app.render.gpu_error = None; if app.render.job.take().is_some() { app.render.texture = None; app.render.shown = None; } + let ctx = ui.ctx().clone(); let now = ctx.input(|i| i.time); - let size = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32); - let key = key(app, size); - let mut g = match app.render.gpu.take() { - Some(g) if g.size == size => g, + let full = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32); + let loading = textures_loading(&app.session); + let moving = app.render.motion.moving(&app.session.camera, now, loading); + if moving { + // Come back and restore the full size once the camera has been still, even with no input + ctx.request_repaint_after(std::time::Duration::from_secs_f64(MOTION_SETTLE_S)); + } + + let size = traced_size(full, moving); + let key = key(app, &scene_key, size); + let mut previous = app.render.gpu.take(); + if let Some(view) = previous.as_mut() { + // Read the completed callback before resizing replaces its status + view.has_image |= view.status.lock().unwrap_or_else(PoisonError::into_inner).samples > 0; + } + + let mut view = match previous { + Some(view) if view.size == size => view, old => { - let out = GpuTracer::output_texture(&rs.device, size.0, size.1); + let out = GpuTracer::output_texture(&render_state.device, size.0, size.1); let out_view = out.create_view(&Default::default()); - // A resized view keeps its scene and egui texture id. - let (texture, scene_key, scene) = match old { + + // A resized view keeps its scene and egui texture id + let old_has_image = old.as_ref().is_some_and(|previous| previous.has_image); + let old_spp = old.as_ref().map_or(1, |previous| rescale_spp(previous.spp, previous.size, size)); + let mut held_since = old.as_ref().map_or(now, |previous| previous.held_since); + let growing = old.as_ref().is_some_and(|previous| u64::from(previous.size.0) * u64::from(previous.size.1) < u64::from(size.0) * u64::from(size.1)); + let mut held = None; + let (texture, scene_key, scene, spp_control) = match old { + // Returning to full size: the old image stays up under its own texture id + Some(old) if growing && old.has_image => { + let mut renderer = render_state.renderer.write(); + if let Some(texture) = old.held { + renderer.free_texture(&texture); + } + + held = Some(old.texture); + held_since = now; + (renderer.register_native_texture(&render_state.device, &out_view, wgpu::FilterMode::Linear), old.scene_key, old.scene, old.spp_control) + } Some(old) => { - rs.renderer.write().update_egui_texture_from_wgpu_texture(&rs.device, &out_view, wgpu::FilterMode::Linear, old.texture); - (old.texture, old.scene_key, old.scene) + let mut renderer = render_state.renderer.write(); + if let Some(texture) = old.held { + renderer.free_texture(&texture); + } + + renderer.update_egui_texture_from_wgpu_texture(&render_state.device, &out_view, wgpu::FilterMode::Linear, old.texture); + (old.texture, old.scene_key, old.scene, old.spp_control) } None => ( - rs.renderer.write().register_native_texture(&rs.device, &out_view, wgpu::FilterMode::Linear), + render_state.renderer.write().register_native_texture(&render_state.device, &out_view, wgpu::FilterMode::Linear), scene_key.clone(), Arc::new(trace_scene(app)), + SppControl::default(), ), }; - GpuView { size, scene_key, scene, key: String::new(), started: now, out, out_view, texture, status: Arc::default(), spp: 1, read: Arc::default() } + + GpuView { + size, + scene_key, + scene, + key: String::new(), + started: now, + out, + out_view, + texture, + status: Arc::default(), + spp: old_spp, + spp_control, + read: Arc::default(), + has_image: old_has_image, + held, + held_since, + } } }; + let (samples, error) = { - let mut st = g.status.lock().unwrap_or_else(PoisonError::into_inner); - if g.key != key { - st.samples = 0; + let mut status = view.status.lock().unwrap_or_else(PoisonError::into_inner); + if view.key != key { + status.samples = 0; } - (st.samples, st.error.take()) + + (status.samples, status.error.take()) }; - if let Some(e) = error { - log::warn!("GPU path tracing failed, rendering on the CPU: {e}"); - app.render.gpu_error = Some((scene_key, e)); - app.render.gpu = Some(g); + + if let Some(error) = error { + log::warn!("GPU path tracing failed, rendering on the CPU: {error}"); + app.render.gpu_error = Some((scene_key, error)); + app.render.gpu = Some(view); return false; } - if g.key != key { - g.key = key.clone(); - g.started = now; + + if view.key != key { + view.key = key.clone(); + view.started = now; } - if g.scene_key != scene_key { - g.scene = Arc::new(trace_scene(app)); - g.scene_key = scene_key; + if view.scene_key != scene_key { + view.scene = Arc::new(trace_scene(app)); + view.scene_key = scene_key; } + let max_samples = app.ui.render.max_samples.max(1); if samples < max_samples { - // Keep the UI near 60 fps: more samples while frames are quick, half as many when slow. - let dt = ctx.input(|i| i.stable_dt); - g.spp = if dt > 1.0 / 40.0 { - (g.spp / 2).max(1) - } else if dt < 1.0 / 60.0 { - (g.spp + 1).min(16) - } else { - g.spp - }; - app.render.elapsed = now - g.started; + // Loading time includes compositing, so it cannot reliably steer the tracer's sample count + view.spp = if loading { view.spp.min(LOADING_MAX_SPP) } else { view.spp_control.next(view.spp, f64::from(ctx.input(|i| i.stable_dt))) }; + app.render.elapsed = now - view.started; ctx.request_repaint(); } + app.render.samples = samples; - if poll_read(app, &rs.device, &g) { + if poll_read(app, &render_state.device, &view) { ctx.request_repaint(); } - let cb = TraceCallback { + + let callback = TraceCallback { key, - scene: g.scene.clone(), + scene: view.scene.clone(), camera: app.session.camera, settings: settings(app), display: display(app), max_samples, - spp: g.spp, + spp: view.spp, + loading, + now, size, - out: g.out.clone(), - out_view: g.out_view.clone(), - status: g.status.clone(), - read: g.read.clone(), + out: view.out.clone(), + out_view: view.out_view.clone(), + status: view.status.clone(), + read: view.read.clone(), }; - ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, cb)); - paint(ui, rect, (samples > 0).then_some(g.texture)); - app.render.gpu = Some(g); + ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback)); + if let Some(held) = view.held { + let elapsed = now - view.held_since; + if holds_previous(samples, elapsed) { + // A render capped below the hold threshold still needs a frame to release the image + ctx.request_repaint_after(std::time::Duration::from_secs_f64((SETTLE_HOLD_MAX_S - elapsed).max(0.0))); + } else { + render_state.renderer.write().free_texture(&held); + view.held = None; + } + } + + paint(ui, rect, show_image(view.has_image, samples).then_some(view.held.unwrap_or(view.texture))); + app.render.gpu = Some(view); true } @@ -461,6 +663,9 @@ struct TraceCallback { display: TraceDisplay, max_samples: u32, spp: u32, + /// Textures are still loading (see [`LOADING_RESTART_S`]) and the egui time of this frame. + loading: bool, + now: f64, size: (u32, u32), out: wgpu::Texture, out_view: wgpu::TextureView, @@ -469,41 +674,51 @@ struct TraceCallback { } impl TraceCallback { + /// Synchronize scene data, add samples and resolve the frame for the UI. fn run( &self, - st: &mut TraceState, + state: &mut TraceState, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, renderer: &Renderer, ) -> Result<(), String> { - let t = &mut st.tracer; - if !st.scene.as_ref().is_some_and(|s| Arc::ptr_eq(s, &self.scene)) { - t.set_scene(device, queue, &self.scene)?; - st.scene = Some(self.scene.clone()); + let tracer = &mut state.tracer; + if !state.scene.as_ref().is_some_and(|scene| Arc::ptr_eq(scene, &self.scene)) { + tracer.set_scene(device, queue, &self.scene)?; + state.scene = Some(self.scene.clone()); } - if t.sync_materials(device, queue, encoder, renderer)? || st.key != self.key { - t.reset(device, encoder, self.size.0, self.size.1)?; - st.key.clone_from(&self.key); - st.resolved = None; + + let sync_textures = take_in_textures(self.loading, self.now, state.last_sync); + if sync_textures { + state.last_sync = self.now; } - let done = t.samples(); - if done < self.max_samples { - t.pass(device, queue, encoder, &self.camera, &self.settings, self.spp.min(self.max_samples - done)); + if (sync_textures && tracer.sync_materials(device, queue, encoder, renderer)?) || state.key != self.key { + tracer.reset(device, encoder, self.size.0, self.size.1)?; + state.key.clone_from(&self.key); + state.resolved = None; } - if st.resolved != Some(t.samples()) { - t.resolve(device, queue, encoder, &self.display, &self.out_view); - st.resolved = Some(t.samples()); + + let samples = tracer.samples(); + if samples < self.max_samples { + tracer.pass(device, queue, encoder, &self.camera, &self.settings, self.spp.min(self.max_samples - samples)); } + if state.resolved != Some(tracer.samples()) { + tracer.resolve(device, queue, encoder, &self.display, &self.out_view); + state.resolved = Some(tracer.samples()); + } + let mut read = self.read.lock().unwrap_or_else(PoisonError::into_inner); if matches!(*read, Read::Wanted) { *read = Read::Copied(Readback::new(device, encoder, &self.out)); } + Ok(()) } } impl CallbackTrait for TraceCallback { + /// Submit tracing work and report its samples or failure to the next UI frame. fn prepare( &self, device: &wgpu::Device, @@ -514,7 +729,7 @@ impl CallbackTrait for TraceCallback { ) -> Vec { let state = match resources.remove::() { Some(st) => Ok(st), - None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None }), + None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None, last_sync: f64::MIN }), }; let result = state.and_then(|mut st| { let r = match resources.get::() { @@ -538,14 +753,21 @@ impl CallbackTrait for TraceCallback { /// Free the GPU render (its texture and the tracer's scene memory; the pipelines stay). fn drop_gpu(app: &mut TextureCraftApp) { - let Some(g) = app.render.gpu.take() else { return }; - if let Some(rs) = &app.render_state { - let mut r = rs.renderer.write(); - r.free_texture(&g.texture); - if let Some(st) = r.callback_resources.get_mut::() { - st.tracer.release(); - (st.scene, st.resolved) = (None, None); - st.key.clear(); + let Some(view) = app.render.gpu.take() else { return }; + if let Some(render_state) = &app.render_state { + let mut renderer = render_state.renderer.write(); + renderer.free_texture(&view.texture); + if let Some(held) = view.held { + renderer.free_texture(&held); + } + + if let Some(state) = renderer.callback_resources.get_mut::() { + state.tracer.release(); + (state.scene, state.resolved) = (None, None); + state.key.clear(); + + // The materials went with the release: the next render takes textures in at once + state.last_sync = f64::MIN; } } } diff --git a/crates/ui-egui/src/render_mode/frame_floor.rs b/crates/ui-egui/src/render_mode/frame_floor.rs new file mode 100644 index 00000000..442003a5 --- /dev/null +++ b/crates/ui-egui/src/render_mode/frame_floor.rs @@ -0,0 +1,33 @@ +//! Recent frame-time baseline for adaptive sampling. + +/// Frames over which [`FrameFloor`] keeps the quickest frame time. +pub(super) const FLOOR_FRAMES: usize = 30; + +/// The range the quickest frame time is held to (seconds): from 75 frames a second to 30, so a +/// run of slow frames never makes slow look normal. The quick end matters as much: frames that +/// are not paced by the display (or tiny ones while little is traced) can take 3 ms, and taking +/// that as the baseline cuts the samples per frame to one at the first frame that does real work, +/// which left the render grainy for seconds. Below this, frames count as quick, not as the target. +pub(super) const FLOOR_RANGE_S: (f64, f64) = (1.0 / 75.0, 1.0 / 30.0); + +/// The quickest of the last [`FLOOR_FRAMES`] frame times: about the display's refresh interval +/// while the GPU keeps up. +#[derive(Default)] +pub(super) struct FrameFloor { + recent: std::collections::VecDeque, +} + +impl FrameFloor { + /// Record frame time `frame_seconds` (seconds); the quickest recent one, within [`FLOOR_RANGE_S`]. + pub(super) fn push(&mut self, frame_seconds: f64) -> f64 { + if frame_seconds.is_finite() && frame_seconds > 0.0 { + if self.recent.len() >= FLOOR_FRAMES { + self.recent.pop_front(); + } + + self.recent.push_back(frame_seconds); + } + + self.recent.iter().copied().fold(FLOOR_RANGE_S.1, f64::min).clamp(FLOOR_RANGE_S.0, FLOOR_RANGE_S.1) + } +} diff --git a/crates/ui-egui/src/render_mode/motion.rs b/crates/ui-egui/src/render_mode/motion.rs new file mode 100644 index 00000000..500b730e --- /dev/null +++ b/crates/ui-egui/src/render_mode/motion.rs @@ -0,0 +1,36 @@ +//! Camera and texture-loading activity used to select render resolution. + +use texturecraft_engine::geom::OrbitCamera; + +use super::MOTION_SETTLE_S; + +/// Whether the camera is moving, for [`super::MOVING_SCALE`]. +#[derive(Default)] +pub(super) struct Motion { + /// The camera as last seen (compared, never parsed). + camera: String, + /// When it last changed. The first frame counts as a change: a render that has just started + /// begins at the smaller size too (four times the samples at once, so it opens smooth + /// instead of as raw one-sample noise) and grows to full size like after any move. + last_change: Option, +} + +impl Motion { + /// Record `camera` at time `now` (seconds); true while it changed within [`MOTION_SETTLE_S`]. + /// `loading`: textures are still being composited. Each finished tile restarts the render, so + /// like a moving camera it keeps being redone from no samples, and is traced small for the + /// same reason (four times the samples per restart). + pub(super) fn moving(&mut self, camera: &OrbitCamera, now: f64, loading: bool) -> bool { + if loading { + self.last_change = Some(now); + } + + let camera_key = format!("{camera:?}"); + if self.camera != camera_key { + self.last_change = Some(now); + self.camera = camera_key; + } + + self.last_change.is_some_and(|last_change| now - last_change < MOTION_SETTLE_S) + } +} diff --git a/crates/ui-egui/src/render_mode/spp_control.rs b/crates/ui-egui/src/render_mode/spp_control.rs new file mode 100644 index 00000000..3c676f3a --- /dev/null +++ b/crates/ui-egui/src/render_mode/spp_control.rs @@ -0,0 +1,73 @@ +//! Adaptive samples per pixel for the GPU render. + +use super::frame_floor::FrameFloor; + +/// Most samples per pixel one frame adds. +pub(super) const MAX_SPP: u32 = 16; + +/// A frame quicker than this many times the quickest recent one adds one more sample next time. +/// With vsync, frames come at the display's refresh rate however light they are, so the limits +/// are relative to it (a fixed 1/90 s never let a 60 Hz display grow at all). +const SPP_GROW_BELOW: f64 = 1.25; + +/// A frame at least this many times the quickest recent one (a missed refresh with vsync is two; +/// wide enough that ordinary variation in a busy frame does not cut) cuts the samples per frame (by a +/// quarter, by the same ratio the frame overshoots when that is larger), so a slow frame is +/// followed by a short one, not a long one. With vsync a frame that misses the refresh takes two. +const SPP_CUT_ABOVE: f64 = 1.75; + +/// Frames after a cut during which the samples per frame do not grow again, so they settle +/// below the limit instead of climbing straight back to the frame that missed it (a hitch every +/// few frames). +pub(super) const SPP_GROW_PAUSE_FRAMES: u32 = 6; + +/// Samples per pixel for the next frame, from the last frame's time `frame_seconds` and the quickest recent +/// one `floor` (seconds; see [`FrameFloor`]): one more while frames are quick, fewer when slow, +/// steady in between and for [`SPP_GROW_PAUSE_FRAMES`] after a cut (`since_cut` frames ago). +/// Steady between the two limits is what stops the count from climbing until the GPU backs up, +/// jumping down, and climbing again. +pub(super) fn next_spp(spp: u32, frame_seconds: f64, floor: f64, since_cut: u32) -> u32 { + let cut_above = floor * SPP_CUT_ABOVE; + if frame_seconds >= cut_above { + let by_ratio = (f64::from(spp) * cut_above / frame_seconds) as u32; + by_ratio.min(spp * 3 / 4).max(1) + } else if frame_seconds < floor * SPP_GROW_BELOW && since_cut >= SPP_GROW_PAUSE_FRAMES { + (spp + 1).min(MAX_SPP) + } else { + spp + } +} + +/// What steers the GPU render's samples per pixel per frame (see [`next_spp`]). +pub(super) struct SppControl { + floor: FrameFloor, + /// Frames since the samples per frame were last cut. + since_cut: u32, +} + +impl Default for SppControl { + /// A new render may grow from its first frame. + fn default() -> SppControl { + SppControl { floor: FrameFloor::default(), since_cut: SPP_GROW_PAUSE_FRAMES } + } +} + +impl SppControl { + /// The samples per frame after a frame of `frame_seconds` seconds traced with `spp`. + pub(super) fn next(&mut self, spp: u32, frame_seconds: f64) -> u32 { + let floor = self.floor.push(frame_seconds); + let next = next_spp(spp, frame_seconds, floor, self.since_cut); + self.since_cut = if next < spp { 0 } else { self.since_cut.saturating_add(1) }; + + next + } +} + +/// Samples per frame after the traced size changed from `old` to `new` pixels (frame time is +/// about proportional to samples times pixels). +pub(super) fn rescale_spp(spp: u32, old: (u32, u32), new: (u32, u32)) -> u32 { + let old_pixels = u64::from(old.0) * u64::from(old.1); + let new_pixels = (u64::from(new.0) * u64::from(new.1)).max(1); + + ((u64::from(spp) * old_pixels / new_pixels).max(1) as u32).min(MAX_SPP) +} diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs new file mode 100644 index 00000000..247acd98 --- /dev/null +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -0,0 +1,349 @@ +//! Rendering-mode cache and frame-lifecycle regressions. + +use super::frame_floor::{FLOOR_FRAMES, FLOOR_RANGE_S, FrameFloor}; +use super::spp_control::{MAX_SPP, SPP_GROW_PAUSE_FRAMES, SppControl, next_spp, rescale_spp}; +use super::{ + LOADING_RESTART_S, MOTION_SETTLE_S, Motion, OrbitCamera, SETTLE_HOLD_MAX_S, SETTLE_HOLD_SAMPLES, gpu_scene_key, holds_previous, scene_key, show_image, + take_in_textures, textures_loading, traced_size, +}; +use texturecraft_engine::Session; +use texturecraft_engine::geom::primitives; + +/// A small, fully composed sphere avoids unrelated texture-loading transitions. +fn session() -> Session { + let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + session.update(); + + session +} + +/// Bump-strength edits invalidate GPU scene data even without displaced geometry. +#[test] +fn height_strength_changes_restart_the_gpu_scene_without_displacement() { + let mut session = session(); + let before = gpu_scene_key(&session); + assert!(!session.doc.project.display.displacement); + + texturecraft_engine::execute(&mut session, "textureSet.settings", &serde_json::json!({"heightStrength": 5.0})).unwrap(); + session.update(); + + assert_ne!(gpu_scene_key(&session), before, "the GPU shader must receive the new bump strength"); +} + +/// Keeping an imported image alive prevents its cached identity from being reused for another image. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn environment_cache_retains_source_identity_until_replaced() { + use std::sync::Arc; + use texturecraft_engine::compose::ImageRes; + + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); + app.session.doc.project.display.environment = "resource:environment".into(); + let source = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]; 2], srgb: false }); + let original_source = Arc::downgrade(&source); + app.session.images.insert("environment".into(), source); + let first = super::trace_scene(&app).env; + assert!(Arc::ptr_eq(&first, &super::trace_scene(&app).env), "unchanged images reuse the decoded environment"); + + let replacement = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[0.0, 1.0, 0.0, 1.0]; 2], srgb: false }); + app.session.images.insert("environment".into(), replacement.clone()); + + assert!(original_source.upgrade().is_some(), "the cache must retain its source so its address cannot be reused"); + let second = super::trace_scene(&app).env; + assert!(!Arc::ptr_eq(&first, &second)); + assert_ne!(first.data, second.data, "replacing the image changes the lighting"); + assert!(Arc::ptr_eq(&second, &super::trace_scene(&app).env)); + assert!(original_source.upgrade().is_none(), "replacing the cache releases the previous source"); + + app.session.images.insert("renamed".into(), replacement); + app.session.doc.project.display.environment = "resource:renamed".into(); + assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key"); +} + +/// Create one harness device, skipping unavailable or non-compute backends. +#[cfg(not(target_arch = "wasm32"))] +fn gpu_app() -> Option { + use eframe::egui_wgpu::{RenderState, RendererOptions, WgpuConfiguration}; + use egui_kittest::wgpu::{WgpuTestRenderer, default_wgpu_setup}; + + let setup = default_wgpu_setup(); + let instance = pollster::block_on(setup.new_instance()); + let configuration = WgpuConfiguration { wgpu_setup: setup, ..Default::default() }; + let render_state = match pollster::block_on(RenderState::create(&configuration, &instance, None, RendererOptions::PREDICTABLE)) { + Ok(render_state) => render_state, + Err(error) => { + eprintln!("skipping: could not create the harness GPU device: {error}"); + return None; + } + }; + + let adapter = render_state.adapter.get_info(); + if !super::GpuTracer::supported(&render_state.device) { + eprintln!("skipping: harness adapter {} ({:?}) cannot run the GPU tracer", adapter.name, adapter.backend); + return None; + } + + eprintln!("GPU lifecycle test adapter: {} ({:?})", adapter.name, adapter.backend); + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut app = egui_kittest::Harness::builder() + .with_size(egui::vec2(800.0, 600.0)) + .renderer(WgpuTestRenderer::from_render_state(render_state)) + .build_eframe(|context| crate::TextureCraftApp::new(context, session())) + .into_state(); + app.session.update(); + for cache in &mut app.session.caches { + cache.upload.clear(); + } + + Some(app) +} + +/// Build a GPU rendering frame at a controlled time without executing its callback. +#[cfg(not(target_arch = "wasm32"))] +fn draw_gpu(app: &mut crate::TextureCraftApp, context: &egui::Context, time: f64) -> egui::FullOutput { + context.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { + assert!(super::show_gpu(app, ui, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(128.0, 96.0)))); + }) +} + +/// A first completed callback must survive a slow frame's switch to full resolution. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn settling_after_the_first_gpu_frame_keeps_its_image() { + let Some(mut app) = gpu_app() else { return }; + + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let view = app.render.gpu.as_ref().unwrap(); + let previous_texture = view.texture; + + // The callback finishes the first frame before a slow frame returns to the UI + view.status.lock().unwrap().samples = 1; + assert!(!view.has_image); + + draw_gpu(&mut app, &context, MOTION_SETTLE_S + 0.1).drop_without_applying_deltas(); + + let view = app.render.gpu.as_ref().unwrap(); + assert_eq!(view.size, (128, 96)); + assert!(view.has_image, "resizing must read the completed callback before replacing its status"); + assert_eq!(view.held, Some(previous_texture)); +} + +/// A finished low-sample render must wake again to release its retained preview. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_low_sample_limit_schedules_the_held_image_timeout() { + let Some(mut app) = gpu_app() else { return }; + + app.ui.render.max_samples = 1; + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let view = app.render.gpu.as_mut().unwrap(); + view.has_image = true; + view.status.lock().unwrap().samples = 1; + let settled_at = MOTION_SETTLE_S + 0.1; + draw_gpu(&mut app, &context, settled_at).drop_without_applying_deltas(); + app.render.gpu.as_ref().unwrap().status.lock().unwrap().samples = 1; + + for frame in 1..=5 { + let output = draw_gpu(&mut app, &context, settled_at + f64::from(frame) * 0.01); + let delay = output.viewport_output[&egui::ViewportId::ROOT].repaint_delay; + output.drop_without_applying_deltas(); + assert!(delay.as_secs_f64() <= SETTLE_HOLD_MAX_S, "a finished render must wake to release its held image: {delay:?}"); + } + + draw_gpu(&mut app, &context, settled_at + SETTLE_HOLD_MAX_S + 0.01).drop_without_applying_deltas(); + assert!(app.render.gpu.as_ref().unwrap().held.is_none()); +} + +/// Every composited chunk bumps a revision. The CPU render restarts on it (it reads the +/// composites); the GPU render does not (it copies the display textures when they change, +/// throttled while loading) unless the heights displace its geometry. +#[test] +fn composited_chunks_restart_the_gpu_render_only_when_displaced() { + let mut session = session(); + let (cpu, gpu) = (scene_key(&session, true), gpu_scene_key(&session)); + session.caches[0].revision += 1; + + assert_ne!(scene_key(&session, true), cpu); + assert_eq!(gpu_scene_key(&session), gpu, "the GPU scene is kept while textures load"); + + session.doc.project.display.displacement = true; + let displaced = gpu_scene_key(&session); + session.caches[0].revision += 1; + + assert_ne!(gpu_scene_key(&session), displaced, "displaced geometry follows the heights"); +} + +/// Loading lasts until the composited tiles are uploaded too (the GPU render reads them). +#[test] +fn textures_load_until_their_tiles_are_uploaded() { + let mut session = session(); + session.caches[0].upload.clear(); + assert!(!textures_loading(&session)); + + session.caches[0].upload.insert((0, 0)); + assert!(textures_loading(&session), "a tile waits to be uploaded"); + + session.caches[0].upload.clear(); + session.caches[0].invalidate_all(); + assert!(textures_loading(&session), "tiles wait to be composited"); +} + +/// Orbiting restarts the render every frame (samples back to 0): the last image stays up. +#[test] +fn a_restart_keeps_the_previous_image_on_screen() { + assert!(show_image(true, 0), "restart with an earlier frame must not show the placeholder"); + assert!(show_image(true, 5)); + assert!(show_image(false, 1)); +} + +/// Motion halves each dimension without shrinking already tiny views. +#[test] +fn a_moving_camera_traces_smaller_and_a_still_one_at_full_size() { + assert_eq!(traced_size((1600, 900), false), (1600, 900)); + assert_eq!(traced_size((1600, 900), true), (800, 450)); + + // Tiny views are never made smaller than they are or than 16 pixels + assert_eq!(traced_size((10, 10), true), (10, 10)); + assert_eq!(traced_size((20, 400), true), (16, 200)); +} + +/// Camera changes and unfinished uploads keep the preview small until activity settles. +#[test] +fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { + let mut motion = Motion::default(); + let mut camera = OrbitCamera::default(); + assert!(motion.moving(&camera, 0.0, false), "a render that just started opens at the smaller size"); + assert!(!motion.moving(&camera, 1.0, false)); + + camera.yaw += 0.1; + assert!(motion.moving(&camera, 2.0, false)); + assert!(motion.moving(&camera, 2.0 + MOTION_SETTLE_S * 0.5, false)); + assert!(!motion.moving(&camera, 2.0 + MOTION_SETTLE_S * 1.5, false)); + + assert!(motion.moving(&camera, 5.0, true), "textures still loading count as motion"); + assert!(motion.moving(&camera, 5.0 + MOTION_SETTLE_S * 0.5, false), "and settle a moment after they finish"); + assert!(!motion.moving(&camera, 5.0 + MOTION_SETTLE_S * 1.5, false)); +} + +/// Either sufficient samples or the deadline replaces the retained preview. +#[test] +fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out() { + assert!(holds_previous(0, 0.0)); + assert!(holds_previous(SETTLE_HOLD_SAMPLES - 1, SETTLE_HOLD_MAX_S * 0.5)); + assert!(!holds_previous(SETTLE_HOLD_SAMPLES, 0.0), "enough samples: show the new render"); + assert!(!holds_previous(0, SETTLE_HOLD_MAX_S), "a slow GPU: don't hold it forever"); +} + +/// Sampling grows gradually, holds through jitter and cuts promptly on overload. +#[test] +fn samples_per_frame_grow_slowly_hold_in_between_and_drop_fast() { + let (floor, free) = (1.0 / 144.0, SPP_GROW_PAUSE_FRAMES); + + assert_eq!(next_spp(4, floor, floor, free), 5, "frames at the refresh rate: one more"); + assert_eq!(next_spp(MAX_SPP, floor, floor, free), MAX_SPP); + assert_eq!(next_spp(4, floor, floor, 0), 4, "just after a cut: no growth yet"); + assert_eq!(next_spp(6, floor * 1.4, floor, free), 6, "between the limits: steady"); + assert_eq!(next_spp(8, floor * 2.5, floor, free), 5, "slow frame: cut by the overshoot (8 * 1.75/2.5), more than a quarter"); + assert_eq!(next_spp(8, floor * 1.7, floor, free), 8, "a little slow: steady, not a cut (cuts are for real overload)"); + assert_eq!(next_spp(8, floor * 1.8, floor, free), 6, "slightly over the limit: a quarter fewer"); + assert_eq!(next_spp(8, floor * 20.0, floor, free), 1, "very slow frame: by the overshoot, at least one"); + assert_eq!(next_spp(1, floor * 20.0, floor, free), 1); +} + +/// With vsync on a 60 Hz display every frame takes ~16.7 ms however light: that is the +/// refresh, not a slow GPU, so the samples grow; a missed refresh (two intervals) cuts them. +#[test] +fn samples_per_frame_grow_at_60_hz_and_drop_on_a_missed_refresh() { + let refresh_seconds = 1.0 / 60.0; + let mut control = SppControl::default(); + let mut spp = 2; + + for _ in 0..10 { + spp = control.next(spp, refresh_seconds); + } + + assert_eq!(spp, 12, "one more per frame at the refresh rate"); + + let cut = control.next(spp, 2.0 * refresh_seconds); + assert!(cut < spp && cut >= spp / 2, "a missed refresh cuts: {spp} -> {cut}"); + + // No climb straight back to the frame that missed: steady for a while, then growth again + let mut after = cut; + for _ in 0..SPP_GROW_PAUSE_FRAMES - 1 { + after = control.next(after, refresh_seconds); + } + + assert_eq!(after, cut, "steady after the cut"); + + for _ in 0..3 { + after = control.next(after, refresh_seconds); + } + + assert!(after > cut, "then it grows again"); +} + +/// Frames that are not paced by the display (or take almost no work) can be a few ms; a frame +/// that then does real work must not read as slow and cut the samples to one (the render was +/// left grainy for seconds). +#[test] +fn a_few_very_quick_frames_do_not_collapse_the_samples_per_frame() { + let mut control = SppControl::default(); + for _ in 0..5 { + control.next(4, 0.003); + } + + let working_seconds = 0.012; + let mut spp = 4; + + for _ in 0..10 { + spp = control.next(spp, working_seconds); + } + + assert!(spp >= 4, "12 ms frames after 3 ms ones are fine: {spp}"); +} + +/// Invalid timings are ignored and old timings expire within the bounded window. +#[test] +fn the_frame_floor_is_the_quickest_recent_frame_within_range() { + let mut floor = FrameFloor::default(); + + assert_eq!(floor.push(1.0 / 60.0), 1.0 / 60.0); + assert_eq!(floor.push(0.05), 1.0 / 60.0, "a slow frame does not raise it"); + assert_eq!(floor.push(f64::NAN), 1.0 / 60.0, "a broken time is ignored"); + assert_eq!(floor.push(0.0001), FLOOR_RANGE_S.0, "never below the quick end of the range"); + + for _ in 0..FLOOR_FRAMES { + floor.push(0.2); + } + + assert_eq!(floor.push(0.2), FLOOR_RANGE_S.1, "only recent frames count, and at most 1/30 s"); +} + +/// Resolution changes preserve approximate tracing work within the sample limits. +#[test] +fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { + assert_eq!(rescale_spp(12, (500, 400), (1000, 800)), 3, "four times the pixels: a quarter of the samples"); + assert_eq!(rescale_spp(3, (1000, 800), (500, 400)), 12); + assert_eq!(rescale_spp(1, (500, 400), (1000, 800)), 1, "never below one"); + assert_eq!(rescale_spp(16, (100, 100), (10, 10)), MAX_SPP, "never above the cap"); +} + +/// Loading throttles texture synchronization without delaying the first or settled update. +#[test] +fn loading_textures_are_taken_in_at_a_limited_rate() { + assert!(take_in_textures(false, 1.0, 1.0), "not loading: every frame"); + assert!(!take_in_textures(true, 1.0 + LOADING_RESTART_S * 0.5, 1.0)); + assert!(take_in_textures(true, 1.0 + LOADING_RESTART_S, 1.0)); + assert!(take_in_textures(true, 0.0, f64::MIN), "the first frame always"); +} + +/// The placeholder appears only before the first image has been traced. +#[test] +fn nothing_traced_yet_shows_the_placeholder() { + assert!(!show_image(false, 0)); +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 3b25125f..e52a2907 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -118,6 +118,13 @@ pub struct Prefs { /// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at /// startup). Empty or relative: `Documents/TextureCraft`. pub data_folder: String, + /// Cores a project save leaves to the UI; Settings bounds this to the available logical CPUs + /// (desktop). At least one save worker always runs. + pub reserved_cores: u32, + /// Maximum decompressed project size accepted on open, in GiB (at least one). + pub project_open_limit_gib: u32, + /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100). + pub save_ram_percent: u8, } impl Default for Prefs { @@ -132,10 +139,22 @@ impl Default for Prefs { 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, + save_ram_percent: 50, } } } +impl Prefs { + /// Apply resource preferences before commands or file workers can start. + pub fn apply_resource_limits(&self) { + texturecraft_engine::formats::set_project_open_limit_gib(self.project_open_limit_gib); + #[cfg(not(target_arch = "wasm32"))] + texturecraft_engine::formats::set_save_resources(self.reserved_cores as usize, self.save_ram_percent); + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NewProject { pub mesh: String, @@ -257,6 +276,9 @@ pub struct UiState { /// The docked, tabbed and floating panels around the viewport. #[serde(default)] pub dock: Dock, + /// The panel open against the icon rail, if any; not saved, so the app starts with the rail closed + #[serde(skip)] + pub rail_panel: Option, #[serde(default = "Dock::for_baking")] pub(crate) inactive_mode_dock: Dock, #[serde(default)] @@ -304,6 +326,9 @@ pub struct UiState { /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// How the 3D view shows symmetry + #[serde(default)] + pub symmetry: crate::symmetry::SymmetryDisplay, /// What bake mode's 3D view draws besides the low poly (the Baking Visualization panel) #[serde(default)] pub bake_visualization: crate::bake_mode::BakeVisualizationToggles, @@ -353,6 +378,7 @@ impl Default for UiState { layout: ViewLayout::Split, split_ratio: default_split_ratio(), dock: Dock::default(), + rail_panel: None, inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, bake_layout_version: BAKE_LAYOUT_VERSION, @@ -376,6 +402,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + symmetry: crate::symmetry::SymmetryDisplay::default(), bake_visualization: crate::bake_mode::BakeVisualizationToggles::default(), } } diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs new file mode 100644 index 00000000..9c492896 --- /dev/null +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -0,0 +1,131 @@ +//! Symmetry: the toolbar toggle and settings popup, and what the 3D view draws for it + +mod ribbons; +mod settings_popup; +mod symmetry_display; +mod symmetry_drag; +mod symmetry_intersection; +mod symmetry_manipulator; +mod symmetry_manipulator_arrow; +mod view_overlay; + +use egui::Ui; +use egui_phosphor::regular as ic; +use texturecraft_engine::Tool; +use texturecraft_engine::paint::Symmetry; + +pub use symmetry_display::SymmetryDisplay; +pub(crate) use view_overlay::{manipulator_hovered, manipulator_input, overlay, scene_overlay}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +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 +pub(crate) fn applies_to(tool: Tool) -> bool { + matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path) +} + +/// Whether the 3D view shows symmetry now +pub(crate) fn shown(app: &TextureCraftApp) -> bool { + app.ui.mode == crate::state::Mode::Painting && applies_to(app.session.tool.tool) && app.session.tool.brush.symmetry.any() +} + +/// The world axes any active mirror plane or radial axis can move along, even while symmetry is disabled +pub(crate) fn movable_axes(symmetry: &Symmetry) -> [bool; 3] { + let mirrors = [symmetry.x, symmetry.y, symmetry.z]; + let radial_axis = symmetry.axis_index(); + [0, 1, 2].map(|axis| mirrors[axis] || (symmetry.radial > 1 && axis != radial_axis)) +} + +/// The toolbar's Symmetry toggle: turning it on with nothing set mirrors on X +fn toggle(symmetry: &mut Symmetry) { + if symmetry.any() { + symmetry.enabled = false; + return; + } + + symmetry.enabled = true; + if !symmetry.x && !symmetry.y && !symmetry.z && symmetry.radial <= 1 { + symmetry.x = true; + } +} + +/// Apply changed symmetry settings through the same command used by scripts and agents +fn apply(app: &mut TextureCraftApp, symmetry: Symmetry) { + if symmetry == app.session.tool.brush.symmetry { + return; + } + + app.run( + "tool.brush", + serde_json::json!({ + "symmetryOn": symmetry.enabled, + "symmetryX": symmetry.x, + "symmetryY": symmetry.y, + "symmetryZ": symmetry.z, + "symmetryRadial": symmetry.radial, + "symmetryAxis": (["x", "y", "z"][symmetry.axis_index()]), + "symmetryOffset": symmetry.offset, + "symmetryAngleSpan": symmetry.angle_span, + }), + ); +} + +/// The Symmetry toggle and the settings button with its popup +pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry"), app.session.tool.brush.symmetry.any(), button_size).clicked() { + let mut symmetry = app.session.tool.brush.symmetry; + toggle(&mut symmetry); + apply(app, symmetry); + } + + // No tooltip on the settings button; the label still names it for screen readers + let popup_id = ui.make_persistent_id("symmetry_settings"); + let mut open = ui.data(|data| data.get_temp::(popup_id)).unwrap_or(false); + let response = icon_badge_dropdown_button(ui, ic::FLIP_HORIZONTAL, ic::GEAR, tr("Symmetry settings"), open, button_size); + if response.clicked() { + open = !open; + } + + // egui's single popup slot is needed by the color picker inside this popup + let shown = egui::Popup::from_response(&response) + .id(popup_id) + .open_bool(&mut open) + .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) + .show(|ui| settings_popup::show(app, ui)); + + // A click outside the popup and the dropdowns it opens (foreground layers too) closes it + if let Some(shown) = shown + && !response.clicked() + && ui.input(|input| input.pointer.any_click()) + && let Some(at) = ui.input(|input| input.pointer.interact_pos()) + && ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground) + { + open = false; + } + + ui.data_mut(|data| data.insert_temp(popup_id, open)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn combined_symmetry_can_move_every_active_plane_and_axis() { + for enabled in [true, false] { + for axis in 0..3 { + let symmetry = Symmetry { enabled, x: axis == 0, y: axis == 1, z: axis == 2, radial: 5, axis, ..Symmetry::default() }; + + let movable = movable_axes(&symmetry); + + assert_eq!(movable, [true; 3], "the mirror plane still moves along the radial axis: {symmetry:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/symmetry/ribbons.rs b/crates/ui-egui/src/symmetry/ribbons.rs new file mode 100644 index 00000000..24b49c51 --- /dev/null +++ b/crates/ui-egui/src/symmetry/ribbons.rs @@ -0,0 +1,35 @@ +//! Lines drawn into the 3D view as thin quads + +use egui::Rect; +use texturecraft_engine::geom::glam::{Mat4, Vec3}; +use texturecraft_render::OverlayQuad; + +use crate::TextureCraftApp; + +/// Height of the view in normalized device coordinates (−1 to 1) +const NDC_HEIGHT: f32 = 2.0; + +/// Lines drawn as thin quads turned to face the camera, a steady width on screen +pub(crate) struct Ribbons { + eye: Vec3, + view_proj: Mat4, + /// World units per screen point at clip-space w = 1 + world_per_point: f32, +} + +impl Ribbons { + pub(crate) fn new(app: &TextureCraftApp, rect: Rect) -> Self { + let camera = &app.session.camera; + let view_proj = camera.view_proj(rect.width() / rect.height().max(1.0)); + let ndc_per_unit = view_proj.row(1).truncate().length(); + Ribbons { eye: camera.eye(), view_proj, world_per_point: NDC_HEIGHT / (rect.height() * ndc_per_unit).max(f32::EPSILON) } + } + + /// The line from `from` to `to`, `width` points wide + pub(crate) fn quad(&self, from: Vec3, to: Vec3, width: f32, color: [f32; 3], opacity: f32) -> OverlayQuad { + let middle = (from + to) * 0.5; + let clip_w = (self.view_proj * middle.extend(1.0)).w.max(0.0); + let side = (to - from).cross(self.eye - middle).normalize_or_zero() * (clip_w * self.world_per_point * width * 0.5); + OverlayQuad { corners: [from - side, to - side, to + side, from + side], color, opacity } + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs new file mode 100644 index 00000000..4d11e82a --- /dev/null +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -0,0 +1,143 @@ +//! The symmetry settings popup: independent mirror and radial copies, their position and display + +use egui::{Align, Color32, Layout, Stroke, Ui, vec2}; +use texturecraft_engine::paint::{FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Symmetry}; + +use super::{DEFAULT_RADIAL_COUNT, movable_axes}; +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::{color_swatch, section, slider}; + +/// The popup's width (points) +const POPUP_WIDTH: f32 = 340.0; + +/// Width of the radial Axis row's label column +const LABEL_WIDTH: f32 = 64.0; + +const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; + +/// Space between the mirror section and the radial toggle +const SECTIONS_GAP: f32 = 4.0; + +/// The color square's width (points) and the Manipulator size slider's range +const COLOR_SWATCH_WIDTH: f32 = 48.0; +const MANIPULATOR_SIZES: std::ops::RangeInclusive = 0.1..=1.0; + +/// Side of the radial copies preview beside the Count and Angle span sliders +const PREVIEW_SIZE: f32 = 96.0; + +/// The popup's content, applying brush changes through the engine and display preferences in place +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.set_width(POPUP_WIDTH); + let (minimum, maximum) = app.session.mesh.bounds(); + let half_extent = (maximum - minimum) * 0.5; + let display = &mut app.ui.symmetry; + let mut edited = app.session.tool.brush.symmetry; + let symmetry = &mut edited; + section(ui, "symmetry_mirror", tr("Mirror symmetry"), true, |ui| { + ui.horizontal(|ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (name, enabled) in AXIS_NAMES.into_iter().zip([&mut symmetry.x, &mut symmetry.y, &mut symmetry.z]) { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + ui.checkbox(enabled, name); + }); + } + }); + }); + ui.add_space(SECTIONS_GAP); + + let mut radial = symmetry.radial > 1; + if ui.checkbox(&mut radial, tr("Radial symmetry")).changed() { + symmetry.radial = if radial { DEFAULT_RADIAL_COUNT } else { 0 }; + } + + if radial { + section(ui, "symmetry_radial", tr("Radial settings"), true, |ui| { + labelled_row(ui, tr("Axis"), |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| { + ui.radio_value(&mut symmetry.axis, axis as u8, name); + }); + } + }); + ui.horizontal_top(|ui| { + let sliders_width = ui.available_width() - PREVIEW_SIZE - ui.spacing().item_spacing.x; + ui.allocate_ui_with_layout(vec2(sliders_width, PREVIEW_SIZE), Layout::top_down(Align::Min), |ui| { + let mut count = f32::from(symmetry.radial); + if slider(ui, tr("Count"), &mut count, 2.0..=f32::from(MAX_RADIAL_COPIES), 0).changed() { + symmetry.radial = count.round() as u8; + } + slider(ui, tr("Angle span"), &mut symmetry.angle_span, 0.0..=FULL_TURN_DEGREES, 0); + }); + copies_preview(ui, symmetry, super::view_overlay::color(display.color, u8::MAX)); + }); + }); + } + + let movable = movable_axes(symmetry); + section(ui, "symmetry_axis_position", tr("Axis position"), true, |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)); + } + }); + + section(ui, "symmetry_display", tr("Display"), true, |ui| { + ui.horizontal(|ui| { + ui.label(tr("Symmetry color display")); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| color_swatch(ui, "symmetry_color", &mut display.color, COLOR_SWATCH_WIDTH)); + }); + if symmetry.x || symmetry.y || symmetry.z { + ui.checkbox(&mut display.show_plane, tr("Show plane")); + } + if radial { + ui.checkbox(&mut display.show_axis, tr("Show axis")); + } + ui.checkbox(&mut display.show_intersection, tr("Show intersection")); + ui.checkbox(&mut display.show_cursor, tr("Show cursor")); + ui.indent("symmetry_hide_while_painting", |ui| { + ui.add_enabled(display.show_cursor, egui::Checkbox::new(&mut display.hide_while_painting, tr("Hide while painting"))); + }); + ui.checkbox(&mut display.show_manipulator, tr("Show axis position manipulator")); + ui.add_enabled_ui(display.show_manipulator, |ui| slider(ui, tr("Manipulator size"), &mut display.manipulator_size, MANIPULATOR_SIZES, 1)); + }); + + super::apply(app, edited); +} + +/// A row with `label` in a fixed-width column and the control filling the rest +fn labelled_row(ui: &mut Ui, label: &str, control: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let height = ui.spacing().interact_size.y; + ui.allocate_ui_with_layout(vec2(LABEL_WIDTH, height), Layout::left_to_right(Align::Center), |ui| { + ui.set_min_width(LABEL_WIDTH); + ui.label(label); + }); + control(ui); + }); +} + +/// Where the radial copies go, on the view's backdrop: the stroke in white on the right, its copies in `copy_color` +fn copies_preview(ui: &mut Ui, symmetry: &Symmetry, copy_color: Color32) { + const RING_FRACTION: f32 = 0.32; + const DOT_RADIUS: f32 = 3.0; + const CROSS_HALF: f32 = 4.0; + const CORNER_RADIUS: f32 = 2.0; + + let tokens = crate::theme::Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(PREVIEW_SIZE, PREVIEW_SIZE), egui::Sense::hover()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, CORNER_RADIUS, tokens.viewport); + + let center = rect.center(); + let ring = PREVIEW_SIZE * RING_FRACTION; + let cross = Stroke::new(1.0, tokens.viewport_text); + painter.line_segment([center - vec2(CROSS_HALF, 0.0), center + vec2(CROSS_HALF, 0.0)], cross); + painter.line_segment([center - vec2(0.0, CROSS_HALF), center + vec2(0.0, CROSS_HALF)], cross); + for copy in 0..symmetry.radial { + // Screen y points down: positive angles turn counter-clockwise + let angle = symmetry.radial_angle(copy); + let at = center + vec2(angle.cos(), -angle.sin()) * ring; + painter.circle_filled(at, DOT_RADIUS, if copy == 0 { Color32::WHITE } else { copy_color }); + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_display.rs b/crates/ui-egui/src/symmetry/symmetry_display.rs new file mode 100644 index 00000000..5ef64405 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_display.rs @@ -0,0 +1,41 @@ +//! How the 3D view shows symmetry: the settings popup's Display section + +use serde::{Deserialize, Serialize}; + +/// The manipulator size the popup starts at; the manipulator's measurements are given at this size +pub(crate) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.4; + +/// Display settings for the symmetry plane, axis, intersection, cursors and manipulator +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SymmetryDisplay { + /// Linear RGB of everything drawn for symmetry + pub color: [f32; 3], + /// Mirror: a see-through plane between the two sides + pub show_plane: bool, + /// Radial: a see-through line along the axis + pub show_axis: bool, + /// Where the plane cuts the mesh (a line) or the axis meets it (a point) + pub show_intersection: bool, + /// A brush cursor at every copy of the cursor + pub show_cursor: bool, + pub hide_while_painting: bool, + pub show_manipulator: bool, + /// Manipulator scale; [`DEFAULT_MANIPULATOR_SIZE`] draws it at its base size + pub manipulator_size: f32, +} + +impl Default for SymmetryDisplay { + fn default() -> Self { + SymmetryDisplay { + color: [1.0, 0.0, 0.0], + show_plane: false, + show_axis: false, + show_intersection: true, + show_cursor: true, + hide_while_painting: true, + show_manipulator: false, + manipulator_size: DEFAULT_MANIPULATOR_SIZE, + } + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_drag.rs b/crates/ui-egui/src/symmetry/symmetry_drag.rs new file mode 100644 index 00000000..5c5b39f5 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_drag.rs @@ -0,0 +1,12 @@ +//! A symmetry manipulator drag in progress + +use egui::Pos2; + +/// Kept in egui's memory between the frames of one drag +#[derive(Clone, Copy, Debug)] +pub(crate) struct SymmetryDrag { + /// The world axes the grabbed handle moves along + pub(crate) axes: [bool; 3], + pub(crate) from: Pos2, + pub(crate) start_offset: [f32; 3], +} diff --git a/crates/ui-egui/src/symmetry/symmetry_intersection.rs b/crates/ui-egui/src/symmetry/symmetry_intersection.rs new file mode 100644 index 00000000..2099d304 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_intersection.rs @@ -0,0 +1,50 @@ +//! Where a mirror plane cuts the mesh, kept between frames + +use std::sync::Arc; + +use texturecraft_engine::geom::Mesh; +use texturecraft_engine::geom::glam::Vec3; + +/// The segments where the plane `p[axis] = position` crosses the mesh's triangles +#[derive(Clone, Debug)] +pub(crate) struct SymmetryIntersection { + mesh_id: u64, + axis: usize, + position: f32, + pub(crate) segments: Arc>, +} + +impl SymmetryIntersection { + /// Every triangle's crossing with the plane (mesh `mesh_id`, the plane `p[axis] = position`) + pub(crate) fn compute(mesh: &Mesh, mesh_id: u64, axis: usize, position: f32) -> Self { + let mut segments = Vec::new(); + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(&first), Some(&second), Some(&third)) = (mesh.positions.get(first), mesh.positions.get(second), mesh.positions.get(third)) else { + continue; + }; + + let corners = [first, second, third]; + + // Each edge whose ends lie on opposite sides crosses the plane once + let side = |corner: usize| corners[corner][axis] - position; + let mut crossings = [Vec3::ZERO; 2]; + let mut count = 0; + for (start, end) in [(0, 1), (1, 2), (2, 0)] { + if (side(start) < 0.0) != (side(end) < 0.0) && count < crossings.len() { + crossings[count] = corners[start].lerp(corners[end], side(start) / (side(start) - side(end))); + count += 1; + } + } + if count == crossings.len() { + segments.push(crossings); + } + } + SymmetryIntersection { mesh_id, axis, position, segments: Arc::new(segments) } + } + + /// Whether this is the cut of mesh `mesh_id` by the plane `p[axis] = position` + pub(crate) fn is_for(&self, mesh_id: u64, axis: usize, position: f32) -> bool { + self.mesh_id == mesh_id && self.axis == axis && self.position == position + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_manipulator.rs b/crates/ui-egui/src/symmetry/symmetry_manipulator.rs new file mode 100644 index 00000000..ce691988 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_manipulator.rs @@ -0,0 +1,194 @@ +//! The axis position manipulator: arrows at the symmetry origin that move it + +use egui::{Pos2, Rect, Vec2}; +use texturecraft_engine::geom::glam::Vec3; + +use super::symmetry_display::DEFAULT_MANIPULATOR_SIZE; +use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; +use crate::TextureCraftApp; + +/// Arrow length at the default manipulator size, as a fraction of the view height +const ARROW_LENGTH: f32 = 0.1; + +/// Gap between the center and where the shafts start (points at the default size) +const SHAFT_GAP: f32 = 5.0; + +/// Cone length and base radius (points at the default size, at the origin's depth) +pub(crate) const CONE_LENGTH: f32 = 15.0; +pub(crate) const CONE_RADIUS: f32 = 5.0; + +/// Radial: the square handle spans this part of the arrows, clear of the shafts +const SQUARE_FROM: f32 = 0.16; +const SQUARE_TO: f32 = 0.46; + +/// How far (fraction of the mesh diagonal, at least a minimum) the screen scale is measured along each axis +const PROBE_FRACTION: f32 = 0.01; +const MIN_PROBE: f32 = 1e-4; + +/// Shortest on-screen axis (points per world unit) the manipulator offers a handle for +const MIN_SCREEN_SCALE: f32 = 1e-3; + +/// Grab radius around an arrow and around the center (points, at least this at any size) +const GRAB_RADIUS: f32 = 7.0; + +/// The manipulator as the 3D view shows it this frame +#[derive(Clone, Debug)] +pub(crate) struct SymmetryManipulator { + pub(crate) center: Pos2, + pub(crate) arrows: Vec, + /// Radial: a square between the two arrows that moves the axis along both + pub(crate) square: Option<[Pos2; 4]>, + /// World units per screen point at the origin + pub(crate) world_per_point: f32, + /// The manipulator size relative to the default: every measurement scales with it + pub(crate) scale: f32, + /// Screen points per world unit along X, Y and Z at the origin + screen_per_unit: [Vec2; 3], +} + +impl SymmetryManipulator { + /// Handles along the axes the plane or axis can move on, or None when the manipulator is hidden + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + let symmetry = app.session.tool.brush.symmetry; + if !app.ui.symmetry.show_manipulator || !super::shown(app) { + return None; + } + + let project = |point: Vec3| crate::viewport::project(app, rect, point); + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let center = project(origin)?; + let step = ((hi - lo).length() * PROBE_FRACTION).max(MIN_PROBE); + let screen_per_unit = [Vec3::X, Vec3::Y, Vec3::Z].map(|axis| project(origin + axis * step).map_or(Vec2::ZERO, |point| (point - center) / step)); + + // Sized in points at the origin's depth, so the arrows keep their size on screen but still turn in 3D + let right = app.session.camera.forward().cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let points_per_unit = project(origin + right * step).map_or(0.0, |point| (point - center).length() / step); + if points_per_unit <= MIN_SCREEN_SCALE { + return None; + } + + let world_per_point = 1.0 / points_per_unit; + let scale = app.ui.symmetry.manipulator_size / DEFAULT_MANIPULATOR_SIZE; + let length = rect.height() * ARROW_LENGTH * scale * world_per_point; + + let movable = super::movable_axes(&symmetry); + let signs: &[f32] = if symmetry.radial_mode() { &[1.0] } else { &[1.0, -1.0] }; + let arrows: Vec = (0..3) + .filter(|axis| movable[*axis] && screen_per_unit[*axis].length() > MIN_SCREEN_SCALE) + .flat_map(|axis| signs.iter().map(move |sign| (axis, [Vec3::X, Vec3::Y, Vec3::Z][axis] * *sign))) + .filter_map(|(axis, direction)| { + let tip_world = origin + direction * length; + let base_world = origin + direction * (length - CONE_LENGTH * scale * world_per_point); + let start = project(origin + direction * SHAFT_GAP * scale * world_per_point)?; + Some(SymmetryManipulatorArrow { axis, direction, start, base: project(base_world)?, tip: project(tip_world)?, base_world, tip_world }) + }) + .collect(); + + let square = match movable_pair(&movable) { + Some((first, second)) if symmetry.radial_mode() => { + let corner = |along_first: f32, along_second: f32| { + let mut point = origin; + (point[first], point[second]) = (origin[first] + along_first * length, origin[second] + along_second * length); + project(point) + }; + let (from, to) = (SQUARE_FROM, SQUARE_TO); + match [corner(from, from), corner(to, from), corner(to, to), corner(from, to)] { + [Some(near), Some(along_first), Some(far), Some(along_second)] => Some([near, along_first, far, along_second]), + _ => None, + } + } + _ => None, + }; + Some(SymmetryManipulator { center, arrows, square, world_per_point, scale, screen_per_unit }) + } + + /// The axes the handle under `point` moves along: the center and the square move along all movable axes (two at most) + pub(crate) fn grab(&self, point: Pos2) -> Option<[bool; 3]> { + let mut all = [false; 3]; + self.arrows.iter().for_each(|arrow| all[arrow.axis] = true); + let grab_radius = GRAB_RADIUS * self.scale.max(1.0); + + // The center moves along all movable axes, which a screen drag can only do for two of them + let center_grabs = all.iter().filter(|axis| **axis).count() <= 2 && point.distance(self.center) <= grab_radius; + if center_grabs || self.square.is_some_and(|square| inside(&square, point)) { + return Some(all); + } + + let arrow = self.arrows.iter().find(|arrow| distance_to_segment(point, arrow.start, arrow.tip) <= grab_radius)?; + let mut axes = [false; 3]; + axes[arrow.axis] = true; + Some(axes) + } + + /// The world offset change that follows a pointer move of `moved` along `axes` + pub(crate) fn world_delta(&self, axes: [bool; 3], moved: Vec2) -> Vec3 { + let picked: Vec = (0..3).filter(|axis| axes[*axis]).collect(); + let mut delta = Vec3::ZERO; + match picked.as_slice() { + [axis] => { + let along = self.screen_per_unit[*axis]; + delta[*axis] = moved.dot(along) / along.length_sq().max(MIN_SCREEN_SCALE); + } + [first, second] => { + // Solve moved = a * first_axis + b * second_axis on screen + let (first_axis, second_axis) = (self.screen_per_unit[*first], self.screen_per_unit[*second]); + let determinant = first_axis.x * second_axis.y - first_axis.y * second_axis.x; + if determinant.abs() > MIN_SCREEN_SCALE { + delta[*first] = (moved.x * second_axis.y - moved.y * second_axis.x) / determinant; + delta[*second] = (first_axis.x * moved.y - first_axis.y * moved.x) / determinant; + } + } + _ => {} + } + delta + } +} + +/// The two movable axes, when there are two +fn movable_pair(movable: &[bool; 3]) -> Option<(usize, usize)> { + let picked: Vec = (0..3).filter(|axis| movable[*axis]).collect(); + match picked.as_slice() { + [first, second] => Some((*first, *second)), + _ => None, + } +} + +fn distance_to_segment(point: Pos2, from: Pos2, to: Pos2) -> f32 { + let along = to - from; + let fraction = ((point - from).dot(along) / along.length_sq().max(f32::EPSILON)).clamp(0.0, 1.0); + point.distance(from + along * fraction) +} + +/// Whether `point` is inside the convex quad `corners` +fn inside(corners: &[Pos2; 4], point: Pos2) -> bool { + let side = |index: usize| { + let (start, end) = (corners[index], corners[(index + 1) % 4]); + (end - start).x * (point - start).y - (end - start).y * (point - start).x + }; + let sides = [side(0), side(1), side(2), side(3)]; + sides.iter().all(|side| *side >= 0.0) || sides.iter().all(|side| *side <= 0.0) +} + +#[cfg(test)] +mod tests { + use egui::pos2; + + use super::*; + + #[test] + fn a_two_axis_drag_splits_the_move_between_both_axes() { + let manipulator = SymmetryManipulator { + center: pos2(0.0, 0.0), + arrows: Vec::new(), + square: None, + world_per_point: 1.0, + scale: 1.0, + screen_per_unit: [Vec2::new(10.0, 0.0), Vec2::new(0.0, -10.0), Vec2::ZERO], + }; + + let delta = manipulator.world_delta([true, true, false], Vec2::new(20.0, -30.0)); + + assert!((delta - Vec3::new(2.0, 3.0, 0.0)).length() < 1e-5, "{delta}"); + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs b/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs new file mode 100644 index 00000000..29d5144e --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs @@ -0,0 +1,18 @@ +//! One arrow of the symmetry manipulator + +use egui::Pos2; +use texturecraft_engine::geom::glam::Vec3; + +/// An arrow along one world axis, in 3D (so it foreshortens) and where it lands on screen +#[derive(Clone, Copy, Debug)] +pub(crate) struct SymmetryManipulatorArrow { + pub(crate) axis: usize, + /// The world axis, pointing toward the tip + pub(crate) direction: Vec3, + /// Where the shaft starts, just off the center, and where it meets the cone + pub(crate) start: Pos2, + pub(crate) base: Pos2, + pub(crate) tip: Pos2, + pub(crate) base_world: Vec3, + pub(crate) tip_world: Vec3, +} diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs new file mode 100644 index 00000000..3ceb5be6 --- /dev/null +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -0,0 +1,314 @@ +//! What the 3D view draws for symmetry: the plane or axis, where they meet the mesh, the cursor copies and the manipulator + +use egui::{Color32, PointerButton, Pos2, Rect, Response, Stroke, Ui}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_render::OverlayQuad; + +use super::ribbons::Ribbons; +use super::shown; +use super::symmetry_drag::SymmetryDrag; +use super::symmetry_intersection::SymmetryIntersection; +use super::symmetry_manipulator::SymmetryManipulator; +use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; +use crate::TextureCraftApp; + +/// The plane reaches this far past the mesh, as a fraction of its size +const PLANE_MARGIN: f32 = 0.05; +const PLANE_OPACITY: f32 = 0.18; + +/// The radial axis line's width (points) and opacity +const AXIS_WIDTH: f32 = 1.5; +const AXIS_OPACITY: f32 = 0.85; + +/// The intersection line's opacity +const LINE_OPACITY: f32 = 0.9; + +/// A point counts as visible when nothing is in front of it by more than this fraction of the mesh diagonal +const VISIBILITY_TOLERANCE: f32 = 2e-3; + +/// Width of the cut line and radius of the radial axis points (points) +const INTERSECTION_WIDTH: f32 = 1.5; +const INTERSECTION_POINT_RADIUS: f32 = 3.0; + +/// Manipulator arrows along X, Y and Z (the view-corner axis colors, a little softer) +const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; + +/// Arrow shaft width, its dark halo and the halo's extra width (points at the default size) +const SHAFT_WIDTH: f32 = 2.2; +const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); +const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; + +/// Faces around a cone +const CONE_SEGMENTS: usize = 20; + +/// Cone faces facing the camera more than this (cosine) are tinted toward white, the others toward black +const CONE_LIT_FROM: f32 = 0.55; + +/// How strongly the cone faces' tint follows their facing, toward white and toward black +const CONE_LIGHTEN: f32 = 0.9; +const CONE_DARKEN: f32 = 0.8; + +/// The center: a small disc in the arrows' material, its rim shaded and its middle lit like the cones +const CENTER_RADIUS: f32 = 4.0; +const CENTER_LIT_RADIUS: f32 = 0.6; +const CENTER_SHADE: f32 = 0.3; +const CENTER_LIGHT: f32 = 0.25; + +/// The radial square at rest and the opacity of its accent fill when active +const SQUARE_EDGE_WIDTH: f32 = 1.3; +const SQUARE_FILL: Color32 = Color32::from_rgba_premultiplied(40, 40, 40, 40); +const SQUARE_EDGE: Color32 = Color32::from_rgba_premultiplied(190, 190, 190, 190); +const SQUARE_ACTIVE_OPACITY: f32 = 0.45; + +/// `linear` RGB as a screen color with `alpha` +pub(super) fn color(linear: [f32; 3], alpha: u8) -> Color32 { + let [r, g, b] = linear.map(|channel| (texturecraft_engine::texel::linear_to_srgb(channel.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(r, g, b, alpha) +} + +/// The planes, the axis and where the planes cut the mesh, drawn by the renderer: the mesh hides them pixel by pixel where it is in front +pub(crate) fn scene_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> Vec { + if !shown(app) { + return Vec::new(); + } + + let symmetry = app.session.tool.brush.symmetry; + let display = app.ui.symmetry; + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let ribbon = Ribbons::new(app, rect); + let mut quads = Vec::new(); + + for (axis, on) in [symmetry.x, symmetry.y, symmetry.z].into_iter().enumerate() { + if !on { + continue; + } + + if display.show_plane { + let margin = (hi - lo) * PLANE_MARGIN; + let (lo, hi) = (lo - margin, hi + margin); + let (u, v) = ((axis + 1) % 3, (axis + 2) % 3); + let corner = |at_u: f32, at_v: f32| { + let mut point = origin; + (point[u], point[v]) = (at_u, at_v); + point + }; + let corners = [corner(lo[u], lo[v]), corner(hi[u], lo[v]), corner(hi[u], hi[v]), corner(lo[u], hi[v])]; + quads.push(OverlayQuad { corners, color: display.color, opacity: PLANE_OPACITY }); + } + if display.show_intersection { + let segments = intersection(app, ui, axis, origin[axis]); + quads.extend(segments.iter().map(|[from, to]| ribbon.quad(*from, *to, INTERSECTION_WIDTH, display.color, LINE_OPACITY))); + } + } + + if display.show_axis && symmetry.radial_mode() { + let direction = symmetry.radial_axis(); + let reach = (hi - lo).length() * 0.5; + quads.push(ribbon.quad(origin - direction * reach, origin + direction * reach, AXIS_WIDTH, display.color, AXIS_OPACITY)); + } + + quads +} + +/// Whether `point` is on the mesh's surface where the camera sees it: in the air (a copy that missed the mesh) or hidden behind the mesh, it is not +fn on_visible_surface(app: &TextureCraftApp, rect: Rect, point: Vec3, tolerance: f32) -> bool { + let camera = &app.session.camera; + let aspect = rect.width() / rect.height().max(1.0); + let Some(ndc) = camera.project(point, aspect) else { return false }; + + let ray = camera.ray(ndc.truncate(), aspect); + let distance = (point - ray.origin).dot(ray.dir); + app.session.bvh.closest(ray.origin, ray.dir, f32::MAX).is_some_and(|hit| (hit.t - distance).abs() <= tolerance) +} + +/// Over the 3D view: where the planes or axis meet the mesh, copies of the brush `cursor` (position, normal) and the manipulator +pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, cursor: Option<(Vec3, Vec3)>) { + if !shown(app) { + return; + } + + let symmetry = app.session.tool.brush.symmetry; + let display = app.ui.symmetry; + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + + // Bounds scan the mesh's vertices; every cursor copy shares these measurements + let diagonal = (hi - lo).length(); + let tolerance = diagonal * VISIBILITY_TOLERANCE; + let brush_radius = app.session.tool.brush.size * diagonal; + + let painter = ui.painter_at(rect); + let line = Stroke::new(INTERSECTION_WIDTH, color(display.color, u8::MAX)); + let project = |point: Vec3| crate::viewport::project(app, rect, point); + + // The planes' lines are drawn in the scene (see scene_overlay); where the radial axis enters the mesh, from either end, is drawn here + if display.show_intersection && symmetry.radial_mode() { + let axis = symmetry.radial_axis(); + let reach = diagonal; + for (start, direction) in [(origin - axis * reach, axis), (origin + axis * reach, -axis)] { + if let Some(hit) = app.session.bvh.closest(start, direction, reach * 2.0) + && let point = start + direction * hit.t + && on_visible_surface(app, rect, point, tolerance) + && let Some(at) = project(point) + { + painter.circle_filled(at, INTERSECTION_POINT_RADIUS, line.color); + } + } + } + + let painting = app.session.stroke_active(); + if display.show_cursor + && !(display.hide_while_painting && painting) + && let Some((position, normal)) = cursor + { + for map in symmetry.transforms().iter().skip(1) { + let copy = origin + *map * (position - origin); + if on_visible_surface(app, rect, copy, tolerance) { + crate::viewport::brush_cursor(app, ui, rect, copy, (*map * normal).normalize_or_zero(), brush_radius); + } + } + } + + if let Some(manipulator) = SymmetryManipulator::of(app, rect) { + draw_manipulator(app, ui, rect, &painter, &manipulator); + } +} + +/// Where the mirror plane `p[axis] = position` cuts the mesh, recomputed only when it moves +fn intersection(app: &TextureCraftApp, ui: &Ui, axis: usize, position: f32) -> std::sync::Arc> { + let id = egui::Id::unique("symmetry_intersection").with(axis); + let mesh_id = app.session.mesh_id; + let cached = ui.ctx().data(|data| data.get_temp::(id)).filter(|cached| cached.is_for(mesh_id, axis, position)); + let current = cached.unwrap_or_else(|| { + let computed = SymmetryIntersection::compute(&app.session.mesh, mesh_id, axis, position); + ui.ctx().data_mut(|data| data.insert_temp(id, computed.clone())); + computed + }); + current.segments +} + +/// The manipulator: the radial square, the arrows with their cones and the center; copper where hovered or dragged +fn draw_manipulator(app: &TextureCraftApp, ui: &Ui, rect: Rect, painter: &egui::Painter, manipulator: &SymmetryManipulator) { + let accent = crate::theme::Tokens::get(ui.ctx()).viewport_accent; + let hovered = ui.ctx().pointer_hover_pos().and_then(|pointer| manipulator.grab(pointer)); + let dragging = ui.ctx().data(|data| data.get_temp::(drag_id())).map(|drag| drag.axes); + let highlighted = dragging.or(hovered).unwrap_or_default(); + let all_highlighted = manipulator.arrows.iter().all(|arrow| highlighted[arrow.axis]); + let tint = |axis: usize| if highlighted[axis] { accent } else { AXIS_COLORS[axis] }; + + if let Some(square) = manipulator.square { + let fill = if all_highlighted { accent.gamma_multiply(SQUARE_ACTIVE_OPACITY) } else { SQUARE_FILL }; + let edge = if all_highlighted { accent } else { SQUARE_EDGE }; + painter.add(egui::Shape::convex_polygon(square.to_vec(), fill, Stroke::new(SQUARE_EDGE_WIDTH * manipulator.scale, edge))); + } + + for arrow in &manipulator.arrows { + let color = tint(arrow.axis); + painter.line_segment([arrow.start, arrow.base], Stroke::new((SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) * manipulator.scale, SHAFT_HALO)); + painter.line_segment([arrow.start, arrow.base], Stroke::new(SHAFT_WIDTH * manipulator.scale, color)); + cone(app, rect, painter, arrow, manipulator.world_per_point * super::symmetry_manipulator::CONE_RADIUS * manipulator.scale, color); + } + + let center_color = if all_highlighted { accent } else { manipulator.arrows.first().map_or(AXIS_COLORS[0], |arrow| AXIS_COLORS[arrow.axis]) }; + painter.circle_filled(manipulator.center, CENTER_RADIUS * manipulator.scale, center_color.lerp_to_gamma(Color32::BLACK, CENTER_SHADE)); + painter.circle_filled(manipulator.center, CENTER_RADIUS * CENTER_LIT_RADIUS * manipulator.scale, center_color.lerp_to_gamma(Color32::WHITE, CENTER_LIGHT)); +} + +/// A flat-shaded 3D cone over `arrow`'s head: faces facing the camera lighter, back to front +fn cone(app: &TextureCraftApp, rect: Rect, painter: &egui::Painter, arrow: &SymmetryManipulatorArrow, radius: f32, color: Color32) { + let camera = &app.session.camera; + let (eye, forward) = (camera.eye(), camera.forward()); + let side = arrow.direction.any_orthonormal_vector(); + let up = arrow.direction.cross(side); + let rim: Vec = (0..CONE_SEGMENTS) + .map(|segment| { + let angle = segment as f32 / CONE_SEGMENTS as f32 * std::f32::consts::TAU; + arrow.base_world + (side * angle.cos() + up * angle.sin()) * radius + }) + .collect(); + + // Each face: its corners, its depth and how much it faces the camera + let mut faces: Vec<(Vec, f32, f32)> = (0..CONE_SEGMENTS) + .map(|segment| { + let (rim_start, rim_end) = (rim[segment], rim[(segment + 1) % CONE_SEGMENTS]); + let middle = (rim_start + rim_end + arrow.tip_world) / 3.0; + let normal = (rim_end - rim_start).cross(arrow.tip_world - rim_start).normalize_or_zero(); + (vec![arrow.tip_world, rim_start, rim_end], (middle - eye).dot(forward), normal.dot((eye - middle).normalize_or_zero())) + }) + .collect(); + faces.push((rim.clone(), (arrow.base_world - eye).dot(forward), (-arrow.direction).dot((eye - arrow.base_world).normalize_or_zero()))); + faces.sort_by(|(_, nearer, _), (_, farther, _)| farther.total_cmp(nearer)); + + // One plain triangle mesh: anti-aliased polygons smear thin edge-on faces into long hairlines + let mut mesh = egui::Mesh::default(); + for (corners, _, facing) in faces { + let Some(points) = corners.iter().map(|corner| crate::viewport::project(app, rect, *corner)).collect::>>() else { + continue; + }; + + let facing = facing.max(0.0); + let fill = if facing > CONE_LIT_FROM { + color.lerp_to_gamma(Color32::WHITE, (facing - CONE_LIT_FROM) * CONE_LIGHTEN) + } else { + color.lerp_to_gamma(Color32::BLACK, (CONE_LIT_FROM - facing) * CONE_DARKEN) + }; + let first = mesh.vertices.len() as u32; + points.iter().for_each(|point| mesh.colored_vertex(*point, fill)); + for corner in 1..points.len().saturating_sub(1) as u32 { + mesh.add_triangle(first, first + corner, first + corner + 1); + } + } + painter.add(egui::Shape::mesh(mesh)); +} + +fn drag_id() -> egui::Id { + egui::Id::unique("symmetry_manipulator_drag") +} + +/// Whether the pointer is on a manipulator handle or dragging one (the brush cursor hides then) +pub(crate) fn manipulator_hovered(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> bool { + let dragging = ui.ctx().data(|data| data.get_temp::(drag_id())).is_some(); + let hovered = + ui.ctx().pointer_hover_pos().is_some_and(|pointer| SymmetryManipulator::of(app, rect).is_some_and(|manipulator| manipulator.grab(pointer).is_some())); + dragging || hovered +} + +/// Drags on the manipulator move the symmetry origin. Returns whether a drag owns the pointer +pub(crate) fn manipulator_input(app: &mut TextureCraftApp, ui: &Ui, response: &Response, rect: Rect) -> bool { + let ctx = ui.ctx(); + let manipulator = SymmetryManipulator::of(app, rect); + let mut drag = ctx.data(|data| data.get_temp::(drag_id())); + if response.drag_started_by(PointerButton::Primary) + && let (Some(manipulator), Some(from)) = (&manipulator, ctx.input(|input| input.pointer.press_origin())) + && let Some(axes) = manipulator.grab(from) + { + drag = Some(SymmetryDrag { axes, from, start_offset: app.session.tool.brush.symmetry.offset }); + } + + let dragging = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary); + let (Some(manipulator), Some(drag)) = (manipulator, drag.filter(|_| dragging)) else { + ctx.data_mut(|data| data.remove::(drag_id())); + if let (Some(manipulator), Some(hover)) = (SymmetryManipulator::of(app, rect), response.hover_pos()) + && manipulator.grab(hover).is_some() + { + ctx.set_cursor_icon(egui::CursorIcon::Move); + } + + return false; + }; + + if let Some(pointer) = response.interact_pointer_pos() { + let (lo, hi) = app.session.mesh.bounds(); + let half_extent = (hi - lo) * 0.5; + let moved = Vec3::from(drag.start_offset) + manipulator.world_delta(drag.axes, pointer - drag.from); + let offset = moved.clamp(-half_extent, half_extent).to_array(); + if offset != app.session.tool.brush.symmetry.offset { + app.run("tool.brush", serde_json::json!({"symmetryOffset": offset})); + } + } + + ctx.data_mut(|data| data.insert_temp(drag_id(), drag)); + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + true +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 889d2de7..9c0013bc 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -253,15 +253,12 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, button_size).clicked() { - brush.symmetry.x = !brush.symmetry.x; - } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, button_size).clicked() { - brush.symmetry.y = !brush.symmetry.y; - } if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, button_size).clicked() { brush.particles.enabled = !brush.particles.enabled; } + if crate::symmetry::applies_to(tool) { + crate::symmetry::toolbar_controls(app, ui); + } if tool == Tool::Smudge { ui.separator(); @@ -325,25 +322,25 @@ pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; - let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() { - path.closed = !path.closed; - } - let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; - if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() { - path.fill = !path.fill; + let path = &app.session.tool.path; + 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(); + if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { + app.session.set_path_closed(!closed); } - let has_points = !path.points.is_empty(); - if ui - .add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply")))) - .on_hover_text(tr("Paint the path with the brush (Enter)")) - .clicked() - { - app.run("tool.path", json!({"commit": true})); + let fill_tip = if closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, fill, button_size).clicked() { + app.session.set_path_fill(!fill); } - if ui.add_enabled(has_points, egui::Button::new(format!("{} {}", ic::X, tr("Cancel")))).on_hover_text(tr("Remove the path (Esc)")).clicked() { - app.run("tool.path", json!({"clear": true})); + + 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(); + } + + if ui.add_enabled_ui(has_points, |ui| icon_button(ui, ic::CHECK, tr("Apply"), false, button_size)).inner.clicked() { + app.run("tool.path", json!({"commit": true})); } } @@ -386,22 +383,39 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } +/// Width of the icon rail beside the dock +const RAIL_WIDTH: f32 = 38.0; + +/// Size of the rail's icons +const RAIL_ICON_SIZE: f32 = 26.0; + +/// Gap between the rail's icons +const RAIL_ICON_GAP: f32 = 4.0; + +/// Padding inside the rail's card around its icons, as the tool shelf's +const RAIL_CARD_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); + +/// The icon rail: Export, then the rail panels that are not in the dock, each opening its popup pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::right("rail").resizable(false).exact_size(38.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { - ui.spacing_mut().item_spacing.y = 4.0; - if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, 26.0).clicked() { + let tokens = Tokens::get(ui.ctx()); + egui::Panel::right("rail").resizable(false).exact_size(RAIL_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| { + ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP; + crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect()); + if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() { app.ui.windows.export = !app.ui.windows.export; } - for (panel, icon, id) in [ - (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), - (Panel::Display, ic::MONITOR, "ui.view.display"), - (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), - (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.dock.is_visible(panel), 26.0).clicked() { - app.ui.dock.toggle(panel); + + // A panel in the dock, docked or floating, leaves the rail until it is closed there + for (panel, icon, id) in crate::rail_popup::RAIL_PANELS { + if app.ui.dock.is_open(panel) { + continue; + } + + let response = icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.rail_panel == Some(panel), RAIL_ICON_SIZE); + crate::rail_popup::remember_icon(ui.ctx(), panel, response.rect); + if response.clicked() { + crate::rail_popup::toggle(app, panel); } } }); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 5eb9846a..4ac469eb 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1,7 +1,7 @@ //! The 3D viewport and the 2D UV view: navigation, painting input, brush cursor and the GPU //! callbacks that render them. -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use egui::emath::GuiRounding as _; use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; @@ -16,6 +16,8 @@ use crate::TextureCraftApp; use crate::decal_drop::DecalDrop; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; +use crate::path_hit::PathHit; +use crate::path_surface_cache::{PathSurfaceCache, SurfaceCurve}; use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -571,11 +573,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } + // A dismissing click cannot paint or place a decal through the rail popup + let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); + // 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 { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt + && !rail_popup && !DecalDrop::blocks_input(ui.ctx()) && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() @@ -587,7 +593,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); - let popup = app.properties_popup.is_some(); + let popup = app.properties_popup.is_some() || rail_popup; // A pending ID color pick takes the next click instead of the brush let picking_id_color = app.picking_id_color.is_some(); @@ -613,6 +619,21 @@ 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 symmetry_drag = !alt + && !adjusting + && !s_held + && !v_held + && !focus_pick + && !popup + && placing.is_none() + && !picking_id_color + && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()) + && !decal_drag + && crate::symmetry::manipulator_input(app, ui, &response, rect); + + // A handle owns a new click, but a stroke already under way must still finish over it + let symmetry_handle = !app.session.stroke_active() && crate::symmetry::manipulator_hovered(app, ui, rect); // Painting let painting = app.ui.mode == crate::state::Mode::Painting @@ -626,13 +647,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !picking_id_color && touch.is_none() && !decal_drag + && !symmetry_drag + && !symmetry_handle && !DecalDrop::blocks_input(ui.ctx()); let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); let mut fill_box = None; if painting && path_tool { - path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + path_input(app, ui, &response, (rect, false), |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); } else if painting && app.session.tool.tool == Tool::PolygonFill { fill_box = polygon_fill_input( app, @@ -683,6 +706,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin camera: app.session.camera, shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), + overlay: crate::symmetry::scene_overlay(app, ui, rect), }; add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); @@ -691,16 +715,22 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin 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 + let mut symmetry_cursor = None; if app.ui.mode == crate::state::Mode::Painting && !navigating && response.hovered() && brush_tool(app.session.tool.tool) + && (app.session.tool.tool != Tool::Path || adjusting) + && !crate::symmetry::manipulator_hovered(app, ui, rect) && app.picking_id_color.is_none() && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); - brush_cursor(app, ui, rect, hit.pos, hit.nrm); + let (bounds_min, bounds_max) = app.session.mesh.bounds(); + let radius = app.session.tool.brush.size * (bounds_max - bounds_min).length(); + brush_cursor(app, ui, rect, hit.pos, hit.nrm, radius); + symmetry_cursor = Some((hit.pos, hit.nrm)); if app.session.tool.tool == Tool::Clone && let Some(source) = app.session.clone_source_point(Some(hit.uv)) { @@ -712,13 +742,14 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !path_tool && let Some(from) = app.last_paint_point { - rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos); + rubber_band(ui, rect, &[pos2(rect.left() + from.x, rect.top() + from.y), hover_pos]); } } if app.ui.mode == crate::state::Mode::Painting && path_tool { path_overlay(app, ui, rect, &response, false, show); } + crate::symmetry::overlay(app, ui, rect, symmetry_cursor); stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); brush_readout(app, ui, &response, adjusting); @@ -1004,22 +1035,51 @@ fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { painter.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0)); } -/// A world point on screen in the 3D view `rect` (None behind the camera). -fn project(app: &TextureCraftApp, rect: Rect, p: Vec3) -> Option { - let n = app.session.camera.project(p, rect.width() / rect.height().max(1.0))?; - Some(pos2(rect.left() + (n.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - n.y * 0.5) * rect.height())) +/// A world point on screen in the 3D view `rect` (None behind the camera) +pub(crate) fn project(app: &TextureCraftApp, rect: Rect, point: Vec3) -> Option { + let ndc = app.session.camera.project(point, rect.width() / rect.height().max(1.0))?; + Some(pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height())) } -/// Control point grab radius (points). +/// Control point and curve grab radius (points) const HANDLE_GRAB: f32 = 8.0; +/// Opacity of the selected layer's other stored paths +const PATH_STORED_OPACITY: f32 = 0.55; +/// Opacity of a curve where the mesh hides it +const PATH_HIDDEN_OPACITY: f32 = 0.5; +/// A control point counts as hidden when the surface under it is this much closer (relative) +const PATH_HIDDEN_DEPTH: f32 = 0.01; +/// The Path tool's pointer glyph size (points) +const PATH_CURSOR_SIZE: f32 = 18.0; +/// A path's line and the dark outline under it (points) +const PATH_LINE_WIDTH: f32 = 1.4; +const PATH_OUTLINE_WIDTH: f32 = 3.0; +/// Where the view hint sits from the view's bottom left corner, and its text size (points) +const PATH_HINT_OFFSET: egui::Vec2 = vec2(56.0, -12.0); +const PATH_HINT_FONT_SIZE: f32 = 12.0; +/// The pen pointer's drop shadow, and the space before its insert plus (points) +const PATH_CURSOR_SHADOW_OFFSET: egui::Vec2 = vec2(1.0, 1.0); +const PATH_CURSOR_PLUS_GAP: f32 = 1.0; +/// The insert plus beside the pen pointer, relative to the pen's size +const PATH_CURSOR_PLUS_SCALE: f32 = 0.6; +/// Space kept right of the view hint, and its narrowest wrap width (points) +const PATH_HINT_MARGIN: f32 = 8.0; +const PATH_HINT_MIN_WIDTH: f32 = 80.0; +/// How much a control point marker grows under the pointer, and when selected (points) +const PATH_POINT_HOVER_GROWTH: f32 = 1.5; +const PATH_POINT_SELECTED_GROWTH: f32 = 0.5; +/// Control point marker radius (points) +const PATH_POINT_RADIUS: f32 = 3.0; +/// Curve sampling step on screen (points) +const PATH_SCREEN_STEP: f32 = 3.0; -/// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with -/// the global shortcuts, cancels it). +/// Path tool keys: Enter applies the path, Backspace removes the selected (or last) point; Esc is a global shortcut fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { #[cfg(not(target_arch = "wasm32"))] if crate::updates_ui::blocks_input(app) { return; } + if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Path || app.session.tool.path.points.is_empty() @@ -1027,24 +1087,116 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { { return; } + let (enter, back) = ui.input_mut(|i| (i.consume_key(egui::Modifiers::NONE, egui::Key::Enter), i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace))); if enter { app.run("tool.path", json!({"commit": true})); } if back { - app.session.tool.path.points.pop(); + app.session.remove_selected_path_point(); } } -/// Path tool input in a view (`uv`: the 2D view). Pressing on a control point drags it, -/// elsewhere adds a point (and drags it); clicking the first point of an open path closes it. -/// `place` maps a pointer position to a path point (None off the surface), `show` a path point -/// to the screen. +/// The selected layer's stored paths except the edited one: (path sublayer, index, path) +fn other_paths(app: &TextureCraftApp) -> Vec<(texturecraft_engine::core::LayerId, usize, texturecraft_engine::PathState)> { + let s = &app.session; + let Some(layer) = s.selected_layer().and_then(|id| s.doc.project.layer(id).ok()) else { return Vec::new() }; + let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|m| m.effects.iter())); + effects + .flat_map(|e| s.stored_path_states(e.id).into_iter().enumerate().map(move |(i, path)| (e.id, i, path))) + .filter(|(e, i, _)| s.tool.path.editing != Some((*e, *i))) + .collect() +} + +/// The screen curve through `points` per segment, each starting on its first point +fn screen_segments(points: &[Pos2], 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) + .into_iter() + .zip(points) + .map(|(samples, first)| std::iter::once(*first).chain(samples.into_iter().map(|v| pos2(v.x, v.y))).collect()) + .collect() +} + +/// A path's curve in a view per segment: screen position and whether the mesh leaves it visible (None off the mesh or screen) +type ScreenCurve = Vec>>; + +/// The nearest segment of `curve` within grab distance of `at`, with the nearest position on it +fn segment_near(curve: &ScreenCurve, at: Pos2) -> Option<(usize, Pos2)> { + let nearest = |segment: &Vec>| { + segment.windows(2).filter_map(|w| Some(closest_on_line(w[0]?.0, w[1]?.0, at))).min_by(|a, b| a.distance(at).total_cmp(&b.distance(at))) + }; + curve + .iter() + .enumerate() + .filter_map(|(i, segment)| nearest(segment).map(|p| (i, p))) + .filter(|(_, p)| p.distance(at) < HANDLE_GRAB) + .min_by(|a, b| a.1.distance(at).total_cmp(&b.1.distance(at))) +} + +/// `path`'s curve in a view; a 3D curve lies where its paint lands, and without `depth_test` (hit tests) every sample counts as visible +fn curve_on_screen( + app: &TextureCraftApp, + ui: &Ui, + (rect, uv, depth_test): (Rect, bool, bool), + path: &texturecraft_engine::PathState, + stored: Option<(texturecraft_engine::core::LayerId, usize)>, + show: &impl Fn(&TextureCraftApp, Vec3) -> Option, +) -> 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(); + } + 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))); + 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()) + .collect() +} + +/// Sample the stored curve once while visible, invalidating it when the path or mesh changes +fn stored_surface(app: &TextureCraftApp, ui: &Ui, eid: texturecraft_engine::core::LayerId, index: usize) -> Option { + ui.memory_mut(|memory| memory.caches.cache::().get(&app.session, eid, index)) +} + +/// The point of the segment `a`–`b` nearest to `p` +fn closest_on_line(a: Pos2, b: Pos2, p: Pos2) -> Pos2 { + let ab = b - a; + let t = if ab.length_sq() > 0.0 { ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + a + ab * t +} + +/// What `at` is over in a view (`uv`: the 2D view); `show` maps a path point to the screen +fn path_hit(app: &TextureCraftApp, ui: &Ui, (rect, uv): (Rect, bool), at: Pos2, show: &impl Fn(&TextureCraftApp, Vec3) -> Option) -> PathHit { + let path = &app.session.tool.path; + if path.uv == uv { + if let Some(i) = path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) { + return PathHit::Point(i); + } + if let Some((i, on)) = segment_near(&curve_on_screen(app, ui, (rect, uv, false), path, path.editing, show), at) { + return PathHit::Curve(i, on); + } + } + for (eid, i, other) in other_paths(app) { + if other.uv == uv + && (other.points.iter().any(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) + || segment_near(&curve_on_screen(app, ui, (rect, uv, false), &other, Some((eid, i)), show), at).is_some()) + { + return PathHit::Stored(eid, i); + } + } + PathHit::Miss +} + +/// Path tool presses in a view: select and drag a point, insert on the curve, open another path, close on the first point, or add a point fn path_input( app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, - uv: bool, + (rect, uv): (Rect, bool), place: impl Fn(&TextureCraftApp, Pos2) -> Option, show: impl Fn(&TextureCraftApp, Vec3) -> Option, ) { @@ -1054,71 +1206,191 @@ fn path_input( && let Some(at) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) { let path = &app.session.tool.path; - let near = if path.uv == uv { path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) } else { None }; - match near { - Some(0) if clicked && !path.closed && path.points.len() >= 3 => app.session.tool.path.closed = true, - Some(i) => ui.data_mut(|d| { - d.insert_temp(drag_id, i); - }), - None => match place(app, at) { - Some(p) => { - app.session.tool.path.push(p, uv); - let last = app.session.tool.path.points.len().saturating_sub(1); - ui.data_mut(|d| { - d.insert_temp(drag_id, last); - }); + let (closed, len) = (path.closed, path.points.len()); + let hit = path_hit(app, ui, (rect, uv), at, &show); + + let grab = match hit { + PathHit::Point(0) if clicked && !closed && len >= 3 => { + app.session.set_path_closed(true); + None + } + PathHit::Point(i) => { + app.session.select_path_point(i); + Some(i) + } + PathHit::Stored(eid, index) => { + app.run("path.edit", json!({"effect": eid.0, "index": index})); + None + } + hit => match place(app, if let PathHit::Curve(_, on) = hit { on } else { at }) { + Some(p) => match hit { + PathHit::Curve(i, _) => app.session.insert_path_point(i + 1, p), + _ => app.session.append_path_point(p, uv), + }, + None => { + app.toast(tr("Place path points on the mesh"), false); + None } - None => app.toast(tr("Place path points on the mesh"), false), }, + }; + if let Some(i) = grab { + ui.data_mut(|d| d.insert_temp(drag_id, (i, true))); } } + if resp.dragged_by(PointerButton::Primary) - && let Some(i) = ui.data(|d| d.get_temp::(drag_id)) + && let Some((index, begin_drag)) = ui.data(|data| data.get_temp::<(usize, bool)>(drag_id)) && let Some(p) = resp.interact_pointer_pos().and_then(|pos| place(app, pos)) - && let Some(q) = app.session.tool.path.points.get_mut(i) + && app.session.move_path_point(index, p, begin_drag) { - *q = p; + ui.data_mut(|data| data.insert_temp(drag_id, (index, false))); } + if !resp.is_pointer_button_down_on() { - ui.data_mut(|d| d.remove::(drag_id)); + ui.data_mut(|data| data.remove::<(usize, bool)>(drag_id)); } } -/// The path being edited: its curve, control points (the first one in the accent color) and, -/// while open, a dashed preview of the next segment. +/// Is path point `p` (on screen at `at`) in front of the mesh in the 3D view `rect`? +fn path_point_visible(app: &TextureCraftApp, rect: Rect, p: Vec3, at: Pos2) -> bool { + let eye = app.session.camera.eye(); + let local = Vec2::new(at.x - rect.left(), at.y - rect.top()); + app.session.pick(local, app.session.viewport).is_none_or(|hit| hit.pos.distance(eye) >= p.distance(eye) * (1.0 - PATH_HIDDEN_DEPTH)) +} + +/// Draw `curve` in `color` over a dark outline, as a faint line where the mesh hides it +fn draw_path_curve(painter: &egui::Painter, curve: &ScreenCurve, color: Color32) { + let draw = |run: &mut Vec, shown: bool| { + if run.len() > 1 { + // Hidden parts are a ghost line: no outline, half strength + if shown { + painter.add(egui::Shape::line(run.clone(), Stroke::new(PATH_OUTLINE_WIDTH, Color32::from_black_alpha(140)))); + } + painter.add(egui::Shape::line( + std::mem::take(run), + Stroke::new(PATH_LINE_WIDTH, if shown { color } else { color.gamma_multiply(PATH_HIDDEN_OPACITY) }), + )); + } + run.clear(); + }; + for segment in curve { + // Runs of samples the view shows (or hides) alike, joined at the sample where that changes + let (mut run, mut shown) = (Vec::new(), true); + for sample in segment { + match *sample { + Some((at, visible)) => { + if visible != shown && !run.is_empty() { + run.push(at); + draw(&mut run, shown); + } + shown = visible; + run.push(at); + } + None => draw(&mut run, shown), + } + } + draw(&mut run, shown); + } +} + +/// The layer's other paths (lit under the pointer), then the edited path with its points, the next segment's preview and the pen cursor fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option) { let tk = Tokens::get(ui.ctx()); - let p = ui.painter_at(rect); - let path = &app.session.tool.path; - let hint = tr("Path: click adds a point, drag moves it, Enter applies, Esc cancels"); - p.text(rect.left_bottom() + vec2(56.0, -12.0), egui::Align2::LEFT_BOTTOM, hint, egui::FontId::proportional(12.0), tk.viewport_text); - if path.uv != uv { - return; - } - let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); - let pts: Vec = handles.iter().map(|h| Vec2::new(h.x, h.y)).collect(); - let curve: Vec = texturecraft_engine::paint::spline(&pts, path.closed, 3.0).into_iter().map(|v| pos2(v.x, v.y)).collect(); - let color = if path.closed && path.fill { tk.viewport_accent } else { Color32::from_white_alpha(230) }; - p.add(egui::Shape::line(curve.clone(), Stroke::new(3.0, Color32::from_black_alpha(140)))); - p.add(egui::Shape::line(curve, Stroke::new(1.4, color))); + 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); + let hint = painter.layout(hint.to_string(), egui::FontId::proportional(PATH_HINT_FONT_SIZE), tk.viewport_text, wrap); + painter.galley(at - vec2(0.0, hint.size().y), hint, tk.viewport_text); + let hover = resp.hover_pos(); - if !path.closed - && let (Some(last), Some(to)) = (handles.last(), hover) - { - rubber_band(ui, rect, *last, to); + 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) }); } - for (i, h) in handles.iter().enumerate() { - let r = if hover.is_some_and(|m| m.distance(*h) < HANDLE_GRAB) { 5.5 } else { 4.0 }; - p.circle(*h, r, if i == 0 { tk.viewport_accent } else { Color32::WHITE }, Stroke::new(1.5, Color32::from_black_alpha(180))); + + let path = &app.session.tool.path; + if path.uv == uv { + draw_path_curve(&painter, &curve_on_screen(app, ui, (rect, uv, true), path, path.editing, &show), tk.viewport_accent); + let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); + if !path.closed + && !handles.is_empty() + && let Some((to, PathHit::Miss)) = hit + { + let mut next = handles.clone(); + next.push(to); + if let Some(segment) = screen_segments(&next, false).last() { + rubber_band(ui, rect, segment); + } + } + + for (index, point) in path.points.iter().enumerate() { + let Some(handle) = show(app, *point) else { continue }; + + // 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 }; + 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))); + } else { + painter.circle(handle, radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 }))); + } + } + } + + if let Some((at, hit)) = hit + && !ui.input(|i| i.modifiers.command) + { + if let PathHit::Curve(_, on) = hit { + // Where the click inserts its point + painter.circle(on, PATH_POINT_RADIUS, Color32::from_black_alpha(60), Stroke::new(1.0, Color32::from_white_alpha(110))); + } + path_cursor(ui, &painter, at, matches!(hit, PathHit::Curve(..))); } } -/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes. -fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let Some(visible) = visible_dashes(rect, from, to) else { return }; +/// The Path tool's pointer: a pen with its nib at `at`, and a plus when a click inserts a point +fn path_cursor(ui: &Ui, painter: &egui::Painter, at: Pos2, insert: bool) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let glyph = |icon: &str, size: f32, color: Color32| painter.layout_no_wrap(icon.to_string(), egui::FontId::proportional(size), color); + for (offset, color) in [(PATH_CURSOR_SHADOW_OFFSET, Color32::from_black_alpha(200)), (egui::Vec2::ZERO, Color32::WHITE)] { + // The pen's nib is the bottom left corner of the drawn glyph + let pen = glyph(egui_phosphor::regular::PEN_NIB, PATH_CURSOR_SIZE, color); + let origin = at + offset - pen.mesh_bounds.left_bottom().to_vec2(); + let right = origin + pen.mesh_bounds.right_bottom().to_vec2(); + painter.galley(origin, pen, color); + if insert { + let plus = glyph(egui_phosphor::regular::PLUS, PATH_CURSOR_SIZE * PATH_CURSOR_PLUS_SCALE, color); + painter.galley(right + vec2(PATH_CURSOR_PLUS_GAP, 0.0) - plus.mesh_bounds.left_top().to_vec2(), plus, color); + } + } +} + +/// Dashed curve preview clipped segment by segment to bound offscreen dash allocation +fn rubber_band(ui: &Ui, rect: Rect, line: &[Pos2]) { let painter = ui.painter_at(rect); - for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { - painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP; + let mut distance = 0.0; + for pair in line.windows(2) { + if let Some(visible) = visible_dashes(rect, pair[0], pair[1]) { + // Continue the dash pattern across sampled curve segments and clipped portions + let phase = (distance + pair[0].distance(visible[0])) % period; + for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] { + // Draw any dash already in progress without extending behind this curve segment + if phase > 0.0 && phase < RUBBER_BAND_DASH { + let direction = visible[1] - visible[0]; + let end = visible[0] + direction.normalized() * (RUBBER_BAND_DASH - phase).min(direction.length()); + painter.line_segment([visible[0], end], stroke); + } + let offset = if phase == 0.0 { 0.0 } else { period - phase }; + painter.add(egui::Shape::dashed_line_with_offset(&visible, stroke, &[RUBBER_BAND_DASH], &[RUBBER_BAND_GAP], offset)); + } + } + distance = (distance + pair[0].distance(pair[1])) % period; } } @@ -1294,35 +1566,38 @@ fn adjust_brush(brush: &mut texturecraft_engine::paint::BrushSettings, right: bo } } -fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) { - let (lo, hi) = app.session.mesh.bounds(); - let r = app.session.tool.brush.size * (hi - lo).length(); - let t = nrm.any_orthonormal_vector(); - let b = nrm.cross(t); - let to_screen = |p: Vec3| project(app, rect, p); - let mut pts = Vec::with_capacity(49); - for k in 0..=48 { - let a = k as f32 / 48.0 * std::f32::consts::TAU; - if let Some(s) = to_screen(pos + (t * a.cos() + b * a.sin()) * r) { - pts.push(s); +pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, position: Vec3, normal: Vec3, radius: f32) { + const CIRCLE_SEGMENTS: usize = 48; + + let tangent = 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 p = ui.painter_at(rect); - p.add(egui::Shape::line(pts.clone(), Stroke::new(2.5, Color32::from_black_alpha(140)))); - p.add(egui::Shape::line(pts, Stroke::new(1.2, Color32::from_white_alpha(230)))); - let h = app.session.tool.brush.hardness; - if h > 0.05 { + + 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; + if hardness > 0.05 { let mut inner = Vec::new(); - for k in 0..=48 { - let a = k as f32 / 48.0 * std::f32::consts::TAU; - if let Some(s) = to_screen(pos + (t * a.cos() + b * a.sin()) * r * h) { - inner.push(s); + 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); } } - p.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(&inner, Stroke::new(1.0, Color32::from_white_alpha(120)), 3.0, 3.0)); } - if let Some(c) = to_screen(pos) { - p.circle_filled(c, 1.5, Color32::WHITE); + + if let Some(center) = to_screen(position) { + painter.circle_filled(center, 1.5, Color32::WHITE); } } @@ -1435,6 +1710,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Painting in UV space let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() + && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !alt && !adjusting && !v_held @@ -1442,7 +1718,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !DecalDrop::blocks_input(ui.ctx()); let mut fill_box = None; if painting && path_tool { - path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + path_input(app, ui, &response, (rect, true), |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting && app.session.tool.tool == Tool::PolygonFill { fill_box = polygon_fill_input( app, @@ -1466,6 +1742,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin camera: app.session.camera, shade: shade(app), visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), + overlay: Vec::new(), }; add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); @@ -1508,7 +1785,7 @@ 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); + rubber_band(ui, rect, &[to_screen(from.x, from.y), hover]); } if app.ui.mode == crate::state::Mode::Baking { @@ -1623,6 +1900,60 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t mod tests { use super::*; + #[test] + fn stored_surfaces_release_after_a_frame_without_paths() { + 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(); + session.viewport = Vec2::splat(400.0); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + let result = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(result["committed"]["effect"].as_u64().unwrap()); + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; + paths.resize(8, paths[0].clone()); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let context = egui::Context::default(); + let mut previous = Vec::>>>>::new(); + + // Every path in the selection stays warm, and leaving it releases every sampled buffer + for _ in 0..4 { + let output = context.run_ui(Default::default(), |ui| { + for index in 0..8 { + let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); + assert!(surface.iter().map(Vec::len).sum::() > 10); + if let Some(cached) = previous.get(index) { + assert!(Arc::ptr_eq(&cached.upgrade().unwrap(), &surface), "unchanged paths must not be resampled"); + } else { + previous.push(Arc::downgrade(&surface)); + } + } + }); + + // This cache lifecycle test has no renderer to consume texture updates + output.drop_without_applying_deltas(); + } + + let EffectKind::Path(paths) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; + for path in paths { + path.viewport = [800.0, 800.0]; + } + let output = context.run_ui(Default::default(), |ui| { + for (index, previous) in previous.iter_mut().enumerate() { + let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); + assert!(previous.upgrade().is_none(), "editing a path releases its obsolete samples"); + *previous = Arc::downgrade(&surface); + } + }); + output.drop_without_applying_deltas(); + + for _ in 0..2 { + context.run_pass(Default::default(), |_| {}).drop_without_applying_deltas(); + } + + assert!(previous.iter().all(|surface| surface.upgrade().is_none()), "unused path surfaces must be freed while the window stays open"); + } + /// A selected mask decal on the ball, with another texture set available for selection tests fn decal_frame_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { let session = diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 7c24ec78..bdf0bb7a 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -161,6 +161,10 @@ const ICON_SCALE: f32 = 0.62; /// Extra width an `icon_dropdown_button` gives its caret, as a fraction of the button height const CARET_STRIP_SCALE: f32 = 0.34; +/// Caret glyph size, and how far its center sits from the right edge, as fractions of the button height +const CARET_SCALE: f32 = 0.34; +const CARET_INSET_SCALE: f32 = 0.25; + /// An `icon_button` with no tooltip, whose `label` still names it for screen readers pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { let style = icon_button_style(&Tokens::get(ui.ctx())); @@ -176,10 +180,6 @@ pub fn icon_dropdown_button_width(size: f32) -> f32 { /// An `icon_button_without_tooltip` with a dropdown caret after the icon, drawn in the icon's color pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { - // Caret glyph size, and how far its center sits from the right edge, as fractions of the height - const CARET_SCALE: f32 = 0.34; - const CARET_INSET_SCALE: f32 = 0.25; - let style = icon_button_style(&Tokens::get(ui.ctx())); IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); @@ -189,6 +189,32 @@ pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool }) } +/// An `icon_dropdown_button` whose icon carries a small `badge` glyph at its lower right (e.g. a gear for a feature's settings) +pub fn icon_badge_dropdown_button(ui: &mut Ui, icon: &str, badge: &str, label: &str, selected: bool, size: f32) -> Response { + // Badge glyph size and inset, as fractions of the height + const BADGE_SCALE: f32 = 0.5; + const BADGE_INSET_SCALE: f32 = 0.24; + // The icon shrinks a little and moves up and left, making room for the badge + const ICON_WITH_BADGE_SCALE: f32 = 0.78; + const ICON_SHIFT_SCALE: f32 = 0.09; + + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { + let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); + let badge_center = rect.left_top() + vec2(size - size * BADGE_INSET_SCALE, size - size * BADGE_INSET_SCALE); + let caret_center = rect.right_center() - vec2(size * CARET_INSET_SCALE, 0.0); + ui.painter().text( + icon_center - vec2(size, size) * ICON_SHIFT_SCALE, + egui::Align2::CENTER_CENTER, + icon, + egui::FontId::proportional(size * ICON_SCALE * ICON_WITH_BADGE_SCALE), + color, + ); + ui.painter().text(badge_center, egui::Align2::CENTER_CENTER, badge, egui::FontId::proportional(size * BADGE_SCALE), color); + ui.painter().text(caret_center, egui::Align2::CENTER_CENTER, egui_phosphor::regular::CARET_DOWN, egui::FontId::proportional(size * CARET_SCALE), color); + }) +} + /// Transparent at rest, a hover well, and the active-tool well when pressed or selected fn icon_button_style(tokens: &Tokens) -> IconButtonStyle { let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 068cd0bf..c8448913 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -367,7 +367,12 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { // Each row is the state after that many steps let steps = done_count - row as i64; if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - jump = steps; + // Point history is consumed before the document rows shown here + jump = if steps >= 0 { + app.session.history_undo_steps(steps as usize) as i64 + } else { + -(app.session.history_redo_steps((-steps) as usize) as i64) + }; } } }); @@ -384,6 +389,7 @@ 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, } @@ -393,7 +399,9 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.start { return; } - let tk = Tokens::get(ctx); + + #[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| { @@ -405,11 +413,12 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { 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(tk.text_dim)); + 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); @@ -433,15 +442,17 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); }); - if let Some(a) = action { + + if let Some(action) = action { app.ui.windows.start = false; - match a { + 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; } @@ -565,6 +576,25 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { } } +#[cfg(not(target_arch = "wasm32"))] +fn settings_resources(ctx: &egui::Context) -> (u32, u64) { + let id = egui::Id::unique("settings_resources"); + let now = ctx.input(|input| input.time); + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + + // Query the operating system once a second while Settings is open, rather than every frame + if let Some((sampled_at, cores, available_ram_bytes)) = ctx.data(|data| data.get_temp::<(f64, u32, u64)>(id)) + && (0.0..1.0).contains(&(now - sampled_at)) + { + return (cores, available_ram_bytes); + } + + let (cores, available_ram_bytes) = texturecraft_engine::formats::available_save_resources(); + let cores = u32::try_from(cores).unwrap_or(u32::MAX); + ctx.data_mut(|data| data.insert_temp(id, (now, cores, available_ram_bytes))); + (cores, available_ram_bytes) +} + fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); let mut open = app.ui.windows.settings; @@ -646,14 +676,40 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + ui.label(caption(tr("Project"))); #[cfg(not(target_arch = "wasm32"))] - { - ui.label(caption(tr("Project"))); - form("settings_project").show(ui, |ui| { + let (available_cores, available_ram_bytes) = settings_resources(ctx); + form("settings_project").show(ui, |ui| { + #[cfg(not(target_arch = "wasm32"))] + { ui.label(tr("Autosave every")); ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))); ui.end_row(); - }); + let label = ui.label(tr("Cores kept for the UI")); + ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label.id); + ui.end_row(); + } + + let label = ui.label(tr("Max project size on open")); + ui.add(egui::DragValue::new(&mut p.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) + .labelled_by(label.id) + .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); + ui.end_row(); + + #[cfg(not(target_arch = "wasm32"))] + { + let label = ui.label(tr("Max RAM while saving")); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label.id); + let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); + ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); + }); + ui.end_row(); + } + }); + #[cfg(not(target_arch = "wasm32"))] + { + ui.label(RichText::new(tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")).small().color(tk.text_dim)); ui.label( RichText::new(trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])) .small() diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 00000000..d7c447db --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.TextureCraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak", "--filesystem=xdg-data/ArtCraft/versions:ro"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 643f0c42..12e4f08b 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -35,7 +35,7 @@ const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) }), ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), - ("Lazy mouse and symmetry", "Lazy mouse distance", false, |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), + ("Lazy mouse", "Lazy mouse distance", false, |brush, defaults| brush.lazy = defaults.lazy), ]; /// A valid brush with every section field changed and a custom alpha that resets must preserve @@ -60,7 +60,7 @@ fn changed_brush() -> BrushSettings { depth: 2.0, particles: Particles { enabled: true, count: 8, lifetime: 12, gravity: 0.5 }, lazy: 50.0, - symmetry: Symmetry { x: true, y: true, z: true, radial: 4, axis: 2 }, + symmetry: Symmetry { x: true, y: true, z: true, radial: 4, axis: 2, ..Symmetry::default() }, alpha: BrushAlpha::Star, ..BrushSettings::default() } @@ -193,7 +193,7 @@ fn narrow_headers_keep_title_clicks_separate_from_reset() { for right_to_left in [false, true] { for width in [120.0, 180.0, 300.0] { - let title = "Lazy mouse and symmetry"; + let title = "Lazy mouse"; let mut harness = Harness::builder().with_size(egui::vec2(width, 180.0)).with_context_setup(texturecraft_ui_egui::theme::install).build_ui_state( |ui, resets| { let alignment = if right_to_left { egui::Align::RIGHT } else { egui::Align::LEFT }; diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 81c34868..eb80adf6 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -164,6 +164,31 @@ fn escape_cancels_the_pick_without_editing_colors() { assert_eq!(harness.state().session.history_labels(), history); } +#[test] +fn escape_cancels_id_picking_with_a_hidden_rail_popup() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.log"); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Close"); + harness.key_press(egui::Key::Tab); + harness.run_steps(3); + assert!(harness.state().ui.hide_ui); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Close").is_none()); + assert!(harness.state().picking_id_color.is_some()); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.state().picking_id_color.is_none(), "one Escape cancels ID picking despite the hidden popup"); + assert_eq!(harness.state().session.view, ViewMode::Material); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); + assert_eq!(harness.state().session.history_labels(), history); +} + #[test] fn picking_from_the_popup_closes_it_before_the_viewport_click() { use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index b3f134f0..7103161b 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -3,9 +3,162 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +/// Show document history so row clicks exercise the same command dispatch as the application +fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.focus(Panel::History); + harness.run_steps(4); + harness +} + +/// Three document rows provide an intermediate target that detects both short and excessive jumps +fn renamed_session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + session +} + +/// Canceling a preview can be its own undo or part of undoing the first placed point +#[test] +fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { + for placed in [false, true] { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + if placed { + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + for point in [Vec3::new(0.2, 0.5, 0.0), Vec3::new(0.5, 0.3, 0.0), Vec3::new(0.8, 0.5, 0.0)] { + session.append_path_point(point, true); + session.path_live().unwrap(); + } + } else { + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + } + session.path_checkpoint(); + let mut harness = history_harness(session); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), 2); + assert!(harness.state().session.tool.path.points.is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); + } +} + +/// A row jump traverses point history, while the Undo and Redo buttons still take one point step +#[test] +fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + session.move_path_point(0, original[0], true); + session.path_live().unwrap(); + session.path_checkpoint(); + let done = session.history_labels().len(); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, moved); + assert_eq!(harness.state().session.history_labels().len(), done); + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_by_label("Edit path 1").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), done - 1); + assert!(harness.state().session.tool.path.points.is_empty()); +} + +/// Incomplete filled curves keep point redo separate from the document redo rows +#[test] +fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let report = + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.3], [0.8, 0.5]], "closed": true, "fill": true, "commit": true})).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + let done = session.history_labels().len(); + execute(&mut session, "edit.undo", &json!({"steps": 3})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + + // Partial filled shapes do not repaint; their undo/redo leaves document redo available + for points in [json!([[0.2, 0.5], [0.8, 0.5]]), json!([[0.2, 0.5]]), json!([[0.2, 0.5], [0.8, 0.5]])] { + session.path_checkpoint(); + execute(&mut session, "tool.path", &json!({"uvPoints": points})).unwrap(); + } + for _ in 0..3 { + session.undo().unwrap(); + } + assert_eq!(session.redo_labels().len(), 3); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + + harness.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step C"); + assert_eq!(harness.state().session.history_labels().len(), done); + assert!(harness.state().session.redo_labels().is_empty()); + assert!(harness.state().session.tool.path.points.is_empty()); +} + +/// Returning to the current document row cancels a draft without undoing a document step +#[test] +fn clicking_the_current_history_row_cancels_a_draft() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + let mut harness = history_harness(session); + + harness.get_by_label("Project opened").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.path.points.is_empty()); + assert!(harness.state().session.history_labels().is_empty()); + assert!(harness.state().session.redo_labels().is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); +} + #[test] fn clicking_a_history_step_returns_to_it() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 12329400..6f1c5092 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -21,10 +21,12 @@ mod layers_panel; mod levels_editor; mod mask_value_swap; mod new_project_baked_maps; +mod path_in_view; mod path_list; mod pen_pressure; mod polygon_fill; mod properties_popup; +mod rail; mod shelf_drop; mod shelf_hover_preview; mod shift_lines_2d; @@ -33,3 +35,5 @@ mod skew_paint; mod split_divider; mod start_window; mod toolbar; + +mod symmetry; diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs new file mode 100644 index 00000000..819a5468 --- /dev/null +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -0,0 +1,204 @@ +//! The Path tool in the 2D view: placing previews the path, and points are edited where they are drawn + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +type AppHarness<'a> = Harness<'a, TextureCraftApp>; + +// Three points left to right across the middle of the 2D view's texture +const A: Pos2 = pos2(600.0, 500.0); +const B: Pos2 = pos2(700.0, 500.0); +const C: Pos2 = pos2(800.0, 500.0); + +/// A Path tool session whose texture fills the test pointer coordinates in the 2D view +fn harness() -> AppHarness<'static> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + // Tall enough that the 2D view's texture square takes A, B and C + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = ViewLayout::Only2D; + h.run_steps(4); + h +} + +/// Advance one input frame, optionally changing the primary button's state +fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { + let events = &mut h.input_mut().events; + events.push(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.step(); +} + +/// Send a complete pointer click and allow the resulting preview to update +fn click(h: &mut AppHarness<'_>, at: Pos2) { + pointer(h, at, Some(true)); + pointer(h, at, Some(false)); + h.run_steps(2); +} + +/// Move through several frames so the test exercises drag grouping as well as its final position +fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + for k in 1..=6 { + pointer(h, from + (to - from) * (k as f32 / 6.0), None); + } + pointer(h, to, Some(false)); + h.run_steps(2); +} + +/// Dispatch an unmodified tool key and settle the resulting UI state +fn key(h: &mut AppHarness<'_>, key: Key) { + h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// The path sublayers of the selected layer: (id, stored paths) +fn path_sublayers(h: &AppHarness<'_>) -> Vec<(LayerId, usize)> { + let s = &h.state().session; + let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); + layer.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id, p.len()))).collect() +} + +/// Channel images painted in path sublayer `eid` +fn painted_channels(h: &AppHarness<'_>, eid: LayerId) -> usize { + h.state().session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == eid).count() +} + +#[test] +fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() { + let mut h = harness(); + let steps = h.state().session.history_labels().len(); + for at in [A, B, C] { + click(&mut h, at); + } + assert_eq!(h.state().session.tool.path.points.len(), 3); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("the preview is a path in a path sublayer: {:?}", path_sublayers(&h)) }; + assert!(painted_channels(&h, eid) > 0, "the preview painted"); + assert_eq!(h.state().session.history_labels().len(), steps, "no undo step while placing"); + key(&mut h, Key::Enter); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert_eq!(h.state().session.undo_label(), Some("Path")); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), vec![(eid, 1)]); +} + +/// Applying with the pointer commits the preview without leaving the current texture set +#[test] +fn apply_button_commits_the_path_in_the_current_texture_set() { + let mut h = harness(); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + let steps = h.state().session.history_labels().len(); + let texture_set = h.state().session.ts(); + for at in [A, B, C] { + click(&mut h, at); + } + let paths = path_sublayers(&h); + let preview = h.state().session.doc.pixels.layers.clone(); + + // Path controls share the horizontally scrolling brush toolbar + h.get_all_by_label("Apply").next().unwrap().scroll_to_me(); + h.run_steps(30); + assert!(!h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + h.get_all_by_label("Apply").next().unwrap().click(); + h.run_steps(2); + + assert_eq!(h.state().session.ts(), texture_set); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), paths); + assert_eq!(h.state().session.doc.pixels.layers, preview); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); +} + +#[test] +fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + key(&mut h, Key::Enter); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("one path") }; + let stored = |h: &AppHarness<'_>| h.state().session.paths(eid).unwrap()[0].points.clone(); + let before = stored(&h); + let steps = h.state().session.history_labels().len(); + + // A click on the path's curve opens it for editing without repainting it + click(&mut h, A.lerp(B, 0.5)); + assert_eq!(h.state().session.tool.path.editing, Some((eid, 0))); + assert_eq!(h.state().session.history_labels().len(), steps, "opening a path repaints nothing"); + + drag(&mut h, B, B + egui::vec2(0.0, 60.0)); + let after = stored(&h); + assert_eq!(after.len(), 3); + assert_eq!((after[0], after[2]), (before[0], before[2])); + assert!(after[1][1] > before[1][1], "the dragged point moved down: {:?} -> {:?}", before[1], after[1]); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step"); +} + +#[test] +fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { + 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(); + let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [260, 210]], "viewport": [400, 400], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + 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 view_2d_center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + + click(&mut harness, view_2d_center); + + assert_eq!(harness.state().session.tool.path, path); + 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); +} + +#[test] +fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + let path = |h: &AppHarness<'_>| h.state().session.tool.path.clone(); + let before = path(&h).points; + click(&mut h, B.lerp(C, 0.5)); + let after = path(&h); + assert_eq!(after.points.len(), 4, "inserted, not appended"); + assert_eq!(after.selected, Some(2)); + assert_eq!((after.points[1], after.points[3]), (before[1], before[2])); + assert!(after.points[2].x > before[1].x && after.points[2].x < before[2].x); + + // B, not A: clicking the first point closes the path + click(&mut h, B); + assert_eq!(path(&h).selected, Some(1)); + key(&mut h, Key::Backspace); + assert_eq!(path(&h).points, vec![after.points[0], after.points[2], after.points[3]]); + + // Undo brings the point back and keeps the path; again, the inserted point goes + let undo = |h: &mut AppHarness<'_>| { + h.input_mut().events.push(Event::Key { key: Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); + h.run_steps(2); + }; + undo(&mut h); + assert_eq!(path(&h).points, after.points); + undo(&mut h); + assert_eq!(path(&h).points, before); + assert!(!path_sublayers(&h).is_empty(), "the path is still there"); +} diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs new file mode 100644 index 00000000..db4046f6 --- /dev/null +++ b/crates/ui-egui/tests/it/rail.rs @@ -0,0 +1,444 @@ +//! The rail opens its panels in a popup beside their icons, one at a time; dragging the popup's title docks or floats the panel + +use egui::{Event, Modifiers, PointerButton, Pos2, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::state::ViewLayout; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// The rail is the last 38 points of the window; the popup's own buttons sit left of it +const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; + +// Small texture and bake sizes keep the sample session fast; the rail 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; + +/// Where a drag out of the popup ends: in the viewport, clear of every panel +const INTO_THE_VIEWPORT: egui::Vec2 = egui::vec2(-500.0, 100.0); + +/// Moves a drag takes, so the dock sees it pass its threshold and move +const DRAG_STEPS: usize = 6; + +/// Frames between a drag's events: the press must land before the moves, and each move be seen +const FRAMES_PER_DRAG_EVENT: usize = 2; + +/// Frames for a click to reach the rail, the popup and the dock +const SETTLE_FRAMES: usize = 3; + +// A setting only Shader Settings shows, and one only Display Settings shows +const SHADER_SETTING: &str = "Index of refraction"; +const DISPLAY_SETTING: &str = "Environment opacity"; + +fn app() -> Harness<'static, TextureCraftApp> { + app_of_size(WINDOW_SIZE) +} + +fn app_of_size(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(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 +} + +/// The rail icon of the panel named `name`, if the rail shows one +fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Option> { + // A rail icon's label is its tooltip, which adds the shortcut when the panel has one + let is_panel = |label: &str| label == name || label.starts_with(&format!("{name} (")); + harness + .get_all_by_role(Role::Button) + .find(|button| button.rect().min.x >= RAIL_LEFT_EDGE && button.accesskit_node().label().is_some_and(|label| is_panel(&label))) +} + +fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + rail_icon(harness, name).expect("the panel's icon on the rail").click(); + harness.run_steps(SETTLE_FRAMES); +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { + harness.hover_at(position); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); +} + +/// Drag with the primary button from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + + for step in 1..=DRAG_STEPS { + harness.hover_at(from + (to - from) * (step as f32 / DRAG_STEPS as f32)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + } + + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); +} + +/// The popup's Close button, left of the rail (the window's own Close sits above the rail) +fn popup_close_button(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness + .query_all(by().role(Role::Button)) + .find(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some("Close")) + .map(|button| button.rect()) +} + +/// The title of the popup open on the panel named `name`: that name, level with the popup's Close button +fn open_popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Option { + let close = popup_close_button(harness)?; + harness + .get_all_by_label(name) + .map(|node| node.rect()) + .find(|title| title.right() < close.left() && (close.top()..=close.bottom()).contains(&title.center().y)) +} + +fn popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { + open_popup_title(harness, name).expect("the popup's title") +} + +fn popup_shows(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + open_popup_title(harness, name).is_some() +} + +fn popup_closed(harness: &Harness<'_, TextureCraftApp>) -> bool { + popup_close_button(harness).is_none() +} + +#[test] +fn the_rail_shows_one_panel_at_a_time() { + let mut harness = app(); + + click_rail(&mut harness, "Shader Settings"); + + assert!(popup_shows(&harness, "Shader Settings")); + assert!(harness.query_by_label(SHADER_SETTING).is_some()); + + click_rail(&mut harness, "Display Settings"); + + assert!(popup_shows(&harness, "Display Settings")); + assert!(harness.query_by_label(SHADER_SETTING).is_none(), "opening Display Settings closed Shader Settings"); + assert!(harness.query_by_label(DISPLAY_SETTING).is_some()); + assert!(!harness.state().ui.dock.is_open(Panel::Shader), "the rail's panels are not dock windows"); + + click_rail(&mut harness, "Display Settings"); + + assert!(popup_closed(&harness), "its own icon closes it"); +} + +#[test] +fn the_popup_lines_up_with_its_icon() { + let mut harness = app(); + + click_rail(&mut harness, "History"); + let icon = rail_icon(&harness, "History").expect("the History icon").rect(); + let title = popup_title(&harness, "History"); + + assert!(title.top() >= icon.top() && title.top() <= icon.bottom(), "the title {title:?} is not level with the icon {icon:?}"); +} + +#[test] +fn the_close_button_a_press_outside_and_escape_close_it() { + let mut harness = app(); + + click_rail(&mut harness, "Display Settings"); + harness.get_by_role_and_label(Role::Button, "Close").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness), "Close"); + + click_rail(&mut harness, "Log"); + harness.get_by_label("Assets").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness), "a press outside"); + + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness), "Escape"); +} + +#[test] +fn dragging_the_title_out_floats_the_panel_and_frees_the_rail() { + let mut harness = app(); + + click_rail(&mut harness, "History"); + let title = popup_title(&harness, "History").center(); + drag(&mut harness, title, title + INTO_THE_VIEWPORT); + + assert!(popup_closed(&harness)); + assert!(harness.state().ui.dock.is_visible(Panel::History), "History floats on its own"); + assert!(rail_icon(&harness, "History").is_none(), "a panel in the dock has no rail icon"); + + click_rail(&mut harness, "Shader Settings"); + + assert!(popup_shows(&harness, "Shader Settings")); + assert!(harness.state().ui.dock.is_visible(Panel::History), "History stays open beside the rail's panel"); +} + +#[test] +fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { + let mut harness = app(); + + click_rail(&mut harness, "Log"); + let title = popup_title(&harness, "Log").center(); + let properties_tab = harness.get_by_label("Properties - Paint").rect().center(); + drag(&mut harness, title, properties_tab); + + let layout = &harness.state().ui.dock.workspace().layout; + assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); +} + +#[test] +fn a_panel_closed_in_the_dock_returns_to_the_rail() { + let mut harness = app(); + assert!(rail_icon(&harness, "Texture Set Settings").is_none(), "Texture Set Settings starts in the dock, beside Layers"); + + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Texture Set Settings"); + + assert!(popup_shows(&harness, "Texture Set Settings")); +} + +#[test] +fn window_views_open_the_rail_panels_popup() { + let mut harness = app(); + + let ctx = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.view.shader"); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Shader Settings")); + assert!(!harness.state().ui.dock.is_open(Panel::Shader)); + + // Project configuration opens Display Settings, in its popup too + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig"); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Display Settings")); +} + +#[test] +fn a_popup_that_would_run_past_the_bottom_moves_up() { + // Too short for Display Settings below its icon + const SHORT_WINDOW: egui::Vec2 = egui::vec2(1600.0, 600.0); + let mut harness = app_of_size(SHORT_WINDOW); + + click_rail(&mut harness, "Display Settings"); + let icon = rail_icon(&harness, "Display Settings").expect("the Display Settings icon").rect(); + let title = popup_title(&harness, "Display Settings"); + + assert!(title.top() < icon.top(), "the popup at {title:?} did not move up from the icon at {icon:?}"); +} + +#[test] +fn display_settings_remain_reachable_in_a_short_window() { + let mut harness = app_of_size(egui::vec2(1600.0, 600.0)); + click_rail(&mut harness, "Display Settings"); + + let last_setting = "Temporal anti-aliasing (refines the 3D view while it is still)"; + harness.get_by_label(last_setting).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + let setting = harness.get_by_label(last_setting).rect(); + assert!(harness.ctx.content_rect().contains_rect(setting), "the last setting must be reachable: {setting:?}"); +} + +#[test] +fn history_actions_remain_reachable_in_a_short_window() { + let mut harness = app_of_size(egui::vec2(1600.0, 400.0)); + click_rail(&mut harness, "History"); + + for label in ["Undo", "Redo"] { + let button = harness + .get_all_by_role(Role::Button) + .find(|button| button.accesskit_node().label().is_some_and(|text| text.ends_with(label))) + .expect("the History action") + .rect(); + assert!(harness.ctx.content_rect().contains_rect(button), "{label} must be reachable: {button:?}"); + } +} + +#[test] +fn opening_the_window_menu_closes_the_rail_popup() { + let mut harness = app(); + click_rail(&mut harness, "Shader Settings"); + + harness.get_by_role_and_label(Role::Button, "Window").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness)); +} + +#[test] +fn escape_closes_a_dropdown_before_its_rail_popup() { + let mut harness = app(); + click_rail(&mut harness, "Display Settings"); + let environment_row = harness.get_by_label("Environment map").rect(); + harness + .get_all_by_role(Role::ComboBox) + .find(|combo| (combo.rect().center().y - environment_row.center().y).abs() < 1.0) + .expect("the environment dropdown") + .click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(egui::Popup::is_any_open(&harness.ctx)); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(!egui::Popup::is_any_open(&harness.ctx)); + assert!(popup_shows(&harness, "Display Settings")); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_closed(&harness)); +} + +#[test] +fn dismissing_a_rail_popup_does_not_paint_the_viewport() { + for layout in [ViewLayout::Only3D, ViewLayout::Only2D] { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = layout; + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + let center = if layout == ViewLayout::Only2D { egui::pos2(700.0, 420.0) } else { harness.state().viewport_rect.center() }; + let history = harness.state().session.history_labels().len(); + + click_at(&mut harness, center); + + assert!(popup_closed(&harness)); + assert_eq!(harness.state().session.history_labels().len(), history, "dismissing the popup must not paint in {layout:?}"); + + click_at(&mut harness, center); + + assert_eq!(harness.state().session.history_labels().len(), history + 1, "the next click paints in {layout:?}"); + + click_rail(&mut harness, "Log"); + drag(&mut harness, center, center + egui::vec2(40.0, 0.0)); + + assert!(popup_closed(&harness)); + assert!(!harness.state().session.stroke_active()); + assert_eq!(harness.state().session.history_labels().len(), history + 1, "a dismissing drag must not paint in {layout:?}"); + } +} + +#[test] +fn opening_a_rail_popup_during_a_stroke_still_finishes_the_stroke() { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(SETTLE_FRAMES); + let center = harness.state().viewport_rect.center(); + let history = harness.state().session.history_labels().len(); + harness.drag_at(center); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.hover_at(center + egui::vec2(20.0, 0.0)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(harness.state().session.stroke_active()); + + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.log"); + harness.run_steps(SETTLE_FRAMES); + harness.drop_at(center + egui::vec2(30.0, 0.0)); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Log")); + assert!(!harness.state().session.stroke_active()); + assert_eq!(harness.state().session.history_labels().len(), history + 1); +} + +#[test] +fn escape_cancels_a_stroke_with_a_hidden_rail_popup() { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); + assert!(popup_closed(&harness)); + let center = harness.state().viewport_rect.center(); + let history = harness.state().session.history_labels(); + harness.drag_at(center); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.hover_at(center + egui::vec2(20.0, 0.0)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(harness.state().session.stroke_active()); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().session.stroke_active(), "one Escape cancels the stroke despite the hidden popup"); + harness.drop_at(center + egui::vec2(30.0, 0.0)); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.history_labels(), history, "the canceled stroke must not be committed on release"); +} + +#[test] +fn escape_cancels_a_path_with_a_hidden_rail_popup() { + for stored_path in [false, true] { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + let path = texturecraft_engine::execute( + &mut harness.state_mut().session, + "tool.path", + &serde_json::json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": stored_path}), + ) + .unwrap(); + if stored_path { + texturecraft_engine::execute( + &mut harness.state_mut().session, + "path.edit", + &serde_json::json!({"effect": path["committed"]["effect"], "index": 0}), + ) + .unwrap(); + } + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); + assert!(popup_closed(&harness)); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + + // Drafts and committed paths both have a live preview target while edited + let (effect, index) = harness.state().session.tool.path.editing.unwrap(); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.state().session.tool.path.points.is_empty(), "one Escape clears the path despite the hidden popup"); + assert!(harness.state().session.tool.path.editing.is_none()); + assert_eq!(harness.state().session.history_labels(), history); + assert_eq!( + harness.state().session.paths(effect).and_then(|paths| paths.get(index)).is_some(), + stored_path, + "Escape removes a draft but keeps a committed path" + ); + + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Log"), "showing the UI restores its remembered popup"); + } +} diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs new file mode 100644 index 00000000..2d6181be --- /dev/null +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -0,0 +1,319 @@ +//! Symmetry: the toolbar toggle, the settings popup and the 3D view's manipulator + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{Queryable, by}; +use serde_json::{Value, json}; +use texturecraft_engine::Tool; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_ui_egui::TextureCraftApp; + +/// The settings popup's width and its color square's (points) +const POPUP_WIDTH: f32 = 340.0; +const COLOR_SWATCH_WIDTH: f32 = 48.0; + +/// How far along Y (world units) the test measures the arrow's direction on screen +const AXIS_PROBE: f32 = 0.05; + +/// Points from the manipulator's center to grab the arrow (inside its length at the default size) and how far to drag it +const ON_THE_SHAFT: f32 = 40.0; +const DRAG_DISTANCE: f32 = 60.0; + +/// A point inside the 3D view near its lower left corner, clear of the mesh and the popup (points from the corner) +const VIEW_CORNER_INSET: f32 = 40.0; + +fn app_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(1024, 256).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = Tool::Paint; + harness.run_steps(4); + harness +} + +/// Hold a primary-button drag from `from` to `to` without releasing it +fn hold_drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + 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); + } +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + release(harness, at); +} + +fn release(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// The brush settings as agents read them +fn brush(harness: &mut Harness<'_, TextureCraftApp>) -> Value { + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({})).unwrap() +} + +/// 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(egui::accesskit::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(egui::Key::End); + harness.run_steps(1); + for _ in 0..length { + harness.key_press(egui::Key::Backspace); + harness.run_steps(1); + } + number_field(harness, label).type_text(value); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); +} + +/// Where world `point` is in the 3D view +fn on_screen(harness: &Harness<'_, TextureCraftApp>, point: Vec3) -> Pos2 { + let rect = harness.state().viewport_rect; + let ndc = harness.state().session.camera.project(point, rect.width() / rect.height()).unwrap(); + egui::pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height()) +} + +#[test] +fn the_toolbar_popup_and_manipulator_change_the_brush_symmetry() { + let mut harness = app_harness(); + let revision = harness.state().session.revision; + let history = harness.state().session.history_labels(); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert!(harness.state().session.revision > revision, "the toggle runs the brush command"); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false]), "the toggle mirrors on X"); + + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "X").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Y").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["symmetry"], json!([false, true, false]), "mirror axes can be toggled independently"); + + harness.get_by_label("Symmetry settings").click(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + + // Drag the arrow along Y, starting on its shaft + let (lo, hi) = harness.state().session.mesh.bounds(); + let origin = (lo + hi) * 0.5; + let center = on_screen(&harness, origin); + let along = (on_screen(&harness, origin + Vec3::Y * AXIS_PROBE) - center).normalized(); + let from = center + along * ON_THE_SHAFT; + let to = from + along * DRAG_DISTANCE; + let revision = harness.state().session.revision; + + hold_drag(&mut harness, from, to); + release(&mut harness, to); + + assert!(harness.state().session.revision > revision, "the manipulator runs the brush command"); + assert_eq!(harness.state().session.history_labels(), history, "symmetry settings do not add undo steps"); + let offset = brush(&mut harness)["symmetryOffset"].clone(); + assert!(offset[1].as_f64().unwrap() > 0.05, "the plane moved up: {offset}"); + assert_eq!((offset[0].as_f64(), offset[2].as_f64()), (Some(0.0), Some(0.0)), "only along Y: {offset}"); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + let settings = brush(&mut harness); + assert_eq!(settings["symmetryOn"], json!(false), "the toggle turns it off"); + assert_eq!(settings["symmetry"], json!([false, true, false]), "and keeps the settings"); +} + +#[test] +fn the_color_picker_opens_inside_the_combined_symmetry_popup() { + let mut harness = app_harness(); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["radialSymmetry"], json!({"copies": 6, "axis": "y"})); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false])); + assert!(harness.query_by_label("Angle span").is_some(), "the popup stays open after enabling radial symmetry"); + + // The color square sits at the right end of its row + let row = harness.get_by_label("Symmetry color display").rect(); + let left = harness.get_by_label("Radial symmetry").rect().left(); + click_at(&mut harness, egui::pos2(left + POPUP_WIDTH - COLOR_SWATCH_WIDTH / 2.0, row.center().y)); + harness.run_steps(2); + assert!(harness.query_by_label("Copy RGB values").is_some(), "the color picker opened"); + assert!(harness.query_by_label("Show cursor").is_some(), "the popup stays open with the color picker"); + + // A click on the view closes it + let view_corner = harness.state().viewport_rect.left_bottom() + egui::vec2(VIEW_CORNER_INSET, -VIEW_CORNER_INSET); + click_at(&mut harness, view_corner); + harness.run_steps(2); + assert!(harness.query_by_label("Show cursor").is_none(), "a click elsewhere closes the popup"); +} + +#[test] +fn radial_axis_edits_preserve_combined_symmetry() { + let mut harness = app_harness(); + harness + .state_mut() + .run("tool.brush", json!({"symmetryX": true, "symmetryZ": true, "symmetryRadial": 5, "symmetryAxis": "y", "symmetryAngleSpan": 215})) + .unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let revision = harness.state().session.revision; + let history = harness.state().session.history_labels(); + + harness.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Z").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true]), "editing radial symmetry must preserve every mirror axis"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 5, "axis": "z"})); + assert_eq!(settings["symmetryAngleSpan"], json!(215.0)); + assert!(harness.state().session.revision > revision, "the edit runs the brush command"); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn the_popup_creates_and_edits_mirror_and_radial_copies_independently() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryOn": false})).unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let history = harness.state().session.history_labels(); + + for axis in ["X", "Z"] { + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, axis).click(); + harness.run_steps(2); + } + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true])); + assert_eq!(settings["radialSymmetry"], json!({"copies": 6, "axis": "y"})); + assert_eq!(settings["symmetryOn"], json!(false), "editing settings preserves the master toggle"); + assert!(harness.query_by_label("Show plane").is_some()); + assert!(harness.query_by_label("Show axis").is_some()); + + set_number(&mut harness, "Count", "9"); + set_number(&mut harness, "Angle span", "180"); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true]), "radial edits keep both mirror axes"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 9, "axis": "y"})); + assert_eq!(settings["symmetryAngleSpan"], json!(180.0)); + + for axis in ["X", "Y", "Z"] { + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, axis).click(); + harness.run_steps(2); + } + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([false, true, false])); + assert_eq!(settings["radialSymmetry"], json!({"copies": 9, "axis": "y"}), "mirror edits keep the radial settings"); + assert_eq!(settings["symmetryAngleSpan"], json!(180.0)); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + let combined = harness.state().session.tool.brush.symmetry; + assert!(combined.enabled); + assert_eq!(combined.transforms().len(), 18, "the engine receives both symmetry settings"); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert_eq!(harness.state().session.tool.brush.symmetry, texturecraft_engine::paint::Symmetry { enabled: false, ..combined }); + + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([false, true, false]), "disabling radial symmetry keeps the mirror"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 0, "axis": "y"})); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn clicking_a_symmetry_handle_does_not_paint() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryY": true})).unwrap(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + let (lo, hi) = harness.state().session.mesh.bounds(); + let center = on_screen(&harness, (lo + hi) * 0.5); + let history = harness.state().session.history_labels(); + + click_at(&mut harness, center); + + assert_eq!(harness.state().session.history_labels(), history, "clicking a handle must not add a paint dab"); + assert!(!harness.state().session.stroke_active()); +} + +#[test] +fn a_paint_stroke_can_cross_and_end_on_a_symmetry_handle() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryY": true})).unwrap(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + let (lo, hi) = harness.state().session.mesh.bounds(); + let center = on_screen(&harness, (lo + hi) * 0.5); + let from = center + egui::vec2(80.0, 0.0); + let history = harness.state().session.history_labels().len(); + + hold_drag(&mut harness, from, center); + release(&mut harness, center); + + assert!(!harness.state().session.stroke_active(), "releasing over the handle must finish painting"); + assert_eq!(harness.state().session.history_labels().len(), history + 1); + assert_eq!(harness.state().session.tool.brush.symmetry.offset, [0.0; 3]); +} + +#[test] +fn ctrl_drag_on_a_symmetry_handle_only_adjusts_the_brush() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryY": true})).unwrap(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + let (lo, hi) = harness.state().session.mesh.bounds(); + let from = on_screen(&harness, (lo + hi) * 0.5); + let to = from + egui::vec2(-60.0, -40.0); + let before = harness.state().session.tool.brush.clone(); + let history = harness.state().session.history_labels(); + + harness.event(Event::ModifiersChanged(Modifiers::COMMAND)); + harness.hover_at(from); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::COMMAND }); + 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::COMMAND }); + harness.event(Event::ModifiersChanged(Modifiers::NONE)); + harness.run_steps(2); + + let after = &harness.state().session.tool.brush; + assert!(after.flow < before.flow); + assert_ne!(after.angle, before.angle); + assert_eq!(after.symmetry, before.symmetry, "adjusting the brush must not also move symmetry"); + assert_eq!(harness.state().session.history_labels(), history); +} diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs new file mode 100644 index 00000000..7363a5dd --- /dev/null +++ b/crates/ui-egui/tests/project_limits.rs @@ -0,0 +1,55 @@ +use eframe::App as _; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::{Session, formats, geom}; +use texturecraft_ui_egui::{TextureCraftApp, UiState, control, state::Prefs}; + +#[path = "../src/ui_state_store/memory_storage.rs"] +mod memory_storage; +use memory_storage::MemoryStorage; + +#[test] +fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() { + let legacy: Prefs = serde_json::from_str("{}").unwrap(); + assert_eq!(legacy.project_open_limit_gib, 8); + let mut state = UiState::default(); + state.prefs.language = "en".into(); + state.prefs.project_open_limit_gib = 16; + state.prefs.reserved_cores = u32::MAX; + state.windows.settings = true; + let mut storage = MemoryStorage::default(); + storage.values.insert("ui.json".into(), serde_json::to_string(&state).unwrap()); + let session = Session::new_project("Limits", geom::primitives::plane(2.0, 1), "builtin:plane", None, 128).unwrap(); + let available_cores = u32::try_from(std::thread::available_parallelism().unwrap().get()).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).with_accessibility_check(false).build_eframe(|context| { + context.egui_ctx.data_mut(|data| data.insert_temp(egui::Id::unique("settings_resources"), (0.0_f64, available_cores, 16_u64 << 30))); + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(&storage); + TextureCraftApp::new(&creation, session) + }); + + assert_eq!(formats::project_open_limit_gib(), 16, "saved preferences apply during startup"); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "preferences from a larger machine are clamped"); + harness.get_by_role_and_label(egui::Role::SpinButton, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "editing cannot exceed this machine's CPU count"); + assert!(harness.query_by_label("≈ 8.00 GiB").is_some(), "50% of 16 GiB is shown beside the percentage"); + harness.get_by_role_and_label(egui::Role::SpinButton, "Max RAM while saving").set_value_accesskit(25.0); + harness.run_steps(3); + assert!(harness.query_by_label("≈ 4.00 GiB").is_some(), "the byte estimate follows the edited percentage"); + + harness.get_by_role_and_label(egui::Role::SpinButton, "Max project size on open").set_value_accesskit(24.0); + harness.run_steps(3); + assert_eq!(formats::project_open_limit_gib(), 24, "the input field applies the edited value"); + + let context = egui::Context::default(); + let reply = control::handle(harness.state_mut(), &context, "ui.set", &serde_json::json!({"prefs": {"project_open_limit_gib": 32}})); + + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(formats::project_open_limit_gib(), 32, "no frame is needed before the next command"); + harness.state_mut().save(&mut storage); + let restored: UiState = serde_json::from_str(&storage.values["ui.json"]).unwrap(); + assert_eq!(restored.prefs.project_open_limit_gib, 32); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 21c4a045..4ca66c96 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -28,6 +28,73 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { eprintln!("wrote {}", path.display()); } +/// Capture the moving preview and settled render after submitting real GPU callbacks. +#[test] +#[ignore] +fn rendering_mode_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1280.0, 800.0)) + .with_pixels_per_point(1.0) + .wgpu() + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Rendering; + harness.state_mut().ui.render.max_samples = 16; + eprintln!("Rendering-mode adapter: {}", harness.state().gpu.as_ref().unwrap().adapter); + + // Submit each frame so the snapshots exercise the tracer callback, including size switches + for _ in 0..6 { + harness.state_mut().session.camera.yaw += 0.08; + harness.run_steps(1); + harness.render().unwrap(); + } + let moving_path = output_dir.join("rendering-moving.png"); + harness.render().unwrap().save(&moving_path).unwrap(); + eprintln!("wrote {}", moving_path.display()); + + for _ in 0..45 { + harness.run_steps(1); + harness.render().unwrap(); + } + save(&mut harness, &output_dir, "rendering-settled"); +} + +#[test] +#[ignore] +fn symmetry_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(1024, 256).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryY": true, "symmetryOffset": [0, 0.1, 0]})).unwrap(); + harness.state_mut().ui.symmetry.show_plane = true; + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(4); + harness.get_by_label("Symmetry settings").click(); + + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-mirror-{name}")); + } + + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryY": false, "symmetryRadial": 6, "symmetryAxis": "y", "symmetryAngleSpan": 240})).unwrap(); + harness.state_mut().ui.symmetry.show_axis = true; + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + save(&mut harness, &output_dir, "symmetry-radial"); + + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryX": true, "symmetryY": true})).unwrap(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-combined-{name}")); + } +} + #[test] #[ignore] fn window_snapshots() { @@ -372,3 +439,61 @@ fn nested_layers_snapshot() { } save(&mut harness, &output_dir, "panel-layers-narrow-nested"); } + +#[test] +#[ignore] +fn path_tool_snapshots() { + 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(); + texturecraft_engine::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + texturecraft_engine::execute(&mut session, "tool.path", &serde_json::json!({"uvPoints": [[0.25, 0.5], [0.5, 0.3], [0.75, 0.5]]})).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Only2D; + harness.state_mut().session.select_path_point(1); + harness.hover_at(egui::pos2(800.0, 600.0)); + save(&mut harness, &output_dir, "path-preview-2d"); + + harness.state_mut().session.commit_path(texturecraft_engine::geom::glam::Vec2::splat(400.0)).unwrap(); + save(&mut harness, &output_dir, "path-stored-2d"); +} + +#[test] +#[ignore] +fn rail_window_snapshots() { + let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { + eprintln!("set TC_UI_SNAPSHOTS= to write the pictures"); + return; + }; + + std::fs::create_dir_all(&output_dir).unwrap(); + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + let context = harness.ctx.clone(); + + for (command, name) in [ + ("ui.view.textureSetSettings", "rail-texture-set-settings"), + ("ui.view.display", "rail-display"), + ("ui.view.shader", "rail-shader"), + ("ui.view.history", "rail-history"), + ("ui.view.log", "rail-log"), + ] { + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, command); + save(&mut harness, &output_dir, name); + } + + harness.set_size(egui::vec2(1600.0, 600.0)); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.display"); + harness.run_steps(6); + harness.get_by_label("Temporal anti-aliasing (refines the 3D view while it is still)").scroll_to_me(); + save(&mut harness, &output_dir, "rail-display-short"); + + harness.set_size(egui::vec2(1600.0, 400.0)); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.history"); + save(&mut harness, &output_dir, "rail-history-short"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c02a7617..f255a509 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -182,6 +182,15 @@ call("auth", {"token": token}) print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1, 0.1]}})) ``` +The UI's `prefs.project_open_limit_gib` sets the maximum decompressed project data accepted on open +(default 8 GiB, minimum 1 GiB). Set it with `ui.set {"prefs":{"project_open_limit_gib":16}}`; +it takes effect before the next control request, without waiting for a frame, and persists with +the UI preferences. Individual entry limits still apply. This controls opening only, independently +of `prefs.reserved_cores` and `prefs.save_ram_percent` for saving. +Settings bounds the reserved-core input to the available logical CPU count and shows the estimated +save budget in GiB beside the RAM percentage. The readout refreshes once a second from currently +available RAM; a save calculates its budget when it starts. + ## MCP server `texturecraft-cli mcp` speaks MCP on stdin/stdout (stdout carries only protocol messages). diff --git a/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml index 259e2396..56d29581 100644 --- a/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml @@ -17,6 +17,12 @@ runtime-version: '26.08' sdk: org.freedesktop.Sdk command: texturecraft finish-args: + # Honor the launcher's pinned and nightly version choices before offering updates. + - --filesystem=xdg-data/ArtCraft/versions:ro + # Release checks and downloads use HTTPS. + - --share=network + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 @@ -30,9 +36,6 @@ finish-args: # line, Open Recent, "Save" next to the original) work in the usual places. - --filesystem=xdg-pictures - --filesystem=xdg-documents - # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in - # the sandbox; `flatpak override --user --share=network ai.storyteller.texturecraft` exposes it to - # host agents) and home/host filesystem access. modules: - name: texturecraft buildsystem: simple diff --git a/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml b/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml index 3b680178..8529d8bc 100644 --- a/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.TextureCraft.yml @@ -18,6 +18,12 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: texturecraft finish-args: + # Honor the launcher's pinned and nightly version choices before offering updates. + - --filesystem=xdg-data/ArtCraft/versions:ro + # Release checks and downloads use HTTPS. + - --share=network + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland - --socket=fallback-x11 @@ -31,9 +37,6 @@ finish-args: # line, Open Recent, "Save" next to the original) work in the usual places. - --filesystem=xdg-pictures - --filesystem=xdg-documents - # Deliberately not granted: network (the optional --control server listens on 127.0.0.1 in - # the sandbox; `flatpak override --user --share=network ai.storyteller.texturecraft` exposes it to - # host agents) and home/host filesystem access. build-options: append-path: /usr/lib/sdk/rust-stable/bin modules: