diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index ab63e5a3..61714f01 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -4,10 +4,10 @@ "repository_id": 1419654881, "producer_workflow_id": 429738073, "producer_workflow_path": ".github/workflows/nightly.yml", - "producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", - "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "producer_tooling_revision": "main", + "producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main", "signer_workflow_path": ".github/workflows/nightly-sign.yml", - "signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a", + "signer_tooling_revision": "main", "release_branch": "nightly-signer", "manual_actors": [ "bflatastic", @@ -100,7 +100,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", diff --git a/.github/workflows/nightly-macos.yml b/.github/workflows/nightly-macos.yml index 1c49c360..a863bbfa 100644 --- a/.github/workflows/nightly-macos.yml +++ b/.github/workflows/nightly-macos.yml @@ -44,12 +44,12 @@ jobs: persist-credentials: false # The release's pin (release.yml craft-fonts-ref), so the bundle's notices match a shipped build. - name: Check out craft-fonts - uses: storytold/craft-common-actions/actions/checkout-craft-fonts@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/actions/checkout-craft-fonts@main with: ref: aced4137c022f1f587624d48e81ec77e1914a9cc - - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + - uses: storytold/craft-common-actions/actions/checkout-craft-i18n@main - id: rust - uses: storytold/craft-common-actions/actions/rust-channel@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/actions/rust-channel@main with: targets: aarch64-apple-darwin - uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 diff --git a/.github/workflows/nightly-sign.yml b/.github/workflows/nightly-sign.yml index 65767940..82d408c1 100644 --- a/.github/workflows/nightly-sign.yml +++ b/.github/workflows/nightly-sign.yml @@ -34,12 +34,26 @@ jobs: checks: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main with: - tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a + tooling-revision: main app-name: texturecraft producer_run_id: ${{ inputs.producer_run_id }} producer_run_attempt: ${{ inputs.producer_run_attempt }} + secrets: + APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }} + APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }} + KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }} + APPLE_ID: ${{ secrets.APPLE_ID }} + APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }} + APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }} + AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }} + AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }} + AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }} + AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }} + AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }} + AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }} + LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }} # No secrets: inherit or raw platform values in this caller. Only the isolated native # callee job may bind the release environment and export its keys; that environment must # admit nightly-signer alongside release before the first dispatch. diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index a0933e12..c05c2e31 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -22,9 +22,9 @@ jobs: actions: read attestations: write id-token: write - uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a + uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main with: - tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a + tooling-revision: main app-name: texturecraft manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]' craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc @@ -32,3 +32,4 @@ jobs: # craft-common-actions main commit that merged the exact-analysis admission (#371, after #370, # #369 and #364). platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]' + linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]' diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index c2eab178..481b8d70 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -30,6 +30,9 @@ licensed and keep their license file next to them. | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | | `apps/texturecraft/src/xwayland_pen.rs` | Pen on Wayland opens the window through Xwayland: pen detection, the Xwayland decision and the X11 library check (adapted, reduced to the pen decision) | PhotoCraft contributors | storytold/photocraft `830316b775f1f6734498ac6e39fd1298955ff93f`: [`apps/photocraft/src/tablet.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/tablet.rs), [`apps/photocraft/src/linux_libs.rs`](https://github.com/storytold/photocraft/blob/830316b775f1f6734498ac6e39fd1298955ff93f/apps/photocraft/src/linux_libs.rs) | MIT OR Apache-2.0 | +Native autosave recovery uses `same-file` to compare file identities. Copyright (c) 2017 Andrew Gallant. +The crate is available under Unlicense OR MIT. [Upstream source and licences](https://github.com/BurntSushi/same-file) + ## Third-party assets compiled into the binary These come from Rust crate dependencies (not files in this repository) and keep their licenses. diff --git a/Cargo.lock b/Cargo.lock index 2ccaed92..01e17558 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6118,6 +6118,7 @@ dependencies = [ "harfrust 0.12.0", "rayon", "serde", + "serde_json", "skrifa 0.44.0", "texturecraft-compose", "texturecraft-core", @@ -6172,6 +6173,7 @@ dependencies = [ "egui", "egui-phosphor", "egui_kittest", + "flate2", "image", "js-sys", "log", @@ -6179,6 +6181,7 @@ dependencies = [ "raw-window-handle", "rayon", "rfd", + "same-file", "serde", "serde_json", "skera", diff --git a/Cargo.toml b/Cargo.toml index 1f07aa7a..bb398c92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,12 +138,26 @@ codegen-units = 16 [profile.wasm-release] inherits = "release" -opt-level = "s" +# "z" over "s": the browser build must stay under the 24 MiB gate in packaging/web/package.sh. +# Measured on main 7c8dd1ae: 30,812,862 bytes with "s", 26,654,524 bytes with the levels below. +opt-level = "z" lto = "fat" codegen-units = 1 strip = "debuginfo" [profile.wasm-release.package."*"] +opt-level = "z" + +# Kept at "s": these rely on inlining, and at "z" they come out larger, not smaller. +[profile.wasm-release.package.fearless_simd] +opt-level = "s" +[profile.wasm-release.package.vello_cpu] +opt-level = "s" +[profile.wasm-release.package.vello_common] +opt-level = "s" +[profile.wasm-release.package.craft-image-codecs] +opt-level = "s" +[profile.wasm-release.package.texturecraft-core] opt-level = "s" [profile.wasm-release.package.texturecraft-texel] diff --git a/NOTICE b/NOTICE index c3f3e481..844e265c 100644 --- a/NOTICE +++ b/NOTICE @@ -26,6 +26,9 @@ Studio Small 09 HDR environment (assets/hdr/studio_small_09_512.hdr), by Sergej Majboroda (Poly Haven) — CC0-1.0. Source: https://polyhaven.com/a/studio_small_09 (1K HDR, reduced to 512x256). +Native autosave file identity checks use same-file (Unlicense OR MIT). +Copyright (c) 2017 Andrew Gallant. + Native eyedropper components: - raw-window-handle — MIT OR Apache-2.0 OR Zlib. Copyright (c) 2019, 2020 Osspial. - winsafe — MIT. Copyright (c) 2019-present, Rodrigo Cesar de Freitas Dias. diff --git a/apps/texturecraft-cli/src/args.rs b/apps/texturecraft-cli/src/args.rs index 64373804..549d8b0c 100644 --- a/apps/texturecraft-cli/src/args.rs +++ b/apps/texturecraft-cli/src/args.rs @@ -48,7 +48,7 @@ pub(crate) enum Command { /// /// --camera looks through a camera saved in the project (camera.add); --samples path traces it /// instead (Rendering mode), on the GPU when it has compute shaders, else (or with --cpu) on - /// the CPU. + /// the CPU (no GPU needed). #[command(after_help = INPUTS)] Render(RenderArgs), /// A new project from a mesh or a built-in mesh diff --git a/apps/texturecraft-cli/tests/cli.rs b/apps/texturecraft-cli/tests/cli.rs index a5089e96..0d838118 100644 --- a/apps/texturecraft-cli/tests/cli.rs +++ b/apps/texturecraft-cli/tests/cli.rs @@ -184,6 +184,34 @@ fn render_writes_a_png() { let _ = std::fs::remove_dir_all(&d); } +/// Without a GPU, the viewport render's error says what still works, and that does work. A backend +/// this platform lacks stands in for a machine without a GPU: the CLI's wgpu instance reads +/// `WGPU_BACKEND`. +#[test] +fn render_without_a_gpu_points_to_path_tracing() { + let d = tmp("no-gpu"); + let out = d.join("cube.png"); + let absent = if cfg!(target_os = "macos") { "dx12" } else { "metal" }; + let render = |extra: &[&str]| { + Command::new(cli_binary()) + .env("WGPU_BACKEND", absent) + .env_remove("WGPU_ADAPTER_NAME") + .env_remove("WGPU_POWER_PREF") + .args(["render", "builtin:cube", p(&out), "--size", "64x64"]) + .args(extra) + .output() + .unwrap() + }; + let o = render(&[]); + let err = String::from_utf8_lossy(&o.stderr); + assert_eq!(o.status.code(), Some(1), "{err}"); + assert!(err.contains("cannot render") && err.contains("path tracing (`samples`) needs no GPU"), "{err}"); + let o = render(&["--samples", "2"]); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert_eq!(image::open(&out).unwrap().width(), 64); + let _ = std::fs::remove_dir_all(&d); +} + #[test] fn path_traced_render_needs_no_gpu() { let d = tmp("trace"); diff --git a/apps/texturecraft-web/Cargo.toml b/apps/texturecraft-web/Cargo.toml index bb5c79a6..b2e7dbe7 100644 --- a/apps/texturecraft-web/Cargo.toml +++ b/apps/texturecraft-web/Cargo.toml @@ -18,8 +18,9 @@ texturecraft-engine = { workspace = true } texturecraft-ui-egui = { workspace = true } log = { workspace = true } -# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. -eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] } +# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback. No `default_fonts`: the UI takes egui's faces +# from craft-ui's deflated copies (the wasm is under a download budget). +eframe = { workspace = true, features = ["wgpu", "accesskit", "persistence"] } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index 71265909..db10fdae 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -178,13 +178,21 @@ fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, /// Nightly's writes at another app's files. fn private_subdirectory(root: &Path, name: impl AsRef, label: &str) -> Result { let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?; - let child = canonical_future(&chosen.join(name))?; + let entry = chosen.join(name); + let metadata = std::fs::symlink_metadata(&entry).map_err(|e| format!("cannot inspect the nightly {label}: {e}"))?; + if !metadata.is_dir() { + return Err(format!("the nightly {label} must be a directory inside its selected profile")); + } + let child = canonical_future(&entry)?; if child == chosen || !child.starts_with(&chosen) { return Err(format!("the nightly {label} must stay inside its selected profile")); } Ok(child) } +/// Known folder-only entries directly inside a Nightly profile. +const PROFILE_FOLDERS: [&str; 10] = ["autosave", "logs", "cache", "library", "layouts", "templates", "brushes", "export", "export-presets", "Samples"]; + /// Every existing entry directly in the profile (autosave, logs, library and so on) must resolve /// inside it. fn entries_stay_inside(root: &Path) -> Result<(), String> { @@ -195,11 +203,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> { }; for entry in entries { let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - private_subdirectory(root, entry.file_name(), "profile entry")?; + let path = entry.path(); + let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; + // Settings and session state are ordinary files, not directories. Keep the existing + // directory-boundary check for folders (including the known folder-only entries). + let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name)); + if metadata.is_file() && !folder_only { + private_regular_file(&path, &metadata)?; + } else { + private_subdirectory(root, entry.file_name(), "profile entry")?; + } } Ok(()) } +/// Persisted files must have their own ordinary file identity, not an alias to other data. +fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt as _; + if metadata.nlink() != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + #[cfg(windows)] + { + use winsafe::{HFILE, co}; + let (file, _) = HFILE::CreateFile( + path.to_str().ok_or("the nightly profile file path is not textual")?, + co::GENERIC::default(), + Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE), + None, + co::DISPOSITION::OPEN_EXISTING, + co::FILE_ATTRIBUTE::NORMAL, + Some(co::FILE_FLAG::OPEN_REPARSE_POINT), + None, + None, + ) + .map_err(|e| e.to_string())?; + let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?; + if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) { + return Err("the nightly profile file must not be an alias or directory".into()); + } + if info.nNumberOfLinks != 1 { + return Err("the nightly profile file must not be shared".into()); + } + } + let _ = (path, metadata); + Ok(()) +} + /// The app's writable probe: create a file exclusively in the profile and remove it again. pub fn ensure_writable(dir: &Path) -> std::io::Result<()> { let probe = dir.join("exclusive-write-probe"); @@ -474,6 +527,31 @@ mod tests { assert!(fixture.check(Platform::Linux, &fixture.home().join("Documents").join(BRAND)).is_err()); } + #[test] + fn nightly_profile_reopens_after_saving_settings_and_session_state() { + let fixture = Fixture::new(); + for platform in [Platform::Mac, Platform::Linux, Platform::Windows] { + let private = fixture.root.join(format!("nightly-reopen-{platform:?}")); + assert_eq!(fixture.check(platform, &private).unwrap(), private); + for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { + std::fs::write(private.join(name), b"saved profile data").unwrap(); + } + for name in PROFILE_FOLDERS { + std::fs::create_dir(private.join(name)).unwrap(); + } + assert_eq!(fixture.check(platform, &private).unwrap(), private); + assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data"); + for name in PROFILE_FOLDERS { + let path = private.join(name); + std::fs::remove_dir(&path).unwrap(); + std::fs::write(&path, b"not a directory").unwrap(); + assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + } + } + } + #[test] #[cfg(unix)] fn a_profile_whose_existing_ancestor_is_a_link_resolves_before_the_fence() { diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 7eaed255..e536444e 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -401,7 +401,7 @@ impl Headless { let gpu = match self.gpu.get_or_insert_with(Gpu::new) { Ok(g) => g, - Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))), + Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}; path tracing (`samples`) needs no GPU"))), }; // Last-resort guard: wgpu panics on device errors; drop the device and report instead diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index c12ce621..2db6ce00 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -6,6 +6,7 @@ use std::sync::{Arc, Weak}; use rayon::prelude::*; use texturecraft_engine::compose::{DisplayKind, ImageRes, all_tiles, tile_bytes}; +use texturecraft_engine::core::AoMixing; use texturecraft_engine::{Session, ViewMode}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; @@ -67,6 +68,7 @@ impl Gpu { let empty = Default::default(); let baked = session.doc.baked.get(&set_index).unwrap_or(&empty); let composite = &cache.composite; + let ao_mixing = session.doc.project.texture_sets.get(set_index).map_or(AoMixing::Multiply, |set| set.ao_mixing); // Limit live converted pixels while retaining parallel conversion within each batch const UPLOAD_TILES_PER_BATCH: usize = 64; @@ -74,7 +76,7 @@ impl Gpu { let bytes: Vec<_> = batch .par_iter() .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) - .map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (kind, tile_x, tile_y, tile_bytes(composite, baked, ao_mixing, kind, tile_x, tile_y))) .collect(); for (kind, tile_x, tile_y, pixels) in bytes { headless.renderer.upload_tile(&headless.device, &headless.queue, set_index, kind, tile_x, tile_y, &pixels); @@ -162,7 +164,14 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) { .texture_sets .iter() .zip(&s.caches) - .map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() }) + .map(|(ts, c)| TraceSet { + material: ts.material, + composite: c.composite.clone(), + height_strength: ts.atlas_height_strength(), + height_y_factor: ts.atlas_height_y_factor(), + height_in_normal: ts.height_in_normal(), + height_to_normal: ts.height_to_normal, + }) .collect(); let d = &s.doc.project.display; let env_image = d.environment_resource().and_then(|n| s.images.get(n)); @@ -197,10 +206,15 @@ pub fn shade(s: &Session) -> Shade { ViewMode::UvChecker => (3, 0), ViewMode::NormalHeightMesh => (4, 0), }; + let active_set = s.doc.project.texture_sets.get(s.ts()); Shade { - height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0), + height_strength: active_set.map_or(1.0, |t| t.atlas_height_strength()), + height_y_factor: active_set.map_or(1.0, |t| t.atlas_height_y_factor()), + height_in_normal: active_set.is_none_or(|t| t.height_in_normal()), + height_to_normal: active_set.map_or_else(Default::default, |t| t.height_to_normal), view_mode, channel, + // Only the 2D view uses this default wireframe: true, ..Shade::from_project(&s.doc.project) diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 5fbff34d..e07c2551 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -124,8 +124,9 @@ impl Headless { } } -/// Answer one request line. A panic inside a command becomes an error reply (edits run on a -/// snapshot, so the session stays consistent). +/// Answer one request line. A panic inside a command becomes an error reply. `Session::edit` +/// rolls the document back on unwind, but work outside it (scripted strokes) and other session +/// state, such as the selection or tool, is not rolled back. pub fn respond(h: &Mutex, line: &str) -> Value { let req: Value = match serde_json::from_str(line) { Ok(v) => v, diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index f2ebfee6..3b71dbd2 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -338,8 +338,9 @@ impl TexturecraftMcp { match &*self.backend { Backend::Headless(h) => { let (h, m) = (h.clone(), method.to_string()); - // A panicking command poisons the lock, but edits run on a document snapshot - // (`Session::edit`), so the session stays consistent: keep serving. + // A panicking command poisons the lock: keep serving. `Session::edit` rolls the + // document back on unwind, but work outside it (scripted strokes) and other + // session state, such as the selection or tool, is not rolled back. tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p)) .await .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`")))) diff --git a/crates/automation/tests/perf.rs b/crates/automation/tests/perf.rs index ef73dc98..cdd80201 100644 --- a/crates/automation/tests/perf.rs +++ b/crates/automation/tests/perf.rs @@ -57,9 +57,10 @@ fn display_all(session: &mut Session) -> usize { let tiles = session.take_uploads(texture_set); let baked = session.baked(texture_set).cloned().unwrap_or_default(); let composite = &session.caches[texture_set].composite; + let ao_mixing = session.doc.project.texture_sets[texture_set].ao_mixing; bytes += tiles .par_iter() - .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, kind, tile_x, tile_y).len())) + .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.map(|kind| tile_bytes(composite, &baked, ao_mixing, kind, tile_x, tile_y).len())) .sum::(); } diff --git a/crates/compose/src/channel_store.rs b/crates/compose/src/channel_store.rs new file mode 100644 index 00000000..c74282e0 --- /dev/null +++ b/crates/compose/src/channel_store.rs @@ -0,0 +1,76 @@ +//! What a channel's storage format keeps of a composited value + +use std::sync::OnceLock; + +use texturecraft_core::{ChannelFormat, lum}; +use texturecraft_texel::{linear_to_srgb, srgb_to_linear}; + +/// What `value` keeps in `format`: 8-bit = 256 steps (sRGB8 gamma-spaced), L = grey, others = the tiles' 16 bits; `signed` = stored offset into 0..1 +pub(crate) fn stored(format: ChannelFormat, signed: bool, mut value: [f32; 3], components: usize) -> [f32; 3] { + if format.is_grey() && components == 3 { + value = [lum(value); 3]; + } + value.map(|component| stored_value(format, signed, component)) +} + +fn stored_value(format: ChannelFormat, signed: bool, component: f32) -> f32 { + let value = if signed { component * 0.5 + 0.5 } else { component }; + let unit = |unit_value: f32| if signed { unit_value * 2.0 - 1.0 } else { unit_value }; + let step = |unit_value: f32| (unit_value.clamp(0.0, 1.0) * 255.0).round(); + match format { + ChannelFormat::Rgb8 | ChannelFormat::L8 => unit(step(value) / 255.0), + ChannelFormat::Srgb8 => unit(srgb8_linear().get(step(linear_to_srgb(value.clamp(0.0, 1.0))) as usize).copied().unwrap_or(0.0)), + ChannelFormat::L16 | ChannelFormat::Rgb16 | ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F => component, + } +} + +/// The linear value of each 8-bit sRGB step, so storing a colour decodes no sRGB per texel +fn srgb8_linear() -> &'static [f32; 256] { + static LINEAR: OnceLock<[f32; 256]> = OnceLock::new(); + LINEAR.get_or_init(|| std::array::from_fn(|step| srgb_to_linear(step as f32 / 255.0))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn eight_bit_formats_keep_256_steps_and_sixteen_bit_ones_everything() { + let x = 0.3_f32 + 1.0 / 1024.0; + let eight = stored(ChannelFormat::L8, false, [x; 3], 1)[0]; + + assert!((eight * 255.0 - (eight * 255.0).round()).abs() < 1e-4, "on a 1/255 step"); + assert!((eight - x).abs() > 1e-4 && (eight - x).abs() <= 0.5 / 255.0 + 1e-6); + assert_eq!(stored(ChannelFormat::L16, false, [x; 3], 1)[0], x); + assert_eq!(stored(ChannelFormat::Rgb32F, true, [-x; 3], 1)[0], -x); + } + + #[test] + fn srgb8_keeps_more_of_the_darks_than_rgb8() { + let dark = 0.002_f32; + let srgb = stored(ChannelFormat::Srgb8, false, [dark; 3], 3)[0]; + let linear = stored(ChannelFormat::Rgb8, false, [dark; 3], 3)[0]; + + assert!((srgb - dark).abs() < (linear - dark).abs()); + } + + #[test] + fn srgb8_keeps_the_same_steps_as_decoding_each_one() { + for value in (0..=1000).map(|step| step as f32 / 1000.0) { + let decoded = srgb_to_linear((linear_to_srgb(value) * 255.0).round() / 255.0); + + assert_eq!(stored(ChannelFormat::Srgb8, false, [value; 3], 3)[0], decoded, "at {value}"); + } + } + + #[test] + fn grey_formats_turn_colours_grey_and_signed_values_keep_their_sign() { + let grey = stored(ChannelFormat::L16, false, [1.0, 0.0, 0.0], 3); + + assert!(grey[0] == grey[1] && grey[1] == grey[2] && grey[0] > 0.0 && grey[0] < 1.0); + assert_eq!(stored(ChannelFormat::Rgb16, false, [1.0, 0.0, 0.0], 3), [1.0, 0.0, 0.0]); + + let low = stored(ChannelFormat::L8, true, [-0.5; 3], 1)[0]; + assert!(low < -0.49 && low > -0.51); + } +} diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 9fce5480..4a09573c 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -25,7 +25,7 @@ //! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a //! tile with a non-default value arrives. -use texturecraft_core::{BakedMap, Channel}; +use texturecraft_core::{AoMixing, BakedMap, Channel}; use texturecraft_texel::{TILE, TILE_AREA, srgb_lut}; use crate::eval::Composite; @@ -93,7 +93,7 @@ impl DisplayKind { /// The texel of a set that has none of this texture's channels (the GPU clear value). pub fn default_texel(self) -> Vec { - let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), self, 0, 0); + let mut px = tile_bytes(&Composite::new(&[], TILE), &BakedMaps::default(), AoMixing::Multiply, self, 0, 0); px.truncate(self.bytes_per_texel()); px } @@ -110,8 +110,8 @@ fn u8_of(v: u16) -> u8 { (v >> 8) as u8 } -/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles. -pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { +/// Tile bytes (`TILE × TILE`, row-major) for `kind` mixing baked occlusion by `ao_mixing`, with channel defaults for absent source tiles +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32) -> Vec { let bytes_per_texel = kind.bytes_per_texel(); let mut out = vec![0u8; TILE_AREA * bytes_per_texel]; let srgb = srgb_lut(); @@ -183,9 +183,12 @@ pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, t for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked - .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) - .map_or(1.0, |value| value[0]); + let baked_ao = match ao_mixing { + AoMixing::Multiply => baked + .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) + .map_or(1.0, |value| value[0]), + AoMixing::None => 1.0, + }; let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); let pixel = &mut out[i * 4..i * 4 + 4]; @@ -263,7 +266,7 @@ mod tests { } for kind in DisplayKind::ALL.into_iter().filter(|k| !kinds_for(channels).any(|n| n == *k)) { let want = kind.default_texel().repeat(TILE_AREA); - assert!(tile_bytes(&comp, &BakedMaps::default(), kind, 0, 0) == want, "{kind:?} for {channels:?}"); + assert!(tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, kind, 0, 0) == want, "{kind:?} for {channels:?}"); } } } @@ -274,7 +277,7 @@ mod tests { comp.channels.get_mut(&Channel::BaseColor).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]); comp.channels.get_mut(&Channel::Opacity).unwrap().set(0, 0, &[to_u16(0.5)]); - let b = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::BaseColor, 0, 0); + let b = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); assert_eq!(b[0], 255); assert!((b[1] as i32 - 188).abs() <= 1, "{}", b[1]); @@ -288,7 +291,7 @@ mod tests { set.uv_tiles = vec![1001, 1002]; set.tile_resolutions.insert(1002, 64); let comp = Composite { block_scales: set.block_scales(), ..Composite::new(&[], 512) }; - let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, tx, 0)[3]; + let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, tx, 0)[3]; // Tile 1001 fills its block; 1002 fills a quarter, encoded as 32 × log2(4) assert_eq!((alpha(0), alpha(3), alpha(4), alpha(7)), (0, 0, 64, 64)); @@ -297,20 +300,28 @@ mod tests { #[test] fn missing_channels_fall_back_to_defaults() { let comp = Composite::new(&[], 64); - let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0); + let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0); assert_eq!(&orm[..4], &[255, 128, 0, 128]); assert_eq!(normal_texel(&comp, &BakedMaps::default(), 0), [0.0, 0.0, 1.0, 0.5], "flat, sheen roughness 0.5 rides in alpha"); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Lobes, 0, 0)[..4], &[0, 25, 0, 0], "lobes off, coat roughness 0.1"); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]); - assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, 0, 0)[..4], &[128, 128, 0, 0], "flat coat normal, no transmission"); + assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Emissive, 0, 0)[..4], &[0, 0, 0, 0]); + assert_eq!( + &tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Lobes, 0, 0)[..4], + &[0, 25, 0, 0], + "lobes off, coat roughness 0.1" + ); + assert_eq!(&tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Sheen, 0, 0)[..4], &[255, 255, 255, 0]); + assert_eq!( + &tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Extra, 0, 0)[..4], + &[128, 128, 0, 0], + "flat coat normal, no transmission" + ); for k in DisplayKind::ALL { - assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), k, 3, 5)[..k.bytes_per_texel()]); + assert_eq!(k.default_texel(), tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 3, 5)[..k.bytes_per_texel()]); } - let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0); + let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0); assert_eq!(h.len(), TILE_AREA * 8); assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0"); } @@ -339,7 +350,7 @@ mod tests { /// Decode texel `i` of the Normal display tile (0, 0). fn normal_texel(comp: &Composite, baked: &BakedMaps, i: usize) -> [f32; 4] { - let bytes = tile_bytes(comp, baked, DisplayKind::Normal, 0, 0); + let bytes = tile_bytes(comp, baked, AoMixing::Multiply, DisplayKind::Normal, 0, 0); [0, 1, 2, 3].map(|k| half::f16::from_le_bytes([bytes[i * 8 + k * 2], bytes[i * 8 + k * 2 + 1]]).to_f32()) } @@ -374,11 +385,11 @@ mod tests { comp.channels.get_mut(&Channel::Glossiness).unwrap().set(0, 0, &[to_u16(0.8)]); comp.channels.get_mut(&Channel::Specular).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]); - let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0); + let orm = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Orm, 0, 0); assert!((orm[1] as i32 - 51).abs() <= 1, "roughness = 1 - 0.8, got {}", orm[1]); - let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0); + let h = tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, DisplayKind::Height, 0, 0); let at = |k: usize| half::f16::from_le_bytes([h[k * 2], h[k * 2 + 1]]).to_f32(); assert_eq!(at(0), 0.0); @@ -402,7 +413,7 @@ mod tests { set(Channel::Transmission, &[to_u16(0.6)]); set(Channel::CoatNormal, &[to_u16(1.0), to_u16(0.5), to_u16(1.0)]); - let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), k, 0, 0)[4..8].to_vec(); + let px = |k: DisplayKind| tile_bytes(&comp, &BakedMaps::default(), AoMixing::Multiply, k, 0, 0)[4..8].to_vec(); let near = |a: &[u8], b: &[u8]| a.iter().zip(b).all(|(x, y)| x.abs_diff(*y) <= 1); assert!(near(&px(DisplayKind::Lobes), &[255, 51, 153, 64]), "{:?}", px(DisplayKind::Lobes)); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 52184129..1a9e393b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -12,16 +12,16 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_core::{ - AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelKind, ColorMatch, CompareSource, ContentsOffset, + AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelFormat, ChannelKind, ColorMatch, CompareSource, ContentsOffset, CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind, - GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground, - MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source, - SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters, - blend1, blend3, lum, mix3, per_unit, posterize, udim_at, + GrayscaleConversionParameters, HeightMask, HeightToNormal, HeightToNormalMethod, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, + MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, + ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, + WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer}; -use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; +use texturecraft_texel::{TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed}; use crate::ProjectorDepthCache; use crate::below::{Band, BelowCache, Level, StackKey}; @@ -67,6 +67,9 @@ const MIN_BOUNDS_EXTENT: f32 = 1e-6; /// Stack values being composited, per channel. type Acc = [[f32; 3]; NCH]; +/// What the live stroke's stencil lets through at a texel ([`Stencil::paint_world`]) +type StencilPaint = Option<(Option<[f32; 3]>, f32)>; + /// How tall a baked height of 1 stands, as a fraction of a UV tile, when Baked Lighting Stylized tilts normals by its slope const HEIGHT_RELIEF: f32 = 1.0 / 32.0; @@ -82,39 +85,66 @@ pub enum PaintTarget { Mask(LayerId), } -/// A screen-pinned image painted through the camera (projection tool / stencil). +/// Smallest clip w a stencil paints at and smallest half extent it divides by +const STENCIL_EPSILON: f32 = 1e-6; + +/// Rec. 709 red, green and blue weights of a gray's luminance +const REC709_LUMINANCE_WEIGHTS: [f32; 3] = [0.2126, 0.7152, 0.0722]; + +/// A screen-pinned image every brush tool paints through #[derive(Clone, Debug)] pub struct Stencil { pub image: std::sync::Arc, - /// Camera view-projection captured when the stroke started. + /// Camera view-projection captured when the stroke started pub view_proj: texturecraft_geom::glam::Mat4, - /// Image placement in normalized device coordinates: center, half extents, rotation. + /// Image placement in normalized device coordinates: center, half extents, rotation pub center: [f32; 2], pub half: [f32; 2], pub rotation: f32, - /// Repeat the image beyond its bounds (otherwise nothing is painted outside it). + /// Repeat the image beyond its bounds (otherwise nothing is painted outside it) pub tile: bool, + /// The Projection tool paints the image's colors; every other tool paints through its gray + pub colors: bool, } impl Stencil { - /// Linear color and alpha of the stencil at world point `p` (None outside the image). - pub fn sample_world(&self, p: Vec3) -> Option<([f32; 3], f32)> { - let c = self.view_proj * p.extend(1.0); - if c.w <= 1e-6 { + /// Linear color and alpha of the stencil at world point `point` (None outside the image) + pub fn sample_world(&self, point: Vec3) -> Option<([f32; 3], f32)> { + let sample = self.sample_raw(point)?; + let rgb = [sample[0], sample[1], sample[2]]; + let rgb = if self.image.srgb { rgb.map(texturecraft_texel::srgb_to_linear) } else { rgb }; + Some((rgb, sample[3].clamp(0.0, 1.0))) + } + + /// How much paint passes at world point `point` when the stencil masks a stroke: its gray times its alpha, read as stored like a brush alpha image (0 outside the image) + pub fn mask_world(&self, point: Vec3) -> f32 { + let Some([red, green, blue, alpha]) = self.sample_raw(point) else { return 0.0 }; + let [red_weight, green_weight, blue_weight] = REC709_LUMINANCE_WEIGHTS; + ((red_weight * red + green_weight * green + blue_weight * blue) * alpha).clamp(0.0, 1.0) + } + + /// The paint a stroke receives at world point `point`: the stencil's color (Projection only) and the factor scaling the stroke there, None where nothing is painted + pub fn paint_world(&self, point: Vec3) -> Option<(Option<[f32; 3]>, f32)> { + if self.colors { self.sample_world(point).map(|(color, alpha)| (Some(color), alpha)) } else { Some((None, self.mask_world(point))) } + } + + /// The stored image value under world point `point` (None outside the image) + fn sample_raw(&self, point: Vec3) -> Option<[f32; 4]> { + let clip = self.view_proj * point.extend(1.0); + if clip.w <= STENCIL_EPSILON { return None; } - let (dx, dy) = (c.x / c.w - self.center[0], c.y / c.w - self.center[1]); - let (sn, cs) = (-self.rotation).sin_cos(); - let lx = (dx * cs - dy * sn) / self.half[0].max(1e-6); - let ly = (dx * sn + dy * cs) / self.half[1].max(1e-6); - if !self.tile && (lx.abs() > 1.0 || ly.abs() > 1.0) { + let offset_x = clip.x / clip.w - self.center[0]; + let offset_y = clip.y / clip.w - self.center[1]; + let (sine, cosine) = (-self.rotation).sin_cos(); + let local_x = (offset_x * cosine - offset_y * sine) / self.half[0].max(STENCIL_EPSILON); + let local_y = (offset_x * sine + offset_y * cosine) / self.half[1].max(STENCIL_EPSILON); + if !self.tile && (local_x.abs() > 1.0 || local_y.abs() > 1.0) { return None; } - let s = self.image.sample(lx * 0.5 + 0.5, 0.5 - ly * 0.5); - let rgb = if self.image.srgb { [s[0], s[1], s[2]].map(texturecraft_texel::srgb_to_linear) } else { [s[0], s[1], s[2]] }; - Some((rgb, s[3].clamp(0.0, 1.0))) + Some(self.image.sample(local_x * 0.5 + 0.5, 0.5 - local_y * 0.5)) } } @@ -171,6 +201,12 @@ impl Inputs<'_> { self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1)) } + /// Texels across and down an atlas block + fn block_size(&self) -> [u32; 2] { + let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols.max(1), g.rows.max(1))); + [self.gbuf.width / cols, self.gbuf.height / rows] + } + /// The current UV tile can occupy only part of its atlas block fn tile_res_at(&self, x: u32, y: u32) -> u32 { ((self.tile_res() as f32 * self.block_scales.at(x, y)).round() as u32).max(1) @@ -438,10 +474,10 @@ enum Op { Halo, /// The shapes moved by `offset` (whole texels), box blurred and laid under them Shadow { offset: [i32; 2] }, - /// Each UV tile's texels read from where `mirror` sends them in their tile (`block` texels across the set's atlas blocks) - Mirror { mirror: Mirror, block: u32 }, + /// Each UV tile's texels read from where `mirror` sends them in their tile + Mirror { mirror: Mirror }, /// Each UV tile's texels read from where `transform` sends them (its `affine`, worked out once), repeating round the tile or empty past it - Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]), block: u32 }, + Transform { transform: TileTransform, affine: ([[f32; 2]; 2], [f32; 2]) }, /// A band along the edge of the shapes past a threshold, from the box blur of the shapes Outline(MaskOutline), /// Drawn from the distance to the shapes' edge (see [`distance_filter`]) @@ -498,11 +534,13 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } EffectKind::Filter(Filter::HighPass { radius, space, alpha }) => Some((index, texels(*radius), Op::HighPass { space: *space, alpha: *alpha })), EffectKind::Filter(Filter::EdgeDetect { width }) => Some((index, texels(*width), Op::Edge)), + // Three box passes ramp an edge over about twice their radius EffectKind::Filter(Filter::Bevel { width, .. }) => Some((index, texels(*width * 0.5), Op::Bevel)), EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))), EffectKind::Filter(Filter::Mosaic { size, alpha }) => Some((index, texels(*size), Op::Mosaic { alpha: *alpha })), EffectKind::Filter(Filter::Fxaa { alpha }) => Some((index, FXAA_SEARCH as f32 + 1.0, Op::Fxaa { alpha: *alpha })), + // Both the direction search and the ellipse can reach twice the radius EffectKind::Filter(Filter::AnisotropicKuwahara(kuwahara)) if kuwahara.radius > 0.0 => { Some((index, texels(kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS)) * (2.0 + kuwahara.tensor_reach()) + 1.0, Op::Kuwahara(*kuwahara))) @@ -529,10 +567,11 @@ fn neighbourhood_filters(effects: &[Effect], res: u32, channel: Option) } // A mirror reads anywhere in its UV tile - EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror, block: res })), + EffectKind::Filter(Filter::Mirror(mirror)) => Some((index, res as f32, Op::Mirror { mirror: *mirror })), + // A transform reads anywhere in its UV tile; one that changes nothing is skipped EffectKind::Filter(Filter::Transform(transform)) if !transform.is_identity() => { - Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine(), block: res })) + Some((index, res as f32, Op::Transform { transform: *transform, affine: transform.affine() })) } // Three box passes reach the band's width @@ -771,15 +810,15 @@ fn gather( keep_coverage(&mut acc, comps, center.get(3)); } } - Op::Mirror { mirror, block } => { - mirror_texel(&mirror, (x, y), (block, res), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) + Op::Mirror { mirror } => { + mirror_texel(&mirror, (x, y), (block_size, tile_size), comps, orig.get((row * width + col) * comps + comps - 1), &mut acc, &sample) } - Op::Transform { transform, affine, block } => transform_texel(&transform, affine, (x, y), (block, res), &mut acc, &sample), + Op::Transform { transform, affine } => transform_texel(&transform, affine, (x, y), (block_size, tile_size), &mut acc, &sample), Op::SourceWarp(warp) => warp_texel((&warp, &warp_directions), (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)), Op::HeightToNormal(filter) => { let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]); - height_to_normal_texel(&filter, (x, y), (res, center), &mut acc, &input); + height_to_normal_texel(&filter, (x, y), (tile_size, center), &mut acc, &input); } Op::Kuwahara(kuwahara) => { let radius = (kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS) * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS); @@ -920,21 +959,18 @@ fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] { fn height_to_normal_texel( filter: &HeightToNormal, (x, y): (f32, f32), - (res, center): (u32, &[f32]), + (tile_size, center): ([u32; 2], &[f32]), acc: &mut [f32; 5], height: &dyn Fn(f32, f32) -> Option, ) { let (Some(own), [red, green, blue, cov]) = (height(x, y), center) else { return }; + if *cov <= 0.0 { return; } - let at = |dx: f32, dy: f32| height(x + dx, y + dy).unwrap_or(own); - - // Sobel gradients over the kernel's weight sum - let gx = (at(1.0, -1.0) + 2.0 * at(1.0, 0.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(-1.0, 0.0) - at(-1.0, 1.0)) / 8.0; - let gy = (at(-1.0, 1.0) + 2.0 * at(0.0, 1.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(0.0, -1.0) - at(1.0, -1.0)) / 8.0; - let made = filter.normal([gx, gy], res).map(|v| v * 0.5 + 0.5); + let slope = HeightToNormalMethod::Smooth.slope(|dx, dy| height(x + dx as f32, y + dy as f32).unwrap_or(own)); + let made = filter.normal_for_size(slope, tile_size).map(|value| value * 0.5 + 0.5); let packed = if filter.overwrite { made } else { texturecraft_core::blend::rnm([red, green, blue].map(|v| v / cov), made) }; for (slot, value) in acc.iter_mut().zip(packed) { *slot = value * cov; @@ -1164,21 +1200,14 @@ fn fxaa_texel((x, y): (f32, f32), comps: usize, center: &[f32], acc: &mut [f32; fn mirror_texel( mirror: &Mirror, (x, y): (f32, f32), - (block, res): (u32, u32), + (block, tile): ([u32; 2], [u32; 2]), comps: usize, alpha: Option<&f32>, acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5]), ) { - let (block, size) = (block.max(1) as f32, res.max(1) as f32); - let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); - let (local_x, local_y) = (x - origin_x, y - origin_y); - if local_x >= size || local_y >= size { - return; - } - - let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; - let line = (Mirror::DEBUG_HALF_WIDTH * size / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size; + let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return }; + let line = (Mirror::DEBUG_HALF_WIDTH * size[0] / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS) / size[0]; if mirror.debug && mirror.on_axis(uv, line) { // Content stays premultiplied by its own coverage; masks are one value let cover = if comps == 4 { alpha.copied().unwrap_or(0.0) } else { 1.0 }; @@ -1192,30 +1221,35 @@ fn mirror_texel( let [u, v] = mirror.source(uv); // Whole texels, so an even mirror copies texels exactly - let at = |origin: f32, along: f32| origin + (along * size - 0.5).round().clamp(0.0, size - 1.0); - sample(at(origin_x, u), at(origin_y, v), acc); + let at = |origin: f32, along: f32, extent: f32| origin + (along * extent - 0.5).round().clamp(0.0, extent - 1.0); + sample(at(origin_x, u, size[0]), at(origin_y, v, size[1]), acc); } -/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`res` texels from its `block`'s top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty +/// The top left of texel `(x, y)`'s UV tile (`tile` texels at its `block`'s top left), the texel centre's UV in it and the tile's size, None past the tile +fn tile_local((x, y): (f32, f32), (block, tile): ([u32; 2], [u32; 2])) -> Option<([f32; 2], [f32; 2], [f32; 2])> { + let (block, size) = (block.map(|b| b.max(1) as f32), tile.map(|t| t.max(1) as f32)); + let origin = [(x / block[0]).floor() * block[0], (y / block[1]).floor() * block[1]]; + let local = [x - origin[0], y - origin[1]]; + if local[0] >= size[0] || local[1] >= size[1] { + return None; + } + + Some((origin, [(local[0] + 0.5) / size[0], (local[1] + 0.5) / size[1]], size)) +} + +/// Transform `transform` (whose read is `affine`) at texel `(x, y)` into `acc`: bilinear between the four texels round where it reads in its UV tile (`tile` texels per axis from its block's top left), each wrapped round the tile; where it does not repeat, a read past the tile counts as empty fn transform_texel( transform: &TileTransform, (columns, shift): ([[f32; 2]; 2], [f32; 2]), (x, y): (f32, f32), - (block, res): (u32, u32), + (block, tile): ([u32; 2], [u32; 2]), acc: &mut [f32; 5], sample: &dyn Fn(f32, f32, &mut [f32; 5]), ) { - let (block, size) = (block.max(1) as f32, res.max(1) as f32); - let (origin_x, origin_y) = ((x / block).floor() * block, (y / block).floor() * block); - let (local_x, local_y) = (x - origin_x, y - origin_y); - if local_x >= size || local_y >= size { - return; - } - - let uv = [(local_x + 0.5) / size, (local_y + 0.5) / size]; + let Some(([origin_x, origin_y], uv, size)) = tile_local((x, y), (block, tile)) else { return }; // Texel space of the tile, centres at whole numbers - let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size - 0.5); + let at = [0, 1].map(|axis| (columns[0][axis] * uv[0] + columns[1][axis] * uv[1] + shift[axis]) * size[axis] - 0.5); if !at.iter().all(|a| a.is_finite()) { return; } @@ -1230,7 +1264,7 @@ fn transform_texel( } let (cx, cy) = (base_x + dx, base_y + dy); - let inside = (0.0..size).contains(&cx) && (0.0..size).contains(&cy); + let inside = (0.0..size[0]).contains(&cx) && (0.0..size[1]).contains(&cy); if !repeat && !inside { // Empty: no value, full weight total[4] += k; @@ -1239,7 +1273,7 @@ fn transform_texel( // One whole texel: the sample's own weights, so this matches its bilinear read let mut one = [0.0f32; 5]; - sample(origin_x + cx.rem_euclid(size), origin_y + cy.rem_euclid(size), &mut one); + sample(origin_x + cx.rem_euclid(size[0]), origin_y + cy.rem_euclid(size[1]), &mut one); for (slot, value) in total.iter_mut().zip(one) { *slot += value * k; } @@ -1596,11 +1630,17 @@ fn unpad(data: &[f32], comps: usize, (w, h): (usize, usize), (pad_x, pad_y): (us /// A neighbourhood filter's radius in whole texels and how many texels around a texel it reads fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) { let longest_side = inputs.gbuf.width.max(inputs.gbuf.height); + // Clamped so a hostile radius can't overflow the region arithmetic let radius_texels = radius.round().clamp(1.0, longest_side as f32) as u32; - // Three box passes reach three radii; the gathering filters one radius plus a bilinear texel - let reach = if is_box_blur(op) { 3 * radius_texels } else { radius_texels + 1 }; + // Three box passes reach three radii and gathering filters reach one radius plus a bilinear texel + // Mirror and transform can read across the whole block + let reach = match op { + Op::Mirror { .. } | Op::Transform { .. } => (radius_texels + 1).max(inputs.block_size().into_iter().max().unwrap_or(0)), + _ if is_box_blur(op) => 3 * radius_texels, + _ => radius_texels + 1, + }; // A shadow also reads the shapes it was moved from let moved = match op { @@ -1615,7 +1655,7 @@ fn filter_extent(radius: f32, op: Op, inputs: &Inputs) -> (u32, u32) { _ => None, }; let source_reach = if tiled_source.is_some_and(|source| source.mode != WarpSourceMode::DefaultNoise && source.tiling_factor() != 1.0) { - inputs.tile_grid().map_or(longest_side, |_| inputs.tile_res()) + inputs.tile_grid().map_or(longest_side, |_| inputs.block_size().into_iter().max().unwrap_or(0)) } else { 0 }; @@ -1825,7 +1865,7 @@ fn filter_region( // A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels let (block_size, tiled) = match inputs.tile_grid() { - Some(_) => ([inputs.tile_res(); 2], true), + Some(_) => (inputs.block_size(), true), None => ([inputs.gbuf.width, inputs.gbuf.height], false), }; let filtered = |scale: f32| -> Vec { @@ -1838,7 +1878,7 @@ fn filter_region( let scaled = neighbourhood_filters(effects, tile_resolution, channel).find(|filter| filter.0 == index); let scaled_radius = scaled.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32); if !is_box_blur(op) { - let tile_size = if tiled { [tile_resolution; 2] } else { block_size }; + let tile_size = if tiled { block_size.map(|side| ((side as f32 * scale).round() as u32).max(1)) } else { block_size }; return gather( op, (&stack_values, &cover, &grays), @@ -3015,6 +3055,8 @@ struct Texel<'a, 'b> { tape: Tape<'b>, /// The copy of a symmetric fill being sampled: the surface point and normal it sees, and its image's flip copy: Option<(usize, FillCopy)>, + /// The live stroke's stencil sampled here once for every channel (None until a channel reads it) + stencil_paint: Option, } /// What a layer contributes (its mask, its content value and coverage per channel): evaluated @@ -3050,7 +3092,22 @@ type ChannelContents = [Option<([f32; 3], f32)>; NCH]; impl<'a, 'b> Texel<'a, 'b> { fn new(inp: &'b Inputs<'a>, x: u32, y: u32, o: usize, stroke: f32) -> Self { - Texel { inp, x, y, o, res: inp.gbuf.width, coords: None, stroke, stop: None, anchors: Vec::new(), below: None, lit: None, tape: Tape::Off, copy: None } + Texel { + inp, + x, + y, + o, + res: inp.gbuf.width, + coords: None, + stroke, + stop: None, + anchors: Vec::new(), + below: None, + lit: None, + tape: Tape::Off, + copy: None, + stencil_paint: None, + } } /// Run `f` with `tape` as this texel's tape. @@ -3193,6 +3250,24 @@ impl<'a, 'b> Texel<'a, 'b> { self.surface((self.y * self.inp.gbuf.width + self.x) as usize).map(|s| s.pos) } + /// What the live stroke's `stencil` lets through here, sampled once for all of the texel's channels + fn stencil_paint(&mut self, stencil: &Stencil) -> StencilPaint { + let sample = |texel: &Self| texel.world().and_then(|world| stencil.paint_world(world)); + + // A symmetric fill's copy sees another surface point, so only the texel's own sample is kept + if self.copy.is_some() { + return sample(self); + } + + if let Some(paint) = self.stencil_paint { + return paint; + } + + let paint = sample(self); + self.stencil_paint = Some(paint); + paint + } + /// The surface at G-buffer index `i`, as the fill copy being sampled sees it #[inline(always)] fn surface(&self, i: usize) -> Option { @@ -3286,9 +3361,11 @@ impl<'a, 'b> Texel<'a, 'b> { let (width, height) = (self.res, self.inp.gbuf.height); let at = |x: u32, y: u32| self.inp.baked.sample_working(BakedMap::Height, x, y, (width, height), &self.inp.block_scales).map(|h| h[0]); let (origin_x, origin_y, tile_width, tile_height) = if let Some(grid) = self.inp.tile_grid() { - let block = (width / grid.cols.max(1)).max(1); - let tile = ((block as f32 * self.inp.block_scales.at(self.x, self.y)).round() as u32).max(1); - (self.x / block * block, self.y / block * block, tile, tile) + let block_width = (width / grid.cols.max(1)).max(1); + let block_height = (height / grid.rows.max(1)).max(1); + let scale = self.inp.block_scales.at(self.x, self.y); + let tile_side = |block_side| ((block_side as f32 * scale).round() as u32).max(1); + (self.x / block_width * block_width, self.y / block_height * block_height, tile_side(block_width), tile_side(block_height)) } else { (0, 0, width, height) }; @@ -3897,7 +3974,7 @@ impl<'a, 'b> Texel<'a, 'b> { self.mask_effects(plan, value, skip, plan.effects.len()) } - /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them. + /// Mask effects `from..to` of `plan` over `value`, recording the anchors among them fn mask_effects(&mut self, plan: &MaskPlan, mut value: f32, from: usize, to: usize) -> f32 { // Avoid amplifying rounding error when unpremultiplying faint paint const MIN_PAINT_COVERAGE: f32 = 1e-5; @@ -3915,10 +3992,19 @@ impl<'a, 'b> Texel<'a, 'b> { Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))), None => (0.0, 0.0), }; + if effect.preview && let Some(preview) = self.inp.preview { - let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + let mut stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0); + + // The stencil shapes the stroke as the commit does + if let Some(stencil) = preview.stencil.as_ref() + && stroke > 0.0 + { + stroke *= self.stencil_paint(stencil).map_or(0.0, |(_, factor)| factor); + } + if preview.erase { painted *= 1.0 - stroke; coverage *= 1.0 - stroke; @@ -3932,6 +4018,7 @@ impl<'a, 'b> Texel<'a, 'b> { coverage = stroke + coverage * (1.0 - stroke); } } + if coverage > 0.0 { let layer_value = painted / coverage.max(MIN_PAINT_COVERAGE); value += (blend1(effect.blend, value, layer_value) - value) * coverage * opacity; @@ -4271,62 +4358,66 @@ impl<'a, 'b> Texel<'a, 'b> { (coverage > 0.0).then_some((value, coverage.min(1.0))) } - /// Straight value and coverage of painted data of one channel (premultiplied values plus - /// coverage per texel), with the live stroke when `preview`. - fn painted(&mut self, data: Option<&[u16]>, c: &ChanPlan, preview: bool) -> ([f32; 3], f32) { - let pv = if preview { self.inp.preview } else { None }; - let mut sa = pv.map(|p| (self.stroke * p.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); + /// Straight value and coverage of one channel's painted data (premultiplied values plus coverage per texel), with the live stroke when `preview` + fn painted(&mut self, data: Option<&[u16]>, chan_plan: &ChanPlan, preview: bool) -> ([f32; 3], f32) { + // Coverage floor the premultiplied value is divided by + const MIN_COVERAGE: f32 = 1e-5; - // Projection: the stencil's alpha shapes the stroke and its color is the base color - let stencil = match pv.and_then(|p| p.stencil.as_ref()) { - Some(st) if sa > 0.0 => { - let s = self.world().and_then(|w| st.sample_world(w)); - sa *= s.map(|(_, a)| a).unwrap_or(0.0); - s.map(|(c, _)| c) + let stroke_preview = if preview { self.inp.preview } else { None }; + let mut stroke_alpha = stroke_preview.map(|stroke| (self.stroke * stroke.opacity).clamp(0.0, 1.0)).unwrap_or(0.0); + + // The stencil shapes the stroke; on the Projection tool its color is the base color + let stencil_color = match stroke_preview.and_then(|stroke| stroke.stencil.as_ref()) { + Some(stencil) if stroke_alpha > 0.0 => { + let stencil_paint = self.stencil_paint(stencil); + stroke_alpha *= stencil_paint.map(|(_, factor)| factor).unwrap_or(0.0); + stencil_paint.and_then(|(color, _)| color) } _ => None, }; - let mut val = [0.0f32; 3]; - let mut cov = 0.0f32; - if let Some(d) = data { - let base = self.o * (c.comps + 1); - for (k, slot) in val.iter_mut().take(c.comps).enumerate() { - *slot = decode(c.kind, d.get(base + k).copied().unwrap_or(0)); + + let mut value = [0.0f32; 3]; + let mut coverage = 0.0f32; + if let Some(texels) = data { + let base = self.o * (chan_plan.comps + 1); + for (component, slot) in value.iter_mut().take(chan_plan.comps).enumerate() { + *slot = decode(chan_plan.kind, texels.get(base + component).copied().unwrap_or(0)); } - cov = from_u16(d.get(base + c.comps).copied().unwrap_or(0)); + coverage = from_u16(texels.get(base + chan_plan.comps).copied().unwrap_or(0)); } - if let Some(p) = pv - && sa > 0.0 + + if let Some(stroke) = stroke_preview + && stroke_alpha > 0.0 { - if p.erase { - val = val.map(|v| v * (1.0 - sa)); - cov *= 1.0 - sa; - } else if let Some(ch) = Channel::ALL.get(c.ch) - && let Some(pval) = p.values.get(ch) + if stroke.erase { + value = value.map(|component| component * (1.0 - stroke_alpha)); + coverage *= 1.0 - stroke_alpha; + } else if let Some(channel) = Channel::ALL.get(chan_plan.ch) + && let Some(stroke_value) = stroke.values.get(channel) { - let pval = match stencil { - Some(col) if *ch == Channel::BaseColor => col, - _ => match p.carried.get(ch) { - Some(img) => { - let raw = img.get(self.x, self.y).map(|v| decode(c.kind, v)); + let stroke_value = match stencil_color { + Some(color) if *channel == Channel::BaseColor => color, + _ => match stroke.carried.get(channel) { + Some(carried) => { + let raw = carried.get(self.x, self.y).map(|stored| decode(chan_plan.kind, stored)); [raw[0], raw[1], raw[2]] } - None => *pval, + None => *stroke_value, }, }; - for k in 0..c.comps { - val[k] = pval[k] * sa + val[k] * (1.0 - sa); + for component in 0..chan_plan.comps { + value[component] = stroke_value[component] * stroke_alpha + value[component] * (1.0 - stroke_alpha); } - cov = sa + cov * (1.0 - sa); + coverage = stroke_alpha + coverage * (1.0 - stroke_alpha); } } - if cov <= 0.0 { + if coverage <= 0.0 { return ([0.0; 3], 0.0); } - let inv = 1.0 / cov.max(1e-5); - let v = if c.comps == 3 { val.map(|x| x * inv) } else { [val[0] * inv; 3] }; - (v, cov.min(1.0)) + let inverse_coverage = 1.0 / coverage.max(MIN_COVERAGE); + let straight = if chan_plan.comps == 3 { value.map(|component| component * inverse_coverage) } else { [value[0] * inverse_coverage; 3] }; + (straight, coverage.min(1.0)) } /// Apply one content effect to a channel's straight value and coverage @@ -4672,13 +4763,15 @@ fn composite_block( quota: usize, fields: &Fields, ) -> Vec<((u32, u32), Vec)> { - let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); + let formats: Vec<(Channel, ChannelFormat)> = inp.project.texture_set(inp.ts).map(TextureSet::formats).unwrap_or_default(); + let channels: Vec = formats.iter().map(|(c, _)| *c).collect(); let (w, h) = (out.resolution, out.height); let split = below.map(|(_, l)| l); let cached = |t: (u32, u32)| below.and_then(|(b, _)| b.tile(t)); let fresh: Vec<(u32, u32)> = tiles.iter().copied().filter(|t| cached(*t).is_none()).collect(); let recorded: std::collections::BTreeSet<(u32, u32)> = if split.is_some() { fresh.iter().copied().take(quota).collect() } else { Default::default() }; - let lanes: Vec = channels.iter().map(|c| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed }).collect(); + let lanes: Vec = + formats.iter().map(|(c, f)| Lane { ch: c.index(), n: c.components(), signed: c.kind() == ChannelKind::Signed, format: *f }).collect(); let stride: usize = lanes.iter().map(|l| l.n).sum(); let level_count = split.map_or(0, <[Level]>::len); let defaults: Acc = Channel::ALL.map(Channel::default_value); @@ -4767,7 +4860,7 @@ fn composite_block( anchors.clear(); } for (l, buf) in lanes.iter().zip(&mut channel_buffers) { - let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); + let v = crate::channel_store::stored(l.format, l.signed, acc.get(l.ch).copied().unwrap_or([0.0; 3]), l.n); for (k, x) in v.iter().take(l.n).enumerate() { let encoded = if l.signed { to_u16_signed(*x) } else { to_u16(*x) }; if let Some(slot) = buf.get_mut(band_offset * l.n + k) { @@ -4784,20 +4877,26 @@ fn composite_block( // Join the bands of each tile (in parallel; uncovered tiles are freed) let joined: Vec = results - .par_chunks(bands as usize) + .par_chunks_mut(bands as usize) .map(|parts| { let any = parts.iter().any(|p| p.2); let data = (0..channels.len()) .map(|k| { any.then(|| { let mut v = Vec::with_capacity(parts.iter().map(|p| p.0.get(k).map_or(0, Vec::len)).sum()); - for p in parts { + for p in parts.iter() { v.extend_from_slice(p.0.get(k).map_or(&[][..], Vec::as_slice)); } std::sync::Arc::new(v) }) }) .collect(); + + // Only replay data is needed after joining the tile + for (channel_buffers, _, _) in parts { + channel_buffers.clear(); + } + (data, any) }) .collect(); @@ -4845,6 +4944,8 @@ struct Lane { ch: usize, n: usize, signed: bool, + /// What the channel is stored in + format: ChannelFormat, } /// Restore the cached stack value of slot `o` (a texel at one nesting level). Scalars are @@ -4874,37 +4975,42 @@ fn store_below(cache: &mut [f32], lanes: &[Lane], stride: usize, o: usize, acc: } } -/// UV padding for display: fill uncovered texels in `tiles` and their neighbours from their -/// nearest covered texel. Returns the tiles it wrote. -pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { +/// UV padding for display: fill uncovered texels in `tiles`, their neighbours and the tiles padding continues into across a seam from the covered texel `padding` gives each, returning the tiles written +pub fn pad_tiles(out: &mut Composite, padding: &crate::PaddingMaps, tiles: &[(u32, u32)]) -> std::collections::BTreeSet<(u32, u32)> { let mut written = std::collections::BTreeSet::new(); let (w, h) = (out.resolution, out.height); - if (dmap.width, dmap.height) != (w, h) { + if padding.size() != (w, h) { return written; } - let (nx, ny) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64); - let mut set = std::collections::BTreeSet::new(); + // The tiles and their neighbours, which padding reaches into + let (tiles_across, tiles_down) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64); + let mut near_tiles = std::collections::BTreeSet::new(); for &(tx, ty) in tiles { for dy in -1..=1i64 { for dx in -1..=1i64 { let (x, y) = (tx as i64 + dx, ty as i64 + dy); - if x >= 0 && y >= 0 && x < nx && y < ny { - set.insert((x as u32, y as u32)); + if x >= 0 && y >= 0 && x < tiles_across && y < tiles_down { + near_tiles.insert((x as u32, y as u32)); } } } + + // Padding across a seam can continue from this tile into one far away + near_tiles.extend(padding.tiles_crossed_from((tx, ty))); } - let set: Vec<(u32, u32)> = set.into_iter().collect(); - for img in out.channels.values_mut() { + let near_tiles: Vec<(u32, u32)> = near_tiles.into_iter().collect(); + + for (channel, img) in out.channels.iter_mut() { let comps = img.comps(); let src: &TileImage = img; + let across_seams = crate::PaddingMaps::crosses_seams(*channel); // Each tile pads from the original image, so parallel writes stay independent - let padded: Vec<((u32, u32), Vec)> = set + let padded: Vec<((u32, u32), Vec)> = near_tiles .par_iter() .filter_map(|&(tx, ty)| { - let mut data: Option> = None; + let mut padded_tile: Option> = None; for ly in 0..TILE { for lx in 0..TILE { let (x, y) = (tx * TILE + lx, ty * TILE + ly); @@ -4912,24 +5018,25 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)]) continue; } - let Some((sx, sy)) = dmap.source(x, y) else { continue }; + let Some((sx, sy)) = padding.source(across_seams, x, y) else { continue }; + if (sx, sy) == (x, y) { continue; } - let v = src.get(sx, sy); - let d = data.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec)); - let o = (ly * TILE + lx) as usize * comps; - if let Some(px) = d.get_mut(o..o + comps) { - px.copy_from_slice(&v[..comps]); + let source_texel = src.get(sx, sy); + let tile_data = padded_tile.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec)); + let offset = (ly * TILE + lx) as usize * comps; + if let Some(texel) = tile_data.get_mut(offset..offset + comps) { + texel.copy_from_slice(&source_texel[..comps]); } } } - Some(((tx, ty), data?)) + Some(((tx, ty), padded_tile?)) }) .collect(); - for ((tx, ty), d) in padded { - img.set_tile(tx, ty, Some(std::sync::Arc::new(d))); + for ((tx, ty), tile_data) in padded { + img.set_tile(tx, ty, Some(std::sync::Arc::new(tile_data))); written.insert((tx, ty)); } } @@ -5524,6 +5631,17 @@ mod tests { run_with_images(f, preview, &ImageStore::default()) } + #[test] + fn a_mirror_on_a_wide_set_reflects_across_its_own_height() { + let mirror = Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY }; + let (size, near_bottom) = ([256, 128], 120.0); + let read = std::cell::Cell::new(None); + mirror_texel(&mirror, (10.0, near_bottom), (size, size), 4, None, &mut [0.0; 5], &|x, y, _| read.set(Some((x, y)))); + let (x, y) = read.get().unwrap(); + assert_eq!(x, 10.0); + assert!(y < size[1] as f32 / 2.0, "the bottom half copies the top half: read row {y}"); + } + #[test] fn a_mirrored_fill_culls_against_the_mesh_in_each_copy_view() { let mut fixture = fixture(); @@ -5562,6 +5680,52 @@ mod tests { assert!(close(composite.value(Channel::BaseColor, 48, 32), [1.0, 0.0, 0.0]), "the exposed side takes the fill"); } + #[test] + fn a_rectangular_height_filter_tilts_equally_for_equal_uv_slopes() { + let (width, height) = (16, 32); + let texels = (width * height) as usize; + let normals: Vec = [0.5, 0.5, 1.0, 1.0].into_iter().cycle().take(texels * 4).collect(); + let coverage = vec![1.0; texels]; + let heights: Vec<_> = (0..width * height).map(|index| (index % width) as f32 / width as f32 + (index / width) as f32 / height as f32).collect(); + + let normal = gather( + Op::HeightToNormal(HeightToNormal::LIBRARY), + (&normals, &coverage, &heights), + 4, + (0, 0, width, height), + 1.0, + (width, [width, height], [width, height]), + 1.0, + ); + let center = (height / 2 * width + width / 2) as usize * 4; + let (red, green) = (normal[center], normal[center + 1]); + + assert!(red < 0.5 && green > 0.5); + assert!((1.0 - red - green).abs() < 1e-6, "equal UV slopes produced unequal tilt: {red}, {green}"); + } + + #[test] + fn baked_height_slopes_respect_rectangular_udim_blocks() { + let mut fixture = fixture(); + let (block_width, block_height) = (64, 128); + let set = &mut fixture.project.texture_sets[0]; + set.set_size(block_width, block_height); + set.uv_tiles = vec![1001, 1011]; + let (width, height) = set.size(); + fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, width, height); + fixture.baked.resolution = width; + let heights = (0..width * height).map(|i| (i % width) as f32 / block_width as f32 + (i / width % block_height) as f32 / block_height as f32).collect(); + fixture.baked.maps.insert(BakedMap::Height, Arc::new(heights)); + let images = ImageStore::default(); + let inputs = inputs(&fixture, &images, None); + + for y in [block_height - 1, block_height] { + let slope = Texel::new(&inputs, 10, y, 0, 0.0).height_slope(); + + assert_eq!(slope, Some([1.0; 2]), "slope at row {y} must stay within its rectangular tile"); + } + } + #[test] fn baked_height_slopes_stay_within_each_uv_tile() { let mut fixture = fixture(); @@ -6417,12 +6581,61 @@ soft {soft:?}" out.channels.get_mut(&Channel::Roughness).unwrap().set(10, 10, &[to_u16(0.9)]); let mut covered = vec![false; 64 * 64]; covered[10 * 64 + 10] = true; - let dmap = DilationMap::new(&covered, 64, 64, Some(4)); - pad_tiles(&mut out, &dmap, &[(0, 0)]); + let padding = crate::PaddingMaps { + flat: texturecraft_texel::DilationMap::new(&covered, 64, 64, Some(4)), + crossed: Vec::new(), + row_starts: Vec::new(), + crossed_into: Default::default(), + }; + pad_tiles(&mut out, &padding, &[(0, 0)]); assert!((out.value(Channel::Roughness, 12, 12)[0] - 0.9).abs() < 1e-3); assert!(out.value(Channel::Roughness, 30, 30)[0] < 0.1 || !out.channels[&Channel::Roughness].is_allocated(0, 0)); } + /// Two islands of one 3D edge, tiles apart: repainting the far island repads the near island's padding past the seam + #[test] + fn padding_past_a_seam_follows_a_change_to_its_other_side_tiles_away() { + use texturecraft_geom::{UvSeam, UvSeamSide}; + let (width, height) = (8 * TILE, TILE); + let (left, right) = (4..=59u32, 404..=460u32); + let covered: Vec = (0..width * height).map(|i| left.contains(&(i % width)) || right.contains(&(i % width))).collect(); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + let seam = UvSeam { + sides: [ + UvSeamSide { triangle: 0, start: at(60.0, 0.0), end: at(60.0, height as f32), interior: at(4.0, 0.0) }, + UvSeamSide { triangle: 1, start: at(404.0, 0.0), end: at(404.0, height as f32), interior: at(460.0, 0.0) }, + ], + }; + let triangles: Vec<_> = covered + .iter() + .enumerate() + .map(|(pixel, covered)| if *covered { u32::from(pixel % width as usize > 400) } else { texturecraft_geom::NO_TRI }) + .collect(); + let mesh = texturecraft_geom::primitives::plane(1.0, 1); + let partition = texturecraft_geom::TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + let seam_input = crate::SeamPaddingInput::new(vec![seam], &triangles, partition); + + let padding = crate::PaddingMaps::new(texturecraft_core::UvPaddingMode::Space3d, &covered, (width, height), Some(4), (0, 0), Some(&seam_input)); + + let mut out = Composite::with_size(&[Channel::Roughness], width, height); + let paint = |out: &mut Composite, xs: std::ops::RangeInclusive, value: f32| { + for y in 0..height { + for x in xs.clone() { + out.channels.get_mut(&Channel::Roughness).unwrap().set(x, y, &[to_u16(value)]); + } + } + }; + paint(&mut out, left.clone(), 0.2); + paint(&mut out, right.clone(), 0.2); + pad_tiles(&mut out, &padding, &all_tiles(width, height)); + + // Past the left island's seam edge, padding continues from the right island six tiles away + paint(&mut out, right, 0.9); + let written = pad_tiles(&mut out, &padding, &[(404 / TILE, 0)]); + assert!((out.value(Channel::Roughness, 61, 3)[0] - 0.9).abs() < 1e-3, "{:?}", out.value(Channel::Roughness, 61, 3)); + assert!(written.contains(&(0, 0)), "the repadded tile is uploaded: {written:?}"); + } + fn content_fx(f: &mut Fixture, id: LayerId, kind: EffectKind) -> LayerId { let eid = f.project.alloc_id(); f.project.layer_mut(id).unwrap().content_effects.push(Effect::new(eid, kind)); @@ -6662,6 +6875,33 @@ soft {soft:?}" } } + /// A set taller than wide: a mirror or transform reads anywhere down its block, so a tile composited alone near the bottom matches the whole set + #[test] + fn a_tile_alone_on_a_tall_set_reads_a_mirror_or_transform_from_the_far_end() { + const WIDTH: u32 = 64; + const HEIGHT: u32 = 256; + let column_of = |out: &Composite| (HEIGHT - TILE..HEIGHT).map(|y| out.value(Channel::Roughness, 20, y)[0]).collect::>(); + let composite = |filter: &Filter, tiles: &[(u32, u32)]| { + let mut f = fixture(); + f.gbuf = UvGBuffer::new(&f.mesh, 0, WIDTH, HEIGHT); + f.project.texture_sets[0].set_size(WIDTH, HEIGHT); + checker_roughness(&mut f, Some(filter.clone())); + let images = ImageStore::default(); + let mut out = Composite::with_size(&f.project.texture_sets[0].channel_list(), WIDTH, HEIGHT); + composite_tiles(&inputs(&f, &images, None), &mut out, tiles); + column_of(&out) + }; + + let mirror = Filter::Mirror(Mirror { mode: texturecraft_core::MirrorMode::AxisY, ..Mirror::LIBRARY }); + let shift = Filter::Transform(TileTransform { offset: [0.0, 0.25], ..TileTransform::LIBRARY }); + for filter in [mirror, shift] { + let whole = composite(&filter, &all_tiles(WIDTH, HEIGHT)); + let bottom_tile = composite(&filter, &[(0, HEIGHT / TILE - 1)]); + let label = filter.label(); + assert!(whole.iter().zip(&bottom_tile).all(|(a, b)| (a - b).abs() < 1e-3), "{label}: the bottom tile alone\n{bottom_tile:?}\nwhole\n{whole:?}"); + } + } + #[test] fn a_gradients_blur_intensity_blurs_what_it_looks_up() { let row = |filter: Option| { diff --git a/crates/compose/src/field_cache.rs b/crates/compose/src/field_cache.rs index 0f3b99b2..17aa3544 100644 --- a/crates/compose/src/field_cache.rs +++ b/crates/compose/src/field_cache.rs @@ -57,6 +57,7 @@ pub(crate) fn field_identity(inputs: &Inputs) -> u64 { mesh.submeshes.iter().for_each(|part| (part.material, part.start, part.count).hash(&mut hash)); set.uv_tiles.hash(&mut hash); set.resolution.hash(&mut hash); + set.resolution_height.hash(&mut hash); set.tile_resolutions.hash(&mut hash); } diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 32b480e0..62341969 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -10,6 +10,7 @@ pub mod axis_frame; mod baked_maps; pub mod below; +mod channel_store; mod curvature_size_level; pub mod curvature_sizes; pub mod display; @@ -37,6 +38,7 @@ mod mask_gray; mod micro_detail; pub mod mip_level; mod organic; +mod padding_maps; pub mod pattern; mod pattern_context; pub mod projector_cover; @@ -44,6 +46,8 @@ pub mod projector_depth; mod projector_depth_cache; pub mod projector_view; mod sampled_map; +pub mod seam_padding; +mod seam_padding_input; mod sections; mod shape_distance; mod slope_texel; @@ -51,6 +55,7 @@ mod slot_placement; mod soft_box; pub mod solo; pub mod store; +mod texel_edge; mod texture_layer; mod three_d_distance; pub mod thumb; @@ -77,8 +82,10 @@ pub use eval::{ stack_reads_neighbours, }; pub use mask_gray::MaskGray; +pub use padding_maps::PaddingMaps; pub use pattern_context::PatternContext; pub use projector_depth_cache::ProjectorDepthCache; +pub use seam_padding_input::SeamPaddingInput; pub use solo::solo_project; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs new file mode 100644 index 00000000..28c90f27 --- /dev/null +++ b/crates/compose/src/padding_maps.rs @@ -0,0 +1,183 @@ +//! A texture set's UV padding: from island edges, and across seams for the texels past one + +use std::collections::{BTreeMap, BTreeSet}; + +use texturecraft_core::{Channel, ChannelKind, UvPaddingMode}; +use texturecraft_texel::TILE; +use texturecraft_texel::dilate::DilationMap; + +use crate::SeamPaddingInput; +use crate::seam_padding::{SEAM_REACH, cross_seams}; + +/// A texture set's padding: `flat` for every texel, with the few texels past a seam listed apart in `crossed` by row +#[derive(Clone, Debug, PartialEq)] +pub struct PaddingMaps { + /// Padding from island edges (2D), which tangent-space normals always take: a normal turns with its island, so it can't continue across a seam + pub flat: DilationMap, + /// Across seams (3D): (texel, source texel) indices of the padding texels that continue from a seam's other side, sorted by texel + pub crossed: Vec<(u32, u32)>, + /// Where each row's texels start in `crossed`, one more than the rows (empty without any), so a lookup searches one row + pub(crate) row_starts: Vec, + /// For each tile holding a seam's far side, the tiles whose padding continues from it, so a change there repads them however far they are + pub(crate) crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>>, +} + +impl PaddingMaps { + /// The padding for `mode`: `covered` texels of a `width × height` set padded up to `max_dist` texels inside each `block` + pub fn new( + mode: UvPaddingMode, + covered: &[bool], + (width, height): (u32, u32), + max_dist: Option, + block: (u32, u32), + seams: Option<&SeamPaddingInput<'_>>, + ) -> PaddingMaps { + let flat = DilationMap::in_rectangular_blocks(covered, width, height, max_dist, block); + let crossed = seams + .filter(|_| mode == UvPaddingMode::Space3d) + .map_or_else(Vec::new, |seams| cross_seams(&flat, max_dist.map_or(SEAM_REACH, |d| d.min(SEAM_REACH)), block, seams)); + let row_starts = + if crossed.is_empty() { Vec::new() } else { (0..=height).map(|y| crossed.partition_point(|(texel, _)| *texel < y * width) as u32).collect() }; + let tile_of = |texel: u32| ((texel % width) / TILE, (texel / width) / TILE); + let mut crossed_into: BTreeMap<(u32, u32), BTreeSet<(u32, u32)>> = BTreeMap::new(); + for &(texel, source) in &crossed { + crossed_into.entry(tile_of(source)).or_default().insert(tile_of(texel)); + } + PaddingMaps { flat, crossed, row_starts, crossed_into } + } + + /// The tiles whose padding continues across a seam from texels in `tile` + pub fn tiles_crossed_from(&self, tile: (u32, u32)) -> impl Iterator + '_ { + self.crossed_into.get(&tile).into_iter().flatten().copied() + } + + /// Texels across and down + pub fn size(&self) -> (u32, u32) { + (self.flat.width, self.flat.height) + } + + /// Whether `channel` pads across seams; tangent-space normals pad from island edges + pub fn crosses_seams(channel: Channel) -> bool { + channel.kind() != ChannelKind::NormalMap + } + + /// The covered texel padding (x, y), itself when covered; `across_seams` takes the seams' other sides + pub fn source(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> { + let source = self.flat.source(x, y)?; + if !across_seams || source == (x, y) { + return Some(source); + } + + let (texel, width) = (y * self.flat.width + x, self.flat.width); + let row = match (self.row_starts.get(y as usize), self.row_starts.get(y as usize + 1)) { + (Some(&start), Some(&end)) => self.crossed.get(start as usize..end as usize).unwrap_or_default(), + _ => &[], + }; + match row.binary_search_by_key(&texel, |(crossed_texel, _)| *crossed_texel) { + Ok(found) => row.get(found).map(|(_, crossed_source)| (crossed_source % width, crossed_source / width)), + Err(_) => Some(source), + } + } +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::glam::Vec2; + use texturecraft_geom::{NO_TRI, TrianglePartition, UvSeam, UvSeamSide, primitives}; + + use super::*; + + /// Two islands of one 3D edge: the left one's right side is the right one's left side + fn two_islands() -> (Vec, Vec) { + let (width, height) = (32u32, 8u32); + let covered = (0..width * height).map(|i| matches!(i % width, 4..=11 | 20..=27)).collect(); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + let left = UvSeamSide { triangle: 0, start: at(12.0, 0.0), end: at(12.0, 8.0), interior: at(4.0, 0.0) }; + let right = UvSeamSide { triangle: 1, start: at(20.0, 0.0), end: at(20.0, 8.0), interior: at(28.0, 0.0) }; + (covered, vec![UvSeam { sides: [left, right] }]) + } + + fn islands(seams: Vec, triangles: &[u32]) -> SeamPaddingInput<'_> { + // A synthetic raster supplies its island ids directly + let mesh = primitives::plane(1.0, 2); + let partition = TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + SeamPaddingInput::new(seams, triangles, partition) + } + + #[test] + fn a_flat_seam_keeps_the_last_row_within_its_reach() { + let (width, height) = (128, 128); + let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32); + // The length rounds the normalized edge slightly below one + let near = UvSeamSide { triangle: 0, start: at(1.0, 32.5), end: at(16.25, 32.5), interior: at(1.0, 40.0) }; + let far = UvSeamSide { triangle: 1, start: at(65.0, 32.5), end: at(80.25, 32.5), interior: at(65.0, 100.0) }; + let triangles: Vec<_> = (0..width * height) + .map(|index| match (index % width, index / width) { + (1..=15, 32..=39) => 0, + (65..=79, 32..=99) => 1, + _ => NO_TRI, + }) + .collect(); + let covered: Vec<_> = triangles.iter().map(|&triangle| triangle != NO_TRI).collect(); + let seams = islands(vec![UvSeam { sides: [near, far] }], &triangles); + + let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(SEAM_REACH), (64, height), Some(&seams)); + + assert!(padding.source(true, 15, 0).is_some_and(|(x, _)| x >= 64), "the boundary row borrows from the far island"); + assert!(padding.source(false, 15, 0).is_some_and(|(x, _)| x < 64), "flat padding still uses the near island"); + } + + #[test] + fn padding_stops_at_the_far_islands_edge() { + let (_, seams) = two_islands(); + let (width, height) = (32, 8); + for (gap, far_strip) in [(false, 2), (true, 2), (true, 1)] { + let triangles: Vec<_> = (0..width * height) + .map(|pixel| match pixel % width { + 4..=11 => 0, + 20..=21 => 1, + 22 if gap => NO_TRI, + 22..=27 => far_strip, + _ => NO_TRI, + }) + .collect(); + let covered: Vec<_> = triangles.iter().map(|id| *id != NO_TRI).collect(); + let input = islands(seams.clone(), &triangles); + + let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(4), (0, 0), Some(&input)); + + assert_eq!(padding.source(true, 13, 3), Some((21, 3)), "a texel inside the far island continues the seam"); + assert_eq!(padding.source(true, 15, 3), padding.source(false, 15, 3), "another island is out of reach even with no texel gap"); + } + } + + #[test] + fn padding_past_a_seam_continues_from_its_other_side_and_normals_stay_flat() { + let (covered, seams) = two_islands(); + let triangles: Vec<_> = (0..32 * 8) + .map(|pixel| match pixel % 32 { + 4..=11 => 0, + 20..=27 => 1, + _ => NO_TRI, + }) + .collect(); + let input = islands(seams, &triangles); + + let space_3d = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (32, 8), Some(4), (0, 0), Some(&input)); + let space_2d = PaddingMaps::new(UvPaddingMode::Space2d, &covered, (32, 8), Some(4), (0, 0), Some(&input)); + let island = |padding: &PaddingMaps, across_seams: bool, x: u32| { + padding.source(across_seams, x, 3).map(|(source_x, _)| if source_x < 16 { "left" } else { "right" }) + }; + + // Just right of the left island, then just left of the right island + assert_eq!((island(&space_3d, true, 13), island(&space_3d, true, 18)), (Some("right"), Some("left"))); + assert_eq!((island(&space_2d, true, 13), island(&space_2d, true, 18)), (Some("left"), Some("right"))); + assert_eq!((island(&space_3d, false, 13), island(&space_3d, false, 18)), (Some("left"), Some("right"))); + assert!(PaddingMaps::crosses_seams(Channel::BaseColor) && !PaddingMaps::crosses_seams(Channel::Normal)); + + // Away from the seam, both modes pad from the near island, and only texels between the islands are kept apart + assert_eq!(island(&space_3d, true, 2), Some("left")); + assert!(!space_3d.crossed.is_empty() && space_2d.crossed.is_empty()); + assert!(space_3d.crossed.iter().all(|(texel, _)| (12..20).contains(&(texel % 32)))); + } +} diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs new file mode 100644 index 00000000..6707983f --- /dev/null +++ b/crates/compose/src/seam_padding.rs @@ -0,0 +1,153 @@ +//! UV padding across seams (3D): texels past a UV seam continue the surface from the seam's other side + +use std::collections::HashMap; + +use texturecraft_geom::glam::{IVec2, Vec2}; +use texturecraft_texel::dilate::{DilationMap, NONE}; + +use crate::SeamPaddingInput; +use crate::texel_edge::TexelEdge; + +/// Farthest a padding texel reaches across a seam, in texels; farther ones keep their nearest covered texel +pub const SEAM_REACH: u32 = 32; + +/// The padding texels of `flat` just outside a seam, each with the texel as far inside the seam's other side: (texel, source) indices sorted by texel +pub(crate) fn cross_seams(flat: &DilationMap, reach: u32, block: (u32, u32), input: &SeamPaddingInput<'_>) -> Vec<(u32, u32)> { + let (width, height) = (flat.width, flat.height); + let size = Vec2::new(width as f32, height as f32); + let block_of = |x: u32, y: u32| (x.checked_div(block.0).unwrap_or(0), y.checked_div(block.1).unwrap_or(0)); + + // Each crossed texel's source and how far outside its seam it is; a nearer seam replaces it + let mut crossed: HashMap = HashMap::new(); + for seam in &input.seams { + for (near, far) in [(seam.sides[0], seam.sides[1]), (seam.sides[1], seam.sides[0])] { + let (Some(near_edge), Some(far_edge)) = (TexelEdge::new(near, size), TexelEdge::new(far, size)) else { + continue; + }; + + let reach = reach as f32; + let low = near_edge.start.min(near_edge.end) - Vec2::splat(reach); + let high = near_edge.start.max(near_edge.end) + Vec2::splat(reach); + let (x0, y0) = (low.x.floor().max(0.0) as u32, low.y.floor().max(0.0) as u32); + let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32); + let mut side_islands = None; + for y in y0..y1 { + for x in near_edge.outside_columns(y, x0..x1, reach) { + let index = y * width + x; + let Some(&flat_source) = flat.src.get(index as usize) else { continue }; + + if flat_source == NONE || flat_source == index { + continue; + } + + let point = Vec2::new(x as f32 + 0.5, y as f32 + 0.5); + let Some((along, outside)) = near_edge.outside(point) else { continue }; + + if outside > reach || crossed.get(&index).is_some_and(|(_, distance)| outside >= *distance) { + continue; + } + + // Another island's edge nearer than the seam keeps its texel + let (source_x, source_y) = (flat_source % width, flat_source / width); + if (source_x.abs_diff(x).max(source_y.abs_diff(y)) as f32) + 1.0 < outside { + continue; + } + + // Padding stays inside its UV tile, like the 2D padding + let inside = near_edge.start.lerp(near_edge.end, along) + near_edge.inward * 0.5; + if block_of(inside.x.max(0.0) as u32, inside.y.max(0.0) as u32) != block_of(x, y) { + continue; + } + + // Start at the first texel centres on the seam's far side + let far_boundary = far_edge.start.lerp(far_edge.end, along); + let start = far_boundary + far_edge.inward * 0.5; + let target = far_boundary + far_edge.inward * outside.max(0.5); + if target.x < 0.0 || target.y < 0.0 || target.x >= size.x || target.y >= size.y { + continue; + } + + let target_index = target.y as u32 * width + target.x as u32; + if flat.src.get(target_index as usize) != Some(&target_index) { + continue; + } + + let (Some(near_island), Some(far_island)) = + *side_islands.get_or_insert_with(|| (input.triangle_island(near.triangle), input.triangle_island(far.triangle))) + else { + continue; + }; + + if input.island_at(flat_source) != Some(near_island) { + continue; + } + + if input.island_at(target_index) == Some(far_island) && follows_island(input, start, target, far_island, (width, height), block) { + crossed.insert(index, (target_index, outside)); + } + } + } + } + } + + let mut sources: Vec<(u32, u32)> = crossed.into_iter().map(|(texel, (source, _))| (texel, source)).collect(); + sources.sort_unstable(); + sources +} + +fn follows_island(input: &SeamPaddingInput<'_>, start: Vec2, target: Vec2, island: usize, (width, height): (u32, u32), block: (u32, u32)) -> bool { + let mut cell = start.floor().as_ivec2(); + let end = target.floor().as_ivec2(); + let limit = IVec2::new(width as i32, height as i32); + if cell.cmplt(IVec2::ZERO).any() || cell.cmpge(limit).any() { + return false; + } + + if block.0 != 0 && block.1 != 0 { + let block = IVec2::new(block.0 as i32, block.1 as i32); + if cell / block != end / block { + return false; + } + } + + let step = (end - cell).signum(); + let delta = (target - start).abs(); + let step_time = Vec2::new(1.0 / delta.x, 1.0 / delta.y); + let boundary_time = |axis: usize| { + if step[axis] == 0 { + return f32::INFINITY; + } + + let boundary = cell[axis] + i32::from(step[axis] > 0); + (boundary as f32 - start[axis]).abs() * step_time[axis] + }; + let mut next = Vec2::new(boundary_time(0), boundary_time(1)); + + // Visit every texel with a nonzero stretch of the path + let mut last_triangle = None; + loop { + let Some(triangle) = input.triangle_at(cell.y as u32 * width + cell.x as u32) else { return false }; + + if Some(triangle) != last_triangle { + if input.triangle_island(triangle) != Some(island) { + return false; + } + + last_triangle = Some(triangle); + } + + if cell == end { + return true; + } + + let time = next.x.min(next.y); + if next.x == time { + cell.x += step.x; + next.x = if cell.x == end.x { f32::INFINITY } else { next.x + step_time.x }; + } + if next.y == time { + cell.y += step.y; + next.y = if cell.y == end.y { f32::INFINITY } else { next.y + step_time.y }; + } + } +} diff --git a/crates/compose/src/seam_padding_input.rs b/crates/compose/src/seam_padding_input.rs new file mode 100644 index 00000000..cfb2a9fb --- /dev/null +++ b/crates/compose/src/seam_padding_input.rs @@ -0,0 +1,41 @@ +use std::sync::OnceLock; + +use texturecraft_geom::{Mesh, TrianglePartition, UvSeam}; + +/// Seams and the UV island of each rasterized triangle, borrowing the existing texel-to-triangle grid +pub struct SeamPaddingInput<'a> { + pub(crate) seams: Vec, + triangles: &'a [u32], + material: Option<(&'a Mesh, usize)>, + islands: OnceLock, +} + +impl<'a> SeamPaddingInput<'a> { + /// Use seams and a partition from the same mesh and material as the rasterized triangles + pub fn new(seams: Vec, triangles: &'a [u32], islands: TrianglePartition) -> Self { + Self { seams, triangles, material: None, islands: OnceLock::from(islands) } + } + + /// Find seams now and build island ownership only if a padding texel can cross + pub fn of_material(mesh: &'a Mesh, material: usize, triangles: &'a [u32]) -> Option { + let seams = UvSeam::of_material(mesh, material); + if seams.is_empty() { + return None; + } + + Some(Self { seams, triangles, material: Some((mesh, material)), islands: OnceLock::new() }) + } + + pub(crate) fn triangle_island(&self, triangle: u32) -> Option { + let islands = self.islands.get().or_else(|| self.material.map(|(mesh, material)| self.islands.get_or_init(|| UvSeam::islands_of(mesh, material))))?; + islands.index_of(triangle) + } + + pub(crate) fn triangle_at(&self, texel: u32) -> Option { + self.triangles.get(texel as usize).copied() + } + + pub(crate) fn island_at(&self, texel: u32) -> Option { + self.triangle_island(self.triangle_at(texel)?) + } +} diff --git a/crates/compose/src/texel_edge.rs b/crates/compose/src/texel_edge.rs new file mode 100644 index 00000000..30a5e687 --- /dev/null +++ b/crates/compose/src/texel_edge.rs @@ -0,0 +1,103 @@ +//! A UV seam side in texel space + +use std::ops::Range; + +use texturecraft_geom::UvSeamSide; +use texturecraft_geom::glam::Vec2; + +/// A seam side in texel space, with its unit normal into the island +pub(crate) struct TexelEdge { + pub(crate) start: Vec2, + pub(crate) end: Vec2, + pub(crate) inward: Vec2, +} + +impl TexelEdge { + pub(crate) fn new(side: UvSeamSide, size: Vec2) -> Option { + let (start, end, interior) = (side.start * size, side.end * size, side.interior * size); + let normal = (end - start).perp().try_normalize()?; + let inward = if normal.dot(interior - start) < 0.0 { -normal } else { normal }; + Some(TexelEdge { start, end, inward }) + } + + /// How far along the edge (0..1) and how far outside the island `point` is, when it is beside the edge on the outside + pub(crate) fn outside(&self, point: Vec2) -> Option<(f32, f32)> { + let direction = self.end - self.start; + let along = (point - self.start).dot(direction) / direction.length_squared(); + let outside = self.outside_distance(point); + ((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside)) + } + + fn outside_distance(&self, point: Vec2) -> f32 { + -(point - self.start).dot(self.inward) + } + + /// Clip columns to the exterior distance band using the same rounded distances as `outside` + pub(crate) fn outside_columns(&self, row: u32, columns: Range, reach: f32) -> Range { + if columns.is_empty() { + return columns; + } + + let distance = |column| self.outside_distance(Vec2::new(column as f32 + 0.5, row as f32 + 0.5)); + if self.inward.x == 0.0 { + let outside = distance(columns.start); + return if outside > 0.0 && outside <= reach { columns } else { 0..0 }; + } + + // Signed distance is monotone across a row even when adjacent values round to the same distance + let (start, end) = if self.inward.x < 0.0 { + let start = first_column_after(columns.clone(), |column| distance(column) <= 0.0); + (start, first_column_after(start..columns.end, |column| distance(column) <= reach)) + } else { + let start = first_column_after(columns.clone(), |column| distance(column) > reach); + (start, first_column_after(start..columns.end, |column| distance(column) > 0.0)) + }; + start..end + } +} + +fn first_column_after(mut columns: Range, before: impl Fn(u32) -> bool) -> u32 { + while columns.start < columns.end { + let middle = columns.start.midpoint(columns.end); + if before(middle) { + columns.start = middle + 1; + } else { + columns.end = middle; + } + } + + columns.start +} + +#[cfg(test)] +mod tests { + use texturecraft_geom::UvSeamSide; + use texturecraft_geom::glam::Vec2; + + use super::TexelEdge; + + #[test] + fn a_diagonal_edges_band_spans_every_texel_beside_it_without_scanning_the_rectangle() { + let size = Vec2::splat(512.0); + let side = UvSeamSide { triangle: 0, start: Vec2::new(0.05, 0.05), end: Vec2::new(0.95, 0.9), interior: Vec2::new(0.9, 0.1) }; + let edge = TexelEdge::new(side, size).unwrap(); + let reach = 32.0; + + let (mut beside, mut spanned) = (0, 0); + for y in 0..512u32 { + let centre_y = y as f32 + 0.5; + let span = edge.outside_columns(y, 0..512, reach); + spanned += span.len(); + for x in 0..512 { + let point = Vec2::new(x as f32 + 0.5, centre_y); + if edge.outside(point).is_some_and(|(_, outside)| outside <= reach) { + beside += 1; + assert!(span.contains(&x), "{point} is beside the edge but outside its row's span {span:?}"); + } + } + } + + // The diagonal's bounding box holds far more texels than its band + assert!(beside > 0 && spanned < 512 * 512 / 4, "{spanned} texels spanned for {beside} beside the edge"); + } +} diff --git a/crates/core/src/channel.rs b/crates/core/src/channel.rs index eb7b3918..28f7d6d6 100644 --- a/crates/core/src/channel.rs +++ b/crates/core/src/channel.rs @@ -39,6 +39,77 @@ pub enum Channel { Transmission, /// Tangent-space normal of the clear coat (relative to the mesh normal). CoatNormal, + /// How much of the base layer shows (stored and exported: our shader does not read it) + BaseWeight, + /// Roughness of the diffuse base (stored and exported: our shader does not read it) + BaseDiffuseRoughness, + /// Strength of the specular lobe (stored and exported: our shader does not read it) + SpecularWeight, + /// Tint of the specular lobe (stored and exported: our shader does not read it) + SpecularColor, + /// Tint of transmitted light (stored and exported: our shader does not read it) + TransmissionColor, + /// Subsurface scattering color (stored and exported: our shader does not read it) + SubsurfaceColor, + /// Scattering distance per color (stored and exported: our shader does not read it) + SubsurfaceRadiusScale, + /// Clear coat tint (stored and exported: our shader does not read it) + CoatColor, + /// Clear coat anisotropy (stored and exported: our shader does not read it) + CoatAnisotropy, + /// Clear coat reflectance (stored and exported: our shader does not read it) + CoatSpecularLevel, + /// Tangent-space direction of the clear coat anisotropy, packed like a normal (stored and exported: our shader does not read it) + CoatTangent, + /// Thin-film iridescence weight (stored and exported: our shader does not read it) + ThinFilmWeight, + /// Tangent-space anisotropy direction, packed like a normal (stored and exported: our shader does not read it) + Tangent, + /// Mask for blending materials in an engine (stored and exported only) + BlendingMask, + /// Diffuse color of older shaders (stored and exported only) + Diffuse, + /// Signed displacement for render engines (stored and exported only) + Displacement, + /// Index of refraction, 0..1 as the target shader maps it (stored and exported only) + Ior, + /// Reflection amount of older shaders (stored and exported only) + Reflection, + /// Transmissive color of older shaders (stored and exported only) + Transmissive, + /// Free channels for anything a target shader needs (grey, stored and exported) + User0, + User1, + User2, + User3, + User4, + User5, + User6, + User7, + User8, + User9, + User10, + User11, + User12, + User13, + User14, + User15, + User16, + User17, + User18, + User19, + User20, + User21, + User22, + User23, + User24, + User25, + User26, + User27, + User28, + User29, + User30, + User31, } /// How a channel's values are stored and interpreted. @@ -55,7 +126,7 @@ pub enum ChannelKind { } impl Channel { - pub const ALL: [Channel; 21] = [ + pub const ALL: [Channel; 72] = [ Channel::BaseColor, Channel::Metallic, Channel::Roughness, @@ -77,8 +148,62 @@ impl Channel { Channel::ScatterWeight, Channel::Transmission, Channel::CoatNormal, + Channel::BaseWeight, + Channel::BaseDiffuseRoughness, + Channel::SpecularWeight, + Channel::SpecularColor, + Channel::TransmissionColor, + Channel::SubsurfaceColor, + Channel::SubsurfaceRadiusScale, + Channel::CoatColor, + Channel::CoatAnisotropy, + Channel::CoatSpecularLevel, + Channel::CoatTangent, + Channel::ThinFilmWeight, + Channel::Tangent, + Channel::BlendingMask, + Channel::Diffuse, + Channel::Displacement, + Channel::Ior, + Channel::Reflection, + Channel::Transmissive, + Channel::User0, + Channel::User1, + Channel::User2, + Channel::User3, + Channel::User4, + Channel::User5, + Channel::User6, + Channel::User7, + Channel::User8, + Channel::User9, + Channel::User10, + Channel::User11, + Channel::User12, + Channel::User13, + Channel::User14, + Channel::User15, + Channel::User16, + Channel::User17, + Channel::User18, + Channel::User19, + Channel::User20, + Channel::User21, + Channel::User22, + Channel::User23, + Channel::User24, + Channel::User25, + Channel::User26, + Channel::User27, + Channel::User28, + Channel::User29, + Channel::User30, + Channel::User31, ]; + /// How many channels, from the start of [`Channel::ALL`], our shader reads + pub const SHADED_COUNT: usize = 21; + /// The extra shading lobes (clear coat, sheen, anisotropy, subsurface scattering, /// transmission). Their defaults switch the lobes off, so a set without them shades exactly /// as before. @@ -101,8 +226,15 @@ impl Channel { pub fn kind(self) -> ChannelKind { match self { Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => ChannelKind::Color, - Channel::Normal | Channel::CoatNormal => ChannelKind::NormalMap, - Channel::Height => ChannelKind::Signed, + Channel::SpecularColor + | Channel::TransmissionColor + | Channel::SubsurfaceColor + | Channel::SubsurfaceRadiusScale + | Channel::CoatColor + | Channel::Diffuse + | Channel::Transmissive => ChannelKind::Color, + Channel::Normal | Channel::CoatNormal | Channel::Tangent | Channel::CoatTangent => ChannelKind::NormalMap, + Channel::Height | Channel::Displacement => ChannelKind::Signed, _ => ChannelKind::Scalar, } } @@ -133,8 +265,53 @@ impl Channel { Channel::Normal | Channel::CoatNormal => [0.5, 0.5, 1.0], Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3], Channel::SpecularLevel | Channel::Glossiness => [0.5; 3], - // F0 of a common dielectric (4 %). + + // F0 of a common dielectric (4 %) Channel::Specular => [0.04; 3], + Channel::BaseWeight | Channel::SpecularWeight | Channel::SpecularColor | Channel::TransmissionColor | Channel::CoatColor => [1.0; 3], + Channel::BaseDiffuseRoughness + | Channel::CoatAnisotropy + | Channel::ThinFilmWeight + | Channel::BlendingMask + | Channel::Displacement + | Channel::Reflection + | Channel::Transmissive => [0.0; 3], + Channel::SubsurfaceColor => [0.8; 3], + Channel::SubsurfaceRadiusScale => [1.0, 0.5, 0.25], + Channel::CoatSpecularLevel | Channel::Diffuse | Channel::Ior => [0.5; 3], + Channel::CoatTangent | Channel::Tangent => [1.0, 0.5, 0.5], + Channel::User0 + | Channel::User1 + | Channel::User2 + | Channel::User3 + | Channel::User4 + | Channel::User5 + | Channel::User6 + | Channel::User7 + | Channel::User8 + | Channel::User9 + | Channel::User10 + | Channel::User11 + | Channel::User12 + | Channel::User13 + | Channel::User14 + | Channel::User15 + | Channel::User16 + | Channel::User17 + | Channel::User18 + | Channel::User19 + | Channel::User20 + | Channel::User21 + | Channel::User22 + | Channel::User23 + | Channel::User24 + | Channel::User25 + | Channel::User26 + | Channel::User27 + | Channel::User28 + | Channel::User29 + | Channel::User30 + | Channel::User31 => [0.0; 3], } } @@ -161,6 +338,57 @@ impl Channel { Channel::ScatterWeight => "Scattering weight", Channel::Transmission => "Transmission", Channel::CoatNormal => "Coat normal", + Channel::BaseWeight => "Base weight", + Channel::BaseDiffuseRoughness => "Base diffuse roughness", + Channel::SpecularWeight => "Specular weight", + Channel::SpecularColor => "Specular color", + Channel::TransmissionColor => "Transmission color", + Channel::SubsurfaceColor => "Subsurface color", + Channel::SubsurfaceRadiusScale => "Subsurface radius scale", + Channel::CoatColor => "Coat color", + Channel::CoatAnisotropy => "Coat anisotropy", + Channel::CoatSpecularLevel => "Coat specular level", + Channel::CoatTangent => "Coat tangent", + Channel::ThinFilmWeight => "Thin-film weight", + Channel::Tangent => "Tangent", + Channel::BlendingMask => "Blending mask", + Channel::Diffuse => "Diffuse", + Channel::Displacement => "Displacement", + Channel::Ior => "Ior", + Channel::Reflection => "Reflection", + Channel::Transmissive => "Transmissive", + Channel::User0 => "User0", + Channel::User1 => "User1", + Channel::User2 => "User2", + Channel::User3 => "User3", + Channel::User4 => "User4", + Channel::User5 => "User5", + Channel::User6 => "User6", + Channel::User7 => "User7", + Channel::User8 => "User8", + Channel::User9 => "User9", + Channel::User10 => "User10", + Channel::User11 => "User11", + Channel::User12 => "User12", + Channel::User13 => "User13", + Channel::User14 => "User14", + Channel::User15 => "User15", + Channel::User16 => "User16", + Channel::User17 => "User17", + Channel::User18 => "User18", + Channel::User19 => "User19", + Channel::User20 => "User20", + Channel::User21 => "User21", + Channel::User22 => "User22", + Channel::User23 => "User23", + Channel::User24 => "User24", + Channel::User25 => "User25", + Channel::User26 => "User26", + Channel::User27 => "User27", + Channel::User28 => "User28", + Channel::User29 => "User29", + Channel::User30 => "User30", + Channel::User31 => "User31", } } @@ -188,6 +416,57 @@ impl Channel { Channel::ScatterWeight => "scatter", Channel::Transmission => "transm", Channel::CoatNormal => "coat nrm", + Channel::BaseWeight => "base weight", + Channel::BaseDiffuseRoughness => "diffuse rough", + Channel::SpecularWeight => "spec weight", + Channel::SpecularColor => "spec color", + Channel::TransmissionColor => "transm color", + Channel::SubsurfaceColor => "sss color", + Channel::SubsurfaceRadiusScale => "sss radius", + Channel::CoatColor => "coat color", + Channel::CoatAnisotropy => "coat aniso", + Channel::CoatSpecularLevel => "coat spec", + Channel::CoatTangent => "coat tangent", + Channel::ThinFilmWeight => "thin film", + Channel::Tangent => "tangent", + Channel::BlendingMask => "blend mask", + Channel::Diffuse => "diffuse", + Channel::Displacement => "displace", + Channel::Ior => "ior", + Channel::Reflection => "reflection", + Channel::Transmissive => "transmissive", + Channel::User0 => "user0", + Channel::User1 => "user1", + Channel::User2 => "user2", + Channel::User3 => "user3", + Channel::User4 => "user4", + Channel::User5 => "user5", + Channel::User6 => "user6", + Channel::User7 => "user7", + Channel::User8 => "user8", + Channel::User9 => "user9", + Channel::User10 => "user10", + Channel::User11 => "user11", + Channel::User12 => "user12", + Channel::User13 => "user13", + Channel::User14 => "user14", + Channel::User15 => "user15", + Channel::User16 => "user16", + Channel::User17 => "user17", + Channel::User18 => "user18", + Channel::User19 => "user19", + Channel::User20 => "user20", + Channel::User21 => "user21", + Channel::User22 => "user22", + Channel::User23 => "user23", + Channel::User24 => "user24", + Channel::User25 => "user25", + Channel::User26 => "user26", + Channel::User27 => "user27", + Channel::User28 => "user28", + Channel::User29 => "user29", + Channel::User30 => "user30", + Channel::User31 => "user31", } } @@ -215,18 +494,84 @@ impl Channel { Channel::ScatterWeight => "scatterWeight", Channel::Transmission => "transmission", Channel::CoatNormal => "coatNormal", + Channel::BaseWeight => "baseWeight", + Channel::BaseDiffuseRoughness => "baseDiffuseRoughness", + Channel::SpecularWeight => "specularWeight", + Channel::SpecularColor => "specularColor", + Channel::TransmissionColor => "transmissionColor", + Channel::SubsurfaceColor => "subsurfaceColor", + Channel::SubsurfaceRadiusScale => "subsurfaceRadiusScale", + Channel::CoatColor => "coatColor", + Channel::CoatAnisotropy => "coatAnisotropy", + Channel::CoatSpecularLevel => "coatSpecularLevel", + Channel::CoatTangent => "coatTangent", + Channel::ThinFilmWeight => "thinFilmWeight", + Channel::Tangent => "tangent", + Channel::BlendingMask => "blendingMask", + Channel::Diffuse => "diffuse", + Channel::Displacement => "displacement", + Channel::Ior => "ior", + Channel::Reflection => "reflection", + Channel::Transmissive => "transmissive", + Channel::User0 => "user0", + Channel::User1 => "user1", + Channel::User2 => "user2", + Channel::User3 => "user3", + Channel::User4 => "user4", + Channel::User5 => "user5", + Channel::User6 => "user6", + Channel::User7 => "user7", + Channel::User8 => "user8", + Channel::User9 => "user9", + Channel::User10 => "user10", + Channel::User11 => "user11", + Channel::User12 => "user12", + Channel::User13 => "user13", + Channel::User14 => "user14", + Channel::User15 => "user15", + Channel::User16 => "user16", + Channel::User17 => "user17", + Channel::User18 => "user18", + Channel::User19 => "user19", + Channel::User20 => "user20", + Channel::User21 => "user21", + Channel::User22 => "user22", + Channel::User23 => "user23", + Channel::User24 => "user24", + Channel::User25 => "user25", + Channel::User26 => "user26", + Channel::User27 => "user27", + Channel::User28 => "user28", + Channel::User29 => "user29", + Channel::User30 => "user30", + Channel::User31 => "user31", } } - /// Parse an id, label or short label (case-insensitive, spaces/underscores ignored). + /// Parse an id, label or short label, ignoring case, spaces, underscores and hyphens. pub fn parse(s: &str) -> Option { - let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], ""); - let want = norm(s); - Channel::ALL.into_iter().find(|c| norm(c.id()) == want || norm(c.label()) == want || norm(c.short()) == want || norm(&format!("{c:?}")) == want) + if let Some(channel) = Channel::ALL.into_iter().find(|channel| channel.id().eq_ignore_ascii_case(s)) { + return Some(channel); + } + + let normalize = |name: &str| name.to_ascii_lowercase().replace([' ', '_', '-'], ""); + let wanted = normalize(s); + Channel::ALL.into_iter().find(|channel| { + normalize(channel.id()) == wanted + || normalize(channel.label()) == wanted + || normalize(channel.short()) == wanted + || normalize(&format!("{channel:?}")) == wanted + }) } + /// Position in [`Channel::ALL`] (the declaration order) pub fn index(self) -> usize { - Channel::ALL.iter().position(|c| *c == self).unwrap_or(0) + self as usize + } + + /// Whether our shader reads the channel; the others are stored and exported for other shaders + pub fn is_shaded(self) -> bool { + self.index() < Channel::SHADED_COUNT } } @@ -253,6 +598,39 @@ impl ChannelFormat { ChannelKind::Signed => ChannelFormat::L16F, } } + + /// Every format, in the order the channel settings list them + pub const ALL: [ChannelFormat; 9] = [ + ChannelFormat::Srgb8, + ChannelFormat::L8, + ChannelFormat::Rgb8, + ChannelFormat::L16, + ChannelFormat::Rgb16, + ChannelFormat::L16F, + ChannelFormat::Rgb16F, + ChannelFormat::L32F, + ChannelFormat::Rgb32F, + ]; + + /// A format by its label, ignoring case ("srgb8", "L16F") + pub fn parse(label: &str) -> Option { + ChannelFormat::ALL.into_iter().find(|format| format.label().eq_ignore_ascii_case(label.trim())) + } + + /// Grey formats keep one value per texel: a colour channel stored in one turns grey + pub fn is_grey(self) -> bool { + matches!(self, ChannelFormat::L8 | ChannelFormat::L16 | ChannelFormat::L16F | ChannelFormat::L32F) + } + + /// The 16-bit format holding everything an 8-bit one does (itself for the others) + pub fn at_least_16_bit(self) -> ChannelFormat { + match self { + ChannelFormat::Srgb8 | ChannelFormat::Rgb8 => ChannelFormat::Rgb16, + ChannelFormat::L8 => ChannelFormat::L16, + other => other, + } + } + pub fn label(self) -> &'static str { match self { ChannelFormat::Srgb8 => "sRGB8", @@ -279,6 +657,7 @@ mod tests { assert_eq!(Channel::parse(c.label()), Some(c)); assert_eq!(Channel::parse(c.short()), Some(c)); } + assert_eq!(Channel::parse("base color"), Some(Channel::BaseColor)); assert_eq!(Channel::parse("nope"), None); } @@ -293,17 +672,44 @@ mod tests { assert!(prev.is_none_or(|p| p == c), "`{name}` names both {prev:?} and {c:?}"); } } + for c in Channel::LOBES { assert!(Channel::ALL.contains(&c)); - // Tints, roughnesses and the flat coat normal only matter once their lobe has weight. + + // Tints, roughnesses and the flat coat normal only matter once their lobe has weight let off = matches!(c, Channel::CoatRoughness | Channel::SheenColor | Channel::SheenRoughness | Channel::CoatNormal) || c.default_value() == [0.0; 3]; assert!(off, "{c:?} must default to an inactive lobe"); } + assert_eq!(Channel::parse("sheen color"), Some(Channel::SheenColor)); assert_eq!(Channel::parse("coatWeight"), Some(Channel::CoatWeight)); } + #[test] + fn formats_parse_by_label() { + for f in ChannelFormat::ALL { + assert_eq!(ChannelFormat::parse(&f.label().to_lowercase()), Some(f)); + assert!(f.at_least_16_bit().is_grey() == f.is_grey()); + } + + assert_eq!(ChannelFormat::parse("RGB4"), None); + } + + #[test] + fn unshaded_channels_round_trip_through_ids() { + // Project files and commands name channels by id: every added channel must come back as itself + for c in Channel::ALL.into_iter().filter(|c| !c.is_shaded()) { + assert_eq!(Channel::parse(c.id()), Some(c)); + let json = serde_json::to_string(&c).unwrap_or_default(); + assert_eq!(serde_json::from_str::(&json).ok(), Some(c)); + } + + assert!(Channel::LOBES.iter().chain(&Channel::DEFAULT_SET).all(|c| c.is_shaded())); + assert_eq!(Channel::parse("User31"), Some(Channel::User31)); + assert_eq!(Channel::parse("thin-film weight"), Some(Channel::ThinFilmWeight)); + } + #[test] fn index_matches_all_order() { for (i, c) in Channel::ALL.iter().enumerate() { diff --git a/crates/core/src/channel_group.rs b/crates/core/src/channel_group.rs new file mode 100644 index 00000000..99a1ec76 --- /dev/null +++ b/crates/core/src/channel_group.rs @@ -0,0 +1,119 @@ +//! The groups the channel manager lists material channels under + +use crate::Channel; + +/// A group of material channels, in the manager's reading order +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChannelGroup { + Base, + Specular, + Transmission, + Subsurface, + Coat, + Sheen, + Emission, + ThinFilm, + Geometry, + Miscellaneous, + User, +} + +impl ChannelGroup { + pub const ALL: [ChannelGroup; 11] = [ + ChannelGroup::Base, + ChannelGroup::Specular, + ChannelGroup::Transmission, + ChannelGroup::Subsurface, + ChannelGroup::Coat, + ChannelGroup::Sheen, + ChannelGroup::Emission, + ChannelGroup::ThinFilm, + ChannelGroup::Geometry, + ChannelGroup::Miscellaneous, + ChannelGroup::User, + ]; + + pub fn label(self) -> &'static str { + match self { + ChannelGroup::Base => "Base", + ChannelGroup::Specular => "Specular", + ChannelGroup::Transmission => "Transmission", + ChannelGroup::Subsurface => "Subsurface", + ChannelGroup::Coat => "Coat", + ChannelGroup::Sheen => "Fuzz / Sheen", + ChannelGroup::Emission => "Emission", + ChannelGroup::ThinFilm => "Thin-film", + ChannelGroup::Geometry => "Geometry", + ChannelGroup::Miscellaneous => "Miscellaneous", + ChannelGroup::User => "User", + } + } + + /// The group's channels, in the order the manager lists them + pub fn channels(self) -> &'static [Channel] { + use Channel as C; + match self { + ChannelGroup::Base => &[C::BaseWeight, C::BaseColor, C::BaseDiffuseRoughness, C::Metallic], + ChannelGroup::Specular => &[C::SpecularWeight, C::SpecularColor, C::Roughness, C::SpecularLevel, C::AnisotropyLevel, C::AnisotropyAngle], + ChannelGroup::Transmission => &[C::Transmission, C::TransmissionColor], + ChannelGroup::Subsurface => &[C::ScatterWeight, C::SubsurfaceColor, C::SubsurfaceRadiusScale], + ChannelGroup::Coat => &[C::CoatWeight, C::CoatColor, C::CoatRoughness, C::CoatAnisotropy, C::CoatSpecularLevel, C::CoatNormal, C::CoatTangent], + ChannelGroup::Sheen => &[C::SheenWeight, C::SheenColor, C::SheenRoughness], + ChannelGroup::Emission => &[C::Emissive], + ChannelGroup::ThinFilm => &[C::ThinFilmWeight], + ChannelGroup::Geometry => &[C::Opacity, C::Normal, C::Height, C::AmbientOcclusion, C::Tangent], + ChannelGroup::Miscellaneous => &[C::BlendingMask, C::Diffuse, C::Displacement, C::Ior, C::Reflection, C::Specular, C::Glossiness, C::Transmissive], + ChannelGroup::User => &[ + C::User0, + C::User1, + C::User2, + C::User3, + C::User4, + C::User5, + C::User6, + C::User7, + C::User8, + C::User9, + C::User10, + C::User11, + C::User12, + C::User13, + C::User14, + C::User15, + C::User16, + C::User17, + C::User18, + C::User19, + C::User20, + C::User21, + C::User22, + C::User23, + C::User24, + C::User25, + C::User26, + C::User27, + C::User28, + C::User29, + C::User30, + C::User31, + ], + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_channel_is_listed_in_exactly_one_group() { + // A channel added to `Channel` but left out here could never be added from the manager + let mut listed: Vec = ChannelGroup::ALL.iter().flat_map(|group| group.channels().iter().copied()).collect(); + let count = listed.len(); + listed.sort(); + listed.dedup(); + + assert_eq!(listed.len(), count, "a channel is listed twice"); + assert_eq!(listed, Channel::ALL.to_vec()); + } +} diff --git a/crates/core/src/height_to_normal.rs b/crates/core/src/height_to_normal.rs index f88caedf..e3ca2f89 100644 --- a/crates/core/src/height_to_normal.rs +++ b/crates/core/src/height_to_normal.rs @@ -53,9 +53,14 @@ impl HeightToNormal { } /// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down - pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] { - let strength = self.strength(res); - let (x, y) = (-gx * strength, gy * strength); + pub fn normal(&self, slope: [f32; 2], res: u32) -> [f32; 3] { + self.normal_for_size(slope, [res; 2]) + } + + /// The same tangent-space normal for a UV tile with independent width and height + pub fn normal_for_size(&self, [gx, gy]: [f32; 2], [width, height]: [u32; 2]) -> [f32; 3] { + let strength_per_uv = self.strength(1); + let (x, y) = (-gx * (strength_per_uv * width as f32), gy * (strength_per_uv * height as f32)); let length = (x * x + y * y + 1.0).sqrt(); if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] } } diff --git a/crates/core/src/height_to_normal_method.rs b/crates/core/src/height_to_normal_method.rs new file mode 100644 index 00000000..a1784deb --- /dev/null +++ b/crates/core/src/height_to_normal_method.rs @@ -0,0 +1,48 @@ +//! How a texture set turns its Height into normal slopes + +use serde::{Deserialize, Serialize}; + +/// Height to normal method: the slope filter a texture set's height-to-normal uses +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum HeightToNormalMethod { + /// Sharp: the difference of the two neighbours across, so single-texel detail stays crisp + Sharp, + /// Smooth (Sobel): a 3×3 Sobel filter, so the slope also reads the diagonal neighbours + #[default] + Smooth, +} + +impl HeightToNormalMethod { + pub const ALL: [HeightToNormalMethod; 2] = [HeightToNormalMethod::Sharp, HeightToNormalMethod::Smooth]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + HeightToNormalMethod::Sharp => "sharp", + HeightToNormalMethod::Smooth => "smooth", + } + } + + pub fn parse(id: &str) -> Option { + HeightToNormalMethod::ALL.into_iter().find(|value| value.id() == id) + } + + /// The change of height per texel to the right and down, from the heights `h(dx, dy)` around a texel + pub fn slope(self, h: impl Fn(i32, i32) -> f32) -> [f32; 2] { + match self { + HeightToNormalMethod::Sharp => [(h(1, 0) - h(-1, 0)) * 0.5, (h(0, 1) - h(0, -1)) * 0.5], + HeightToNormalMethod::Smooth => { + // Both axes read the same four corner heights + let upper_left = h(-1, -1); + let upper_right = h(1, -1); + let lower_left = h(-1, 1); + let lower_right = h(1, 1); + + [ + (upper_right + 2.0 * h(1, 0) + lower_right - upper_left - 2.0 * h(-1, 0) - lower_left) / 8.0, + (lower_left + 2.0 * h(0, 1) + lower_right - upper_left - 2.0 * h(0, -1) - upper_right) / 8.0, + ] + } + } + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 868d0283..6919b3a3 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -18,6 +18,7 @@ pub mod bevel_smooth; pub mod blend; mod block_scales; pub mod channel; +pub mod channel_group; pub mod color_match; pub mod color_selection; pub mod compare_source; @@ -34,6 +35,7 @@ pub mod gradient_input; pub mod grayscale_conversion; pub mod grayscale_mode; pub mod height_to_normal; +mod height_to_normal_method; pub mod highpass_space; pub mod image_input; pub mod layer; @@ -70,6 +72,7 @@ pub mod target_color_mode; pub mod threshold_mode; pub mod tile_transform; pub mod unit_value; +mod uv_padding_mode; pub mod validation_mode; pub mod warp_blending; pub mod warp_mode; @@ -96,6 +99,7 @@ pub use bevel_direction::BevelDirection; pub use bevel_smooth::BevelSmooth; pub use blend::{BlendMode, blend1, blend3, lum, mix3}; pub use channel::{Channel, ChannelFormat, ChannelKind}; +pub use channel_group::ChannelGroup; pub use color_match::ColorMatch; pub use color_selection::ColorSelection; pub use compare_source::CompareSource; @@ -111,6 +115,7 @@ pub use gradient_input::GradientInput; pub use grayscale_conversion::GrayscaleConversion; pub use grayscale_mode::GrayscaleMode; pub use height_to_normal::HeightToNormal; +pub use height_to_normal_method::HeightToNormalMethod; pub use highpass_space::HighpassSpace; pub use image_input::ImageInput; pub use layer::{ @@ -154,6 +159,7 @@ pub use target_color_mode::TargetColorMode; pub use threshold_mode::ThresholdMode; pub use tile_transform::{FlipMode, RepeatMode, TileTransform}; pub use unit_value::{at_or_above_threshold, finite_unit}; +pub use uv_padding_mode::UvPaddingMode; pub use validation_mode::ValidationMode; pub use warp_blending::WarpBlending; pub use warp_mode::WarpMode; diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index f8b8e6c0..205db3d2 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -4,7 +4,10 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; -use crate::{BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, Layer, LayerId, LayerKind, Result}; +use crate::{ + BakeSettings, BakeSource, BakeSyncGroup, BakedMap, Channel, ChannelFormat, ContentsOffset, CoreError, Effect, HeightToNormalMethod, Layer, LayerId, + LayerKind, Result, UvPaddingMode, +}; pub use crate::env_alignment::EnvAlignment; pub use crate::shadow_mode::ShadowMode; @@ -38,6 +41,22 @@ pub enum NormalMixing { Replace, } +impl NormalMixing { + pub const ALL: [NormalMixing; 2] = [NormalMixing::Combine, NormalMixing::Replace]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + NormalMixing::Combine => "combine", + NormalMixing::Replace => "replace", + } + } + + pub fn parse(id: &str) -> Option { + NormalMixing::ALL.into_iter().find(|mixing| mixing.id() == id) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum AoMixing { #[default] @@ -45,6 +64,22 @@ pub enum AoMixing { None, } +impl AoMixing { + pub const ALL: [AoMixing; 2] = [AoMixing::Multiply, AoMixing::None]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + AoMixing::Multiply => "multiply", + AoMixing::None => "none", + } + } + + pub fn parse(id: &str) -> Option { + AoMixing::ALL.into_iter().find(|mixing| mixing.id() == id) + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TextureSet { pub name: String, @@ -52,15 +87,28 @@ pub struct TextureSet { pub description: String, /// Material index in the mesh this set paints. pub material: usize, - /// Power of two, 128..=8192. + /// Texels across: a power of two, 128..=8192 (the side of a square set) pub resolution: u32, + /// Texels down when they differ from `resolution` (a power of two, 128..=8192); sets with per-tile resolutions stay square + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resolution_height: Option, + /// Channels and their storage formats; see [`TextureSet::formats`] for what they hold pub channels: Vec<(Channel, ChannelFormat)>, + /// Whether channels hold their formats' precision; until a format is set every channel keeps 16 bits, what TextureCraft always stored + #[serde(default)] + pub format_precision: bool, /// Top-level layers, bottom → top. pub stack: Vec, #[serde(default)] pub normal_mixing: NormalMixing, #[serde(default)] pub ao_mixing: AoMixing, + /// Height to normal method; projects without it keep Smooth, the filter their exports already used + #[serde(default)] + pub height_to_normal: HeightToNormalMethod, + /// UV padding; projects without it keep padding from island edges (2D), the padding they were made with + #[serde(default)] + pub uv_padding: UvPaddingMode, /// Height-to-normal strength. #[serde(default = "one")] pub height_strength: f32, @@ -170,10 +218,14 @@ impl TextureSet { description: String::new(), material, resolution, + resolution_height: None, channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(), + format_precision: false, stack: Vec::new(), normal_mixing: NormalMixing::Combine, ao_mixing: AoMixing::Multiply, + height_to_normal: HeightToNormalMethod::Smooth, + uv_padding: UvPaddingMode::Space3d, height_strength: 1.0, bake: BakeSettings::default(), baked: BTreeSet::new(), @@ -214,11 +266,42 @@ impl TextureSet { self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32) } - /// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid. + /// Columns over rows of the atlas grid (1 for a classic set): how much more slopes down the texture tilt than across it, as in export per block + pub fn atlas_height_y_factor(&self) -> f32 { + self.tile_grid().map_or(1.0, |g| g.cols as f32 / g.rows.max(1) as f32) + } + + /// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out) + pub fn height_in_normal(&self) -> bool { + self.normal_mixing == NormalMixing::Combine + } + + /// Texels across and down: [`TextureSet::block_size`] per block of the atlas grid pub fn size(&self) -> (u32, u32) { let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); + let (width, height) = self.block_size(); + (width.saturating_mul(cols), height.saturating_mul(rows)) + } + + /// Texels down of the set's size (`resolution` for a square set) + pub fn height(&self) -> u32 { + self.resolution_height.unwrap_or(self.resolution) + } + + /// Set the size to `width × height` (`height` stored only when it differs) + pub fn set_size(&mut self, width: u32, height: u32) { + self.resolution = width; + self.resolution_height = (height != width).then_some(height); + } + + /// Texels across and down of an atlas block: the set's size, or the largest tile resolution square when tiles have their own + pub fn block_size(&self) -> (u32, u32) { + if self.tile_resolutions.is_empty() { + return (self.resolution, self.height()); + } + let block = self.block_resolution(); - (block.saturating_mul(cols), block.saturating_mul(rows)) + (block, block) } /// Texels per side of UV tile `udim` (its override, else `resolution`). @@ -226,12 +309,12 @@ impl TextureSet { self.tile_resolutions.get(&udim).copied().unwrap_or(self.resolution) } - /// Texels per side of an atlas block: the largest tile resolution (`resolution` for a - /// classic set or one without overrides). + /// Texels across an atlas block: the largest tile resolution (`resolution` without overrides); see [`TextureSet::block_size`] pub fn block_resolution(&self) -> u32 { if self.tile_resolutions.is_empty() { return self.resolution; } + self.uv_tiles.iter().map(|t| self.tile_resolution(*t)).max().unwrap_or(self.resolution) } @@ -246,9 +329,20 @@ impl TextureSet { /// [`TextureSet::tile_scale`] of every atlas block, to look up by atlas texel. pub fn block_scales(&self) -> BlockScales { - let Some(g) = self.tile_grid().filter(|_| !self.tile_resolutions.is_empty()) else { return BlockScales::default() }; - let scales = (0..g.rows).flat_map(|by| (0..g.cols).map(move |bx| g.udim(bx, by))).map(|u| self.tile_scale(u)).collect(); - BlockScales { block: self.block_resolution(), cols: g.cols, scales } + if self.tile_resolutions.is_empty() { + return BlockScales::default(); + } + + let Some(grid) = self.tile_grid() else { return BlockScales::default() }; + let block = self.block_resolution(); + let mut scales = vec![1.0; (grid.rows * grid.cols) as usize]; + for &tile in &self.uv_tiles { + if let Some((column, row)) = grid.block(tile) { + scales[(row * grid.cols + column) as usize] = (self.tile_resolution(tile) as f32 / block.max(1) as f32).clamp(1e-3, 1.0); + } + } + + BlockScales { block, cols: grid.cols, scales } } /// Scale of the tile holding mesh UV `uv` (v down) and that tile's origin corner. @@ -283,6 +377,49 @@ impl TextureSet { pub fn channel_list(&self) -> Vec { self.channels.iter().map(|(c, _)| *c).collect() } + + /// Channels the viewport can display individually, in texture-set order. + pub fn viewport_channels(&self) -> impl Iterator + '_ { + self.channels.iter().map(|(channel, _)| *channel).filter(|channel| channel.is_shaded()) + } + + /// The channels with the formats they are stored in (8-bit ones read as 16-bit without `format_precision`) + pub fn formats(&self) -> Vec<(Channel, ChannelFormat)> { + self.iter_formats().collect() + } + + /// The effective storage formats in texture-set order + pub fn iter_formats(&self) -> impl Iterator + '_ { + self.channels.iter().map(|&(channel, format)| (channel, if self.format_precision { format } else { format.at_least_16_bit() })) + } + + /// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present + pub fn add_channel(&mut self, c: Channel) -> bool { + if self.has_channel(c) { + return false; + } + + let format = ChannelFormat::default_for(c); + self.channels.push((c, if self.format_precision { format.at_least_16_bit() } else { format })); + self.channels.sort_by_key(|(c, _)| c.index()); + true + } + + /// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold + pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool { + if !self.has_channel(target) { + return false; + } + + self.channels = self.formats(); + self.format_precision = true; + for (channel, stored) in &mut self.channels { + if *channel == target { + *stored = format; + } + } + true + } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -424,6 +561,7 @@ impl DisplaySettings { } const AIR_INDEX_OF_REFRACTION: f32 = 1.0; + // Specular Level 0.5 corresponds to OpenPBR specular weight 1 const SPECULAR_LEVEL_TO_WEIGHT_SCALE: f32 = 2.0; let ior = self.ior.clamp(MIN_INDEX_OF_REFRACTION, MAX_INDEX_OF_REFRACTION); @@ -761,24 +899,37 @@ impl Project { if self.format_version > FORMAT_VERSION { return Err(CoreError::Invalid(format!("project format {} is newer than this TextureCraft supports ({FORMAT_VERSION})", self.format_version))); } + if let Some(t) = self.texture_sets.iter().find(|t| !t.uv_tiles.is_empty() && (t.tile_grid().is_none() || !t.uv_tiles.is_sorted_by(|a, b| a < b))) { return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tiles {:?}", t.name, t.uv_tiles))); } + let bad_tile_res = |t: &TextureSet| { t.tile_resolutions.iter().any(|(u, r)| !t.uv_tiles.contains(u) || !r.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(r)) }; if let Some(t) = self.texture_sets.iter().find(|t| bad_tile_res(t)) { return Err(CoreError::Invalid(format!("texture set \"{}\" has invalid UV tile resolutions {:?}", t.name, t.tile_resolutions))); } + + let bad_height = |set: &TextureSet| { + set.resolution_height + .is_some_and(|height| !height.is_power_of_two() || !(MIN_RESOLUTION..=MAX_RESOLUTION).contains(&height) || !set.tile_resolutions.is_empty()) + }; + if let Some(set) = self.texture_sets.iter().find(|set| bad_height(set)) { + return Err(CoreError::Invalid(format!("texture set \"{}\" has an invalid height {:?}", set.name, set.resolution_height))); + } + let mut seen = BTreeSet::new(); for ts in 0..self.texture_sets.len() { for (id, depth) in self.walk(ts) { if depth > MAX_DEPTH { return Err(CoreError::Invalid("layer groups nested too deeply".into())); } + if !self.layers.contains_key(&id) { return Err(CoreError::Invalid(format!("stack references missing layer {}", id.0))); } + if !seen.insert(id) { return Err(CoreError::Invalid(format!("layer {} appears twice", id.0))); } @@ -870,6 +1021,37 @@ mod tests { p } + #[test] + fn older_sets_without_the_new_fields_open_square_with_2d_padding_and_smooth_normals() { + let mut v = serde_json::to_value(TextureSet::new("a", 0, 256)).unwrap(); + for field in ["resolution_height", "format_precision", "height_to_normal", "uv_padding"] { + v.as_object_mut().unwrap().remove(field); + } + + let old: TextureSet = serde_json::from_value(v).unwrap(); + + assert_eq!(old.size(), (256, 256)); + assert_eq!((old.uv_padding, old.height_to_normal), (UvPaddingMode::Space2d, HeightToNormalMethod::Smooth)); + } + + #[test] + fn sets_keep_16_bits_until_a_format_is_set_also_in_older_files() { + let new = TextureSet::new("a", 0, 128); + let mut v = serde_json::to_value(&new).unwrap(); + v.as_object_mut().unwrap().remove("format_precision"); + let mut old: TextureSet = serde_json::from_value(v).unwrap(); + let format = |t: &TextureSet, c: Channel| t.formats().into_iter().find(|(x, _)| *x == c).map(|(_, f)| f); + + assert_eq!(format(&new, Channel::Roughness), Some(ChannelFormat::L16)); + assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16)); + assert_eq!(format(&old, Channel::BaseColor), Some(ChannelFormat::Rgb16)); + + assert!(old.set_channel_format(Channel::Metallic, ChannelFormat::L8)); + assert_eq!(format(&old, Channel::Metallic), Some(ChannelFormat::L8)); + assert_eq!(format(&old, Channel::Roughness), Some(ChannelFormat::L16), "the other channels keep their precision"); + assert!(!old.set_channel_format(Channel::Emissive, ChannelFormat::L8), "a channel the set lacks"); + } + #[test] fn enabling_ior_at_the_default_preserves_legacy_reflectance() { let mut display = DisplaySettings::default(); @@ -1124,6 +1306,50 @@ mod tests { } } + #[test] + fn atlas_slopes_along_each_side_match_a_block_in_wide_tall_and_square_grids() { + let mut t = TextureSet::new("a", 0, 256); + t.height_strength = 3.0; + for tiles in [vec![1001, 1002], vec![1001, 1011], vec![1001, 1002, 1011, 1012], vec![1001, 1002, 1003]] { + t.uv_tiles = tiles; + let ((width, height), (block_width, block_height)) = (t.size(), t.block_size()); + + let across = t.atlas_height_strength() * width as f32; + let down = t.atlas_height_strength() * t.atlas_height_y_factor() * height as f32; + + assert_eq!(across, t.height_strength * block_width as f32, "{:?}", t.uv_tiles); + assert_eq!(down, t.height_strength * block_height as f32, "{:?}", t.uv_tiles); + } + } + + #[test] + fn non_square_sets_are_wider_than_tall_per_block_and_stay_square_with_tile_sizes() { + let mut p = project(); + let t = &mut p.texture_sets[0]; + t.set_size(1024, 256); + let (w, h) = t.size(); + assert!(w > h, "{:?}", t.size()); + t.uv_tiles = vec![1001, 1011]; + + // Tiles stack down, each block keeping the set's shape + assert_eq!(t.size(), (w, h * 2)); + p.validate().unwrap(); + + // A height must be a valid size, and per-tile sizes need a square set + for bad in [Some(100), Some(16384)] { + let mut q = p.clone(); + q.texture_sets[0].resolution_height = bad; + assert!(q.validate().is_err(), "{bad:?}"); + } + let mut q = p.clone(); + q.texture_sets[0].tile_resolutions.insert(1011, 128); + assert!(q.validate().is_err()); + + // The same size both ways is stored as square + p.texture_sets[0].set_size(512, 512); + assert_eq!(p.texture_sets[0].resolution_height, None); + } + #[test] fn validate_rejects_newer_formats_and_dangling_ids() { let mut p = project(); diff --git a/crates/core/src/uv_padding_mode.rs b/crates/core/src/uv_padding_mode.rs new file mode 100644 index 00000000..ab5150ec --- /dev/null +++ b/crates/core/src/uv_padding_mode.rs @@ -0,0 +1,29 @@ +//! Where a texture set's UV padding takes its texels from + +use serde::{Deserialize, Serialize}; + +/// UV padding mode: what fills the texels just outside a texture set's UV islands +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +pub enum UvPaddingMode { + /// Across seams (3D): past a UV seam, the texels continue the surface from the seam's other side + Space3d, + /// From island edges (2D): every texel repeats the nearest covered texel in the texture + #[default] + Space2d, +} + +impl UvPaddingMode { + pub const ALL: [UvPaddingMode; 2] = [UvPaddingMode::Space3d, UvPaddingMode::Space2d]; + + /// Stable id for commands and inspect + pub fn id(self) -> &'static str { + match self { + UvPaddingMode::Space3d => "3d", + UvPaddingMode::Space2d => "2d", + } + } + + pub fn parse(id: &str) -> Option { + UvPaddingMode::ALL.into_iter().find(|value| value.id() == id) + } +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 52b37891..4052d6d8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -18,12 +18,13 @@ texturecraft-paint = { workspace = true } texturecraft-bake = { workspace = true } texturecraft-formats = { workspace = true } rayon = { workspace = true } -epaint_default_fonts = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# The built-in text fonts; the web build gets them from the app (`text_cmds::provide_built_in_fonts`). +epaint_default_fonts = { workspace = true } tempfile = "3" [target.'cfg(any(target_os = "macos", target_os = "freebsd"))'.dependencies] diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ac846ba5..745c8d2b 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with or null, format, bitDepth, dithering, size (width), height, sourceSize, sourceHeight, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)", always, plan ), @@ -426,6 +426,7 @@ impl Session { let files = self.with_export_input( set_index, &mesh_name, + options.padding != Padding::None, |grid| Cow::Owned(grid.coverage_mask()), |input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe), )?; @@ -440,6 +441,7 @@ impl Session { &self, set_index: usize, mesh_name: &str, + needs_padding: bool, coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>, with: impl FnOnce(&ExportInput) -> Result, ) -> Result { @@ -447,6 +449,11 @@ impl Session { let cache = self.caches.get(set_index).ok_or_else(missing)?; let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?; let coverage = coverage(&cache.gbuf); + let seams = if needs_padding { + self.doc.project.texture_sets.get(set_index).and_then(|set| crate::session::padding_seams(&self.mesh, set, &cache.gbuf)) + } else { + None + }; let empty = Default::default(); let input = ExportInput { project: &self.doc.project, @@ -454,6 +461,7 @@ impl Session { composite: &composite, baked: self.doc.baked.get(&set_index).unwrap_or(&empty), coverage: &coverage, + seams: seams.as_ref(), mesh_name, }; with(&input) @@ -472,6 +480,7 @@ impl Session { self.with_export_input( set_index, &mesh_name, + false, |grid| Cow::Borrowed(&grid.tri), |input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe), ) @@ -611,7 +620,7 @@ fn preview(session: &mut Session, params: &Value) -> Result { } fn plan(session: &mut Session, params: &Value) -> Result { - use texturecraft_formats::export::{list_set_outputs, scale_export_side}; + use texturecraft_formats::export::{list_set_outputs, output_dimensions}; let options = export_options(session, params, "export.plan")?; let project = &session.doc.project; @@ -624,12 +633,15 @@ fn plan(session: &mut Session, params: &Value) -> Result { let Some((set_index, _)) = set_outputs.first() else { continue }; let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?; - let block_size = set.block_resolution(); for (_, output) in set_outputs { - let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile)); + let source = output_dimensions(set, output.tile, None); - // A map's own size wins over the export's; a PSD is the size of its largest layer - let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size); + // A PSD's canvas takes the largest width and height of its exported layers + let (size, height) = output + .maps() + .map(|map| output_dimensions(set, output.tile, options.map_size(map))) + .reduce(|(width, height), (next_width, next_height)| (width.max(next_width), height.max(next_height))) + .unwrap_or(source); files.push(json!({ "ts": set_index, @@ -641,7 +653,9 @@ fn plan(session: &mut Session, params: &Value) -> Result { "bitDepth": output.bit_depth, "dithering": output.dither, "size": size, - "sourceSize": source_size, + "height": height, + "sourceSize": source.0, + "sourceHeight": source.1, "warnings": output.warnings, "layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::>(), })); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 4daaace0..da8eb860 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -271,18 +271,25 @@ pub fn texture_set(session: &Session, index: usize) -> Value { json!({ "index": index, "name": texture_set.name, + "originalName": session.original_set_name(index), + "description": texture_set.description, "resolution": texture_set.resolution, + "height": texture_set.height(), "size": texture_set.size(), "blockResolution": texture_set.block_resolution(), "uvTiles": texture_set.uv_tiles, "tiles": tiles, - "channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::>(), + "channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::>(), "layers": session.doc.project.walk(index).len(), "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "outOfDate": out_of_date, "autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id), "visible": texture_set.visible, + "normalMixing": texture_set.normal_mixing.id(), + "aoMixing": texture_set.ao_mixing.id(), + "heightToNormal": texture_set.height_to_normal.id(), + "uvPadding": texture_set.uv_padding.id(), "active": index == session.ts(), }) } diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 73a4317e..1e28b781 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -313,7 +313,8 @@ fn save_source(_: &mut Session, _: &Value) -> Result { Err(EngineError::Other("file paths are not available in the browser".into())) } -/// A MaterialCraft executable: `$`, else next to this program, else `name` on `PATH`. +/// A MaterialCraft executable: `$`, else next to this program, else in the sibling +/// `MaterialCraft` folder (the launcher's layout), else `name` on `PATH`. #[cfg(not(target_arch = "wasm32"))] pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) { @@ -321,7 +322,18 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf { } let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX); - std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join(&exe))).filter(|p| p.is_file()).unwrap_or_else(|| exe.into()) + let app_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf)); + app_dir.and_then(|d| find_installed_tool(&d, &exe)).unwrap_or_else(|| exe.into()) +} + +/// `exe` in `app_dir` (next to this program), else in the sibling `MaterialCraft` folder beside `app_dir` +/// (`/TextureCraft` and `/MaterialCraft`, as the ArtCraft Launcher installs them). `None` if neither has it. +/// Versioned `//` layouts and macOS `.app` bundles are not searched. +#[cfg(not(target_arch = "wasm32"))] +fn find_installed_tool(app_dir: &std::path::Path, exe: &str) -> Option { + let beside = app_dir.join(exe); + let sibling = app_dir.parent().map(|root| root.join("MaterialCraft").join(exe)); + std::iter::once(beside).chain(sibling).find(|p| p.is_file()) } /// A command for a MaterialCraft executable that opens no console window. @@ -335,12 +347,15 @@ fn quiet(program: &std::path::Path) -> std::process::Command { } /// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this -/// program, or on `PATH`). +/// program, in the sibling `MaterialCraft` folder, or on `PATH`). #[cfg(not(target_arch = "wasm32"))] pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> { let app = materialcraft_tool("materialcraft", "MATERIALCRAFT"); quiet(&app).arg(package).spawn().map(drop).map_err(|e| { - EngineError::Other(format!("MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT", app.display())) + EngineError::Other(format!( + "MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT", + app.display() + )) }) } @@ -775,6 +790,70 @@ mod tests { assert!(typed(&p, &json!("#ff8000")).is_some()); } + #[cfg(not(target_arch = "wasm32"))] + fn touch(dir: &std::path::Path, exe: &str) -> std::path::PathBuf { + std::fs::create_dir_all(dir).unwrap(); + let p = dir.join(exe); + std::fs::write(&p, b"").unwrap(); + p + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn launcher_layout_finds_the_sibling_materialcraft_folder() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(&app).unwrap(); + let tool = touch(&root.path().join("MaterialCraft"), "materialcraft-cli"); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(tool)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_tool_beside_the_program_wins_over_the_sibling_folder() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + let beside = touch(&app, "materialcraft-cli"); + touch(&root.path().join("MaterialCraft"), "materialcraft-cli"); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(beside)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_tool_is_none_so_the_caller_falls_back_to_path() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap(); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_folder_named_like_the_tool_is_not_the_tool() { + let root = tempfile::tempdir().unwrap(); + let app = root.path().join("TextureCraft"); + std::fs::create_dir_all(app.join("materialcraft-cli")).unwrap(); + std::fs::create_dir_all(root.path().join("MaterialCraft").join("materialcraft-cli")).unwrap(); + assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn an_app_folder_with_no_parent_does_not_panic() { + // The root (or an empty path) has no parent: only the beside-the-program step can apply. + assert_eq!(super::find_installed_tool(std::path::Path::new(""), "no-such-materialcraft-tool"), None); + let root = std::env::temp_dir().ancestors().last().map(std::path::Path::to_path_buf).unwrap_or_default(); + assert_eq!(super::find_installed_tool(&root, "no-such-materialcraft-tool"), None); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_missing_app_folder_is_none() { + let root = tempfile::tempdir().unwrap(); + let gone = root.path().join("nowhere").join("TextureCraft"); + assert_eq!(super::find_installed_tool(&gone, "materialcraft-cli"), None); + } + #[cfg(not(target_arch = "wasm32"))] fn scratch(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id())); diff --git a/crates/engine/src/link_cmds/link_job.rs b/crates/engine/src/link_cmds/link_job.rs index 145be0e3..ceb350da 100644 --- a/crates/engine/src/link_cmds/link_job.rs +++ b/crates/engine/src/link_cmds/link_job.rs @@ -120,7 +120,7 @@ fn run_bounded(command: &std::process::Command, stdout: &Path, stderr: &Path, re .stdout(std::fs::File::create(stdout).map_err(io)?) .stderr(std::fs::File::create(stderr).map_err(io)?) .spawn() - .map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?; + .map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT_CLI")))?; loop { if canceled.load(Ordering::Relaxed) { diff --git a/crates/engine/src/mask_export.rs b/crates/engine/src/mask_export.rs index 9156b884..c094a426 100644 --- a/crates/engine/src/mask_export.rs +++ b/crates/engine/src/mask_export.rs @@ -42,20 +42,22 @@ impl Session { let (width, height, values) = atlas; let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?; let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) }; - let block = set.block_resolution(); + let (block_width, block_height) = set.block_size(); set.uv_tiles .iter() .map(|&tile| { let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?; // A tile smaller than its block fills the block's top-left corner - let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block); - let mut tile_values = Vec::with_capacity(side as usize * side as usize); - for row in 0..side { - let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize; - tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[])); + let scale = set.tile_scale(tile); + let tile_width = ((block_width as f32 * scale).round() as u32).clamp(1, block_width); + let tile_height = ((block_height as f32 * scale).round() as u32).clamp(1, block_height); + let mut tile_values = Vec::with_capacity(tile_width as usize * tile_height as usize); + for row in 0..tile_height { + let start = ((block_y * block_height + row) as usize) * width as usize + (block_x * block_width) as usize; + tile_values.extend_from_slice(values.get(start..start + tile_width as usize).unwrap_or(&[])); } - Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values }) + Ok(MaskBitmap { tile: Some(tile), width: tile_width, height: tile_height, values: tile_values }) }) .collect() } diff --git a/crates/engine/src/material_lib.rs b/crates/engine/src/material_lib.rs index 9d496630..780db5f2 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -7,7 +7,7 @@ use std::sync::Arc; use serde_json::Value; use texturecraft_compose::PixelStore; -use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet}; +use texturecraft_core::{EffectKind, Fill, LayerId, LayerKind, Project, Source, TextureSet}; use crate::commands::{CommandSpec, always, has_layer}; use crate::materials::Place; @@ -36,7 +36,15 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError { EngineError::Other(e.to_string()) } -/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with) +/// The package and cooked maps of the MaterialCraft material linked to `fill`, if any +fn link_images(fill: &Fill, out: &mut Vec) { + if let Some(link) = &fill.link { + out.push(link.package.clone()); + out.extend(link.outputs.values().cloned()); + } +} + +/// Image resources a layer subtree uses (fill sources and their patterns, linked materials, mask or content effects and the images its paths paint with) pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, depth: usize) { if depth > texturecraft_core::project::MAX_DEPTH { return; @@ -46,15 +54,15 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, if let LayerKind::Fill(fill) = &layer.kind { out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string)); - if let Some(link) = &fill.link { - out.push(link.package.clone()); - out.extend(link.outputs.values().cloned()); - } + link_images(fill, out); } for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) { out.extend(effect.images_read().map(str::to_string)); out.extend(crate::path_tool::path_images(&effect.kind)); + if let EffectKind::Material(fill) = &effect.kind { + link_images(fill, out); + } } for child in layer.children() { @@ -66,9 +74,11 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec, pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document { let mut project = Project::new(name, "builtin:none"); let mut set = TextureSet::new(name, 0, src_set.resolution); + set.resolution_height = src_set.resolution_height; set.uv_tiles = src_set.uv_tiles.clone(); set.tile_resolutions = src_set.tile_resolutions.clone(); set.channels = src_set.channels.clone(); + set.format_precision = src_set.format_precision; project.texture_sets.push(set); Document { diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 6d26d432..781797d2 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -217,15 +217,17 @@ impl Session { .collect() } - /// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh - /// (the Clone tool's destination anchor). + /// Common setup of 3D and 2D strokes, `first_uv` being where the stroke starts on the mesh (the Clone tool's destination anchor) fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option) -> Result<()> { + // Texture size a stroke paints at before the texture set has a cache + const FALLBACK_TEXTURE_SIZE: (u32, u32) = (1024, 1024); + self.refuse_while_baking()?; let tool = self.tool.tool; let erase = tool == Tool::Eraser; let quick_mask = self.quick_mask.editing; let ts = self.ts(); - let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); + let size = self.caches.get(ts).map_or(FALLBACK_TEXTURE_SIZE, |cache| cache.size); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite); if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() { @@ -240,26 +242,30 @@ impl Session { } _ => None, }; + let before = self.doc.clone(); let target = if quick_mask { None } else { match self.paint_target() { - Ok(t) => Some(t), - Err(e) => { + Ok(target) => Some(target), + Err(error) => { self.doc = before; - return Err(e); + return Err(error); } } }; - let values = target.map(|t| self.stroke_values(t)).unwrap_or_default(); + + let values = target.map(|target| self.stroke_values(target)).unwrap_or_default(); // Clone and smudge on a mask read the mask as it was before the stroke let mask_owner = match target { Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner), _ => None, }; - let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None }; + + // The 2D view doesn't show the stencil, so there it shapes only the Projection tool + let stencil = if !quick_mask && tool.uses_stencil() && (tool == Tool::Projection || !uv_mode) { self.capture_stencil(viewport) } else { None }; let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) { Some("no channel enabled to paint: enable channels in the tool's material") } else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode { @@ -267,9 +273,10 @@ impl Session { } else { None }; - if let Some(msg) = problem { + + if let Some(message) = problem { self.doc = before; - return Err(EngineError::Other(msg.into())); + return Err(EngineError::Other(message.into())); } let depth = (!uv_mode).then(|| self.eye_depth(viewport)); @@ -278,6 +285,7 @@ impl Session { if !quick_mask { canvas.limit = self.stroke_limit(ts, size); } + if let Some((mode, offset)) = pickup && let Some(cache) = self.caches.get(ts) { @@ -285,7 +293,7 @@ impl Session { PickupMode::Clone { .. } => { PickupMode::Clone { offset: [(offset[0] * size.0 as f32).round() as i64, (offset[1] * size.1 as f32).round() as i64] } } - m => m, + other_mode => other_mode, }; let mut pickup = match (&layer_source, mask_owner) { // On a mask the stroke reads the mask's own values @@ -317,20 +325,23 @@ impl Session { canvas.pickup = Some(pickup); if tool == Tool::Clone && self.tool.clone_aligned - && let Some(src) = self.tool.clone_source.as_mut() + && let Some(clone_source) = self.tool.clone_source.as_mut() { - src.offset.get_or_insert(offset); + clone_source.offset.get_or_insert(offset); } } + if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) { canvas.pickup = self.brush_pattern(&values); } + let label = if quick_mask { QUICK_MASK_STROKE_LABEL.to_string() } else { let on_mask = matches!(target, Some(PaintTarget::Mask(_))); history_label(stroke_template(tool, on_mask), &self.stroke_layer_name()) }; + self.stroke = Some(ActiveStroke { ts, target, @@ -345,6 +356,7 @@ impl Session { erase, stencil, before, + start_revision: self.revision, label, staging: Staging::default(), }); @@ -394,13 +406,14 @@ impl Session { } } - /// The stencil placed for the current camera and viewport. + /// The stencil placed for the current camera and viewport fn capture_stencil(&self, viewport: Vec2) -> Option { - let st = self.tool.stencil.as_ref()?; - let image = self.images.get(&st.image)?.clone(); + let stencil_state = self.tool.stencil.as_ref()?; + let image = self.images.get(&stencil_state.image)?.clone(); let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); - let (center, half, rotation) = st.placement(image.width as f32 / image.height.max(1) as f32, aspect); - Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile }) + let (center, half, rotation) = stencil_state.placement(image.width as f32 / image.height.max(1) as f32, aspect); + let colors = self.tool.tool == Tool::Projection; + Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: stencil_state.tile, colors }) } /// Painting is paused while a bake preview shows the baked maps instead of the material. @@ -558,6 +571,7 @@ impl Session { /// Commit the active stroke as one undo step pub fn end_stroke(&mut self) -> Result<()> { let Some(mut stroke) = self.stroke.take() else { return Ok(()) }; + let size = (stroke.canvas.alpha.width(), stroke.canvas.alpha.height()); if stroke.canvas.dirty.is_empty() { // Nothing painted: drop any mask effect the stroke created @@ -566,8 +580,15 @@ impl Session { } let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone()); + if stroke.stencil.is_some() && !with_commit_source(&stroke, gbuf.as_deref(), &self.mesh, &stroke.canvas.dirty, stencil_allows_stroke) { + self.mark_painted(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied()); + self.discard_unused_stroke_mask(&stroke); + return Ok(()); + } + let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut stroke.staging); + match stroke.target { Some(PaintTarget::Layer(id)) => { let pixels = &mut self.doc.pixels; @@ -586,7 +607,8 @@ impl Session { return Ok(()); } } - self.add_step(stroke.label.clone(), stroke.before); + + self.add_step(stroke.label, stroke.before); self.redo.clear(); self.mark_modified(); @@ -595,6 +617,32 @@ impl Session { Ok(()) } + fn discard_unused_stroke_mask(&mut self, stroke: &ActiveStroke) { + // An intervening edit may already have recorded the mask effect + if self.revision != stroke.start_revision { + return; + } + + self.doc.project.next_id = stroke.before.project.next_id; + if let Some(PaintTarget::Mask(effect)) = stroke.target + && let Some((owner, _)) = self.doc.project.effect(effect) + && let Some(previous_layer) = stroke.before.project.layers.get(&owner) + && !previous_layer.mask.iter().flat_map(|mask| &mask.effects).any(|previous| previous.id == effect) + && let Some(layer) = self.doc.project.layers.get_mut(&owner) + { + layer.mask = previous_layer.mask.clone(); + + // Removing a new mask background can change texels outside the dabs + if previous_layer.mask.is_none() { + for texture_set in self.doc.project.sets_drawing(owner) { + if let Some(cache) = self.caches.get_mut(texture_set) { + cache.invalidate_all(); + } + } + } + } + } + /// Abandon the active stroke (Esc). pub fn cancel_stroke(&mut self) { if let Some(st) = self.stroke.take() { @@ -735,22 +783,44 @@ impl Session { } } -/// Run `f` with stroke `st` as a commit source over `tiles` (the Projection tool's stencil -/// colors and alpha come from the surface under each texel). +/// Check that some rasterized paint survives the stencil before writing tiles or history. +fn stencil_allows_stroke(source: CommitSource) -> bool { + use texturecraft_texel::{TILE, from_u16}; + + let Some(sample_stencil) = source.per_texel else { return true }; + let opacity = source.opacity.clamp(0.0, 1.0); + source.tiles.iter().any(|&(tile_x, tile_y)| { + source.alpha.tile(tile_x, tile_y).is_some_and(|alpha| { + alpha.iter().enumerate().any(|(index, &coverage)| { + let weight = from_u16(coverage) * opacity; + if weight <= 0.0 { + return false; + } + + let x = tile_x * TILE + index as u32 % TILE; + let y = tile_y * TILE + index as u32 / TILE; + sample_stencil(x, y).is_some_and(|(_, factor)| weight * factor > 0.0) + }) + }) + }) +} + +/// Run `f` with `stroke` as a commit source over `tiles` (the stencil's alpha and, on the Projection tool, its colors come from the surface under each texel) fn with_commit_source( - st: &ActiveStroke, - gbuf: Option<&texturecraft_geom::UvGBuffer>, + stroke: &ActiveStroke, + gbuffer: Option<&texturecraft_geom::UvGBuffer>, mesh: &texturecraft_geom::Mesh, tiles: &BTreeSet<(u32, u32)>, f: impl FnOnce(CommitSource) -> R, ) -> R { - let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> { - let g = gbuf?; - let p = g.surface(mesh, (y * g.width + x) as usize)?.pos; - st.stencil.as_ref()?.sample_world(p) + let stencil_fn = |x: u32, y: u32| -> Option<(Option<[f32; 3]>, f32)> { + let gbuffer = gbuffer?; + let position = gbuffer.surface(mesh, (y * gbuffer.width + x) as usize)?.pos; + stroke.stencil.as_ref()?.paint_world(position) }; - let per_texel: Option = if st.stencil.is_some() { Some(&stencil_fn) } else { None }; - let carried = st.canvas.pickup.as_ref().map(|p| &p.values); - let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values()); - f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask }) + let per_texel: Option = if stroke.stencil.is_some() { Some(&stencil_fn) } else { None }; + + let carried = stroke.canvas.pickup.as_ref().map(|pickup| &pickup.values); + let carried_mask = stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()); + f(CommitSource { alpha: &stroke.canvas.alpha, tiles, opacity: stroke.stroke.settings.opacity, erase: stroke.erase, per_texel, carried, carried_mask }) } diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 1b897729..0413477b 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -1007,36 +1007,51 @@ impl Session { } _ => 0, }; + // Each path goes through the regular stroke and fill code with its own settings; their + // own history entries are dropped (the caller records one step). + let mut out = vec![Value::Null; start]; + let result = self.while_painting_paths(eid, |s| { + let mut result = Ok(()); + for i in start..=shapes.len() { + if i == from.min(shapes.len()) && i > start { + let pixels = &s.doc.pixels; + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); + s.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); + } + let Some(sh) = shapes.get(i) else { break }; + match s.paint_shape(sh) { + Ok(v) => out.push(v), + Err(e) => { + result = Err(e); + break; + } + } + } + result + }); + result.map(|_| out) + } - // Regular stroke and fill code paints each path with its own settings - // Discard its history entries because the caller records one undo step + /// Run `f` with the session switched into path-painting state (path tool on sublayer `eid`, + /// empty history), then put the tool, camera, target, quick-mask flag and the undo/redo + /// stacks back. A panic in `f` restores them too before it continues unwinding: the + /// automation servers catch panics and keep serving this session, and must not find its + /// history gone. + fn while_painting_paths(&mut self, eid: LayerId, f: impl FnOnce(&mut Session) -> T) -> T { let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo)); self.target = StackTarget::Effect(eid); self.quick_mask.editing = false; self.tool.tool = Tool::Path; self.painting_paths = true; - let mut out = vec![Value::Null; start]; - let mut result = Ok(()); - for i in start..=shapes.len() { - if i == from.min(shapes.len()) && i > start { - let pixels = &self.doc.pixels; - let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); - self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); - } - let Some(sh) = shapes.get(i) else { break }; - match self.paint_shape(sh) { - Ok(v) => out.push(v), - Err(e) => { - result = Err(e); - break; - } - } - } + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self))); self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; - result.map(|_| out) + match ran { + Ok(v) => v, + Err(panic) => std::panic::resume_unwind(panic), + } } fn paint_shape(&mut self, shape: &PathShape) -> Result { @@ -1417,4 +1432,27 @@ mod tests { assert!(!off_mesh.is_empty()); assert!(off_mesh.iter().flatten().all(Option::is_none)); } + + #[test] + fn a_panic_while_painting_paths_restores_history_and_tool_state() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + s.update(); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.2], [0.9, 0.25]], "commit": true})).unwrap(); + let eid = texturecraft_core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + assert!(!s.history_labels().is_empty()); + let labels = s.history_labels(); + let (target, tool) = (s.target, s.tool.tool); + + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + s.while_painting_paths(eid, |s| { + s.edit("nested", |_| Ok(())).unwrap(); + panic!("paint failed"); + }) + })); + assert!(panicked.is_err()); + assert_eq!(s.history_labels(), labels); + assert_eq!((s.target, s.tool.tool), (target, tool)); + assert!(!s.painting_paths); + } } diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index 9395ae2d..ee11f119 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -472,6 +472,7 @@ mod tests { assert!(warnings.is_empty(), "{warnings:?}"); assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom); let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap(); + assert_eq!(plan.as_array().unwrap().len(), 1); assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png")); @@ -481,9 +482,11 @@ mod tests { let builtin = format!("builtin:{name}"); assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true)); let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap(); + assert!(builtin_plan.as_array().unwrap().len() > 1); run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap(); run(&mut s, "export.preset.remove", json!({"name": name})).unwrap(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); } diff --git a/crates/engine/src/project_cmds.rs b/crates/engine/src/project_cmds.rs index 33432cda..a9018f4f 100644 --- a/crates/engine/src/project_cmds.rs +++ b/crates/engine/src/project_cmds.rs @@ -1,4 +1,4 @@ -//! Project-level commands: new project, sample project, smart materials, inspection. +//! Project-level commands: new project, rename, sample project, smart materials, inspection. use serde_json::{Value, json}; use texturecraft_compose::BakedMaps; @@ -9,6 +9,9 @@ use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p}; use crate::materials::Place; use crate::{Result, Session, cmd}; +/// Longest project name, in characters; it goes into export file names. +pub const MAX_PROJECT_NAME_CHARS: usize = 128; + pub fn specs() -> Vec { vec![ cmd!( @@ -22,6 +25,15 @@ pub fn specs() -> Vec { ), cmd!("project.sample", "Open sample project", ["File"], None, "{}", always, sample), cmd!("project.inspect", "Inspect project", [], None, "{}", always, |s, _| Ok(crate::inspect::session(s))), + cmd!( + "project.rename", + "Rename project", + [], + None, + "{name: 1-128 characters without control characters} — the name `$project` stands for in export file names; the project file keeps its own name", + always, + rename + ), cmd!( "material.apply", "Add smart material", @@ -51,6 +63,30 @@ fn new(s: &mut Session, p: &Value) -> Result { Ok(crate::inspect::session(s)) } +/// Trim and validate a proposed name without changing the project. +pub fn validate_project_name(name: &str) -> Result<&str> { + let name = name.trim(); + if name.is_empty() || name.chars().nth(MAX_PROJECT_NAME_CHARS).is_some() || name.chars().any(char::is_control) { + return Err(bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters"))); + } + + Ok(name) +} + +fn rename(session: &mut Session, params: &Value) -> Result { + let name = validate_project_name(strp(params, "name").unwrap_or_default())?; + + // The same name is not an undo step and leaves a saved project unmodified + if name != session.doc.project.name { + session.edit("Rename project", |session| { + session.doc.project.name = name.to_owned(); + Ok(()) + })?; + } + + Ok(json!({ "name": name })) +} + fn material(s: &mut Session, p: &Value) -> Result { let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?; let l = crate::materials::apply_at(s, id, Place::from_params(p))?; diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 024243c3..e4265659 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -341,6 +341,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { if to == name { return Ok(json!({ "name": name })); } + if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() { return Err(bad(command, format!("a resource named `{to}` exists already"))); } @@ -348,6 +349,7 @@ fn rename(s: &mut Session, p: &Value) -> Result { s.edit("Rename resource", |s| { let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?; s.doc.resources.insert(to.clone(), bytes); + // The Resources Updater keeps following the file the image came from if let Some(source) = s.doc.project.resource_sources.remove(&name) { s.doc.project.resource_sources.insert(to.clone(), source); @@ -428,17 +430,23 @@ fn images_in_use(s: &Session) -> Vec { } /// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step) -fn remove_unused(s: &mut Session, _: &Value) -> Result { - let used = images_in_use(s); - let unused: Vec = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect(); +fn remove_unused(session: &mut Session, _: &Value) -> Result { + let mut used = images_in_use(session); + used.sort_unstable(); + let unused: Vec<_> = session.doc.resources.keys().filter(|name| used.binary_search(name).is_err()).cloned().collect(); + if !unused.is_empty() { - s.edit("Remove unused resources", |s| { - s.doc.resources.retain(|k, _| !unused.contains(k)); - s.doc.project.resource_sources.retain(|k, _| !unused.contains(k)); + session.edit("Remove unused resources", |session| { + for name in &unused { + session.doc.resources.remove(name); + session.doc.project.resource_sources.remove(name); + } + Ok(()) })?; - s.sync_images(); + session.sync_images(); } + Ok(json!({ "removed": unused })) } @@ -538,6 +546,7 @@ mod tests { let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string(); std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap(); + // An equal-size file counts as changed once its time moved, as a later save's does let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10); std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap(); diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 9388a3ec..86b537e0 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -5,13 +5,13 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use texturecraft_compose::{ - BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours, + BakedMaps, BelowCache, Composite, PaddingMaps, PaintTarget, PixelStore, SeamPaddingInput, StackKey, StrokePreview, covered_tiles, pad_tiles, + stack_reads_neighbours, }; -use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_core::{Channel, ChannelFormat, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas}; -use texturecraft_texel::DilationMap; use crate::fill_mode::FillMode; pub use crate::stencil_look::StencilLook; @@ -43,7 +43,11 @@ pub struct SetCache { /// Texels across and down (`TextureSet::size`). pub size: (u32, u32), pub gbuf: Arc, - pub dilation: Arc, + /// The set's UV padding mode and the display padding it gives + pub uv_padding: UvPaddingMode, + pub padding: Arc, + /// The channels' storage formats the composite was made with + pub formats: Vec<(Channel, ChannelFormat)>, pub covered_tiles: Arc>, pub composite: Composite, /// Tiles to recomposite. @@ -65,15 +69,15 @@ impl SetCache { pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache { let (w, h) = ts.size(); let gbuf = UvGBuffer::new(mesh, ts.material, w, h); - - // Padding stays inside each UV tile - let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution()); + let padding = display_padding(mesh, ts, &gbuf); let covered = covered_tiles(&gbuf); let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect(); SetCache { size: (w, h), gbuf: Arc::new(gbuf), - dilation: Arc::new(dilation), + uv_padding: ts.uv_padding, + padding: Arc::new(padding), + formats: ts.formats(), covered_tiles: Arc::new(covered), composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), @@ -85,11 +89,44 @@ impl SetCache { } } + fn has_channels(&self, set: &TextureSet) -> bool { + if self.composite.channels.len() != set.channels.len() { + return false; + } + + if self.composite.channels.keys().copied().eq(set.channels.iter().map(|&(channel, _)| channel)) { + return true; + } + + // Saved sets can list their channels in a different order from the composite + let mut present = [false; Channel::ALL.len()]; + for &(channel, _) in &set.channels { + present[channel.index()] = true; + } + + self.composite.channels.keys().all(|channel| present[channel.index()]) + } + pub fn invalidate_all(&mut self) { self.dirty.extend(self.covered_tiles.iter().copied()); } } +/// The geometry needed to continue UV padding across the seams of this set +pub(crate) fn padding_seams<'a>(mesh: &'a Mesh, set: &TextureSet, grid: &'a UvGBuffer) -> Option> { + if set.uv_padding == UvPaddingMode::Space2d { + return None; + } + + SeamPaddingInput::of_material(mesh, set.material, &grid.tri) +} + +/// The viewport's padding of `set`, which stays inside each UV tile +fn display_padding(mesh: &Mesh, set: &TextureSet, grid: &UvGBuffer) -> PaddingMaps { + let seams = padding_seams(mesh, set, grid); + PaddingMaps::new(set.uv_padding, &grid.coverage_mask(), (grid.width, grid.height), Some(DISPLAY_PADDING), set.block_size(), seams.as_ref()) +} + /// Active tool. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Tool { @@ -110,6 +147,12 @@ pub enum Tool { impl Tool { pub const ALL: [Tool; 9] = [Tool::Paint, Tool::Eraser, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::Path, Tool::GeometryMask]; + + /// The brush tools whose strokes the stencil shapes + pub fn uses_stencil(self) -> bool { + matches!(self, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone) + } + pub fn label(self) -> &'static str { match self { Tool::Paint => "Paint", @@ -181,7 +224,7 @@ impl ViewMode { } } -/// A screen-pinned image for the Projection tool (a stencil). +/// A screen-pinned image the brush tools paint through (a stencil) #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StencilState { /// Image resource name. @@ -252,7 +295,7 @@ pub struct ToolState { /// Polygon fill boxes in the 3D view select only the polygons the camera sees #[serde(default = "default_fill_visible_only")] pub fill_visible_only: bool, - /// Stencil used by the Projection tool. + /// Stencil the brush tools paint through (the Projection tool paints its colors) #[serde(default)] pub stencil: Option, /// Placement the next stencil starts with: the last stencil's, kept when the stencil is @@ -364,10 +407,12 @@ pub(crate) struct ActiveStroke { /// What a mask stroke paints, resolved once so staging, preview and commit read one image pub mask_gray: texturecraft_compose::MaskGray, pub erase: bool, - /// Projection tool: the stencil captured with the stroke's camera. + /// The stencil captured with the stroke's camera. pub stencil: Option, /// History snapshot taken when the stroke began. pub before: Document, + /// Document revision before any edits made during the stroke. + pub start_revision: u64, pub label: String, /// The commit's destination tiles, copied as the stroke reaches them. pub staging: texturecraft_paint::Staging, @@ -441,7 +486,7 @@ pub struct Session { pub(crate) undo: Vec<(String, Document)>, pub(crate) redo: Vec<(String, Document)>, /// New undo steps so far: it moves even when a full history keeps its length - pub(crate) steps_added: u64, + steps_added: u64, /// Set by [`crate::execute`] from a command's `merge` param: its edits continue the previous /// undo step with the same label (a slider drag is one step however many values it applies). pub(crate) merge_edits: bool, @@ -703,7 +748,8 @@ impl Session { // ----------------------------------------------------------------------------------------- // History - /// Run an undoable edit. On error the document is left untouched. + /// Run an undoable edit. On error, or if `f` panics, the document is left untouched (other + /// session state, such as the selection, is not restored). pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { self.edit_merging(label, self.merge_edits, f) } @@ -719,7 +765,18 @@ impl Session { self.end_polygon_fill_box(); let before = self.doc.clone(); - let result = change(self).and_then(|(value, changed)| { + // A panic inside `change` must not leave a half-edited document behind: the automation + // servers catch panics and keep serving this session. (On wasm a panic aborts, so + // there is nothing to restore.) + let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| change(self))); + let result = match ran { + Ok(result) => result, + Err(panic) => { + self.restore_after_failed_edit(before); + std::panic::resume_unwind(panic); + } + }; + let result = result.and_then(|(value, changed)| { if changed && let Some(id) = self.doc.project.instance_cycle() { return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))); } @@ -735,15 +792,21 @@ impl Session { Ok(value) } Err(error) => { - self.doc = before; - - // A failed repaint may have cached tiles from the discarded document - self.path_cache = None; + self.restore_after_failed_edit(before); Err(error) } } } + /// Put `before` back after an edit failed or panicked. The edit may have recomposited the + /// discarded document (draining the dirty tiles) or cached path tiles from it, so mark what + /// differs between the two dirty again, as undo does. + fn restore_after_failed_edit(&mut self, before: Document) { + let discarded = std::mem::replace(&mut self.doc, before); + self.path_cache = None; + self.invalidate_changed(&discarded); + } + pub(crate) fn push_history(&mut self, label: &str, before: Document) { self.record(label, before, false); } @@ -860,6 +923,12 @@ impl Session { ) }; for (texture_set_index, cache) in self.caches.iter_mut().enumerate() { + // Display-only settings change the uploaded textures, not the composite + let ao_mixing = |document: &Document| document.project.texture_sets.get(texture_set_index).map(|set| set.ao_mixing); + if ao_mixing(previous_document) != ao_mixing(&self.doc) { + cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); + } + if uses_added_resource(texture_set_index) { cache.invalidate_all(); continue; @@ -935,22 +1004,33 @@ impl Session { /// Make caches agree with the project's texture sets (resolution or channel changes). pub fn sync_caches(&mut self) { - let sets = self.doc.project.texture_sets.clone(); + let sets = &self.doc.project.texture_sets; self.caches.truncate(sets.len()); - for (i, ts) in sets.iter().enumerate() { - match self.caches.get_mut(i) { - Some(c) if c.size == ts.size() => { - let (want, scales) = (ts.channel_list(), ts.block_scales()); - if c.composite.channels.keys().copied().collect::>() != want || c.composite.block_scales != scales { - c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) }; - c.upload.extend(texturecraft_compose::all_tiles(c.size.0, c.size.1)); - c.invalidate_all(); + for (index, set) in sets.iter().enumerate() { + match self.caches.get_mut(index) { + Some(cache) if cache.size == set.size() => { + if cache.uv_padding != set.uv_padding { + cache.uv_padding = set.uv_padding; + cache.padding = Arc::new(display_padding(&self.mesh, set, &cache.gbuf)); + cache.invalidate_all(); + } + + if !cache.formats.iter().copied().eq(set.iter_formats()) { + cache.formats = set.formats(); + cache.invalidate_all(); + } + + let scales = set.block_scales(); + if !cache.has_channels(set) || cache.composite.block_scales != scales { + cache.composite = Composite { block_scales: scales, ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) }; + cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); + cache.invalidate_all(); } } _ => { - let cache = SetCache::new(&self.mesh, ts); - if i < self.caches.len() { - self.caches[i] = cache; + let cache = SetCache::new(&self.mesh, set); + if index < self.caches.len() { + self.caches[index] = cache; } else { self.caches.push(cache); } @@ -987,7 +1067,12 @@ impl Session { /// The undone steps, the next one to redo first. pub fn redo_labels(&self) -> Vec { - self.redo.iter().rev().map(|(l, _)| l.clone()).collect() + self.iter_redo_labels().map(str::to_owned).collect() + } + + /// Borrow undone step labels, with the next step to redo first + pub fn iter_redo_labels(&self) -> impl ExactSizeIterator { + self.redo.iter().rev().map(|(label, _)| label.as_str()) } /// Changes with every new undo step, not when a merged edit continues one @@ -997,7 +1082,12 @@ impl Session { /// The done steps, the oldest first pub fn history_labels(&self) -> Vec { - self.undo.iter().map(|(l, _)| l.clone()).collect() + self.iter_history_labels().map(str::to_owned).collect() + } + + /// Borrow the labels of completed steps, oldest first + pub fn iter_history_labels(&self) -> impl ExactSizeIterator { + self.undo.iter().map(|(label, _)| label.as_str()) } /// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order @@ -1061,13 +1151,17 @@ impl Session { self.invalidate_changed(other); // An undone add or duplicate takes the selected effect away - if let StackTarget::Effect(e) = self.target - && self.doc.project.effect(e).is_none() + if let StackTarget::Effect(effect_id) = self.target + && self.doc.project.effect(effect_id).is_none() { - let p = &other.project; - let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e)); + let previous_project = &other.project; + let content = previous_project + .effect(effect_id) + .and_then(|(owner, _)| previous_project.layers.get(&owner)) + .is_some_and(|layer| layer.content_effects.iter().any(|effect| effect.id == effect_id)); self.target = if content { StackTarget::Content } else { StackTarget::Mask }; } + let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some()); if self.target == StackTarget::Mask && !has_mask { self.target = StackTarget::Content; @@ -1202,7 +1296,7 @@ impl Session { ); // The composited tiles and the neighbours their padding reached change - let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); + let padded = pad_tiles(&mut cache.composite, &cache.padding, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); cache.revision = cache.revision.wrapping_add(1); changed = true; diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 2251a182..1df867b3 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelBlend, ChannelFormat}; +use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing, UvPaddingMode}; use std::sync::Arc; @@ -20,13 +20,23 @@ pub fn specs() -> Vec { "Inspect texture set", [], None, - "{ts?} → {index, name, resolution, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}", + "{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}", always, |s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?)) ), - cmd!("textureSet.resolution", "Texture set size", [], None, "{ts?, resolution: 128..8192 (power of two)}", always, resolution), + cmd!( + "textureSet.resolution", + "Texture set size", + [], + None, + "{ts?, resolution: 128..8192 (power of two, texels across), height?: 128..8192 (texels down; default = resolution, a square set)}", + always, + resolution + ), cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)), cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)), + cmd!("textureSet.channels", "Add or remove channels", [], None, "{ts?, add?: [channel], remove?: [channel], allSets?}", always, channels), + cmd!("textureSet.channel.format", "Set channel format", [], None, "{ts?, channel, format}", always, channel_format), cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible), cmd!( "textureSet.visibility", @@ -37,8 +47,24 @@ pub fn specs() -> Vec { always, visibility ), - cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename), - cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings), + cmd!( + "textureSet.rename", + "Rename texture set", + [], + None, + "{ts?, name} or {ts?, reset: true} (back to the mesh material's name, `originalName` in inspect)", + always, + rename + ), + cmd!( + "textureSet.settings", + "Texture set settings", + [], + None, + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, uvPadding?: 3d|2d, normalFormat?: openGl|directX}", + always, + settings + ), cmd!( "textureSet.parts", "List mesh parts", @@ -67,18 +93,21 @@ pub fn parts(s: &Session, ts: usize) -> Vec { } pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { - match u64p(p, "ts") { - Some(t) if (t as usize) < s.set_count() => Ok(t as usize), - Some(t) => Err(bad(cmd, format!("no texture set {t}"))), - None => Ok(s.ts()), + if p.get("ts").is_none_or(Value::is_null) { + return Ok(s.ts()); } + + let index = u64p(p, "ts").ok_or_else(|| bad(cmd, "valid `ts` index required"))?; + usize::try_from(index).ok().filter(|&index| index < s.set_count()).ok_or_else(|| bad(cmd, format!("no texture set {index}"))) } fn select(s: &mut Session, p: &Value) -> Result { - let ts = u64p(p, "ts") - .map(|index| index as usize) - .filter(|index| *index < s.set_count()) - .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + let cmd = "textureSet.select"; + if p.get("ts").is_none_or(Value::is_null) { + return Err(bad(cmd, "valid `ts` index required")); + } + + let ts = ts_param(s, p, cmd)?; select_set(s, ts)?; Ok(json!({ "ts": ts })) } @@ -103,8 +132,12 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> { fn resolution(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.resolution")?; - let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?; - let task = s.resize_task(ts, u32::try_from(r).unwrap_or(0))?; + let width = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?; + let height = match p.get("height") { + None | Some(Value::Null) => width, + Some(_) => u64p(p, "height").ok_or_else(|| bad("textureSet.resolution", "`height` must be a number of texels"))?, + }; + let task = s.resize_task_to(ts, u32::try_from(width).unwrap_or(0), u32::try_from(height).unwrap_or(0))?; let out = task.run(&texturecraft_bake::Progress::new())?; s.apply_resize(out) } @@ -115,9 +148,11 @@ fn resolution(s: &mut Session, p: &Value) -> Result { pub struct ResizeTask { ts: usize, resolution: u32, + height: u32, doc: Document, mesh: Arc, - /// The session's revision and mesh when the task was made: the result applies only to them. + project_id: u64, + /// The revision and mesh used to calculate this result. from: (u64, u64), } @@ -125,10 +160,12 @@ pub struct ResizeTask { pub struct ResizeOutput { ts: usize, resolution: u32, + height: u32, doc: Document, /// The set's new caches (None when its UV tile layout moved: the session rebuilds them). cache: Option, log: crate::log::SessionLog, + project_id: u64, from: (u64, u64), } @@ -136,10 +173,14 @@ impl ResizeTask { /// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its /// caches. Progress goes from 0 to 1. pub fn run(self, progress: &texturecraft_bake::Progress) -> Result { - let ResizeTask { ts, resolution, mut doc, mesh, from } = self; + let ResizeTask { ts, resolution, height, mut doc, mesh, project_id, from } = self; let set = doc.project.texture_set_mut(ts)?; let old = set.clone(); - set.resolution = resolution; + set.set_size(resolution, height); + if set.resolution_height.is_some() && !set.tile_resolutions.is_empty() { + return Err(bad("textureSet.resolution", "a texture set whose UV tiles have their own sizes stays square")); + } + crate::session::check_size(set)?; let size = set.size(); let mut log = crate::log::SessionLog::new(); @@ -154,7 +195,7 @@ impl ResizeTask { let set = doc.project.texture_set(ts)?; let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set)); progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed); - Ok(ResizeOutput { ts, resolution, doc, cache, log, from }) + Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from }) } } @@ -166,23 +207,43 @@ impl ResizeOutput { } impl Session { - /// Prepare resizing texture set `ts` to `resolution` (a power of two, 128..8192). + /// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192) pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result { - let resolution = check_resolution(resolution)?; - self.doc.project.texture_set(ts)?; - self.cancel_stroke(); - Ok(ResizeTask { ts, resolution, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) }) + self.resize_task_to(ts, resolution, resolution) } - /// Apply a finished resize as one undo step. When the document changed while it ran, the - /// resize runs again here on the current document. - pub fn apply_resize(&mut self, out: ResizeOutput) -> Result { - if out.from != (self.revision, self.mesh_id) || self.stroke_active() { - let task = self.resize_task(out.ts, out.resolution)?; - return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?); + /// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192) + pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result { + let (resolution, height) = (check_resolution(width)?, check_resolution(height)?); + self.doc.project.texture_set(ts)?; + self.cancel_stroke(); + Ok(ResizeTask { + ts, + resolution, + height, + doc: self.doc.clone(), + mesh: self.mesh.clone(), + project_id: self.project_id, + from: (self.revision, self.mesh_id), + }) + } + + /// Apply a finished resize to its original project as one undo step. Edits made while the + /// resize ran are preserved by recomputing from the current document. + pub fn apply_resize(&mut self, mut out: ResizeOutput) -> Result { + if out.project_id != self.project_id { + return Err(bad("textureSet.resolution", "the project changed while the texture set was resizing")); } - let ResizeOutput { ts, resolution, doc, cache, log, .. } = out; + if out.from != (self.revision, self.mesh_id) || self.stroke_active() { + let (ts, width, height) = (out.ts, out.resolution, out.height); + + // Release the stale pixels and cache before building their replacement + drop(out); + out = self.resize_task_to(ts, width, height)?.run(&texturecraft_bake::Progress::new())?; + } + + let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out; let before = std::mem::replace(&mut self.doc, doc); // Install the new caches before adding history to avoid rebuilding them @@ -197,7 +258,7 @@ impl Session { } self.log.append(log); self.push_history("Texture set size", before); - Ok(json!({ "ts": ts, "resolution": resolution })) + Ok(json!({ "ts": ts, "resolution": resolution, "height": height })) } } @@ -217,15 +278,82 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result { Ok(Value::Null) } +/// Add and remove several channels in one undo step, on one texture set or on all of them +fn channels(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.channels"; + let list = |key: &str| -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::Array(items)) => items + .iter() + .map(|item| { + let name = item.as_str().ok_or_else(|| bad(cmd, format!("`{key}` lists channel names")))?; + Channel::parse(name).ok_or_else(|| bad(cmd, format!("unknown channel `{name}`"))) + }) + .collect(), + Some(_) => Err(bad(cmd, format!("`{key}` must be a list of channels"))), + } + }; + + let add = list("add")?; + let remove = list("remove")?; + + if remove.contains(&Channel::BaseColor) { + return Err(bad(cmd, "base color can't be removed")); + } + + if let Some(both) = add.iter().find(|c| remove.contains(c)) { + return Err(bad(cmd, format!("{} is both added and removed", both.label()))); + } + + let all_sets = match p.get("allSets") { + None | Some(Value::Null) => false, + Some(value) => value.as_bool().ok_or_else(|| bad(cmd, "`allSets` must be a boolean"))?, + }; + let sets: Vec = if all_sets { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] }; + + s.edit("Add or remove channels", |s| { + for &ts in &sets { + // A channel the set already has keeps its layers' channel switches + for &c in &add { + if !s.doc.project.texture_set(ts)?.has_channel(c) { + add_channel(s, ts, c)?; + } + } + s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c)); + } + Ok(()) + })?; + + Ok(json!({ "ts": sets })) +} + +/// Store a channel in another format; layer data keeps its precision, so a wider format brings back what was painted +fn channel_format(s: &mut Session, p: &Value) -> Result { + let cmd = "textureSet.channel.format"; + let ts = ts_param(s, p, cmd)?; + let c = channel_param(cmd, p, "channel")?.ok_or_else(|| bad(cmd, "`channel` is required"))?; + let name = strp(p, "format").ok_or_else(|| bad(cmd, "`format` is required"))?; + let all = || ChannelFormat::ALL.map(ChannelFormat::label).join(", "); + let format = ChannelFormat::parse(name).ok_or_else(|| bad(cmd, format!("unknown format {name:?} ({})", all())))?; + + s.edit("Channel format", |s| { + if s.doc.project.texture_set_mut(ts)?.set_channel_format(c, format) { + Ok(()) + } else { + Err(bad(cmd, format!("the texture set has no {} channel", c.label()))) + } + })?; + + let float = matches!(format, ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F); + Ok(if float { json!({"note": "float formats are stored at 16 bits for now, and values stay in the channel's range"}) } else { Value::Null }) +} + /// Add channel `c` to texture set `ts` (no-op when present) and enable it on the set's layers. /// Call inside [`Session::edit`]. pub(crate) fn add_channel(s: &mut Session, ts: usize, c: Channel) -> Result<()> { - let set = s.doc.project.texture_set_mut(ts)?; - if !set.has_channel(c) { - set.channels.push((c, ChannelFormat::default_for(c))); - set.channels.sort_by_key(|(c, _)| c.index()); - } - // Existing layers get the new channel enabled. + s.doc.project.texture_set_mut(ts)?.add_channel(c); + let ids: Vec<_> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect(); for id in ids { if let Ok(l) = s.doc.project.layer_mut(id) { @@ -264,13 +392,25 @@ fn visibility(s: &mut Session, p: &Value) -> Result { Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::>() })) } +/// Longest texture set name and description, in characters +const MAX_NAME_CHARS: usize = 128; +const MAX_DESCRIPTION_CHARS: usize = 4096; +/// Highest height strength a set takes +const MAX_HEIGHT_STRENGTH: f32 = 100.0; + fn rename(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.rename")?; - let name = strp(p, "name") - .map(str::trim) - .filter(|n| !n.is_empty() && n.chars().count() <= 128) - .ok_or_else(|| bad("textureSet.rename", "`name` is required"))? - .to_string(); + let name = if boolp(p, "reset") == Some(true) { + s.original_set_name(ts).ok_or_else(|| bad("textureSet.rename", "the mesh has no material name for this set"))?.to_string() + } else { + let name = strp(p, "name").map(str::trim).filter(|name| !name.is_empty()); + let name = name.ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))?; + if name.chars().count() > MAX_NAME_CHARS { + return Err(bad("textureSet.rename", format!("`name` is at most {MAX_NAME_CHARS} characters"))); + } + + name.to_string() + }; s.edit("Rename texture set", |s| { s.doc.project.texture_set_mut(ts)?.name = name; Ok(()) @@ -278,29 +418,184 @@ fn rename(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +impl Session { + /// The name set `ts` had when the mesh loaded: its material's name in the mesh + pub fn original_set_name(&self, ts: usize) -> Option<&str> { + let set = self.doc.project.texture_sets.get(ts)?; + self.mesh.materials.get(set.material).map(String::as_str).filter(|name| !name.trim().is_empty()) + } +} + fn settings(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.settings")?; - let nf = normal_format_param("textureSet.settings", p)?; + let normal_format = normal_format_param("textureSet.settings", p)?; + let normal_mixing = choice_param(p, "normalMixing", "normal mixing", NormalMixing::parse, &NormalMixing::ALL.map(NormalMixing::id))?; + let ao_mixing = choice_param(p, "aoMixing", "ambient occlusion mixing", AoMixing::parse, &AoMixing::ALL.map(AoMixing::id))?; + let height_to_normal = + choice_param(p, "heightToNormal", "height to normal method", HeightToNormalMethod::parse, &HeightToNormalMethod::ALL.map(HeightToNormalMethod::id))?; + let uv_padding = choice_param(p, "uvPadding", "UV padding", UvPaddingMode::parse, &UvPaddingMode::ALL.map(UvPaddingMode::id))?; s.edit("Texture set settings", |s| { - if let Some(n) = nf { - s.doc.project.normal_format = n; + if let Some(format) = normal_format { + s.doc.project.normal_format = format; } let set = s.doc.project.texture_set_mut(ts)?; - if let Some(d) = strp(p, "description") { - set.description = d.chars().take(4096).collect(); + if let Some(description) = strp(p, "description") { + set.description = description.chars().take(MAX_DESCRIPTION_CHARS).collect(); } - if let Some(h) = f32p(p, "heightStrength") { - set.height_strength = h.clamp(0.0, 100.0); + if let Some(strength) = f32p(p, "heightStrength") { + set.height_strength = strength.clamp(0.0, MAX_HEIGHT_STRENGTH); + } + if let Some(mixing) = normal_mixing { + set.normal_mixing = mixing; + } + if let Some(mixing) = ao_mixing { + set.ao_mixing = mixing; + } + if let Some(method) = height_to_normal { + set.height_to_normal = method; + } + if let Some(mode) = uv_padding { + set.uv_padding = mode; } Ok(()) })?; Ok(Value::Null) } +/// The optional setting `key` of `textureSet.settings`, one of `ids` +fn choice_param(p: &Value, key: &str, what: &str, parse: fn(&str) -> Option, ids: &[&str]) -> Result> { + let unknown = |value: &Value| bad("textureSet.settings", format!("unknown {what} {value} ({})", ids.join(" or "))); + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(value @ Value::String(id)) => parse(id).map(Some).ok_or_else(|| unknown(value)), + Some(other) => Err(unknown(other)), + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn channels_add_and_remove_together_in_one_undo_step_on_every_set() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let has = |s: &Session, ts: usize, c: Channel| s.doc.project.texture_sets[ts].has_channel(c); + assert!(has(&s, 1, Channel::Height) && !has(&s, 1, Channel::User3)); + let edit = json!({"add": ["emissive", "User3"], "remove": ["height"], "allSets": true}); + crate::execute(&mut s, "textureSet.channels", &edit).unwrap(); + for ts in 0..2 { + assert!(has(&s, ts, Channel::Emissive) && has(&s, ts, Channel::User3) && !has(&s, ts, Channel::Height), "set {ts}"); + } + crate::execute(&mut s, "edit.undo", &json!({})).unwrap(); + for ts in 0..2 { + assert!(!has(&s, ts, Channel::Emissive) && !has(&s, ts, Channel::User3) && has(&s, ts, Channel::Height), "set {ts}"); + } + + // Without allSets only the chosen set changes + crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["ior"]})).unwrap(); + assert!(has(&s, 1, Channel::Ior) && !has(&s, 0, Channel::Ior)); + assert!(crate::execute(&mut s, "textureSet.channels", &json!({"remove": ["baseColor"]})).is_err()); + assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["ior"], "remove": ["ior"]})).is_err()); + assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err()); + } + + #[test] + fn channels_applied_to_every_set_keep_the_channels_a_layer_switched_off() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "layer.add.fill", &json!({})).unwrap(); + let layer = s.selected_layer().unwrap(); + + // Switched off, as layer.blend {enabled: false} leaves it + s.doc.project.layer_mut(layer).unwrap().channels.remove(&Channel::Roughness); + let layer_has_roughness = |s: &Session| s.doc.project.layer(layer).is_ok_and(|l| l.channels.contains_key(&Channel::Roughness)); + assert!(!layer_has_roughness(&s)); + + // Apply to all Texture Sets sends every ticked channel, the ones the sets already have too + let ticked: Vec<&str> = s.doc.project.texture_sets[0].channel_list().iter().map(|c| c.id()).chain(["ior"]).collect(); + crate::execute(&mut s, "textureSet.channels", &json!({"add": ticked, "allSets": true})).unwrap(); + + assert!(s.doc.project.texture_sets.iter().all(|set| set.has_channel(Channel::Ior))); + assert!(!layer_has_roughness(&s), "the layer's roughness stays off"); + } + + #[test] + fn invalid_set_selectors_cannot_edit_the_active_set() { + let mut session = crate::sample_session(128, 64).unwrap(); + let before = session.doc.project.texture_sets[session.ts()].clone(); + + for ts in [json!("0"), json!(-1), json!(1_u64 << 32)] { + let params = json!({"ts": ts, "description": "wrong set"}); + + assert!(crate::execute(&mut session, "textureSet.settings", ¶ms).is_err(), "{ts}"); + assert_eq!(session.doc.project.texture_sets[session.ts()], before); + assert!(crate::execute(&mut session, "textureSet.select", ¶ms).is_err(), "{ts}"); + } + + let invalid_scope = json!({"add": ["user7"], "allSets": "true"}); + assert!(crate::execute(&mut session, "textureSet.channels", &invalid_scope).is_err()); + assert_eq!(session.doc.project.texture_sets[session.ts()], before); + } + + #[test] + fn malformed_size_and_setting_values_are_refused_and_change_nothing() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 256, "height": 128})).unwrap(); + let before = s.doc.project.texture_sets[0].clone(); + + assert!(crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 512, "height": "256"})).is_err()); + for (key, value) in [("normalMixing", json!(1)), ("aoMixing", json!(true)), ("heightToNormal", json!(["sharp"])), ("uvPadding", json!(2))] { + let mut params = json!({"ts": 0}); + params[key] = value.clone(); + assert!(crate::execute(&mut s, "textureSet.settings", ¶ms).is_err(), "{key}: {value}"); + } + + assert_eq!(s.doc.project.texture_sets[0], before); + } + + #[test] + fn a_sets_size_formats_and_settings_survive_save_and_reopen() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 1, "resolution": 256, "height": 128})).unwrap(); + crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 1, "channel": "roughness", "format": "L8"})).unwrap(); + crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["user7", "coatTangent"]})).unwrap(); + let settings = + json!({"ts": 1, "normalMixing": "replace", "aoMixing": "none", "heightToNormal": "sharp", "uvPadding": "2d", "description": "Ünïcode 説明"}); + crate::execute(&mut s, "textureSet.settings", &settings).unwrap(); + let inspect = |s: &mut Session, ts: usize| crate::execute(s, "textureSet.inspect", &json!({"ts": ts})).unwrap(); + let (first, second) = (inspect(&mut s, 0), inspect(&mut s, 1)); + + let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + + for (ts, before) in [(0, first), (1, second)] { + let after = inspect(&mut back, ts); + for key in ["resolution", "height", "size", "channels", "normalMixing", "aoMixing", "heightToNormal", "uvPadding", "description"] { + assert_eq!(after[key], before[key], "set {ts} {key}"); + } + } + assert_ne!(inspect(&mut back, 0)["uvPadding"], inspect(&mut back, 1)["uvPadding"], "each set keeps its own settings"); + } + + #[test] + fn rename_reset_restores_the_mesh_material_name() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let original = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"].clone(); + crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "Renamed"})).unwrap(); + let inspect = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap(); + assert_eq!((&inspect["name"], &inspect["originalName"]), (&json!("Renamed"), &original)); + crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "reset": true})).unwrap(); + assert_eq!(crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"], original); + assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1})).is_err()); + } + + #[test] + fn a_too_long_name_is_refused_for_its_length_not_as_missing() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let long = "n".repeat(MAX_NAME_CHARS + 1); + let error = crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": long})).unwrap_err().to_string(); + assert!(error.contains("at most") && !error.contains("required"), "{error}"); + assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "n".repeat(MAX_NAME_CHARS)})).is_ok()); + } + #[test] fn visibility_shows_hides_inverts_and_solos() { // The material ball has two texture sets. @@ -314,4 +609,144 @@ mod tests { assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true])); assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err()); } + + #[test] + fn normal_mixing_replace_keeps_height_out_of_the_normal_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mixing = |s: &Session| crate::inspect::texture_set(s, 0)["normalMixing"].clone(); + assert_eq!(mixing(&s), json!("combine")); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "normalMixing": "replace"})).unwrap(); + assert_eq!(mixing(&s), json!("replace")); + assert!(!s.doc.project.texture_sets[0].height_in_normal() && s.doc.project.texture_sets[1].height_in_normal()); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"normalMixing": "blend"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(mixing(&s), json!("combine")); + } + + #[test] + fn height_to_normal_method_is_set_by_command_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let method = |s: &Session, ts: usize| crate::inspect::texture_set(s, ts)["heightToNormal"].clone(); + assert_eq!(method(&s, 0), json!("smooth")); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "heightToNormal": "sharp"})).unwrap(); + assert_eq!((method(&s, 0), method(&s, 1)), (json!("sharp"), json!("smooth"))); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"heightToNormal": "blurry"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(method(&s, 0), json!("smooth")); + } + + #[test] + fn uv_padding_rebuilds_the_viewport_padding_and_undoes() { + // The ball's second set has texels just past its seams at this size + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 512).unwrap(); + let mode = |s: &Session| crate::inspect::texture_set(s, 1)["uvPadding"].clone(); + let crosses_seams = |s: &Session| !s.caches[1].padding.crossed.is_empty(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); + s.update(); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 1, "uvPadding": "2d"})).unwrap(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("2d"), false)); + assert!(!s.caches[1].dirty.is_empty(), "the set recomposites with its new padding"); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"uvPadding": "4d"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true)); + } + + #[test] + fn channel_format_changes_what_the_viewport_holds_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let format = |s: &Session| { + let channels = crate::inspect::texture_set(s, 0)["channels"].clone(); + channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == "roughness")).map(|entry| entry["format"].clone()) + }; + let roughness = |s: &mut Session| { + s.update(); + let img = &s.caches[0].composite.channels[&Channel::Roughness]; + let tile = s.caches[0].covered_tiles[0]; + img.tile(tile.0, tile.1).map(<[u16]>::to_vec).unwrap_or_default() + }; + crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L16"})).unwrap(); + + // A roughness off the 8-bit grid, so 8 bits visibly round it + crate::execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3013})).unwrap(); + let sixteen = roughness(&mut s); + assert_eq!(format(&s), Some(json!("L16"))); + + crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "Roughness", "format": "l8"})).unwrap(); + let eight = roughness(&mut s); + assert_eq!(format(&s), Some(json!("L8"))); + assert_ne!(eight, sixteen, "the composite holds 8 bits"); + let eight_bit_step = u16::MAX / u16::from(u8::MAX); + assert!(eight.iter().all(|v| v % eight_bit_step == 0), "every texel is on an 8-bit step"); + + let float = crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "height", "format": "L32F"})).unwrap(); + assert!(float["note"].is_string(), "a float format says it holds 16 bits"); + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L4"})).is_err()); + assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "emissive", "format": "L8"})).is_err()); + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!((format(&s), roughness(&mut s)), (Some(json!("L16")), sixteen)); + } + + #[test] + fn channels_added_after_a_format_is_set_keep_16_bits() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let format = |s: &Session, id: &str| { + let channels = crate::inspect::texture_set(s, 0)["channels"].clone(); + channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == id)).map(|entry| entry["format"].clone()) + }; + crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 0, "channel": "roughness", "format": "L8"})).unwrap(); + + crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": "user3"})).unwrap(); + crate::execute(&mut s, "textureSet.channels", &json!({"ts": 0, "add": ["user4"]})).unwrap(); + + assert_eq!((format(&s, "user3"), format(&s, "user4")), (Some(json!("L16")), Some(json!("L16")))); + assert_eq!(format(&s, "roughness"), Some(json!("L8")), "the set format stays"); + } + + #[test] + fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + s.update(); + let _ = (s.take_uploads(0), s.take_uploads(1)); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "aoMixing": "none"})).unwrap(); + assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("none")); + assert!(!s.take_uploads(0).is_empty() && s.take_uploads(1).is_empty(), "only the changed set is resent"); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"aoMixing": "screen"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("multiply")); + assert!(!s.take_uploads(0).is_empty(), "undo resends the set too"); + } + + #[test] + fn channels_our_shader_ignores_are_added_marked_and_exported() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + for channel in ["user3", "Displacement", "coat tangent"] { + crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": channel})).unwrap(); + } + let channels = crate::inspect::texture_set(&s, 0)["channels"].clone(); + let shaded = |id: &str| channels.as_array().and_then(|list| list.iter().find(|c| c["channel"] == id)).map(|c| c["shaded"].clone()); + assert_eq!((shaded("user3"), shaded("displacement"), shaded("coatTangent")), (Some(json!(false)), Some(json!(false)), Some(json!(false)))); + assert_eq!(shaded("baseColor"), Some(json!(true))); + + let plan = crate::execute(&mut s, "export.plan", &json!({"preset": "Separate maps"})).unwrap(); + let files: Vec<(Value, String)> = + plan.as_array().into_iter().flatten().map(|f| (f["ts"].clone(), f["file"].as_str().unwrap_or_default().to_ascii_lowercase())).collect(); + for map in ["user3", "displacement", "coattangent"] { + let from = |ts: usize| files.iter().any(|(t, file)| *t == json!(ts) && file.contains(map)); + assert!(from(0) && !from(1), "{map} exported only from the set that has it: {files:?}"); + } + + s.update(); + let composite = &s.caches[0].composite; + assert!(composite.channels.contains_key(&Channel::User3) && composite.channels.contains_key(&Channel::CoatTangent)); + } } diff --git a/crates/engine/src/solo.rs b/crates/engine/src/solo.rs index 454a8817..bf8c1b74 100644 --- a/crates/engine/src/solo.rs +++ b/crates/engine/src/solo.rs @@ -81,7 +81,7 @@ impl Session { let set = inputs.project.texture_sets.get(ts)?; let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) }; composite_tiles(inputs, &mut output, tiles); - pad_tiles(&mut output, &cache.dilation, tiles); + pad_tiles(&mut output, &cache.padding, tiles); Some(Cow::Owned(output)) }) } diff --git a/crates/engine/src/template_cmds.rs b/crates/engine/src/template_cmds.rs index e07370fc..68a2dc46 100644 --- a/crates/engine/src/template_cmds.rs +++ b/crates/engine/src/template_cmds.rs @@ -32,6 +32,8 @@ pub struct ProjectTemplate { pub normal_format: NormalFormat, /// Channels of every texture set, with their formats. pub channels: Vec<(Channel, ChannelFormat)>, + /// Whether the channels hold their formats' precision ([`texturecraft_core::TextureSet::format_precision`]); older templates keep 16 bits + pub format_precision: bool, /// Shader: PBR specular/glossiness instead of metallic/roughness. pub spec_gloss: bool, pub parallax: bool, @@ -49,6 +51,7 @@ impl Default for ProjectTemplate { resolution: 2048, normal_format: NormalFormat::OpenGl, channels: with_formats(&Channel::DEFAULT_SET), + format_precision: false, spec_gloss: d.spec_gloss, parallax: d.parallax, ior: d.ior, @@ -208,6 +211,7 @@ impl Session { for set_index in 0..project.texture_sets.len() { if let Some(set) = project.texture_sets.get_mut(set_index) { set.channels = template.channels.clone(); + set.format_precision = template.format_precision; } for (id, _) in project.walk(set_index) { @@ -304,6 +308,7 @@ fn save(session: &mut Session, params: &Value) -> Result { resolution: set.resolution, normal_format: project.normal_format, channels: set.channels.clone(), + format_precision: set.format_precision, spec_gloss: display.spec_gloss, parallax: display.parallax, ior: display.ior, @@ -443,6 +448,25 @@ mod tests { assert!(execute(&mut s, "project.new", &json!({"template": "nope"})).is_err()); } + #[test] + fn a_template_keeps_the_channel_formats_picked_in_the_set_it_was_saved_from() { + let dir = std::env::temp_dir().join(format!("tc_template_formats_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + s.load_templates(dir.clone()); + execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L8"})).unwrap(); + execute(&mut s, "project.template.save", &json!({"name": "Eight bit roughness"})).unwrap(); + + let mut fresh = Session::new_project("f", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + fresh.load_templates(dir.clone()); + execute(&mut fresh, "project.new", &json!({"template": "Eight bit roughness"})).unwrap(); + let held = |session: &Session, channel: Channel| session.doc.project.texture_sets[0].formats().into_iter().find(|(c, _)| *c == channel).map(|(_, f)| f); + + assert_eq!(held(&fresh, Channel::Roughness), held(&s, Channel::Roughness)); + assert_eq!(held(&fresh, Channel::Metallic), held(&s, Channel::Metallic), "the other channels keep 16 bits"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn save_current_settings_as_template_and_reload() { let dir = std::env::temp_dir().join(format!("tc_templates_{}", std::process::id())); diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index e417ce67..c7216b15 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -24,7 +24,38 @@ pub fn specs() -> Vec { } /// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. +#[cfg(not(target_arch = "wasm32"))] const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; +/// The built-in fonts' names, in [`provide_built_in_fonts`]'s order. +#[cfg(target_arch = "wasm32")] +const BUILT_IN_NAMES: [&str; 2] = ["Ubuntu Light", "Hack"]; +#[cfg(target_arch = "wasm32")] +static BUILT_IN_SOURCE: std::sync::OnceLock [&'static [u8]; 2]> = std::sync::OnceLock::new(); + +/// The web build's built-in fonts, Ubuntu Light and Hack, from `source`. The browser app already carries egui's faces +/// (deflated, for its download budget), so it says where to get them instead of the engine embedding a second, raw +/// copy. `source` runs once, when text first needs a built-in font. Only the first call counts. +#[cfg(target_arch = "wasm32")] +pub fn provide_built_in_fonts(source: fn() -> [&'static [u8]; 2]) { + let _ = BUILT_IN_SOURCE.set(source); +} + +/// The built-in fonts: names and bytes. On the web the bytes are empty without [`provide_built_in_fonts`]. +#[cfg(target_arch = "wasm32")] +fn built_in() -> [(&'static str, &'static [u8]); 2] { + static BYTES: std::sync::OnceLock<[&'static [u8]; 2]> = std::sync::OnceLock::new(); + let bytes = match BUILT_IN_SOURCE.get() { + Some(source) => *BYTES.get_or_init(*source), + None => [&[] as &[u8], &[]], + }; + [(BUILT_IN_NAMES[0], bytes[0]), (BUILT_IN_NAMES[1], bytes[1])] +} + +#[cfg(not(target_arch = "wasm32"))] +fn built_in() -> [(&'static str, &'static [u8]); 2] { + BUILT_IN +} + /// 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"]; @@ -54,7 +85,7 @@ fn fonts() -> Value { let families: Vec<(String, Vec)> = Vec::new(); json!({ "installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::>(), - "builtIn": BUILT_IN.map(|(name, _)| name), + "builtIn": built_in().map(|(name, _)| name), }) } @@ -62,7 +93,8 @@ fn fonts() -> Value { /// or the first default family installed, else the built-in font. fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> { let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b); - if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) { + let built_in = built_in(); + if let Some((_, bytes)) = built_in.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) { return Ok((std::borrow::Cow::Borrowed(bytes), 0)); } #[cfg(not(target_arch = "wasm32"))] @@ -91,7 +123,7 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow: let _ = style; match family { Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))), - None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)), + None => Ok((std::borrow::Cow::Borrowed(built_in[0].1), 0)), } } diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 977f34d6..a890113d 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -12,6 +12,12 @@ use crate::fill_mode::FillMode; use crate::session::{CloneFrom, CloneSource, StackTarget, Tool}; use crate::{Result, Session, cmd}; +/// Brush size the UI's full size slider stands for +const MAX_BRUSH_SIZE: f32 = 0.25; + +/// Full value of the UI's 0–100 brush scales +const PERCENT: f32 = 100.0; + pub fn specs() -> Vec { vec![ cmd!("tool.paint", "Paint", ["Tools"], Some("1"), "{}", always, |s, _| set_tool(s, Tool::Paint)), @@ -36,7 +42,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)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, angleFade?: [from, to] degrees 0..90 (culled faces fade out between them), screenSpace? (the size follows the view), stampDepth?: 0.05..4, 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?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -64,7 +70,7 @@ pub fn specs() -> Vec { ), cmd!( "tool.stencil", - "Projection stencil", + "Stencil", [], None, "{image?: resource name, center?: [x,y] NDC, scale?: 0.01..10, rotation?: degrees, tile?, opacity?, clear?: bool}", @@ -132,14 +138,17 @@ fn select(s: &mut Session, p: &Value) -> Result { /// 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); + let percent = |key: &str| f32p(params, key).map(|value| value / PERCENT); if let Some(value) = percent("size") { - settings.size = value * 0.25; + settings.size = value * MAX_BRUSH_SIZE; } if let Some(value) = percent("minSize") { settings.min_size = value; } + if let Some(value) = boolp(params, "sizePressure") { + settings.size_pressure = value; + } if let Some(value) = percent("flow") { settings.flow = value; @@ -174,11 +183,11 @@ fn brush(session: &mut Session, params: &Value) -> Result { 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; + *slot = value / PERCENT; } } if let Some(value) = f32p(params, "jitterPosition") { - settings.jitter_position = value / 100.0; + settings.jitter_position = value / PERCENT; } let alpha = params.get("alpha"); @@ -215,6 +224,13 @@ fn brush(session: &mut Session, params: &Value) -> Result { if let Some(value) = boolp(params, "backfaceCulling") { settings.backface_culling = value; } + if params.get("angleFade").is_some() { + let [from, to] = pair(params, "angleFade").ok_or_else(|| bad("tool.brush", "`angleFade` must be [from, to] in degrees"))?; + settings.angle_fade = (from, to); + } + if let Some(value) = f32p(params, "stampDepth") { + settings.depth = value; + } if let Some(value) = boolp(params, "symmetryOn") { settings.symmetry.enabled = value; @@ -282,30 +298,32 @@ fn brush(session: &mut Session, params: &Value) -> Result { } } if let Some(value) = f32p(params, "smudgeStrength") { - session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0); + session.tool.smudge_strength = (value / PERCENT).clamp(0.0, 1.0); } session.revision = session.revision.wrapping_add(1); Ok(brush_json(session)) } +/// The brush settings `tool.brush` reports, on the UI's 0–100 scales pub(crate) fn brush_json(session: &Session) -> Value { let settings = &session.tool.brush; json!({ - "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, + "size": settings.size / MAX_BRUSH_SIZE * PERCENT, "minSize": settings.min_size * PERCENT, "sizePressure": settings.size_pressure, "flow": settings.flow * PERCENT, "opacity": settings.opacity * PERCENT, + "spacing": settings.spacing * PERCENT, "hardness": settings.hardness * PERCENT, "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!(settings.alpha.label()), }, - "alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0, - "alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, - "backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z], + "alphaSizeX": settings.alpha_params.size_x * PERCENT, "alphaSizeY": settings.alpha_params.size_y * PERCENT, + "alphaRoundness": settings.alpha_params.roundness * PERCENT, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert, + "backfaceCulling": settings.backface_culling, "angleFade": [settings.angle_fade.0, settings.angle_fade.1], "screenSpace": settings.screen_space, + "stampDepth": settings.depth, "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, - "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles, + "material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * PERCENT, "particles": settings.particles, "cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, "cloneAligned": session.tool.clone_aligned, }) diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index 1b6e23fc..96a9a344 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -50,6 +50,10 @@ fn tile_resolution(session: &mut Session, params: &Value) -> Result { return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles))); } + if texture_set.resolution_height.is_some() && resolution != texture_set.resolution { + return Err(bad(COMMAND, format!("UV tiles of a non-square texture set (\"{}\") can't have their own size", texture_set.name))); + } + let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile); if texture_set.tile_resolution(tile) == resolution && !removes_override { return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() })); @@ -299,6 +303,11 @@ mod tests { } } + /// Width and height of a PNG file, read from its header + fn png_size(bytes: &[u8]) -> (u32, u32) { + image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().unwrap() + } + /// Mean painted alpha over the covered texels of the set's current layout. fn painted_fraction(s: &Session) -> f64 { let id = s.doc.project.texture_sets[0].stack[0]; @@ -374,8 +383,6 @@ mod tests { execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap(); let files = s.export_files(&[0], &opts).unwrap(); - // PNG: width and height are the big-endian words after the IHDR tag. - let png_size = |b: &[u8]| (u32::from_be_bytes(b[16..20].try_into().unwrap()), u32::from_be_bytes(b[20..24].try_into().unwrap())); assert!(files.len() >= 4); for f in &files { let want = if f.name.contains("1002") { 128 } else { 256 }; @@ -383,6 +390,34 @@ mod tests { } } + #[test] + fn non_square_sets_keep_their_paint_export_wide_tiles_and_refuse_tile_sizes() { + let mut s = udim_session(); + paint_all(&mut s, 50000); + execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).unwrap(); + s.update(); + let (w, h) = s.doc.project.texture_sets[0].size(); + assert!(w > 2 * h, "two tiles side by side, each wider than tall: {:?}", (w, h)); + assert_eq!((s.caches[0].gbuf.width, s.caches[0].gbuf.height), (w, h)); + assert!(painted_fraction(&s) > 0.97); + let inspect = execute(&mut s, "textureSet.inspect", &json!({})).unwrap(); + assert!(inspect["height"].as_u64() < inspect["resolution"].as_u64()); + + let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap(); + for f in &s.export_files(&[0], &opts).unwrap() { + let (fw, fh) = png_size(&f.bytes); + assert!(fw > fh, "{} is {fw}x{fh}", f.name); + } + + assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).is_err()); + s.undo().unwrap(); + assert_eq!(s.doc.project.texture_sets[0].size(), (512, 256)); + + // A set whose tiles have their own sizes stays square + execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + assert!(execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).is_err()); + } + /// Paint channel `c` of the first layer over every covered texel as `f(u)`, `u` the texel's /// position across its own UV tile (0..1), so every tile shows the same pattern in UV space. fn paint_across_tiles(s: &mut Session, c: Channel, f: impl Fn(f32) -> Vec) { diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 9d102c13..ed6d8fea 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Set view mode", [], None, - "{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|image (an image resource shown as it is on the mesh and in the 2D view)|mask||map:, image? (the resource, for image), layer? (for mask)}", + "{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|image (an image resource shown as it is on the mesh and in the 2D view)|mask||map:, image? (the resource, for image), layer? (for mask)}", always, view ), @@ -161,7 +161,7 @@ fn set_view(s: &mut Session, v: ViewMode) -> Result { /// C and Shift+C: the set's channels, then "Normal+height+mesh", then round again fn cycle_channel(s: &mut Session, d: i64) -> Result { - let mut views: Vec = s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default().into_iter().map(ViewMode::Channel).collect(); + let mut views: Vec<_> = s.doc.project.texture_sets.get(s.ts()).into_iter().flat_map(|set| set.viewport_channels()).map(ViewMode::Channel).collect(); if views.is_empty() { return set_view(s, ViewMode::Material); } @@ -217,7 +217,14 @@ fn view(s: &mut Session, p: &Value) -> Result { } _ => match m.strip_prefix("map:") { Some(id) => ViewMode::MeshMap(BakedMap::parse(id).ok_or_else(|| bad("viewport.view", format!("unknown mesh map `{id}`")))?), - None => ViewMode::Channel(Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?), + None => { + let channel = Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?; + if !channel.is_shaded() { + return Err(bad("viewport.view", format!("{} is stored for export and has no viewport view", channel.label()))); + } + + ViewMode::Channel(channel) + } }, }; set_view(s, v) @@ -467,14 +474,22 @@ mod tests { assert!(channels.len() > 2); assert_eq!(s.view, ViewMode::Material); + execute(&mut s, "textureSet.channel.add", &json!({"channel": "user31"})).unwrap(); + + let result = execute(&mut s, "viewport.view", &json!({"mode": "user31"})); + assert!(result.is_err(), "the viewport cannot display an export-only channel"); + assert_eq!(s.view, ViewMode::Material); + // From the material C starts at the first channel let mut seen = Vec::new(); for _ in 0..channels.len() + 2 { seen.push(pressed(&mut s, "viewport.nextChannel")); } + let mut expected = channels.clone(); expected.push(ViewMode::NormalHeightMesh); expected.push(channels[0]); + assert_eq!(seen, expected, "channels, then Normal+height+mesh, then round again"); // Shift+C walks it backwards, and from the material starts at the last entry diff --git a/crates/engine/tests/it/bake_resolution.rs b/crates/engine/tests/it/bake_resolution.rs index f690d2ae..1505700d 100644 --- a/crates/engine/tests/it/bake_resolution.rs +++ b/crates/engine/tests/it/bake_resolution.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use serde_json::json; use texturecraft_engine::bake::Progress; -use texturecraft_engine::core::BakedMap; +use texturecraft_engine::core::{AoMixing, BakedMap}; use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives}; use texturecraft_engine::{Session, execute}; @@ -103,8 +103,11 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() { let map = BakedMap::AmbientOcclusion; assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001); let composite = &session.caches[0].composite; - let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1); - assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile"); + let corner = ((56 * 64 + 56) * 4) as usize; + let display = tile_bytes(composite, baked, AoMixing::Multiply, DisplayKind::Orm, 5, 1); + assert_eq!(display[corner], 240, "the viewport samples the far corner of the smaller working tile"); + let unmixed = tile_bytes(composite, baked, AoMixing::None, DisplayKind::Orm, 5, 1); + assert!(unmixed[corner] > display[corner], "ambient occlusion mixing None leaves the baked map out of the viewport"); let options = ExportOptions::new(ExportPreset { name: "Bake detail".into(), diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index dca3a215..e5a01740 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -39,6 +39,7 @@ fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { let small = options(SMALL_SIDE); let large = options(4096); let first = session.export_files(&[0], &small).unwrap(); + assert!(first.len() > 1, "the mesh supplies multiple PSD tiles"); let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4)); diff --git a/crates/engine/tests/it/export_maps.rs b/crates/engine/tests/it/export_maps.rs index f147ef1b..2240b8a8 100644 --- a/crates/engine/tests/it/export_maps.rs +++ b/crates/engine/tests/it/export_maps.rs @@ -70,6 +70,32 @@ fn planned_uv_tile_sizes_match_the_written_files() { std::fs::remove_dir_all(directory).unwrap(); } +#[test] +fn rectangular_map_overrides_plan_the_dimensions_written_by_png_and_psd() { + let mut session = session(); + execute(&mut session, "textureSet.resolution", &json!({"ts": 0, "resolution": 128, "height": 256})).unwrap(); + let directory = tempfile::tempdir().unwrap(); + let preset = json!({"name": "Mixed", "maps": [ + {"file": "one", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}, + {"file": "two", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + let params = json!({"dir": directory.path(), "ts": 0, "preset": preset, "size": 256, "maps": [{"map": 0, "size": 128}, {"map": 1, "size": 128}]}); + + let files = execute(&mut session, "export.plan", ¶ms).unwrap(); + execute(&mut session, "file.exportTextures", ¶ms).unwrap(); + + let files = files.as_array().unwrap(); + assert_eq!(files.len(), 2, "{files:?}"); + for file in files { + let bytes = std::fs::read(directory.path().join(file["file"].as_str().unwrap())).unwrap(); + let (width_bytes, height_bytes) = if file["format"] == "psd" { (&bytes[18..22], &bytes[14..18]) } else { (&bytes[16..20], &bytes[20..24]) }; + let (width, height) = (u32::from_be_bytes(width_bytes.try_into().unwrap()), u32::from_be_bytes(height_bytes.try_into().unwrap())); + assert_eq!(height, 2 * width, "{file}"); + assert_eq!((file["size"].as_u64(), file["height"].as_u64()), (Some(u64::from(width)), Some(u64::from(height))), "{file}"); + assert_eq!(file["size"], file["sourceSize"], "both maps override the export width with the source width"); + } +} + #[test] fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() { let mut s = session(); diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 3dbfd83c..01f63de0 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -67,6 +67,7 @@ mod perf; mod polygon_fill; mod project_recovery; mod rebuilt_uv_layout; +mod rename_project; mod resource_updater; mod resources_used; mod sample; diff --git a/crates/engine/tests/it/materialcraft_link.rs b/crates/engine/tests/it/materialcraft_link.rs index 4a4a5d03..1ee696e1 100644 --- a/crates/engine/tests/it/materialcraft_link.rs +++ b/crates/engine/tests/it/materialcraft_link.rs @@ -47,7 +47,7 @@ fn cooked(roughness: f32, wear: f32) -> CookedMaterial { CookedMaterial::new(serde_json::from_value(interface).unwrap(), maps, 4) } -fn install(session: &mut Session) -> LayerId { +pub(crate) fn install(session: &mut Session) -> LayerId { session.add_cooked_material(&cooked(0.25, 0.5), Arc::new(b"package bytes".to_vec()), "mcmat", Place::Selection).unwrap() } diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index c6ee8dfe..8d95bb01 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -523,19 +523,29 @@ fn sets_with_the_same_file_name_warn_instead_of_overwriting() { fn a_material_never_points_at_a_texture_kept_for_another_set() { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - // The first set's name expands to the same base-colour filename as the second - execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "$channel"})).unwrap(); - execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "baseColor"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "body"})).unwrap(); + execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "trim"})).unwrap(); let directory = temp("shared-map"); - let result = export(&mut session, &directory, OPENPBR, true); + // Give the first set a map with the same filename as the second set's canonical base colour + let mut preset = texturecraft_engine::formats::builtin_preset(OPENPBR).unwrap(); + let mut conflicting_map = preset.maps.iter().find(|map| map.file.ends_with("_base_color")).unwrap().clone(); + let conflicting_stem = "material_ball_trim_base_color"; + conflicting_map.file = conflicting_stem.into(); + preset.maps.push(conflicting_map); - let materials: Vec<_> = files(&result).into_iter().filter(|path| path.ends_with(".mtlx")).collect(); - assert!(materials.len() >= 2, "{result}"); - assert!(std::fs::read_to_string(&materials[0]).unwrap().contains("material_ball_baseColor_base_color.png")); - for material in materials.iter().skip(1) { - assert!(!std::fs::read_to_string(material).unwrap().contains("material_ball_baseColor_base_color.png"), "{material}"); - } + let result = + execute(&mut session, "file.exportTextures", &json!({"dir": directory.display().to_string(), "preset": preset, "ts": [0, 1], "materialX": true})) + .unwrap(); + + let conflicting_file = format!("{conflicting_stem}.png"); + assert!(names(&result).contains(&conflicting_file), "{result}"); + assert!(warned(&result, &format!("\"{conflicting_file}\" was not written")), "{result}"); + let body = referenced(&std::fs::read_to_string(directory.join("material_ball_body.mtlx")).unwrap()); + let trim = referenced(&std::fs::read_to_string(directory.join("material_ball_trim.mtlx")).unwrap()); + assert!(body.iter().any(|file| file == "material_ball_body_base_color.png"), "{body:?}"); + assert!(trim.iter().any(|file| file.starts_with("material_ball_trim_")), "{trim:?}"); + assert!(!trim.contains(&conflicting_file), "{trim:?}"); } #[test] diff --git a/crates/engine/tests/it/perf.rs b/crates/engine/tests/it/perf.rs index d40cde56..2acafc3d 100644 --- a/crates/engine/tests/it/perf.rs +++ b/crates/engine/tests/it/perf.rs @@ -5,7 +5,7 @@ use std::time::{Duration, Instant}; use rayon::prelude::*; use serde_json::{Value, json}; use texturecraft_engine::compose::{DisplayKind, kinds_for, tile_bytes}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{AoMixing, Channel}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; use texturecraft_engine::texel::TILE; @@ -64,7 +64,7 @@ fn upload_bytes(session: &mut Session) -> (usize, usize) { let selected_bytes = tiles .par_iter() .flat_map_iter(|&(tile_x, tile_y)| kinds.iter().map(move |&kind| (kind, tile_x, tile_y))) - .map(|(kind, tile_x, tile_y)| tile_bytes(composite, baked, kind, tile_x, tile_y).len()) + .map(|(kind, tile_x, tile_y)| tile_bytes(composite, baked, AoMixing::Multiply, kind, tile_x, tile_y).len()) .sum(); let all_bytes_per_tile: usize = DisplayKind::ALL.iter().map(|kind| kind.bytes_per_texel() * (TILE * TILE) as usize).sum(); diff --git a/crates/engine/tests/it/rename_project.rs b/crates/engine/tests/it/rename_project.rs new file mode 100644 index 00000000..2bcca1a6 --- /dev/null +++ b/crates/engine/tests/it/rename_project.rs @@ -0,0 +1,63 @@ +//! `project.rename`: the name `$project` stands for in export file names. + +use serde_json::json; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +#[test] +fn a_renamed_project_exports_under_its_new_name_until_undone() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap(); + preset["maps"][0]["file"] = json!("$project_$textureSet"); + + execute(&mut session, "project.rename", &json!({"name": " Knight final "})).unwrap(); + + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + let renamed_file = plan[0]["file"].as_str().unwrap(); + assert!(renamed_file.starts_with("Knight_final_"), "{renamed_file}"); + + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); + assert_eq!(reopened.doc.project.name, "Knight final"); + + execute(&mut session, "edit.undo", &json!({})).unwrap(); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + + assert_eq!(session.doc.project.name, "hero"); + let restored_file = plan[0]["file"].as_str().unwrap(); + assert!(restored_file.starts_with("hero_"), "{restored_file}"); +} + +#[test] +fn an_unusable_or_unchanged_project_name_edits_nothing() { + use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; + + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + + for name in [json!(null), json!(7), json!(" "), json!("a\nb"), json!("界".repeat(MAX_PROJECT_NAME_CHARS + 1))] { + assert!(execute(&mut session, "project.rename", &json!({"name": name})).is_err(), "{name}"); + } + + execute(&mut session, "project.rename", &json!({"name": "hero"})).unwrap(); + + assert_eq!(session.doc.project.name, "hero"); + assert!(!session.modified, "nothing changed"); + assert!(!session.can_undo()); + + let at_limit = "界".repeat(MAX_PROJECT_NAME_CHARS); + let result = execute(&mut session, "project.rename", &json!({"name": format!(" {at_limit} ")})).unwrap(); + + assert_eq!(result["name"], at_limit); +} + +#[test] +fn a_renamed_project_is_inserted_into_the_template_as_literal_text() { + let mut session = Session::new_project("hero", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let mut preset = execute(&mut session, "export.preset.get", &json!({"name": "Document channels + Normal + AO (No Alpha)"})).unwrap(); + preset["maps"][0]["file"] = json!("$project/$mesh"); + + execute(&mut session, "project.rename", &json!({"name": "Knight/$mesh"})).unwrap(); + let plan = execute(&mut session, "export.plan", &json!({"preset": preset})).unwrap(); + + let file = plan[0]["file"].as_str().unwrap(); + assert!(file.starts_with("Knight__mesh/cube."), "{file}"); +} diff --git a/crates/engine/tests/it/resources_used.rs b/crates/engine/tests/it/resources_used.rs index bd89ee77..fbc15d44 100644 --- a/crates/engine/tests/it/resources_used.rs +++ b/crates/engine/tests/it/resources_used.rs @@ -1,7 +1,7 @@ //! The images a project reads beyond fill sources: a colour selection's ID map, a filter's image input, the mask brush and its paths use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, LayerKind}; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, execute}; @@ -53,6 +53,24 @@ fn removing_unused_resources_keeps_the_images_a_selection_a_filter_input_the_mas assert_eq!(reply["removed"], json!([unused]), "only the image nothing reads goes"); } +#[test] +fn removing_unused_resources_keeps_the_package_and_maps_of_a_material_linked_in_a_content_effect() { + let mut session = session(); + let unused = session.import_resource_bytes("unused.png", white_png()).unwrap(); + let linked = crate::materialcraft_link::install(&mut session); + let LayerKind::Fill(fill) = session.doc.project.layer(linked).unwrap().kind.clone() else { panic!("not a fill") }; + + // The linked material moves into a content effect of another layer, the only place that uses it + let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap(); + let effect = LayerId(execute(&mut session, "effect.add.fill", &json!({"layer": layer, "target": "content"})).unwrap()["effect"].as_u64().unwrap()); + session.doc.project.effect_mut(effect).unwrap().kind = EffectKind::Material(fill); + execute(&mut session, "layer.remove", &json!({"layer": linked.0})).unwrap(); + + let reply = execute(&mut session, "file.removeUnused", &Value::Null).unwrap(); + + assert_eq!(reply["removed"], json!([unused]), "the linked package and its maps stay"); +} + #[test] fn a_smart_material_carries_the_images_its_selection_and_filter_input_read() { let mut session = session(); diff --git a/crates/engine/tests/it/tool_settings.rs b/crates/engine/tests/it/tool_settings.rs index 281e28a0..ef5a921b 100644 --- a/crates/engine/tests/it/tool_settings.rs +++ b/crates/engine/tests/it/tool_settings.rs @@ -148,3 +148,26 @@ fn restored_stencil_and_smudge_settings_use_the_tool_limits() { let look = session.tool.stencil_look; assert_eq!((look.center, look.scale, look.opacity, look.rotation), ([-4.0, 4.0], 0.01, 0.0, 345.0)); } + +#[test] +fn tool_brush_sets_and_reports_the_projection_bands_settings() { + let mut session = another_project(); + let defaults = session.tool.brush.clone(); + let reported = execute(&mut session, "tool.brush", &json!({"angleFade": [20, 40], "stampDepth": 2.5, "screenSpace": !defaults.screen_space})).unwrap(); + + let brush = &session.tool.brush; + assert_ne!(brush.angle_fade, defaults.angle_fade, "Angle fade from / to changes through the command"); + assert_ne!(brush.depth, defaults.depth, "Stamp depth changes through the command"); + assert_eq!(reported["angleFade"], json!([brush.angle_fade.0, brush.angle_fade.1])); + assert_eq!(reported["stampDepth"], json!(brush.depth)); + assert_eq!(reported["screenSpace"], json!(brush.screen_space)); +} + +#[test] +fn a_malformed_angle_fade_leaves_the_brush_unchanged() { + let mut session = another_project(); + let before = session.tool.brush.clone(); + + assert!(execute(&mut session, "tool.brush", &json!({"size": 50, "angleFade": "steep"})).is_err()); + assert_eq!(session.tool.brush, before); +} diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index a130f813..55d5eacd 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -410,14 +410,14 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { #[test] fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { - let mut s = ball(); + let mut session = ball(); let dir = temp("psd"); - let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); + let result = export(&mut session, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true})); - assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}"); - let materials = read_back(&s, &dir); + assert!(files(&result).iter().any(|f| f.ends_with(".psd")), "{result}"); + let materials = read_back(&session, &dir); - assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]); - assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}"); + assert!(materials[material_of(&session, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&session, 0)]); + assert!(result["warnings"].to_string().contains("doesn't read PSD files"), "{result}"); } diff --git a/crates/engine/tests/it/uv_strokes.rs b/crates/engine/tests/it/uv_strokes.rs index 18a33fda..9d8466bc 100644 --- a/crates/engine/tests/it/uv_strokes.rs +++ b/crates/engine/tests/it/uv_strokes.rs @@ -103,3 +103,19 @@ fn decreasing_pressure_does_not_stamp_behind_a_turn() { assert!(red_at(&session, 0.33, 0.55), "the new segment is painted"); assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn"); } + +#[test] +fn a_light_pen_paints_at_full_size_with_size_pressure_off() { + let painted_across = |size_pressure: bool| { + let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "sizePressure": size_pressure, "hardness": 90})); + session.begin_stroke_uv([0.5, 0.5].into(), 0.2).unwrap(); + session.continue_stroke_uv([0.5, 0.5001].into(), 0.2); + session.end_stroke().unwrap(); + session.update(); + (0..RESOLUTION).filter(|x| red_at(&session, *x as f32 / RESOLUTION as f32, 0.5)).count() + }; + + let (pressed, ignored) = (painted_across(true), painted_across(false)); + assert!(pressed > 0, "a light pen still paints"); + assert!(ignored > pressed, "with size pressure off a light pen paints wider ({ignored} vs {pressed} texels)"); +} diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index d95c4358..d4f645ba 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -1,8 +1,9 @@ use serde_json::{Value, json}; +use texturecraft_engine::compose::PixelStore; use texturecraft_engine::core::{Channel, MIN_RESOLUTION}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, command_specs, execute}; +use texturecraft_engine::{Document, Session, command_specs, execute}; fn session() -> Session { session_at(256) @@ -17,6 +18,23 @@ fn session_at(texture_size: u32) -> Session { s } +/// Whether two documents hold the same content (`Document` has no `PartialEq`). Destructured so +/// a new public field must be compared here too (crate-private fields, such as `painted_regions`, +/// can't be reached from an integration test). +fn same_document(a: &Document, b: &Document) -> bool { + let Document { project, pixels: PixelStore { layers, masks }, baked, bake_paint, resources, bake_meshes, .. } = a; + // Bake meshes have no equality (each holds a mesh and its BVH): the same high polys and cage + // stand in for them. + let same_meshes = bake_meshes.high.len() == b.bake_meshes.high.len() && bake_meshes.cage.is_some() == b.bake_meshes.cage.is_some(); + *project == b.project + && *layers == b.pixels.layers + && *masks == b.pixels.masks + && *baked == b.baked + && *bake_paint == b.bake_paint + && *resources == b.resources + && same_meshes +} + #[test] fn scripted_stroke_paints_and_undo_restores() { let mut s = session(); @@ -500,6 +518,92 @@ fn an_srgb_hex_colour_matches_its_linear_rgb_value() { assert!(digits[0] - hex[0] > 0.1, "{digits:?} {hex:?}"); } +/// A command that panics halfway through an edit leaves the document and history as they were. +#[test] +fn a_panic_inside_an_edit_restores_the_document() { + let mut s = session(); + let before = s.doc.clone(); + let history = s.history_labels(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = s.edit("Half done", |s| -> texturecraft_engine::Result<()> { + s.doc.project.name = "changed".into(); + s.doc.pixels.mask_mut(texturecraft_engine::core::LayerId(u64::MAX), (64, 64)); + s.doc.resources.insert("half.png".into(), std::sync::Arc::new(vec![1, 2, 3])); + panic!("boom"); + }); + })); + assert!(r.is_err(), "the panic still reaches the caller"); + assert!(same_document(&s.doc, &before), "the half-made change was rolled back"); + assert_eq!(s.history_labels(), history, "no undo step was recorded"); +} + +/// An edit that recomposites the discarded document and then fails or panics: the display shows the +/// restored document again after the next `update`, not the discarded one. +#[test] +fn a_failed_or_panicking_edit_recomposites_the_restored_document() { + for panics in [false, true] { + let mut s = session(); + let hit = s.pick(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap(); + let (x, y) = ((hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32); + let red_at = |s: &mut Session| { + s.update(); + s.caches[0].composite.value(Channel::BaseColor, x, y)[0] + }; + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 90})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + let painted = red_at(&mut s); + assert!(painted > 0.9, "the stroke painted: {painted}"); + + let edit = |s: &mut Session| { + let _ = s.edit("Hide everything", |s| -> texturecraft_engine::Result<()> { + s.doc.project.texture_sets[0].stack.clear(); + s.touched(); + s.update(); + assert!(s.caches[0].composite.value(Channel::BaseColor, x, y)[0] < 0.9, "the edit shows the empty stack"); + if panics { + panic!("boom"); + } + Err(texturecraft_engine::EngineError::Other("nope".into())) + }); + }; + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| edit(&mut s))); + assert_eq!(r.is_err(), panics); + let shown = red_at(&mut s); + assert!(shown > 0.9, "panics={panics}: the restored paint is shown again: {shown}"); + } +} + +/// A command that fails leaves the document and history as they were (commands are atomic). +#[test] +fn failed_commands_leave_the_document_unchanged() { + let hostile = [ + Value::Null, + json!({}), + json!({"layer": u64::MAX, "ts": 99, "channel": "nope", "mode": "???", "opacity": f64::MAX}), + json!({"layer": 1, "index": -5, "delta": i64::MIN, "above": "x", "points": [[f64::MAX, -1e300]], "size": -1e30}), + json!({"resolution": 0, "maps": ["x"], "rays": u64::MAX, "antialiasing": 3, "color": [1], "value": "nan"}), + json!({"effect": 0, "x": 1e30, "y": -1e30, "viewport": [0, 0], "mesh": "../../etc", "material": ""}), + ]; + let mut offenders = Vec::new(); + for spec in command_specs() { + if spec.id == "project.sample" { + continue; // slow (bakes); covered elsewhere + } + for p in &hostile { + let mut s = session_at(MIN_RESOLUTION); + for texture_set in &mut s.doc.project.texture_sets { + texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R64; + } + let (before, history) = (s.doc.clone(), s.history_labels()); + if execute(&mut s, spec.id, p).is_err() && (!same_document(&s.doc, &before) || s.history_labels() != history) { + offenders.push(format!("{} {p}", spec.id)); + } + } + } + assert!(offenders.is_empty(), "failed commands changed the document:\n{}", offenders.join("\n")); +} + #[test] fn copy_paste_flatten_and_resize_keep_the_look() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); @@ -697,6 +801,224 @@ fn projection_tool_paints_the_stencil_colors() { assert!(right[1] > 0.8 && right[0] < 0.2, "right {right:?}"); } +/// The stencil tests' texture size, to turn a picked UV into a texel +const TEXTURE_SIZE: u32 = 256; + +/// Side of the stencil black on its left half and white on its right +const STENCIL_SIZE: u32 = 16; + +/// The view's row over the sphere the stencil tests paint along +const DAB_Y: f32 = 200.0; + +/// A dab behind the stencil's black half +const BLACK_DAB_X: f32 = 150.0; + +/// A dab behind the stencil's white half +const WHITE_DAB_X: f32 = 250.0; + +/// Imports a stencil black on its left half and white on its right, returning its resource name +fn half_black_stencil(session: &mut Session) -> String { + let stencil = image::RgbaImage::from_fn(STENCIL_SIZE, STENCIL_SIZE, |x, _| { + if x < STENCIL_SIZE / 2 { image::Rgba([0, 0, 0, 255]) } else { image::Rgba([255, 255, 255, 255]) } + }); + let mut png = Vec::new(); + stencil.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + + session.import_resource_bytes("half.png", png).unwrap() +} + +/// The composite base color under the view's point at `x` on the dab row +fn base_color_at(session: &Session, x: f32) -> [f32; 3] { + let hit = session.pick(Vec2::new(x, DAB_Y), session.viewport).unwrap(); + let texel = |coordinate: f32| (coordinate * TEXTURE_SIZE as f32) as u32; + + session.caches[0].composite.value(Channel::BaseColor, texel(hit.uv.x), texel(hit.uv.y)) +} + +#[test] +fn the_paint_tool_paints_its_own_color_through_the_stencils_gray() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + let left_before = base_color_at(&session, BLACK_DAB_X); + + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + + let (left, right) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left, left_before, "black stencil blocks the paint"); + assert!(right[0] > 0.8 && right[1] < 0.2 && right[2] < 0.2, "white stencil lets the tool's red through: {right:?}"); +} + +#[test] +fn a_stroke_blocked_by_a_stencil_keeps_pixels_and_history() { + for (tool, alpha) in [("paint", 255), ("projection", 0)] { + let mut session = session_at(TEXTURE_SIZE); + let stencil = image::RgbaImage::from_pixel(STENCIL_SIZE, STENCIL_SIZE, image::Rgba([0, 0, 0, alpha])); + let mut png = Vec::new(); + stencil.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = session.import_resource_bytes("blocked.png", png).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + let layer = session.selected_layer_id().unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let history = session.history_labels(); + let redo = session.redo_labels(); + let revision = session.revision; + let tile_bytes = session.doc.pixels.bytes(); + let tiles = session.doc.pixels.layers.values().map(texturecraft_texel::TileImage::allocated_count).sum::(); + let color = base_color_at(&session, BLACK_DAB_X); + + let stroke = execute(&mut session, "tool.stroke", &json!({"points": [[BLACK_DAB_X, DAB_Y]]})).unwrap(); + let after_tiles = session.doc.pixels.layers.values().map(texturecraft_texel::TileImage::allocated_count).sum::(); + let after_tile_bytes = session.doc.pixels.bytes(); + println!("{tool}: {tiles} -> {after_tiles} retained tiles, {tile_bytes} -> {after_tile_bytes} retained tile bytes"); + + assert!(stroke["stamps"].as_u64().unwrap() > 0); + assert_eq!(base_color_at(&session, BLACK_DAB_X), color); + assert_eq!(after_tile_bytes, tile_bytes, "{tool} stored empty tiles"); + assert_eq!(after_tiles, tiles); + assert_eq!(session.history_labels(), history); + assert_eq!(session.redo_labels(), redo); + assert_eq!(session.revision, revision); + } +} + +#[test] +fn a_stroke_blocked_by_a_stencil_drops_its_unused_mask_effect() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[WHITE_DAB_X, DAB_Y]]})).unwrap(); + let painted_color = base_color_at(&session, WHITE_DAB_X); + let id = session.selected_layer_id().unwrap(); + session.target = texturecraft_engine::StackTarget::Mask; + let history = session.history_labels(); + let next_id = session.doc.project.next_id; + assert!(session.doc.project.layers[&id].mask.is_none()); + + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), session.viewport, 1.0).unwrap(); + + assert!(session.stroke_tiles() > 0); + session.caches[0].invalidate_all(); + session.update(); + assert_ne!(base_color_at(&session, WHITE_DAB_X), painted_color); + session.end_stroke().unwrap(); + session.update(); + + assert!(session.doc.project.layers[&id].mask.is_none()); + assert_eq!(session.doc.project.next_id, next_id); + assert!(session.doc.pixels.masks.is_empty()); + assert_eq!(session.history_labels(), history); + assert_eq!(base_color_at(&session, WHITE_DAB_X), painted_color); + + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), session.viewport, 1.0).unwrap(); + + assert!(session.stroke_tiles() > 0); + execute(&mut session, "layer.rename", &json!({"layer": id.0, "name": "Renamed while painting"})).unwrap(); + let history_after_rename = session.history_labels(); + + session.end_stroke().unwrap(); + + assert_eq!(session.doc.project.layers[&id].name, "Renamed while painting"); + assert!(session.doc.project.layers[&id].mask.is_some()); + assert_eq!(session.history_labels(), history_after_rename); + assert!(session.doc.pixels.masks.is_empty()); +} + +#[test] +fn the_eraser_erases_only_through_the_stencils_gray() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + 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(); + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + let (left_painted, right_painted) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + + execute(&mut session, "tool.eraser", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + for x in [BLACK_DAB_X, WHITE_DAB_X] { + execute(&mut session, "tool.stroke", &json!({"points": [[x, DAB_Y]]})).unwrap(); + } + + assert_eq!(base_color_at(&session, BLACK_DAB_X), left_painted, "black stencil keeps the paint from the eraser"); + assert_ne!(base_color_at(&session, WHITE_DAB_X), right_painted, "white stencil lets the eraser through"); +} + +#[test] +fn a_mask_stroke_shows_through_the_stencil_while_painting_as_it_commits() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + + // A red fill under a white mask the stroke paints black + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "mask.add.white", &Value::Null).unwrap(); + session.target = texturecraft_engine::StackTarget::Mask; + session.tool.mask_value = 0.0; + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + session.update(); + let (left_before, right_before) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + + // A stroke from behind the stencil's black half to its white half + let viewport = session.viewport; + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), 1.0); + session.update(); + let (left_preview, right_preview) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left_preview, left_before, "black stencil hides the live stroke"); + assert_ne!(right_preview, right_before, "white stencil shows the live stroke"); + + session.end_stroke().unwrap(); + session.update(); + let (left_committed, right_committed) = (base_color_at(&session, BLACK_DAB_X), base_color_at(&session, WHITE_DAB_X)); + assert_eq!(left_committed, left_before, "black stencil blocks the committed stroke"); + assert_ne!(right_committed, right_before, "white stencil lets the committed stroke through"); +} + +#[test] +fn a_live_paint_stroke_shows_through_the_stencil_on_every_channel_it_paints() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "roughness", "value": 0.0})).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + let channel_at = |session: &Session, channel: Channel, x: f32| { + let hit = session.pick(Vec2::new(x, DAB_Y), session.viewport).unwrap(); + let texel = |coordinate: f32| (coordinate * TEXTURE_SIZE as f32) as u32; + session.caches[0].composite.value(channel, texel(hit.uv.x), texel(hit.uv.y)) + }; + let before = + [Channel::BaseColor, Channel::Roughness].map(|channel| (channel_at(&session, channel, BLACK_DAB_X), channel_at(&session, channel, WHITE_DAB_X))); + + // A stroke from behind the stencil's black half to its white half, shown before it commits + let viewport = session.viewport; + session.begin_stroke(Vec2::new(BLACK_DAB_X, DAB_Y), viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), 1.0); + session.update(); + + for (channel, (left_before, right_before)) in [Channel::BaseColor, Channel::Roughness].into_iter().zip(before) { + assert_eq!(channel_at(&session, channel, BLACK_DAB_X), left_before, "black stencil hides the live {channel:?}"); + assert_ne!(channel_at(&session, channel, WHITE_DAB_X), right_before, "white stencil shows the live {channel:?}"); + } +} + #[test] fn smart_materials_save_and_load_with_pixels() { let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); @@ -771,6 +1093,36 @@ fn committed_strokes_settle_to_the_full_composite() { assert_eq!(full(&mut s), original); } +#[test] +fn synchronizing_a_saved_channel_order_preserves_the_composite() { + let mut session = texturecraft_engine::sample_session(128, 64).unwrap(); + session.doc.project.texture_sets[0].channels.reverse(); + let bytes = session.to_project_bytes().unwrap(); + let mut reopened = Session::from_project_bytes(&bytes).unwrap(); + reopened.update(); + reopened.caches[0].upload.clear(); + + reopened.sync_caches(); + + assert!(reopened.caches[0].dirty.is_empty(), "the unchanged set should keep its composited tiles"); + assert!(reopened.caches[0].upload.is_empty(), "the unchanged set should require no uploads"); +} + +#[test] +fn a_pending_resize_cannot_change_a_replacement_project() { + let mut session = session_at(128); + let task = session.resize_task_to(0, 512, 256).unwrap(); + execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap(); + let before = session.doc.clone(); + + let output = task.run(&texturecraft_engine::bake::Progress::new()).unwrap(); + let result = session.apply_resize(output); + + assert!(result.is_err(), "a resize from the previous project was accepted"); + assert!(same_document(&session.doc, &before)); + assert!(session.undo_label().is_none()); +} + /// A resize prepared from a snapshot and applied later matches the command, keeps edits made /// while it ran, and undoes in one step. #[test] @@ -1159,21 +1511,21 @@ fn interleaved_sessions_render_depth_from_their_own_mesh() { /// A full history keeps its length and may repeat its newest name, so views follow the count of steps added #[test] fn a_full_history_still_counts_each_new_step() { - let mut s = session(); + let mut session = session(); for _ in 0..texturecraft_engine::session::MAX_HISTORY { - execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); } - let (labels, added) = (s.history_labels(), s.steps_added()); + let (labels, added) = (session.history_labels(), session.steps_added()); - execute(&mut s, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + execute(&mut session, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); - assert_eq!(s.history_labels(), labels); - assert!(s.steps_added() > added); + assert_eq!(session.history_labels(), labels); + assert!(session.steps_added() > added); // A path preview paints through strokes of its own, none of which is a step - let added = s.steps_added(); - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + let added = session.steps_added(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); - assert_eq!(s.history_labels(), labels); - assert_eq!(s.steps_added(), added); + assert_eq!(session.history_labels(), labels); + assert_eq!(session.steps_added(), added); } diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index f7be380c..9e02c3f6 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -7,7 +7,7 @@ use texturecraft_texel::linear_to_srgb; use super::encoding::Encoding; use super::map_renderer::MapRenderer; use super::{ - ExportOptions, ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, Padding, PlannedFile, PlannedLayer, check_psd_size, psd_size, + ExportOptions, ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, Padding, PlannedFile, PlannedLayer, check_psd_size, output_dimensions, quantize_integer, quantize_u8, quantize_u16, }; use crate::{FormatError, Result}; @@ -45,10 +45,10 @@ fn working_set<'a>( ) -> Result<((u32, u32), u64, u64)> { let texels = |(width, height)| u64::from(width) * u64::from(height); let folder_count = layers.clone().map(|layer| layer.name.matches('/').count()).sum(); - let sizes = layers.map(|layer| psd_size(set, tile, options.map_size(layer.map))); + let sizes = layers.map(|layer| output_dimensions(set, tile, options.map_size(layer.map))); let (canvas, file_bytes) = check_psd_size(sizes.clone(), folder_count, depth)?; let float_bytes_per_texel = (PSD_RGBA_PLANES * size_of::()) as u64; - let source_bytes = texels(psd_size(set, tile, None)).saturating_mul(float_bytes_per_texel); + let source_bytes = texels(output_dimensions(set, tile, None)).saturating_mul(float_bytes_per_texel); let largest_layer_bytes = sizes.map(texels).max().unwrap_or(0) * float_bytes_per_texel; // The merged image is built a row at a time: a canvas row and a layer row in floating point @@ -71,7 +71,7 @@ fn working_set<'a>( padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::()) as u64)); } - // The quantized layers kept so far and the merged image are part of the file; the encoder can hold staged pixels, planes and the output at once + // Budget for the retained layers and merged image alongside encoder planes, staging and output let rendering = scratch_bytes.max(merge_bytes).saturating_add(file_bytes); let encoding = 3 * file_bytes; let working_bytes = padding_bytes.saturating_add(rendering.max(encoding)).max(padding_peak); diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index a4401503..c84fbdaf 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -51,13 +51,14 @@ impl MapPreview { } // The file's longer side bounds the preview: the map's own size, else the export size, else the set's - let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); - let file_side = |source| super::scale_export_side(source, tile_res, options.map_size(map)); + let (cols, grid_rows) = set.tile_grid().map_or((1, 1), |grid| (grid.cols.max(1), grid.rows.max(1))); + let block = ((composite_width / cols).max(1), (height / grid_rows).max(1)); + let file_side = |source| super::scale_export_side(source, block.0, options.map_size(map)); let source_side = composite_width.max(height); let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(file_side(composite_width).max(file_side(height))).min(source_side); let width = super::scale_export_side(composite_width, source_side, Some(preview_side)); let rows = super::scale_export_side(height, source_side, Some(preview_side)); - let sampler = Sampler::new(input, options, set, tile_res, uncovered); + let sampler = Sampler::new(input, options, set, block, uncovered); let mut channel_layout = layout(set, spec); let grayscale = file.format == FileFormat::Pgm; if grayscale || matches!(file.format, FileFormat::Jpeg | FileFormat::Hdr) { diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index 3b493ab4..6f2f239b 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -1,9 +1,13 @@ use rayon::prelude::*; +use texturecraft_compose::PaddingMaps; use texturecraft_core::{TextureSet, TileGrid}; -use texturecraft_texel::{ColorSpace, DilationMap}; +use texturecraft_texel::ColorSpace; use super::rendered_map::RenderedMap; -use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, diffuse_blocks, layout, resize, scale_export_side, tile_side}; +use super::{ + At, Dest, ExportInput, ExportOptions, FileFormat, Padding, PlannedFile, Sampler, check_scaled_block, diffuse_blocks, layout, resize, scale_export_side, + tile_side, +}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; /// Renders the output maps of one texture set's export: the padding and sampling every map shares @@ -11,22 +15,23 @@ pub(super) struct MapRenderer<'a> { options: &'a ExportOptions, set: &'a TextureSet, sampler: Sampler<'a>, - dilation_map: Option, + padding: Option, grid: Option, /// The composite's size width: u32, height: u32, - /// Texels per atlas block (the width for a set without UV tiles) - tile_res: u32, + /// Dimensions of an atlas block (the whole texture for a set without UV tiles) + block: (u32, u32), } impl<'a> MapRenderer<'a> { - pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> Result> { + pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions, planned: &[PlannedFile]) -> Result> { let set = input.project.texture_set(input.ts)?; let (width, height) = (input.composite.resolution, input.composite.height); let grid = set.tile_grid(); - let tile_res = width / grid.map_or(1, |g| g.cols.max(1)); - if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) { + let (cols, rows) = grid.map_or((1, 1), |grid| (grid.cols.max(1), grid.rows.max(1))); + let block = (width / cols, height / rows); + if block.0.min(block.1) == 0 || block.0.max(block.1) > MAX_IMAGE_SIZE || (block.0 * cols, block.1 * rows) != (width, height) { return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); } @@ -34,16 +39,19 @@ impl<'a> MapRenderer<'a> { return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); } - // Padding stays inside each UV tile - let dilation_map = match options.padding { + for map in planned.iter().flat_map(PlannedFile::maps) { + check_scaled_block(set, block, options.map_size(map))?; + } + + // All maps share one padding lookup for this texture set + let make_padding = |reach| PaddingMaps::new(set.uv_padding, input.coverage, (width, height), reach, block, input.seams); + let padding = match options.padding { Padding::None => None, - Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => { - Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res)) - } - Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), + Padding::Dilation(reach) | Padding::DilationDefault(reach) | Padding::DilationDiffusion(reach) => Some(make_padding(Some(reach))), + Padding::Infinite => Some(make_padding(None)), }; - let sampler = Sampler::new(input, options, set, tile_res, false); - Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) + let sampler = Sampler::new(input, options, set, block, false); + Ok(MapRenderer { options, set, sampler, padding, grid, width, height, block }) } /// The export size of map `map_index`'s file of `tile` (None: the whole set) @@ -51,7 +59,7 @@ impl<'a> MapRenderer<'a> { let (_, _, w, h) = self.region(tile)?; // An atlas scales by the requested size per tile - let scale = |value| scale_export_side(value, self.tile_res, self.options.map_size(map_index)); + let scale = |value| scale_export_side(value, self.block.0, self.options.map_size(map_index)); Ok((scale(w), scale(h))) } @@ -62,8 +70,13 @@ impl<'a> MapRenderer<'a> { let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; // A tile smaller than its block fills the block's top-left corner - let side = tile_side(self.set, t, self.tile_res); - Ok((bx * self.tile_res, by * self.tile_res, side, side)) + let (width, height) = if self.set.tile_resolutions.is_empty() { + self.block + } else { + let side = tile_side(self.set, t, self.block.0); + (side, side) + }; + Ok((bx * self.block.0, by * self.block.1, width, height)) } _ => Ok((0, 0, self.width, self.height)), } @@ -76,27 +89,29 @@ impl<'a> MapRenderer<'a> { let channel_layout = layout(self.set, map); let component_count = channel_layout.len(); let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); + let pads_flat: Vec = channel_layout.iter().map(|(_, source)| source.pads_flat()).collect(); let (x0, y0, w, h) = self.region(tile)?; let size = self.size(map_index, tile)?; let sampler = &self.sampler; - let dilation_map = self.dilation_map.as_ref(); + let padding = self.padding.as_ref(); let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); let mut data = vec![0.0f32; w as usize * h as usize * component_count]; data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| { let y = y0 + row_y as u32; for (column, x) in (x0..x0 + w).enumerate() { - let at = if sampler.covered(x, y) { - Some(At::Texel(x, y)) - } else { - match dilation_map.and_then(|d| d.source(x, y)) { - Some((sx, sy)) => Some(At::Texel(sx, sy)), - None => beyond_default.then_some(At::Default), - } + let at = |cross_seams| { + padding + .and_then(|padding| padding.source(cross_seams, x, y)) + .map(|(sx, sy)| At::Texel(sx, sy)) + .or_else(|| beyond_default.then_some(At::Default)) }; - let Some(at) = at else { continue }; + let (padded, flat) = if sampler.covered(x, y) { (Some(At::Texel(x, y)), Some(At::Texel(x, y))) } else { (at(true), at(false)) }; + + // The normal cache is shared by virtual normal components, which all use flat padding let mut cache = None; for (component, (_, source)) in channel_layout.iter().enumerate() { + let Some(at) = (if pads_flat.get(component).copied().unwrap_or(false) { flat } else { padded }) else { continue }; if let Some(value) = row.get_mut(column * component_count + component) { let sample = sampler.sample(source, at, &mut cache); *value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample }; @@ -106,9 +121,16 @@ impl<'a> MapRenderer<'a> { }); // Diffuse into the texels the dilation did not reach - if let (Padding::DilationDiffusion(_), Some(dilation)) = (options.padding, dilation_map) { - let block = if tile.is_none() && self.grid.is_some() { self.tile_res } else { w.max(h) }; - diffuse_blocks(&mut data, (w as usize, h as usize), component_count, dilation, (x0 as usize, y0 as usize), block as usize); + if let (Padding::DilationDiffusion(_), Some(padding)) = (options.padding, padding) { + let block = if tile.is_none() && self.grid.is_some() { self.block } else { (w, h) }; + diffuse_blocks( + &mut data, + (w as usize, h as usize), + component_count, + &padding.flat, + (x0 as usize, y0 as usize), + (block.0 as usize, block.1 as usize), + ); } let mut data = resize(data, (w, h), component_count, size); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 8ca37c57..ea6a8cda 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -18,8 +18,8 @@ use std::io::Cursor; use craft_image_codecs::{ChannelLayout, EncodeOptions, Format as CodecFormat, Image as CodecImage, SampleType}; use rayon::prelude::*; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, Composite}; -use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; +use texturecraft_compose::{BakedMaps, Composite, SeamPaddingInput}; +use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, Project, TextureSet}; use texturecraft_geom::glam::Vec3; use texturecraft_texel::{ColorSpace, linear_to_srgb}; @@ -50,8 +50,8 @@ const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; /// Planes of a PSD image or layer: red, green, blue and alpha const PSD_RGBA_PLANES: usize = 4; -/// Preset limits (user presets are untrusted JSON). -const MAX_MAPS: usize = 64; +/// Preset limits (user presets are untrusted JSON); maps leave room for one per channel plus packed maps +const MAX_MAPS: usize = 128; const MAX_TEMPLATE: usize = 256; const MAX_STEM: usize = 200; /// Longest preset name. @@ -309,6 +309,16 @@ impl SourceRef { self.raw_component().min(2) } + /// Whether the source is a tangent-space normal, which pads in 2D whatever the set's UV padding + fn pads_flat(&self) -> bool { + match self { + SourceRef::Channel { channel, .. } => channel.kind() == ChannelKind::NormalMap, + SourceRef::Virtual { map, .. } => matches!(map, VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX | VirtualMap::HeightNormal), + SourceRef::Baked { map, .. } => matches!(map, BakedMap::Normal | BakedMap::BentNormal), + SourceRef::Constant(_) => false, + } + } + /// Components the source has (1 or 3; constants are 1). pub fn components(&self) -> usize { match self { @@ -518,6 +528,8 @@ pub struct ExportInput<'a, Coverage = bool> { pub composite: &'a Composite, pub baked: &'a BakedMaps, pub coverage: &'a [Coverage], + /// The set's UV seams, which padding across seams (3D) crosses + pub seams: Option<&'a SeamPaddingInput<'a>>, pub mesh_name: &'a str, } @@ -717,8 +729,32 @@ fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: imp } /// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. -pub fn sanitize_file_path(s: &str) -> String { - s.split('/').map(sanitize_file_stem).collect::>().join("/") +pub fn sanitize_file_path(path: &str) -> String { + if !path.contains('/') { + return sanitize_file_stem(path); + } + + path.split('/').map(sanitize_file_stem).collect::>().join("/") +} + +/// Expand tokens in the template while keeping the substituted values literal. +fn expand_file_template(template: &str, variables: &[(&str, &str)]) -> String { + let mut expanded = String::with_capacity(template.len()); + let mut remaining = template; + while let Some(index) = remaining.find('$') { + let (literal, variable) = remaining.split_at(index); + expanded.push_str(literal); + if let Some((value, tail)) = variables.iter().find_map(|&(token, value)| variable.strip_prefix(token).map(|tail| (value, tail))) { + expanded.push_str(value); + remaining = tail; + } else { + expanded.push('$'); + remaining = &variable[1..]; + } + } + + expanded.push_str(remaining); + expanded } /// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file @@ -743,10 +779,14 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti // Bucket layers in tile order to move their names into the corresponding PSD let mut psd_layers = Vec::new(); + + // A PSD map scaled past the largest side fails only the set's PSDs, as their other planning failures do + let mut psd_too_large = None; let project_stem = project.name.replace('/', "_"); let mesh_stem = mesh_name.replace('/', "_"); let set_stem = set.name.replace('/', "_"); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; + let (block_width, block_height) = set.block_size(); for (map_index, map) in opts.preset.maps.iter().enumerate() { if !map.is_available_for(set) { continue; @@ -755,6 +795,19 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti let own = opts.maps.get(&map_index); let (format, bit_depth, dither) = opts.map_file_type(map_index, map); let enabled = own.is_none_or(|o| o.enabled); + if enabled && let Err(error) = check_scaled_block(set, (block_width, block_height), opts.map_size(map_index)) { + if format != FileFormat::Psd { + return Err(error); + } + + if psd_too_large.is_none() { + psd_too_large = Some(match error { + FormatError::Invalid(reason) => reason, + other => other.to_string(), + }); + } + } + let space = opts.space_for_map(map, format, bit_depth); let requested_space = opts.space_for_depth(format, bit_depth); let color_map = map.is_color(); @@ -773,14 +826,19 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti } else { std::borrow::Cow::Borrowed(map.file.as_str()) }; + let channel = channel_label(map); let expand_stem = |udim: &str| { - let expanded = template - .replace("$udim", udim) - .replace("$project", &project_stem) - .replace("$mesh", &mesh_stem) - .replace("$textureSet", &set_stem) - .replace("$channel", channel_label(map)) - .replace("$colorSpace", color_space); + let expanded = expand_file_template( + &template, + &[ + ("$udim", udim), + ("$project", &project_stem), + ("$mesh", &mesh_stem), + ("$textureSet", &set_stem), + ("$channel", channel), + ("$colorSpace", color_space), + ], + ); sanitize_file_path(&expanded) }; @@ -880,6 +938,11 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) }; let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + if let Some(reason) = &psd_too_large { + psd_failures.push((name, FormatError::Invalid(reason.clone()))); + continue; + } + if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { psd_failures.push((name, error)); continue; @@ -915,12 +978,14 @@ pub fn is_set_warning(warning: &str) -> bool { fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { let mut name = format!("{stem}.{ext}"); let mut renamed = String::new(); - let mut k = 2; + let mut suffix_number = 2; + while used.contains(&name.to_ascii_lowercase()) { - renamed = format!("_{k}"); + renamed = format!("_{suffix_number}"); name = format!("{stem}{renamed}.{ext}"); - k += 1; + suffix_number += 1; } + if !renamed.is_empty() { warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); } @@ -960,23 +1025,19 @@ pub fn validate_export_paths<'a>(names: impl IntoIterator) -> Re Ok(()) } -/// The size of a PSD layer of a texture set at `export_size` for `tile` (None: the whole set, an atlas of a UV-tiled one) -fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { - let block_resolution = set.block_resolution(); - match (tile, set.tile_grid()) { - (Some(tile), Some(_)) => { - let side = scale_export_side(tile_side(set, tile, block_resolution), block_resolution, export_size); +/// The dimensions of a file or PSD layer, scaling relative to the width of one atlas block. +pub fn output_dimensions(set: &TextureSet, tile: Option, export_size: Option) -> (u32, u32) { + let (block_width, block_height) = set.block_size(); + let (width, height) = match (tile, set.tile_grid()) { + (Some(tile), Some(_)) if !set.tile_resolutions.is_empty() => { + let side = tile_side(set, tile, block_width); (side, side) } - (_, Some(grid)) => { - let side = export_size.unwrap_or(block_resolution); - (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) - } - (_, None) => { - let side = export_size.unwrap_or(block_resolution); - (side, side) - } - } + (Some(_), Some(_)) | (_, None) => (block_width, block_height), + (None, Some(grid)) => (block_width.saturating_mul(grid.cols), block_height.saturating_mul(grid.rows)), + }; + + (scale_export_side(width, block_width, export_size), scale_export_side(height, block_width, export_size)) } /// Plan a selection in export order, keeping only the first case-insensitive use of a name. @@ -1024,9 +1085,8 @@ struct Sampler<'a, Coverage = bool> { uncovered: Coverage, /// Composite width. res: u32, - /// Texels per atlas block (`res` for a classic set): the height slope and the Sobel window - /// follow the block. - tile_res: u32, + /// Texels across and down an atlas block (the composite for a classic set), which the height slope follows + block: (u32, u32), /// The share of its block each tile fills: a smaller tile's height slope shrinks with it. scales: BlockScales, /// Normal convention overriding every normal output. @@ -1047,8 +1107,8 @@ pub fn rnm(base: Vec3, detail: Vec3) -> Vec3 { } impl<'a, Coverage> Sampler<'a, Coverage> { - /// The sampler of `input`'s texture set `set`, whose atlas blocks are `tile_res` texels wide - fn new(input: &ExportInput<'a, Coverage>, options: &ExportOptions, set: &'a TextureSet, tile_res: u32, uncovered: Coverage) -> Self { + /// The sampler of `input`'s texture set `set`, with the given atlas block dimensions + fn new(input: &ExportInput<'a, Coverage>, options: &ExportOptions, set: &'a TextureSet, block: (u32, u32), uncovered: Coverage) -> Self { Sampler { set, comp: input.composite, @@ -1056,7 +1116,7 @@ impl<'a, Coverage> Sampler<'a, Coverage> { coverage: input.coverage, uncovered, res: input.composite.resolution, - tile_res, + block, scales: set.block_scales(), normal_override: options.normal_format, project_normal: input.project.normal_format, @@ -1086,29 +1146,35 @@ impl Sampler<'_, Coverage> { self.coverage.get((y as usize) * self.res as usize + x as usize).is_some_and(|sample| sample != &self.uncovered) } - /// Normal from the height channel (3×3 Sobel; uncovered neighbours repeat the centre). + /// Normal from the height channel (the set's height to normal method; uncovered neighbours repeat the centre) fn height_normal(&self, x: u32, y: u32) -> Vec3 { let center = self.channel(Channel::Height, At::Texel(x, y))[0]; - // Clamped to the texel's UV tile. - let t = self.tile_res.max(1); - let (x0, y0, last) = ((x / t * t) as i64, (y / t * t) as i64, t as i64 - 1); - let h = |dx: i64, dy: i64| { - let (sx, sy) = ((x as i64 + dx).clamp(x0, x0 + last) as u32, (y as i64 + dy).clamp(y0, y0 + last) as u32); + + // Use the current tile's edge values instead of sampling its neighbors + let (block_width, block_height) = (self.block.0.max(1), self.block.1.max(1)); + let (x0, y0) = ((x / block_width * block_width) as i64, (y / block_height * block_height) as i64); + let h = |dx: i32, dy: i32| { + let sx = (x as i64 + dx as i64).clamp(x0, x0 + block_width as i64 - 1) as u32; + let sy = (y as i64 + dy as i64).clamp(y0, y0 + block_height as i64 - 1) as u32; if self.covered(sx, sy) { self.channel(Channel::Height, At::Texel(sx, sy))[0] } else { center } }; - let gx = (h(1, -1) + 2.0 * h(1, 0) + h(1, 1) - h(-1, -1) - 2.0 * h(-1, 0) - h(-1, 1)) / 8.0; - let gy = (h(-1, 1) + 2.0 * h(0, 1) + h(1, 1) - h(-1, -1) - 2.0 * h(0, -1) - h(1, -1)) / 8.0; - let s = self.set.height_strength * self.tile_res as f32 * self.scales.at(x, y) / HEIGHT_SPAN; - // Image y points down; OpenGL normals have +Y up the image. - Vec3::new(-gx * s, gy * s, 1.0).try_normalize().unwrap_or(Vec3::Z) + let [gx, gy] = self.set.height_to_normal.slope(h); + + // Slopes per texel become slopes across the tile along each side + let strength = self.set.height_strength * self.scales.at(x, y) / HEIGHT_SPAN; + let (scale_x, scale_y) = (strength * block_width as f32, strength * block_height as f32); + + // OpenGL normal Y points up as image rows advance down + Vec3::new(-gx * scale_x, gy * scale_y, 1.0).try_normalize().unwrap_or(Vec3::Z) } /// The final tangent-space normal (OpenGL): baked normal ⊕ (height ⊕ normal channel). fn final_normal(&self, at: At) -> Vec3 { let At::Texel(x, y) = at else { return Vec3::Z }; + let base = if self.set.baked.contains(&BakedMap::Normal) { unpack(self.baked(BakedMap::Normal, at)) } else { Vec3::Z }; let mut detail = if self.set.has_channel(Channel::Normal) { unpack(self.channel(Channel::Normal, at)) } else { Vec3::Z }; - if self.set.normal_mixing == NormalMixing::Combine && self.set.has_channel(Channel::Height) && self.set.height_strength != 0.0 { + if self.set.height_in_normal() && self.set.has_channel(Channel::Height) && self.set.height_strength != 0.0 { detail = rnm(self.height_normal(x, y), detail); } rnm(base, detail) @@ -1156,6 +1222,7 @@ impl Sampler<'_, Coverage> { }, SourceRef::Baked { map, .. } => { let v = self.baked(*map, at); + // Tangent-space maps are stored with OpenGL green, like the normal map: write the format of the export if matches!(map, BakedMap::Normal | BakedMap::BentNormal) && self.normal_override.unwrap_or(self.project_normal) == NormalFormat::DirectX { [v[0], 1.0 - v[1], v[2]] @@ -1238,7 +1305,7 @@ fn render_planned_maps_within(input: &ExportInput, options: &ExportOptions, plan } } - let renderer = MapRenderer::new(input, options)?; + let renderer = MapRenderer::new(input, options, &planned)?; planned .into_iter() .zip(psd_sizes.into_iter().chain(std::iter::repeat(None))) @@ -1260,6 +1327,18 @@ fn tile_side(set: &TextureSet, tile: u32, block_resolution: u32) -> u32 { ((block_resolution as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block_resolution.max(1)) } +/// Refuse an export size that scales a non-square set's UV tile past the largest image side +fn check_scaled_block(set: &TextureSet, (block_width, block_height): (u32, u32), export_size: Option) -> Result<()> { + let width = export_size.unwrap_or(block_width); + let height = scale_export_side(block_height, block_width, export_size); + + if width.max(height) > MAX_IMAGE_SIZE { + return Err(FormatError::Invalid(format!("export size makes texture set \"{}\" {width}×{height}, over {MAX_IMAGE_SIZE} texels a side", set.name))); + } + + Ok(()) +} + /// Scale an image side relative to the source block, keeping a pixel for any nonempty source. pub fn scale_export_side(source_side: u32, block_resolution: u32, export_size: Option) -> u32 { let export_size = export_size.unwrap_or(block_resolution); @@ -1273,13 +1352,13 @@ fn diffuse_blocks( channels: usize, dilation: &texturecraft_texel::DilationMap, (origin_x, origin_y): (usize, usize), - block: usize, + (step_x, step_y): (usize, usize), ) { use texturecraft_texel::dilate::NONE; - for block_y in (0..height).step_by(block) { - for block_x in (0..width).step_by(block) { - let (block_width, block_height) = (block.min(width - block_x), block.min(height - block_y)); + for block_y in (0..height).step_by(step_y) { + for block_x in (0..width).step_by(step_x) { + let (block_width, block_height) = (step_x.min(width - block_x), step_y.min(height - block_y)); let source_rows = (origin_y + block_y..origin_y + block_y + block_height).map(|y| { let start = y * dilation.width as usize + origin_x + block_x; &dilation.src[start..start + block_width] diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 49f4b812..971c5d03 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1,7 +1,7 @@ use std::io::Cursor; use image::{DynamicImage, GenericImageView, ImageFormat}; -use texturecraft_core::{ChannelFormat, Project, TextureSet}; +use texturecraft_core::{ChannelFormat, Project, TextureSet, UvPaddingMode}; use texturecraft_texel::{to_u16, to_u16_signed}; use super::*; @@ -50,7 +50,7 @@ impl Fx { } fn input(&self) -> ExportInput<'_> { - ExportInput { project: &self.project, ts: 0, composite: &self.comp, baked: &self.baked, coverage: &self.coverage, mesh_name: "sphere" } + ExportInput { project: &self.project, ts: 0, composite: &self.comp, baked: &self.baked, coverage: &self.coverage, seams: None, mesh_name: "sphere" } } fn render(&self, opts: &ExportOptions) -> Vec { @@ -223,6 +223,20 @@ fn height_becomes_normal_detail() { assert_eq!(flat.get_pixel(30, 30).0, [128, 128, 255]); } +#[test] +fn height_to_normal_method_smooth_reaches_the_diagonal_neighbours() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Height]); + fx.set(Channel::Height, 30, 30, [1.0; 3]); + let normal_at = |fx: &Fx, x: u32, y: u32| decode(find(&fx.render_preset("Separate maps"), "_normal.png")).to_rgb8().get_pixel(x, y).0; + let flat = [128, 128, 255]; + + assert_eq!(fx.project.texture_sets[0].height_to_normal, texturecraft_core::HeightToNormalMethod::Smooth); + assert_ne!(normal_at(&fx, 31, 31), flat, "Sobel reads the bump from the diagonal"); + fx.project.texture_sets[0].height_to_normal = texturecraft_core::HeightToNormalMethod::Sharp; + assert_eq!(normal_at(&fx, 31, 31), flat, "Sharp only reads the neighbours across"); + assert_ne!(normal_at(&fx, 31, 30), flat, "Sharp still tilts beside the bump"); +} + #[test] fn reoriented_normal_mapping_identities() { let d = Vec3::new(0.2, -0.3, 0.9).normalize(); @@ -378,16 +392,17 @@ fn every_format_encodes_and_decodes() { for f in &files { assert!(f.name.ends_with(format.extension())); if format == FileFormat::Exr && f.name.starts_with("la") { - continue; // Y/A EXR is checked with the EXR crate in `exr_exports_luminance_and_alpha_at_both_depths`. + // The EXR-specific test reads luminance and alpha through the native decoder + continue; } assert_eq!(decode(f).dimensions(), (RES, RES), "{}", f.name); } // Roughness 0.25 everywhere survives every format (JPEG within its loss) - let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; + let roughness_sample = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1]; - assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}"); + assert!((roughness_sample - 0.25).abs() < 0.01, "{format:?}/{depth}: {roughness_sample}"); let base = find(&files, "_BaseColor."); match format { FileFormat::Jpeg | FileFormat::Hdr => assert!(base.warnings.iter().any(|w| w.contains("alpha")), "{format:?}"), @@ -670,7 +685,8 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() { } } } - let input = ExportInput { project: &project, ts: 0, composite: &comp, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "udim_plane" }; + let input = + ExportInput { project: &project, ts: 0, composite: &comp, baked: &BakedMaps::default(), coverage: &coverage, seams: None, mesh_name: "udim_plane" }; let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { @@ -721,7 +737,7 @@ fn small_export_size_keeps_each_nonempty_udim_tile_one_pixel_or_larger() { project.texture_sets.push(set); let composite = Composite::with_size(&[Channel::Roughness], 1024, 512); let coverage = vec![true; 1024 * 512]; - let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "m" }; + let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, seams: None, mesh_name: "m" }; for format in [FileFormat::Png, FileFormat::Psd] { let opts = ExportOptions { size: Some(2), padding: Padding::None, ..one_map(format, 8, roughness()) }; @@ -1261,6 +1277,46 @@ fn psd_layer_groups_follow_the_slashes_of_their_names() { assert_eq!(inner.children().iter().map(name).collect::>(), ["Leaf"]); } +#[test] +fn an_export_size_that_scales_a_tall_set_past_the_largest_side_is_refused() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].set_size(RES, RES * 4); + let mut options = one_map(FileFormat::Png, 8, roughness()); + options.size = Some(MAX_IMAGE_SIZE / 2); + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "the height would be twice the largest side"); + + options.size = Some(MAX_IMAGE_SIZE / 4); + assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1, "a tall export within the largest side is kept"); + + options.maps.insert(0, MapOverride { size: Some(MAX_IMAGE_SIZE / 2), ..MapOverride::default() }); + + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "a map's own size must pass the same limit"); + options.maps.get_mut(&0).unwrap().enabled = false; + assert!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().is_empty(), "a disabled map never allocates an image"); +} + +#[test] +fn a_psd_scaled_past_the_largest_side_leaves_the_sets_other_maps() { + let mut fx = Fx::new(&default_channels()); + let (width, height) = (RES, RES * 4); + fx.project.texture_sets[0].set_size(width, height); + fx.comp = Composite::with_size(&default_channels(), width, height); + fx.coverage.resize((width * height) as usize, true); + + let mut options = one_map(FileFormat::Png, 8, roughness()); + let mut psd = options.preset.maps[0].clone(); + (psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 8, rgba_half_alpha()); + options.preset.maps.push(psd); + options.maps.insert(1, MapOverride { size: Some(MAX_IMAGE_SIZE / 2), ..MapOverride::default() }); + + let files = render_maps(&fx.input(), &options).unwrap(); + + assert_eq!(files.len(), 1); + assert!(files[0].name.ends_with(".png")); + assert_eq!(decode(&files[0]).dimensions(), (width, height)); + assert!(files[0].warnings.iter().any(|warning| is_set_warning(warning) && warning.contains(&MAX_IMAGE_SIZE.to_string()))); +} + #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); @@ -1337,6 +1393,7 @@ fn feedback_psd_dithering_tracks_the_document_depth() { options.maps.insert(1, MapOverride { dither: Some(false), ..MapOverride::default() }); let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert!(plan[0].dither && plan[0].layers[0].dither && !plan[0].layers[1].dither); options.preset.maps[1].bit_depth = 16; @@ -1552,6 +1609,45 @@ fn dithering_is_ordered_and_keeps_the_average() { assert!(list_outputs(&fx.project, 0, "sphere", &wide).unwrap().iter().all(|p| !p.dither)); } +#[test] +fn padding_past_a_seam_takes_the_far_island_except_for_normals() { + // Two islands of one 3D edge: the left one's right side (x = 12) is the right one's left side (x = 20) + let mut fx = Fx::new(&default_channels()); + fx.coverage = (0..RES * RES).map(|i| matches!(i % RES, 4..=11 | 20..=27)).collect(); + fx.set_all(Channel::Roughness, |x, _| [if x < 16 { 0.2 } else { 0.8 }; 3]); + fx.set_all(Channel::Normal, |x, _| if x < 16 { [0.3, 0.5, 0.9] } else { [0.7, 0.5, 0.9] }); + let at = |x: f32, y: f32| texturecraft_geom::glam::Vec2::new(x, y) / RES as f32; + let left = texturecraft_geom::UvSeamSide { triangle: 0, start: at(12.0, 0.0), end: at(12.0, 64.0), interior: at(4.0, 0.0) }; + let right = texturecraft_geom::UvSeamSide { triangle: 1, start: at(20.0, 0.0), end: at(20.0, 64.0), interior: at(28.0, 0.0) }; + let triangles: Vec<_> = (0..RES * RES) + .map(|pixel| match pixel % RES { + 4..=11 => 0, + 20..=27 => 1, + _ => texturecraft_geom::NO_TRI, + }) + .collect(); + let mesh = texturecraft_geom::primitives::plane(1.0, 1); + let partition = texturecraft_geom::TrianglePartition::new(&mesh, 0, |_, _| Vec::::new()); + let seams = SeamPaddingInput::new(vec![texturecraft_geom::UvSeam { sides: [left, right] }], &triangles, partition); + let bent: Vec = (0..RES * RES).flat_map(|i| if i % RES < 16 { [0.3, 0.5, 0.9] } else { [0.7, 0.5, 0.9] }).collect(); + fx.baked = BakedMaps { resolution: RES, maps: [(BakedMap::BentNormal, std::sync::Arc::new(bent))].into() }; + fx.project.texture_sets[0].baked.insert(BakedMap::BentNormal); + let normal_x = SourceRef::Channel { channel: Channel::Normal, component: 0 }; + let bent_x = SourceRef::Baked { map: BakedMap::BentNormal, component: 0 }; + let mut options = one_map(FileFormat::Png, 16, vec![(Dest::R, roughness()[0].1.clone()), (Dest::G, normal_x), (Dest::B, bent_x)]); + options.padding = Padding::Dilation(4); + let render = |fx: &Fx| decode(&render_maps(&ExportInput { seams: Some(&seams), ..fx.input() }, &options).unwrap()[0]).to_rgb16(); + + // Just right of the left island: roughness continues from the right island, the normal and bent normal stay the left island's + let space_3d = render(&fx); + let (outside, near, far) = (space_3d.get_pixel(13, 30), space_3d.get_pixel(8, 30), space_3d.get_pixel(24, 30)); + assert_eq!((outside[0], outside[1], outside[2]), (far[0], near[1], near[2])); + + fx.project.texture_sets[0].uv_padding = UvPaddingMode::Space2d; + let space_2d = render(&fx); + assert_eq!(space_2d.get_pixel(13, 30), space_2d.get_pixel(8, 30)); +} + #[test] fn diffusion_padding_fills_beyond_the_dilation_smoothly() { let mut fx = Fx::new(&default_channels()); @@ -1887,9 +1983,10 @@ fn a_map_preview_holds_the_values_its_file_stores() { #[test] fn feedback_jpeg_previews_omit_the_alpha_channel() { let fx = Fx::new(&default_channels()); - let mut la = roughness(); - la.push((Dest::A, SourceRef::Constant(0.5))); - for (channels, expected) in [(la, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] { + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for (channels, expected) in [(gray_alpha, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] { let mut options = one_map(FileFormat::Png, 8, channels); let png_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap(); options.maps.insert(0, MapOverride { format: Some(FileFormat::Jpeg), ..MapOverride::default() }); @@ -1991,8 +2088,15 @@ fn triangle_coverage_preserves_uncovered_texels_and_height_normal_neighbours_in_ } let triangles: Vec<_> = fixture.coverage.iter().map(|covered| if *covered { 0 } else { texturecraft_geom::NO_TRI }).collect(); let input = fixture.input(); - let triangle_input = - ExportInput { project: input.project, ts: input.ts, composite: input.composite, baked: input.baked, coverage: &triangles, mesh_name: input.mesh_name }; + let triangle_input = ExportInput { + project: input.project, + ts: input.ts, + composite: input.composite, + baked: input.baked, + coverage: &triangles, + seams: input.seams, + mesh_name: input.mesh_name, + }; let options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); for map in 0..3 { @@ -2206,11 +2310,13 @@ fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { options.preset.maps[0].file = "Group/Map.$udim".into(); let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].layers[0].name, "Group/Map.1001"); options.preset.maps[0].file = "Map".into(); options.format_override = Some(FileFormat::Png); let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + assert_eq!(plan[0].name, "Map.1001.png"); } @@ -2235,6 +2341,7 @@ fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { assert_eq!(plans[3].1.name, "sphere_Body.1001_1.psd"); assert_eq!(plans[4].1.name, "sphere_Trim.psd"); let separate = list_outputs(&fx.project, 1, "sphere", &options).unwrap(); + assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); } @@ -2269,6 +2376,7 @@ fn psd_document_names_survive_sanitization_and_case_collisions() { assert!(separate.iter().any(|(set, name)| *set == index && name == unchanged)); } let tiled = list_outputs(&fx.project, 3, "sphere", &options).unwrap(); + assert!(tiled[0].udim_name.is_some()); assert_eq!(tiled[0].udim_name, tiled[1].udim_name, "tiles of one set keep the same pattern"); @@ -2312,10 +2420,12 @@ fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); let smaller = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead"); fx.project.texture_sets[0].uv_tiles.extend(1008..1034); let oversized = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB); + assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch"); let set = &fx.project.texture_sets[0]; diff --git a/crates/formats/src/mesh_import/external.rs b/crates/formats/src/mesh_import/external.rs index 3bf375cf..19ee954f 100644 --- a/crates/formats/src/mesh_import/external.rs +++ b/crates/formats/src/mesh_import/external.rs @@ -79,6 +79,7 @@ fn read_inside(dir: &std::path::Path, rel: &str) -> Option> { if !file.starts_with(&root) { return None; } + crate::read_capped(&file, MAX_MESH_FILE_BYTES).ok() } @@ -178,20 +179,22 @@ mod tests { assert_eq!(read_inside(&dir, "tex/missing.png"), None); assert!(link_dir(&dir.join("out"), &outside), "this system would not make a link"); assert_eq!(read_inside(&dir, "out/key.txt"), None, "through a link to another folder"); - // A link that stays inside the folder is an ordinary shortcut and still works. + assert!(link_dir(&dir.join("shortcut"), &dir.join("tex")), "this system would not make a link"); assert_eq!(read_inside(&dir, "shortcut/a.png").as_deref(), Some(&b"inside"[..]), "through a link to a folder inside"); - // A link to a single outside file (Unix symbolic links; Windows file links need privileges). + + // Windows file links can require privileges #[cfg(unix)] { std::os::unix::fs::symlink(outside.join("key.txt"), dir.join("tex/key.png")).unwrap(); assert_eq!(read_inside(&dir, "tex/key.png"), None, "through a link to an outside file"); } - // The mesh's own folder reached through a link is fine: both sides are resolved. + + // Resolve the mesh folder and the linked target before comparing them assert!(link_dir(&base.join("alias"), &dir), "this system would not make a link"); assert_eq!(read_inside(&base.join("alias"), "tex/a.png").as_deref(), Some(&b"inside"[..]), "folder given through a link"); - // The same through read_mesh_file: the outside bytes must not end up in the glTF. + // Check the bytes embedded in the exported mesh std::fs::write( dir.join("m.gltf"), br#"{"asset": {"version": "2.0"}, "buffers": [{"uri": "out/key.txt", "byteLength": 7}, {"uri": "tex/a.png", "byteLength": 6}]}"#, diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 0b34ceb5..54be197b 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -87,9 +87,12 @@ pub fn builtin_presets() -> Vec { vec![ preset(DEFAULT_PRESET, { let mut maps: Vec = - Channel::ALL.into_iter().filter(|c| !matches!(c, Channel::Normal | Channel::AmbientOcclusion)).map(channel_map).collect(); + Channel::ALL.into_iter().filter(|c| c.is_shaded() && !matches!(c, Channel::Normal | Channel::AmbientOcclusion)).map(channel_map).collect(); maps.push(map("normal", 8, rgb(|k| ch(Channel::Normal, k)))); maps.push(map("ambientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0)))); + + // Later channels come last, so the maps automation addresses by index keep their place + maps.extend(Channel::ALL.into_iter().filter(|c| !c.is_shaded()).map(channel_map)); maps }), // Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material diff --git a/crates/geom/src/lib.rs b/crates/geom/src/lib.rs index eb71f854..e9720ba7 100644 --- a/crates/geom/src/lib.rs +++ b/crates/geom/src/lib.rs @@ -13,6 +13,8 @@ pub mod mesh; pub mod primitives; pub mod triangle_partition; pub mod unwrap; +mod uv_seam; +mod uv_seam_side; pub use bvh::{Bvh, Hit}; pub use camera::{OrbitCamera, Ray}; @@ -20,6 +22,8 @@ pub use gbuffer::{NO_TRI, Surface, UvGBuffer, surface_at}; pub use glam; pub use mesh::{BaseColor, MAX_TRIANGLES, Mesh, SubMesh}; pub use triangle_partition::TrianglePartition; +pub use uv_seam::UvSeam; +pub use uv_seam_side::UvSeamSide; #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum GeomError { diff --git a/crates/geom/src/triangle_partition.rs b/crates/geom/src/triangle_partition.rs index 2ad6fb5c..d6a2d658 100644 --- a/crates/geom/src/triangle_partition.rs +++ b/crates/geom/src/triangle_partition.rs @@ -20,42 +20,57 @@ pub struct TrianglePartition { impl TrianglePartition { /// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both - pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { + pub fn new(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec) -> TrianglePartition { // Each triangle's edges once, in mesh order so the groups come out the same every time let triangles: Vec = mesh.triangles_of(material).map(|triangle| triangle as u32).collect(); - let position_of: HashMap = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect(); - let mut edge_lists: Vec> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect(); - let mut by_edge: HashMap> = HashMap::new(); - for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) { - for edge in triangle_edges { - by_edge.entry(edge.clone()).or_default().push(*triangle); + let mut neighbours = Vec::>::new(); + let mut edge_ids = Vec::new(); + let mut offsets = Vec::with_capacity(triangles.len() + 1); + offsets.push(0); + + // Keep compact edge indices for traversal and release the welding keys before the search + { + let mut index_by_edge = HashMap::new(); + for (position, &triangle) in triangles.iter().enumerate() { + for edge in edges(mesh, triangle as usize) { + let index = *index_by_edge.entry(edge).or_insert_with(|| { + neighbours.push(Vec::new()); + neighbours.len() - 1 + }); + neighbours[index].push(position); + edge_ids.push(index); + } + offsets.push(edge_ids.len()); } } let mut groups = Vec::new(); let mut group_of = HashMap::with_capacity(triangles.len()); - for &start in &triangles { - if group_of.contains_key(&start) { + let mut stack = Vec::new(); + for (start, &triangle) in triangles.iter().enumerate() { + if group_of.contains_key(&triangle) { continue; } let mut members = Vec::new(); - let mut stack = vec![start]; - group_of.insert(start, groups.len()); - while let Some(triangle) = stack.pop() { - members.push(triangle); - let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default(); + stack.push(start); + group_of.insert(triangle, groups.len()); + while let Some(position) = stack.pop() { + members.push(triangles[position]); - // Visit a shared edge once, including when many collapsed faces share the same key - for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) { - if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) { - entry.insert(groups.len()); - stack.push(neighbour); + // Visit shared edges once even when many collapsed faces share a key + for &edge in &edge_ids[offsets[position]..offsets[position + 1]] { + for neighbour in std::mem::take(&mut neighbours[edge]) { + if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(triangles[neighbour]) { + entry.insert(groups.len()); + stack.push(neighbour); + } } } } groups.push(members); } + TrianglePartition { groups, group_of } } diff --git a/crates/geom/src/uv_seam.rs b/crates/geom/src/uv_seam.rs new file mode 100644 index 00000000..916581e8 --- /dev/null +++ b/crates/geom/src/uv_seam.rs @@ -0,0 +1,110 @@ +//! UV seams: mesh edges two triangles share in 3D but not in UV space + +use std::collections::HashMap; + +use crate::triangle_partition::CORNER_GRID_STEPS; +use crate::{Mesh, TrianglePartition, UvSeamSide}; + +/// Edge ends closer than this share a UV position +const SAME_UV: f32 = 1e-5; + +/// A UV seam: the same 3D edge on two UV islands; both sides' starts are the same 3D point +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvSeam { + pub sides: [UvSeamSide; 2], +} + +impl UvSeam { + /// The seams between triangles of `material` + pub fn of_material(mesh: &Mesh, material: usize) -> Vec { + let tolerance = position_tolerance(mesh); + let mut first_sides = HashMap::new(); + let mut seams = Vec::new(); + for triangle in mesh.triangles_of(material) { + let Some(corners) = mesh.tri(triangle) else { + continue; + }; + + let triangle = triangle as u32; + + for edge in 0..3 { + let (first, second, third) = (corners[edge], corners[(edge + 1) % 3], corners[(edge + 2) % 3]); + let (Some(first_key), Some(second_key)) = (position_key(mesh, first, tolerance), position_key(mesh, second, tolerance)) else { + continue; + }; + + // A pole's collapsed edges have no length to cross + if first_key == second_key { + continue; + } + + let (Some(&first_uv), Some(&second_uv), Some(&interior)) = (mesh.uvs.get(first), mesh.uvs.get(second), mesh.uvs.get(third)) else { + continue; + }; + + // Each side starts at the corner with the smaller key, so both sides run the same way + let (key, side) = if first_key <= second_key { + ((first_key, second_key), UvSeamSide { triangle, start: first_uv, end: second_uv, interior }) + } else { + ((second_key, first_key), UvSeamSide { triangle, start: second_uv, end: first_uv, interior }) + }; + let Some(other) = first_sides.insert(key, side) else { + continue; + }; + + if side.start.distance(other.start) > SAME_UV || side.end.distance(other.end) > SAME_UV { + seams.push(UvSeam { sides: [other, side] }); + } + } + } + + seams + } + + /// Islands for seam padding, joined only where both the UVs and the surface continue + pub fn islands_of(mesh: &Mesh, material: usize) -> TrianglePartition { + let tolerance = position_tolerance(mesh); + TrianglePartition::new(mesh, material, |mesh, triangle| { + let corner_key = |index| { + let position = position_key(mesh, index, tolerance)?; + let uv = (*mesh.uvs.get(index)? * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64); + Some((position, uv)) + }; + let Some([first, second, third]) = mesh.tri(triangle).map(|corners| corners.map(corner_key)) else { return Vec::new() }; + let [Some(first), Some(second), Some(third)] = [first, second, third] else { return Vec::new() }; + + [(first, second), (second, third), (third, first)] + .into_iter() + .filter(|(start, end)| start != end) + .map(|(start, end)| (start.min(end), start.max(end))) + .collect() + }) + } +} + +fn position_tolerance(mesh: &Mesh) -> f32 { + // Weld positions within a millionth of the mesh size + const RELATIVE_WELD_TOLERANCE: f32 = 1e-6; + let (minimum, maximum) = mesh.bounds(); + (maximum - minimum).length().max(RELATIVE_WELD_TOLERANCE) * RELATIVE_WELD_TOLERANCE +} + +fn position_key(mesh: &Mesh, index: usize, tolerance: f32) -> Option<[i64; 3]> { + mesh.positions.get(index).map(|position| position.to_array().map(|value| (value / tolerance).round() as i64)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_closed_mesh_has_seams_and_a_single_island_has_none() { + let sphere = crate::primitives::sphere(1.0, 16, 8); + let plane = crate::primitives::plane(1.0, 4); + let seams = UvSeam::of_material(&sphere, 0); + + assert!(!seams.is_empty()); + assert!(seams.iter().all(|seam| seam.sides[0].start != seam.sides[1].start || seam.sides[0].end != seam.sides[1].end)); + assert!(UvSeam::of_material(&plane, 0).is_empty()); + } +} diff --git a/crates/geom/src/uv_seam_side.rs b/crates/geom/src/uv_seam_side.rs new file mode 100644 index 00000000..c2e281ce --- /dev/null +++ b/crates/geom/src/uv_seam_side.rs @@ -0,0 +1,13 @@ +//! One side of a UV seam + +use glam::Vec2; + +/// One side of a [`UvSeam`](crate::UvSeam): an island edge in UV space and the third corner of its triangle (which side the island is on) +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct UvSeamSide { + /// Mesh triangle incident to this side of the seam + pub triangle: u32, + pub start: Vec2, + pub end: Vec2, + pub interior: Vec2, +} diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index 0b4bb7af..bff08e96 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -20,3 +20,4 @@ serde = { workspace = true } [dev-dependencies] epaint_default_fonts = { workspace = true } +serde_json = { workspace = true } diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index d1a55036..ffc45e22 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -296,6 +296,9 @@ pub struct BrushSettings { pub size: f32, /// Pen pressure may shrink the size down to this fraction. pub min_size: f32, + /// Pen pressure shrinks the size towards `min_size`; on for projects saved before it could be turned off + #[serde(default = "pressure_on")] + pub size_pressure: bool, /// Per-stamp alpha 0..1. pub flow: f32, /// Caps a whole stroke 0..1. @@ -343,6 +346,7 @@ impl Default for BrushSettings { BrushSettings { size: 0.02, min_size: 0.05, + size_pressure: true, flow: 1.0, opacity: 1.0, spacing: 0.1, @@ -370,11 +374,15 @@ impl Default for BrushSettings { } impl BrushSettings { - /// Radius of a 2D (UV) stamp as a fraction of the UV square, for pen `pressure` 0..1: twice the - /// brush size, shrunk towards `min_size` by a light pen. Painting and the 2D cursor share it. + /// Radius of a 2D (UV) stamp as a fraction of the UV square at pen `pressure` 0..1: twice the brush size, shrunk towards `min_size` by a light pen (shared by painting and the 2D cursor) pub fn uv_stamp_radius(&self, pressure: f32) -> f32 { - let p = pressure.clamp(0.0, 1.0); - self.size * 2.0 * if p < 1.0 { self.min_size + (1.0 - self.min_size) * p } else { 1.0 } + self.size * 2.0 * self.pressure_size(pressure) + } + + /// The fraction of the size a stamp gets at pen `pressure` 0..1: full when size pressure is off + pub fn pressure_size(&self, pressure: f32) -> f32 { + let pressure = pressure.clamp(0.0, 1.0); + if self.size_pressure && pressure < 1.0 { self.min_size + (1.0 - self.min_size) * pressure } else { 1.0 } } /// Clamp every value into its valid range (input from UI, CLI or agents) @@ -415,8 +423,31 @@ impl BrushSettings { } } +fn pressure_on() -> bool { + true +} + #[cfg(test)] mod tests { + #[test] + fn size_pressure_off_keeps_a_light_pen_at_full_size() { + let pressed = BrushSettings { size: 0.1, min_size: 0.2, ..BrushSettings::default() }; + let mouse = BrushSettings { size_pressure: false, ..pressed.clone() }; + + assert!(pressed.uv_stamp_radius(0.3) < mouse.uv_stamp_radius(0.3)); + assert_eq!(mouse.uv_stamp_radius(0.3), mouse.uv_stamp_radius(1.0)); + } + + #[test] + fn settings_saved_before_the_size_pressure_switch_keep_pen_pressure() { + let mut saved = serde_json::to_value(BrushSettings { size_pressure: false, ..BrushSettings::default() }).unwrap(); + saved.as_object_mut().unwrap().remove("size_pressure"); + + let loaded: BrushSettings = serde_json::from_value(saved).unwrap(); + + assert!(loaded.size_pressure); + } + #[test] fn uv_stamp_radius_follows_pen_pressure() { let b = BrushSettings { size: 0.1, min_size: 0.5, ..BrushSettings::default() }; diff --git a/crates/paint/src/commit.rs b/crates/paint/src/commit.rs index e40548bf..d7d105bf 100644 --- a/crates/paint/src/commit.rs +++ b/crates/paint/src/commit.rs @@ -71,26 +71,34 @@ fn over(img: &mut TileImage, b: &Blend, src: &CommitSource, mut staged: Option) { +/// Blend the stroke's alpha tile `stroke_alpha` into tile `(tile_x, tile_y)` of an image (`dst`, `components` per texel) +fn blend_tile( + dst: &mut [u16], + components: usize, + stroke_alpha: &[u16], + (tile_x, tile_y): (u32, u32), + blend: &Blend, + source: &CommitSource, + carried: Option<&[u16]>, +) { // The last component is the coverage, the ones before it the value let value_count = components.saturating_sub(1); let opacity = source.opacity.clamp(0.0, 1.0); let gray_source = if source.erase || carried.is_some() { None } else { blend.gray }; - for i in 0..TILE_AREA { - let mut weight = from_u16(stroke_alpha.get(i).copied().unwrap_or(0)) * opacity; + for texel_index in 0..TILE_AREA { + let mut weight = from_u16(stroke_alpha.get(texel_index).copied().unwrap_or(0)) * opacity; if weight <= 0.0 { continue; } let mut stencil = None; - let (x, y) = (tx * TILE + i as u32 % TILE, ty * TILE + i as u32 / TILE); + let (x, y) = (tile_x * TILE + texel_index as u32 % TILE, tile_y * TILE + texel_index as u32 / TILE); if let Some(per_texel) = source.per_texel { match per_texel(x, y) { Some((color, alpha_factor)) => { weight *= alpha_factor; - stencil = Some(color); + stencil = color; } None => continue, } @@ -99,13 +107,16 @@ fn blend_tile(dst: &mut [u16], components: usize, stroke_alpha: &[u16], (tx, ty) } } - let Some((coverage_slot, values)) = dst.get_mut(i * components..(i + 1) * components).and_then(<[u16]>::split_last_mut) else { continue }; + let Some((coverage_slot, values)) = dst.get_mut(texel_index * components..(texel_index + 1) * components).and_then(<[u16]>::split_last_mut) else { + continue; + }; + let gray = gray_source.map(|gray| gray.at(x, y, (source.alpha.width(), source.alpha.height()))); let coverage = from_u16(*coverage_slot); for (component, slot) in values.iter_mut().enumerate() { let previous = dec(blend.kind, *slot); let target = match (carried, stencil) { - (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(i * value_count + component).copied().unwrap_or(0)), + (Some(carried_tile), _) => dec(blend.kind, carried_tile.get(texel_index * value_count + component).copied().unwrap_or(0)), (None, _) if let Some(gray) = gray => gray, (None, Some(color)) if blend.stencil_color => color.get(component).copied().unwrap_or(0.0), _ => blend.value.get(component).copied().unwrap_or(0.0), @@ -318,8 +329,8 @@ fn mask_blend<'a>(gray: &'a MaskGray, value: &'a [f32; 1]) -> Blend<'a> { Blend { kind: ChannelKind::Scalar, value, stencil_color: false, carried: None, gray } } -/// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint. -pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<([f32; 3], f32)> + Sync); +/// Per-texel override of a stroke: `(x, y)` → (base color, alpha factor), None = no paint; a None color keeps the stroke's own value +pub type TexelFn<'a> = &'a (dyn Fn(u32, u32) -> Option<(Option<[f32; 3]>, f32)> + Sync); /// The stroke being committed: its alpha, touched tiles, opacity cap and mode. #[derive(Clone, Copy)] @@ -328,7 +339,7 @@ pub struct CommitSource<'a> { pub tiles: &'a BTreeSet<(u32, u32)>, pub opacity: f32, pub erase: bool, - /// Projection tool: base color and alpha per texel from a stencil. + /// The stencil: alpha per texel and, on the Projection tool, base color pub per_texel: Option>, /// Clone and smudge: straight values per channel carried by the stroke (replace `values`). pub carried: Option<&'a BTreeMap>, diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index fcca6427..5aef41cb 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -125,11 +125,13 @@ impl Stroke { all } + /// The stamp radius at `pos` under `pressure`, scaled by its distance from the camera for a screen-space brush fn radius_at(&self, ctx: &PickCtx, pos: Vec3, pressure: f32) -> f32 { - let p = pressure.clamp(0.0, 1.0); - let scale = self.settings.min_size + (1.0 - self.settings.min_size) * p; - let r = self.radius * if pressure < 1.0 { scale } else { 1.0 }; - if self.settings.screen_space { r * (pos.distance(ctx.camera.eye()) / ctx.camera.distance.max(1e-4)) } else { r } + // Keeps the screen-space scale finite with the camera on its target + const MIN_CAMERA_DISTANCE: f32 = 1e-4; + + let radius = self.radius * self.settings.pressure_size(pressure); + if self.settings.screen_space { radius * (pos.distance(ctx.camera.eye()) / ctx.camera.distance.max(MIN_CAMERA_DISTANCE)) } else { radius } } fn feed(&mut self, ctx: &PickCtx, screen: Vec2, pressure: f32, depth: u32, out: &mut Vec) { diff --git a/crates/render/Cargo.toml b/crates/render/Cargo.toml index 1e045f28..0f7d2e2e 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -31,3 +31,7 @@ wasm-bindgen-futures = "0.4" [dev-dependencies] image = { workspace = true } texturecraft-formats = { workspace = true } + +# The noop backend stands in for an adapter without compute shaders in the headless tests. +[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +wgpu = { workspace = true, features = ["noop"] } diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index f2e2b19a..78d5b5d2 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -141,7 +141,14 @@ mod tests { img.tile_mut(x, y, &[texturecraft_texel::to_u16_signed(height)]); } } - TraceSet { material: 0, composite, height_strength: strength } + TraceSet { + material: 0, + composite, + height_strength: strength, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + } } #[test] diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 0a8a357c..dbfe1860 100644 --- a/crates/render/src/gpu_bake.rs +++ b/crates/render/src/gpu_bake.rs @@ -121,9 +121,7 @@ pub fn raytracing_available() -> bool { } fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }; - let adapter = pollster::block_on(instance.request_adapter(&options)).map_err(|e| format!("no GPU adapter: {e}"))?; + let adapter = crate::headless::adapter()?; let info = adapter.get_info(); let limits = adapter.limits(); let flags = adapter.get_downlevel_capabilities().flags; @@ -134,7 +132,7 @@ fn bake_adapter() -> Result<(wgpu::Adapter, String, wgpu::Limits), String> { Ok((adapter, info.name, limits)) } -fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { +pub(crate) fn unsupported_adapter(device_type: wgpu::DeviceType, flags: wgpu::DownlevelFlags, limits: &wgpu::Limits) -> Option<&'static str> { if device_type == wgpu::DeviceType::Cpu { return Some("is a software renderer"); } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5d092a0f..24789a2e 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -14,6 +14,7 @@ use std::task::{Context, Poll, Waker}; use bytemuck::{Pod, Zeroable}; use texturecraft_compose::DisplayKind; +use texturecraft_core::HeightToNormalMethod; use texturecraft_geom::glam::{Vec3, Vec4}; use texturecraft_geom::{Mesh, OrbitCamera}; use wgpu::util::DeviceExt; @@ -27,8 +28,14 @@ pub const MAX_SETS: usize = 255; /// Depth of the shader's BVH traversal stack (`STACK` in trace.wgsl). pub(crate) const STACK: usize = 64; const KINDS: usize = DisplayKind::ALL.len(); -/// Bytes of the trace uniform: [`Head`] then 256 texture-set entries (`MAX_SETS` in trace.wgsl). -const PARAMS_SIZE: u64 = (size_of::() + 256 * 16) as u64; +// trace.wgsl reads the smooth bit as `>> 8u` +const _: () = assert!(KINDS == 8); + +/// The placeholder mask word's bit for a set with Smooth (Sobel) height to normal (trace.wgsl reads it) +const SMOOTH_HEIGHT_BIT: f32 = (1 << KINDS) as f32; + +/// Bytes of the trace uniform: [`Head`], 256 texture-set entries (`MAX_SETS` in trace.wgsl), then their height slope factors down the texture, four per entry +const PARAMS_SIZE: u64 = (size_of::() + 256 * 16 + 256 * 4) as u64; /// Post uniform slots: resolve and denoise init, then the five à-trous steps. const STEPS: [u32; 6] = [0, 1, 2, 4, 8, 16]; const WORKGROUP: u32 = 8; @@ -96,6 +103,10 @@ struct SceneConst { rotation: f32, env_camera: bool, heights: Vec, + /// Per set: how much more the height slope tilts down the texture than across it + height_y_factors: Vec, + /// Per set: Smooth (Sobel) height to normal + smooth: Vec, ior: f32, dielectric_f0_scale: f32, /// Focus depth (0: the orbit target) and lens radius in world units (0: pinhole). @@ -419,7 +430,9 @@ impl GpuTracer { sigma: scene.scatter_sigma, rotation: scene.env_rotation, env_camera: scene.env_camera, - heights: scene.sets.iter().map(|s| s.height_strength).collect(), + heights: scene.sets.iter().map(crate::trace::TraceSet::normal_height_strength).collect(), + height_y_factors: scene.sets.iter().map(|s| s.height_y_factor).collect(), + smooth: scene.sets.iter().map(|s| s.height_to_normal == HeightToNormalMethod::Smooth).collect(), ior: scene.ior, dielectric_f0_scale: scene.dielectric_f0_scale, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), @@ -440,27 +453,34 @@ impl GpuTracer { if self.materials.as_ref().is_some_and(|m| m.rev == rev) { return Ok(false); } + let sets = renderer.display_textures(); if sets.len() > MAX_SETS || sets.iter().any(|s| s.len() != KINDS) { return Err(format!("GPU path tracing takes at most {MAX_SETS} texture sets")); } + let layers = sets.len() as u32 + 1; let limits = device.limits(); if layers > limits.max_texture_array_layers { return Err(format!("this GPU takes at most {} texture sets", limits.max_texture_array_layers.saturating_sub(1))); } + let old = self.materials.take(); let mut arrays = Vec::with_capacity(KINDS); for (k, kind) in DisplayKind::ALL.into_iter().enumerate() { - let size = sets.iter().filter_map(|s| s.get(k)).fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h))); + // Fold tall textures into adjacent bands within the widest layer + let sources = sets.iter().filter_map(|set| set.get(k).copied()); + let width = sources.clone().map(wgpu::Texture::width).max().unwrap_or(1); + let height = sources.clone().map(|source| source.height().div_ceil(width / source.width())).max().unwrap_or(1); + let reuse = - old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (size.0, size.1, layers)); + old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (width, height, layers)); let (tex, view) = match reuse { Some(a) => a.clone(), None => scoped(device, "GPU path tracing: material textures", || { let tex = device.create_texture(&wgpu::TextureDescriptor { label: Some("tc_trace_material"), - size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: layers }, + size: wgpu::Extent3d { width, height, depth_or_array_layers: layers }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -475,19 +495,24 @@ impl GpuTracer { if reuse.is_none() { self.bind = None; } - for (layer, src) in sets.iter().filter_map(|s| s.get(k)).enumerate() { - encoder.copy_texture_to_texture( - src.as_image_copy(), - wgpu::TexelCopyTextureInfo { - texture: &tex, - mip_level: 0, - origin: wgpu::Origin3d { x: 0, y: 0, z: layer as u32 }, - aspect: wgpu::TextureAspect::All, - }, - wgpu::Extent3d { width: src.width(), height: src.height(), depth_or_array_layers: 1 }, - ); + + for (layer, source) in sources.enumerate() { + for band in 0..source.height().div_ceil(height) { + let source_y = band * height; + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 0, y: source_y, z: 0 }, ..source.as_image_copy() }, + wgpu::TexelCopyTextureInfo { + texture: &tex, + mip_level: 0, + origin: wgpu::Origin3d { x: band * source.width(), y: 0, z: layer as u32 }, + aspect: wgpu::TextureAspect::All, + }, + wgpu::Extent3d { width: source.width(), height: height.min(source.height() - source_y), depth_or_array_layers: 1 }, + ); + } } - // The default material: one texel of the kind's neutral value. + + // The default material occupies one neutral texel in the last layer let texel = kind.default_texel(); queue.write_texture( wgpu::TexelCopyTextureInfo { @@ -502,10 +527,11 @@ impl GpuTracer { ); arrays.push((tex, view)); } + let mut info: Vec<[f32; 3]> = sets .iter() .map(|s| { - // The set's size is its largest texture's; any kind may still be a 1×1 placeholder. + // Individual kinds may still be neutral 1×1 placeholders let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h))); let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k); [dims.0 as f32, dims.1 as f32, small as f32] @@ -617,10 +643,17 @@ impl GpuTracer { }; let mut sets = [[0.0f32; 4]; 256]; for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() { - *slot = [m[0], m[1], m[2], sc.heights.get(i).copied().unwrap_or(0.0)]; + // The bit past the placeholder mask bits: Smooth (Sobel) height to normal + let smooth = if sc.smooth.get(i).copied().unwrap_or(false) { SMOOTH_HEIGHT_BIT } else { 0.0 }; + *slot = [m[0], m[1], m[2] + smooth, sc.heights.get(i).copied().unwrap_or(0.0)]; + } + let mut height_y_factors = [1.0f32; 256]; + for (slot, factor) in height_y_factors.iter_mut().zip(&sc.height_y_factors) { + *slot = *factor; } let mut bytes = bytemuck::bytes_of(&head).to_vec(); bytes.extend_from_slice(bytemuck::cast_slice(&sets)); + bytes.extend_from_slice(bytemuck::cast_slice(&height_y_factors)); queue.write_buffer(&self.params, 0, &bytes); let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_trace"), timestamp_writes: None }); cpass.set_pipeline(&self.trace_pipe); @@ -825,16 +858,47 @@ mod tests { h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1); for (tx, ty) in all_tiles(64, 64) { for k in DisplayKind::ALL { - h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty)); + h.renderer.upload_tile( + &h.device, + &h.queue, + 0, + k, + tx, + ty, + &tile_bytes(&composite, &BakedMaps::default(), texturecraft_core::AoMixing::Multiply, k, tx, ty), + ); } } let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0) + TraceScene::new( + mesh, + bvh, + vec![TraceSet { + material: 0, + composite, + height_strength: 0.0, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + }], + Arc::new(env), + 0.0, + ) } fn gpu() -> Option<(Headless, GpuTracer)> { - let Ok(h) = Headless::new() else { + gpu_on(Headless::new()) + } + + /// A tracer on a device whose buffers hold at most 256 MiB, as wgpu's default limits do: a GPU's + /// own limits (several GiB on a desktop card) would let an 8192² render succeed. + fn small_buffer_gpu() -> Option<(Headless, GpuTracer)> { + gpu_on(Headless::with_buffer_cap(256 << 20)) + } + + fn gpu_on(headless: Result) -> Option<(Headless, GpuTracer)> { + let Ok(h) = headless else { eprintln!("skipping: no GPU adapter"); return None; }; @@ -908,7 +972,7 @@ mod tests { /// 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 Some((mut headless, mut tracer)) = small_buffer_gpu() else { return }; let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); let camera = camera(); let settings = TraceSettings::default(); @@ -985,6 +1049,33 @@ mod tests { } } + #[test] + fn mixed_aspect_materials_preserve_texels_and_bound_array_storage() { + let Some((mut headless, mut tracer)) = gpu() else { return }; + let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); + let display = TraceDisplay::from_display(&Default::default()); + let settings = TraceSettings { bounces: 2 }; + let tall = ((128, 513), 0); + let wide = ((512, 128), 1); + headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[tall], 1); + for tile_y in 0..9 { + let color = [23 * tile_y as u8, 255 - 23 * tile_y as u8, 0, 255]; + headless.renderer.upload_tile(&headless.device, &headless.queue, 0, DisplayKind::BaseColor, 0, tile_y, &color.repeat(64 * 64)); + } + + let render = |tracer: &mut GpuTracer, headless: &Headless| { + tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera(), &settings, &display, [48, 36], 8).unwrap().2 + }; + let reference = render(&mut tracer, &headless); + headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[tall, wide], 2); + headless.renderer.upload_tile(&headless.device, &headless.queue, 1, DisplayKind::BaseColor, 0, 0, &[255; 64 * 64 * 4]); + let mixed = render(&mut tracer, &headless); + + assert_eq!(mixed, reference, "adding another material must preserve every sample of the tall set"); + let array = &tracer.materials.as_ref().unwrap().arrays[0].0; + assert!(array.width() * array.height() < 2 * 128 * 513, "a partial last band must still fit in a compact array layer"); + } + #[test] fn gpu_reads_full_size_channels_beside_placeholders() { // A 1×1 base-color placeholder must not limit sampling of the full-size roughness map @@ -1001,7 +1092,15 @@ mod tests { h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0)], 1); for (tx, ty) in all_tiles(64, 64) { for k in DisplayKind::ALL { - h.renderer.upload_tile(&h.device, &h.queue, 0, k, tx, ty, &tile_bytes(&composite, &BakedMaps::default(), k, tx, ty)); + h.renderer.upload_tile( + &h.device, + &h.queue, + 0, + k, + tx, + ty, + &tile_bytes(&composite, &BakedMaps::default(), texturecraft_core::AoMixing::Multiply, k, tx, ty), + ); } } let sizes: Vec = h.renderer.display_textures()[0].iter().map(|t| t.width()).collect(); @@ -1010,7 +1109,20 @@ mod tests { let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); let env = crate::ibl::environment("Studio Contrast", 256); - let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0); + let scene = TraceScene::new( + mesh, + bvh, + vec![TraceSet { + material: 0, + composite, + height_strength: 0.0, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + }], + Arc::new(env), + 0.0, + ); let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND }; let settings = TraceSettings { bounces: 4 }; let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index f22dd1d4..a5241dd2 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -9,15 +9,89 @@ pub struct Headless { pub adapter_name: String, } +/// The adapter for work without a window (renders, path tracing, GPU baking). Like the desktop app, +/// it honours `WGPU_ADAPTER_NAME` (part of the adapter's name or backend, any case) and `WGPU_POWER_PREF` +/// (`high`, the default, `low` or `none`); the instance reads wgpu's other variables +/// (`WGPU_BACKEND`, `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`, ...). +pub fn adapter() -> Result { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let power = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); + if let Ok(name) = std::env::var("WGPU_ADAPTER_NAME") { + let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); + let infos: Vec = adapters.iter().map(wgpu::Adapter::get_info).collect(); + if let Some(a) = pick_adapter(&infos, &name, power).and_then(|i| adapters.into_iter().nth(i)) { + return Ok(a); + } + log::warn!("no GPU adapter matches WGPU_ADAPTER_NAME `{name}`; choosing by power preference"); + } + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() })) + .map_err(|e| format!("no GPU adapter: {e}")) +} + +/// Which of `infos` `WGPU_ADAPTER_NAME=name` picks. Several adapters may match (the same GPU on two +/// backends, two GPUs of one vendor): rank them as the desktop app's selector does, hardware before +/// software, then `power`, then native backends before OpenGL, then the listing order. +fn pick_adapter(infos: &[wgpu::AdapterInfo], name: &str, power: wgpu::PowerPreference) -> Option { + use wgpu::{Backend, DeviceType, PowerPreference}; + let wanted = name.to_lowercase(); + infos + .iter() + .enumerate() + .filter(|(_, info)| info.name.to_lowercase().contains(&wanted) || format!("{:?}", info.backend).to_lowercase().contains(&wanted)) + .min_by_key(|(index, info)| { + let lower = info.name.to_lowercase(); + let software = info.device_type == DeviceType::Cpu || ["llvmpipe", "lavapipe", "warp"].iter().any(|s| lower.contains(s)); + let power_rank = match (power, info.device_type) { + (PowerPreference::None, DeviceType::Cpu) => 1, + (PowerPreference::None, _) => 0, + (PowerPreference::LowPower, DeviceType::IntegratedGpu) | (PowerPreference::HighPerformance, DeviceType::DiscreteGpu) => 0, + (PowerPreference::LowPower, DeviceType::DiscreteGpu) | (PowerPreference::HighPerformance, DeviceType::IntegratedGpu) => 1, + (_, DeviceType::Other) => 2, + (_, DeviceType::VirtualGpu) => 3, + (_, DeviceType::Cpu) => 4, + }; + let backend_rank = match (power, info.backend) { + (PowerPreference::None, _) | (_, Backend::Vulkan | Backend::Metal | Backend::Dx12) => 0, + (_, Backend::Gl) => 1, + _ => 2, + }; + (software, power_rank, backend_rank, *index) + }) + .map(|(index, _)| index) +} + +/// A device on `adapter` with all its limits. The viewport draws with fragment passes only, so an +/// adapter without compute shaders (WebGL2-class, or the GL driver WSL2 offers on an integrated GPU) +/// still renders it; the GPU path tracer checks the device's limits itself. +fn device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue), String> { + device_with_limits(adapter, adapter.limits()) +} + +fn device_with_limits(adapter: &wgpu::Adapter, limits: wgpu::Limits) -> Result<(wgpu::Device, wgpu::Queue), String> { + let desc = wgpu::DeviceDescriptor { label: Some("tc_headless"), required_limits: limits, ..Default::default() }; + pollster::block_on(adapter.request_device(&desc)).map_err(|e| format!("no GPU device on {}: {e}", adapter.get_info().name)) +} + impl Headless { - /// Create a device on the default adapter. Errors when no GPU (or software) adapter exists. + /// Create a device on [`adapter`]. Errors when no GPU (or software) adapter exists. pub fn new() -> Result { - let instance = wgpu::Instance::default(); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).map_err(|e| format!("no GPU adapter: {e}"))?; - let adapter_name = adapter.get_info().name; - let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).map_err(|e| format!("no GPU device: {e}"))?; + let adapter = adapter()?; + let (device, queue) = device(&adapter)?; let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); - Ok(Headless { device, queue, renderer, adapter_name }) + Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) + } + + /// A device whose buffers are capped at `bytes` (or the adapter's own limit when that is lower), + /// so tests of "too big for this GPU" paths do not depend on how large the machine's limits are. + #[cfg(test)] + pub(crate) fn with_buffer_cap(bytes: u64) -> Result { + let adapter = adapter()?; + let mut limits = adapter.limits(); + limits.max_buffer_size = limits.max_buffer_size.min(bytes); + limits.max_storage_buffer_binding_size = limits.max_storage_buffer_binding_size.min(bytes); + let (device, queue) = device_with_limits(&adapter, limits)?; + let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); + Ok(Headless { device, queue, renderer, adapter_name: adapter.get_info().name }) } /// Render a frame and read it back as RGBA8 (sRGB-encoded). @@ -28,3 +102,72 @@ impl Headless { self.renderer.read_view(&self.device, &self.queue, frame.view_id) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// An adapter without compute shaders still gets a device for the viewport. wgpu's noop backend + /// stands in for one (WSL2's GL driver on an Intel GPU, a WebGL2-class GPU): asking it for + /// `Limits::default()` failed with "Limit 'max_compute_workgroups_per_dimension' value 65535 is + /// better than allowed 0". + #[test] + fn an_adapter_without_compute_shaders_gets_a_device() { + let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { noop, ..Default::default() }, + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + assert_eq!(adapter.limits().max_compute_workgroups_per_dimension, 0); + device(&adapter).unwrap(); + } + + fn info(name: &str, device_type: wgpu::DeviceType, backend: wgpu::Backend) -> wgpu::AdapterInfo { + wgpu::AdapterInfo { name: name.into(), ..wgpu::AdapterInfo::new(device_type, backend) } + } + + /// A `WGPU_ADAPTER_NAME` that several adapters match still follows `WGPU_POWER_PREF`, and an + /// empty one matches them all. + #[test] + fn a_name_several_adapters_match_follows_the_power_preference() { + use wgpu::{Backend::*, DeviceType::*, PowerPreference as P}; + let gpus = [ + info("Intel(R) Iris(R) Xe Graphics", IntegratedGpu, Vulkan), + info("Intel(R) Arc(TM) A770", DiscreteGpu, Vulkan), + info("llvmpipe (LLVM 15)", Cpu, Gl), + ]; + assert_eq!(pick_adapter(&gpus, "intel", P::HighPerformance), Some(1)); + assert_eq!(pick_adapter(&gpus, "intel", P::LowPower), Some(0)); + assert_eq!(pick_adapter(&gpus, "INTEL", P::None), Some(0)); + assert_eq!(pick_adapter(&gpus, "", P::HighPerformance), Some(1)); + assert_eq!(pick_adapter(&gpus, "llvm", P::HighPerformance), Some(2)); + assert_eq!(pick_adapter(&gpus, "gl", P::HighPerformance), Some(2)); + assert_eq!(pick_adapter(&gpus, "nvidia", P::HighPerformance), None); + // One GPU on two backends: the native one before OpenGL. + let twice = [info("D3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Gl), info("Microsoft Direct3D12 (NVIDIA GeForce RTX 4050)", DiscreteGpu, Vulkan)]; + assert_eq!(pick_adapter(&twice, "rtx 4050", P::HighPerformance), Some(1)); + } + + /// On an adapter with WebGL2-class limits (no compute shaders) the viewport renderer still builds, + /// the GPU path tracer and the GPU baker each refuse with a message instead of panicking. + #[test] + fn an_adapter_without_compute_shaders_gets_an_error_not_a_panic() { + let noop = wgpu::NoopBackendOptions { enable: true, limits: Some(wgpu::Limits::downlevel_webgl2_defaults()), ..Default::default() }; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::NOOP, + backend_options: wgpu::BackendOptions { noop, ..Default::default() }, + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).unwrap(); + let (device, queue) = device(&adapter).unwrap(); + let _renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); + assert!(!crate::gpu_trace::GpuTracer::supported(&device)); + let err = crate::gpu_trace::GpuTracer::new(&device).err().expect("the tracer needs compute shaders"); + assert!(err.contains("compute shaders"), "{err}"); + let flags = adapter.get_downlevel_capabilities().flags; + let reason = crate::gpu_bake::unsupported_adapter(wgpu::DeviceType::IntegratedGpu, flags, &adapter.limits()); + assert!(reason.is_some_and(|r| r.contains("compute")), "{reason:?}"); + } +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 64b44d9a..3e3022dd 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -111,6 +111,7 @@ struct GlobalsRaw { bake_neutral: [f32; 4], bake_bent_normal: [f32; 4], uv_rotation: [f32; 4], + height_slope: [f32; 4], } /// The post pass uniform (see `Post` in post.wgsl). @@ -158,6 +159,12 @@ pub struct Shade { pub env_opacity: f32, pub ao_intensity: f32, pub height_strength: f32, + /// How much more the height slope tilts down the texture than across it ([`texturecraft_core::TextureSet::atlas_height_y_factor`]) + pub height_y_factor: f32, + /// The height slope joins the shaded normal (normal mixing Combine; Replace leaves it out) + pub height_in_normal: bool, + /// How the height becomes normal slopes + pub height_to_normal: texturecraft_core::HeightToNormalMethod, /// -1 for DirectX normal maps in the normal channel, 1 for OpenGL. pub normal_y: f32, /// 0 material, 1 channel, 2 mesh map (aux texture), 3 UV checker. @@ -251,6 +258,7 @@ impl Shade { env_blur: d.env_blur, env_opacity: d.env_opacity, ao_intensity: d.ao_intensity, + // The key light (on with shadows), in environment space light: if d.shadows { [0.5, 0.8, 0.4, 2.5] } else { [0.0; 4] }, shadows: d.shadows, @@ -299,6 +307,9 @@ impl Default for Shade { env_opacity: 0.0, ao_intensity: 0.75, height_strength: 1.0, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, normal_y: 1.0, view_mode: 0, channel: 0, @@ -398,6 +409,20 @@ pub fn aux_size(size: (u32, u32)) -> u32 { impl Tex { fn new(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, mips: u32) -> Tex { + // COPY_SRC: the GPU path tracer copies the display textures into its arrays. + let usage = + wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC; + Self::with_usage(device, label, w, h, format, mips, usage) + } + + /// The environment map, uploaded from the CPU and sampled, never drawn into. As a render target + /// it would need float color buffers, which GLES and WebGL2 may lack (see [`hdr_renderable`]). + fn environment(device: &wgpu::Device, w: u32, h: u32) -> Tex { + let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + Self::with_usage(device, "tc_env", w, h, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS, usage) + } + + fn with_usage(device: &wgpu::Device, label: &str, w: u32, h: u32, format: wgpu::TextureFormat, mips: u32, usage: wgpu::TextureUsages) -> Tex { let texture = device.create_texture(&wgpu::TextureDescriptor { label: Some(label), size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 }, @@ -405,11 +430,7 @@ impl Tex { sample_count: 1, dimension: wgpu::TextureDimension::D2, format, - // COPY_SRC: the GPU path tracer copies the display textures into its arrays. - usage: wgpu::TextureUsages::TEXTURE_BINDING - | wgpu::TextureUsages::COPY_DST - | wgpu::TextureUsages::RENDER_ATTACHMENT - | wgpu::TextureUsages::COPY_SRC, + usage, view_formats: &[], }); let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); @@ -1245,7 +1266,7 @@ impl Renderer { layout: &refraction_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&black) }], }); - let env = Tex::new(device, "tc_env", PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1], wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + let env = Tex::environment(device, PLACEHOLDER_ENV_SIZE[0], PLACEHOLDER_ENV_SIZE[1]); let mut renderer = Renderer { target_format, @@ -1336,7 +1357,7 @@ impl Renderer { let levels = ibl::prefilter(&img, ENV_LEVELS); if self.env.texture.width() != img.width || self.env.texture.height() != img.height { - self.env = Tex::new(device, "tc_env", img.width, img.height, wgpu::TextureFormat::Rgba16Float, ENV_LEVELS); + self.env = Tex::environment(device, img.width, img.height); } for (l, lv) in levels.iter().enumerate() { let bytes: Vec = lv.data.iter().flat_map(|c| [c[0], c[1], c[2], 1.0]).flat_map(|v| half::f16::from_f32(v).to_le_bytes()).collect(); @@ -2122,9 +2143,15 @@ impl Renderer { mode: [s.view_mode as f32, s.channel as f32, s.height_strength, s.normal_y], bg: [s.env_opacity, s.env_blur * (ENV_LEVELS - 1) as f32, uv_view, s.wireframe_opacity.clamp(0.0, 1.0)], uv_xform, - uv_rotation, + uv_rotation: [ + uv_rotation[0], + uv_rotation[1], + uv_rotation[2], + f32::from(u8::from(s.height_to_normal == texturecraft_core::HeightToNormalMethod::Smooth)), + ], light: [light.x, light.y, light.z, lw], light_vp: shadow_vp.unwrap_or(Mat4::IDENTITY).to_cols_array_2d(), + // Offset by 1.5 shadow texels to avoid self-shadowing shadow: [ if shadow_vp.is_some() { 1.0 } else { 0.0 }, @@ -2135,7 +2162,8 @@ impl Renderer { material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior], scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], fwd: [fwd.x, fwd.y, fwd.z, 0.0], - disp, + disp: [disp[0], disp[1], disp[2], if s.height_in_normal { 1.0 } else { 0.0 }], + height_slope: [1.0, s.height_y_factor, 0.0, 0.0], refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, s.dielectric_f0_scale], highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), @@ -2640,6 +2668,23 @@ mod tests { h.renderer.display_textures()[0][0].width() } + /// The environment map is only uploaded and sampled. A render target usage would ask for float + /// color buffers, which GLES and WebGL2 adapters may not have. + #[test] + fn the_environment_map_is_not_a_render_target() { + let Ok(mut h) = Headless::new() else { + eprintln!("skipping: no GPU adapter"); + return; + }; + let usage = wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST; + assert_eq!(h.renderer.env.texture.usage(), usage, "the built-in environment"); + // An imported image of another size makes a new texture. + let image = ImageRes::new(256, 128, vec![[0.5, 0.5, 0.5, 1.0]; 256 * 128], false); + h.renderer.set_environment(&h.device, &h.queue, "resource:grey", Some(&image)); + assert_eq!(h.renderer.env.texture.width(), 256); + assert_eq!(h.renderer.env.texture.usage(), usage, "an imported environment"); + } + fn prepare(h: &mut Headless) { let mut enc = h.device.create_command_encoder(&Default::default()); h.renderer.resolve_pending(&h.device); diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 490ed2d5..74d6a9cf 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -22,7 +22,7 @@ struct Globals { material: vec4, // x specular/glossiness shading (1), y parallax occlusion (1), z accumulation sample index, w IOR of transmission scatter: vec4, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1) fwd: vec4, // xyz camera view direction (unit), w - - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - + disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w height slope in the shaded normal (1) or not (0) refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w dielectric F0 scale highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - @@ -35,7 +35,8 @@ struct Globals { bake_neutral_color: vec4, // rgb the neutral material's color, a its reflection samples this frame bake_neutral: vec4, // x roughness, y metallic, z AO intensity of the neutral material, w on (1) bake_bent_normal: vec4, // x, y how much the bent normal (in the aux texture) turns the diffuse light and dims reflections, zw - - uv_rotation: vec4, // UV view: x cos, y sin of the view rotation (counter-clockwise on screen), z view aspect (width / height), w - + uv_rotation: vec4, // UV view: x cos, y sin of the view rotation (counter-clockwise on screen), z view aspect (width / height); w Smooth (Sobel) height to normal (1) or Sharp (0) + height_slope: vec4, // xy height slope factors across and down the texture (y: columns over rows of a UV tile grid), zw - }; @group(0) @binding(0) var g: Globals; @@ -433,6 +434,21 @@ const DITHER_FRAME_STEP: vec2 = vec2(17.0, 59.0); // Lit single-channel views keep the legacy specular level multiplier const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08; +// Match the axial and Sobel kernels in HeightToNormalMethod::slope +fn height_slope(uv: vec2, ts: vec2) -> vec2 { + let r = textureSample(t_height, samp, uv + vec2(ts.x, 0.0)).r; + let l = textureSample(t_height, samp, uv - vec2(ts.x, 0.0)).r; + let d = textureSample(t_height, samp, uv + vec2(0.0, ts.y)).r; + let u = textureSample(t_height, samp, uv - vec2(0.0, ts.y)).r; + let ru = textureSample(t_height, samp, uv + vec2(ts.x, -ts.y)).r; + let rd = textureSample(t_height, samp, uv + ts).r; + let lu = textureSample(t_height, samp, uv - ts).r; + let ld = textureSample(t_height, samp, uv + vec2(-ts.x, ts.y)).r; + let sharp = vec2(r - l, d - u) * 0.5; + let sobel = vec2(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0; + return select(sharp, sobel, g.uv_rotation.w > 0.5); +} + fn shade_mesh(i: VOut, front: bool) -> Shaded { var n_geo = normalize(i.nrm); if (!front) { @@ -479,15 +495,11 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { let ts = 1.0 / dims; let hgt = textureSample(t_height, samp, uv); let hc = hgt.r; - let hl = textureSample(t_height, samp, uv - vec2(ts.x, 0.0)).r; - let hr = textureSample(t_height, samp, uv + vec2(ts.x, 0.0)).r; - let hu = textureSample(t_height, samp, uv - vec2(0.0, ts.y)).r; - let hd = textureSample(t_height, samp, uv + vec2(0.0, ts.y)).r; - // Match export: a unit height over 1/16 of the width tilts 45° - // Combine the height gradient with the tangent-space normal - let k = g.mode.z * dims.x / 16.0 * tile_scale(uv); - let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); + // Match export (a unit height over 1/16 of a block's width or height tilts 45°), then combine with the tangent-space normal + let k = g.mode.z * g.disp.w * dims * g.height_slope.xy / 16.0 * tile_scale(uv); + let slope = height_slope(uv, ts); + let n_height = normalize(vec3(-slope.x * k.x, slope.y * k.y, 1.0)); // The Normal texture holds the signed normal in half floats (flat is exactly +z) var n_detail = clamp(nrm_s, vec3(-1.0), vec3(1.0)); @@ -728,12 +740,9 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { // The tangent-space normal the shading uses: the height slope turned by the normal channel let dims = vec2(textureDimensions(t_height)); let ts = 1.0 / dims; - let hl = textureSample(t_height, samp, i.uv - vec2(ts.x, 0.0)).r; - let hr = textureSample(t_height, samp, i.uv + vec2(ts.x, 0.0)).r; - let hu = textureSample(t_height, samp, i.uv - vec2(0.0, ts.y)).r; - let hd = textureSample(t_height, samp, i.uv + vec2(0.0, ts.y)).r; - let k = g.mode.z * dims.x / 16.0 * tile_scale(i.uv); - let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); + let k = g.mode.z * g.disp.w * dims * g.height_slope.xy / 16.0 * tile_scale(i.uv); + let slope = height_slope(i.uv, ts); + let n_height = normalize(vec3(-slope.x * k.x, slope.y * k.y, 1.0)); var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3(-1.0), vec3(1.0)); n_detail.y *= g.mode.w; return raw_out(rnm(n_height, normalize(n_detail)) * 0.5 + 0.5); diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index b4a4bba2..0b1ea9c4 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -8,6 +8,8 @@ const TAU: f32 = 6.28318530717959; const BIG: f32 = 3.0e38; const WALK_STEPS: u32 = 48u; const MAX_SETS: u32 = 256u; +// MAX_SETS / 4: the height slope factors pack four sets to an entry +const HEIGHT_Y_FACTOR_ENTRIES: u32 = 64u; struct Params { inv_vp: mat4x4, @@ -18,8 +20,10 @@ struct Params { sigma: vec4, // subsurface extinction per color channel eye: vec4, // camera position lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR, dielectric F0 scale - // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds, height strength. + // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength sets: array, MAX_SETS>, + // Per texture set, four to an entry: how much more the height slope tilts down the texture than across it + height_y_factors: array, HEIGHT_Y_FACTOR_ENTRIES>, }; @group(0) @binding(0) var P: Params; @@ -209,14 +213,37 @@ fn occluded(o: vec3, d: vec3) -> bool { // ---- Materials ---- -// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy). -fn texel(layer: u32, k: u32, uv: vec2, dx: i32, dy: i32) -> vec2 { +// Match the axial and Sobel kernels in HeightToNormalMethod::slope +fn height_slope(layer: u32, uv: vec2, sobel: bool) -> vec2 { + let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0, i32(textureDimensions(t_height).y)), layer, 0).r; + let l = textureLoad(t_height, texel(layer, 3u, uv, -1, 0, i32(textureDimensions(t_height).y)), layer, 0).r; + let d = textureLoad(t_height, texel(layer, 3u, uv, 0, 1, i32(textureDimensions(t_height).y)), layer, 0).r; + let u = textureLoad(t_height, texel(layer, 3u, uv, 0, -1, i32(textureDimensions(t_height).y)), layer, 0).r; + if (!sobel) { + return vec2(r - l, d - u) * 0.5; + } + + let ru = textureLoad(t_height, texel(layer, 3u, uv, 1, -1, i32(textureDimensions(t_height).y)), layer, 0).r; + let rd = textureLoad(t_height, texel(layer, 3u, uv, 1, 1, i32(textureDimensions(t_height).y)), layer, 0).r; + let lu = textureLoad(t_height, texel(layer, 3u, uv, -1, -1, i32(textureDimensions(t_height).y)), layer, 0).r; + let ld = textureLoad(t_height, texel(layer, 3u, uv, -1, 1, i32(textureDimensions(t_height).y)), layer, 0).r; + return vec2(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0; +} + +// Wrap in the source texture before mapping the sample into its array layer +fn texel(layer: u32, k: u32, uv: vec2, dx: i32, dy: i32, band_height: i32) -> vec2 { let info = P.sets[layer]; let small = ((u32(info.z) >> k) & 1u) == 1u; let dims = select(max(vec2(info.xy), vec2(1)), vec2(1), small); let x = i32(floor(uv.x * f32(dims.x))) + dx; let y = i32(floor(uv.y * f32(dims.y))) + dy; - return vec2(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y); + let wrapped = vec2(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y); + if (wrapped.y < band_height) { + return wrapped; + } + + // The upload lays successive vertical bands side by side + return vec2(wrapped.x + (wrapped.y / band_height) * dims.x, wrapped.y % band_height); } struct Surface { @@ -287,24 +314,23 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { let uv = vec2(verts[ix.x * 2u].w, a0.w) * w0 + vec2(verts[ix.y * 2u].w, a1.w) * u + vec2(verts[ix.z * 2u].w, a2.w) * v; let tw = a0.xyz * w0 + a1.xyz * u + a2.xyz * v; - let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0), layer, 0); - let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0), layer, 0); - let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0), layer, 0); - let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0), layer, 0); - let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0), layer, 0); - let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0), layer, 0); - let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0), layer, 0); - let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0), layer, 0); + let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0, i32(textureDimensions(t_base).y)), layer, 0); + let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0, i32(textureDimensions(t_orm).y)), layer, 0); + let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0, i32(textureDimensions(t_normal).y)), layer, 0); + let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0, i32(textureDimensions(t_height).y)), layer, 0); + let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0, i32(textureDimensions(t_emissive).y)), layer, 0); + let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0, i32(textureDimensions(t_lobes).y)), layer, 0); + let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0, i32(textureDimensions(t_sheen).y)), layer, 0); + let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0, i32(textureDimensions(t_extra).y)), layer, 0); let info = P.sets[layer]; // Extra alpha stores 32 × log2(1 / UV tile scale) - let k = info.w * info.x / 16.0 * exp2(-extra.a * 255.0 / 32.0); + let k = info.w * info.xy * vec2(1.0, P.height_y_factors[layer / 4u][layer % 4u]) / 16.0 * exp2(-extra.a * 255.0 / 32.0); var n_height = vec3(0.0, 0.0, 1.0); - if (k != 0.0) { - let hx = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r; - let hy = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r; - n_height = normalize_or(vec3(-hx * 0.5 * k, hy * 0.5 * k, 1.0), vec3(0.0, 0.0, 1.0)); + if (info.w != 0.0) { + let slope = height_slope(layer, uv, ((u32(info.z) >> 8u) & 1u) == 1u); + n_height = normalize_or(vec3(-slope.x * k.x, slope.y * k.y, 1.0), vec3(0.0, 0.0, 1.0)); } // The signed normal in half floats, as in mesh.wgsl (flat is exactly +z) diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a3f2780c..ec1e52e1 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -22,20 +22,35 @@ use std::sync::Arc; use rayon::prelude::*; use texturecraft_compose::{Composite, ImageRes}; -use texturecraft_core::Channel; use texturecraft_core::project::{DisplaySettings, EnvAlignment, LEGACY_DIELECTRIC_F0_SCALE, ToneMapping}; +use texturecraft_core::{Channel, HeightToNormalMethod}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera}; use crate::ibl::EnvImage; +/// A unit height over this share of a side tilts the normal 45°, as in export +const HEIGHT_SPAN: f32 = 16.0; + /// One texture set's composited channels. #[derive(Clone)] pub struct TraceSet { /// Mesh material the set covers. pub material: usize, pub composite: Composite, + /// Height displacement and, with `height_in_normal`, height-to-normal strength pub height_strength: f32, + /// How much more the height slope tilts down the texture than across it ([`texturecraft_core::TextureSet::atlas_height_y_factor`]) + pub height_y_factor: f32, + pub height_in_normal: bool, + pub height_to_normal: HeightToNormalMethod, +} + +impl TraceSet { + /// The strength of the height slope in the shaded normal (0 when normal mixing replaces it) + pub fn normal_height_strength(&self) -> f32 { + if self.height_in_normal { self.height_strength } else { 0.0 } + } } /// Everything a pass reads (cheap to clone: shared or copy-on-write data). @@ -554,7 +569,6 @@ fn surface(scene: &TraceScene, triangle: u32, u: f32, v: f32, origin: Vec3, dire // Match the minimum roughness in the GPU tracer const SPECULAR_ROUGHNESS_FLOOR: f32 = 0.045; const SHEEN_ROUGHNESS_FLOOR: f32 = 0.07; - const HEIGHT_SLOPE_UV_DIVISOR: f32 = 16.0; let mesh = &scene.mesh; let first_index = triangle as usize * 3; @@ -588,21 +602,20 @@ fn surface(scene: &TraceScene, triangle: u32, u: f32, v: f32, origin: Vec3, dire let sample_channel = |channel: Channel| surface_texel.map_or_else(|| channel.default_value(), |(set, _, [x, y])| set.composite.value(channel, x, y)); let base = Vec3::from(sample_channel(Channel::BaseColor)); - // A unit height across one sixteenth of the UV width tilts 45° - // A smaller tile reduces the number of texels across that span + // A unit height over a sixteenth of either UV axis tilts 45° let height_normal = surface_texel.map_or(Vec3::Z, |(set, [width, height], [x, y])| { - let strength = set.height_strength * set.composite.resolution as f32 / HEIGHT_SLOPE_UV_DIVISOR * set.composite.block_scales.at(x, y); + let strength = set.normal_height_strength() / HEIGHT_SPAN * set.composite.block_scales.at(x, y); if strength == 0.0 { return Vec3::Z; } - // Neighbors wrap independently across each axis - let previous = |position, size| if position == 0 { size - 1 } else { position - 1 }; - let next = |position, size| if position + 1 == size { 0 } else { position + 1 }; - let height_at = |x, y| set.composite.value(Channel::Height, x, y)[0]; - let slope_x = height_at(next(x, width), y) - height_at(previous(x, width), y); - let slope_y = height_at(x, next(y, height)) - height_at(x, previous(y, height)); - Vec3::new(-slope_x * 0.5 * strength, slope_y * 0.5 * strength, 1.0).normalize_or(Vec3::Z) + let [slope_x, slope_y] = set.height_to_normal.slope(|dx, dy| { + let x = (x as i32 + dx).rem_euclid(width as i32) as u32; + let y = (y as i32 + dy).rem_euclid(height as i32) as u32; + set.composite.value(Channel::Height, x, y)[0] + }); + let scale_y = height as f32 * set.height_y_factor; + Vec3::new(-slope_x * width as f32 * strength, slope_y * scale_y * strength, 1.0).normalize_or(Vec3::Z) }); let detail = (Vec3::from(sample_channel(Channel::Normal)) * 2.0 - Vec3::ONE).normalize_or(Vec3::Z); @@ -1259,7 +1272,72 @@ mod tests { } } } - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], env, 0.0) + TraceScene::new( + mesh, + bvh, + vec![TraceSet { + material: 0, + composite, + height_strength: 0.0, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: texturecraft_core::HeightToNormalMethod::Smooth, + }], + env, + 0.0, + ) + } + + /// How far the shaded normal of a plane leans from straight up under a height ramp along x or along y over `texture_set`'s atlas + fn ramp_tilt(texture_set: &texturecraft_core::TextureSet, along_x: bool) -> f32 { + let mesh = Arc::new(primitives::plane(2.0, 1)); + let bvh = Arc::new(Bvh::new(&mesh)); + let ((width, height), (block_width, block_height)) = (texture_set.size(), texture_set.block_size()); + let mut composite = Composite::with_size(&[Channel::Height], width, height); + let img = composite.channels.get_mut(&Channel::Height).unwrap(); + for y in 0..height { + for x in 0..width { + // The same rise per block side along either side + let rise = if along_x { x as f32 / block_width as f32 } else { y as f32 / block_height as f32 }; + img.set(x, y, &[texturecraft_texel::to_u16(rise * 0.5)]); + } + } + let set = TraceSet { + material: 0, + composite, + height_strength: texture_set.atlas_height_strength(), + height_y_factor: texture_set.atlas_height_y_factor(), + height_in_normal: true, + height_to_normal: HeightToNormalMethod::Sharp, + }; + let env = Arc::new(EnvImage { width: 8, height: 4, data: vec![[1.0; 3]; 32] }); + let s = TraceScene::new(mesh, bvh, vec![set], env, 0.0); + let (o, d) = (Vec3::new(0.1, 1.0, 0.1), Vec3::NEG_Y); + let hit = s.bvh.closest(o, d, f32::MAX).unwrap(); + let surf = surface(&s, hit.tri, hit.u, hit.v, o, d, hit.t).unwrap(); + surf.n.angle_between(Vec3::Y) + } + + #[test] + fn a_wide_set_tilts_the_normal_alike_for_the_same_rise_along_either_side() { + let mut wide = texturecraft_core::TextureSet::new("wide", 0, 128); + wide.set_size(128, 64); + + let (across, down) = (ramp_tilt(&wide, true), ramp_tilt(&wide, false)); + + assert!(across > 0.05, "the ramp tilts the normal: {across}"); + assert!((across - down).abs() < 0.1 * across, "across {across} down {down}"); + } + + #[test] + fn a_uv_tile_row_tilts_the_normal_alike_for_the_same_rise_along_either_side_of_a_tile() { + let mut row = texturecraft_core::TextureSet::new("row", 0, 64); + row.uv_tiles = vec![1001, 1002]; + + let (across, down) = (ramp_tilt(&row, true), ramp_tilt(&row, false)); + + assert!(across > 0.05, "the ramp tilts the normal: {across}"); + assert!((across - down).abs() < 0.1 * across, "across {across} down {down}"); } /// Mean radiance of parallel rays over the whole disc of the sphere (grazing hits included) @@ -1475,7 +1553,14 @@ mod tests { fn dielectric_scene(display: &DisplaySettings) -> TraceScene { let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); - let sets = vec![TraceSet { material: 0, composite: dielectric_composite(), height_strength: 0.0 }]; + let sets = vec![TraceSet { + material: 0, + composite: dielectric_composite(), + height_strength: 0.0, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: HeightToNormalMethod::Sharp, + }]; TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(crate::ibl::environment("Studio Soft", 32))) } @@ -1497,7 +1582,14 @@ mod tests { let height = composite.channels.get_mut(&Channel::Height).unwrap(); height.set(3, 0, &[u16::MAX]); height.set(0, 4, &[u16::MAX]); - let sets = vec![TraceSet { material: 0, composite, height_strength: 1.0 }]; + let sets = vec![TraceSet { + material: 0, + composite, + height_strength: 1.0, + height_y_factor: 1.0, + height_in_normal: true, + height_to_normal: HeightToNormalMethod::Sharp, + }]; let scene = TraceScene::new(mesh, bvh, sets, Arc::new(crate::ibl::environment("Studio Soft", 8)), 0.0); let normal = surface(&scene, 0, 0.25, 0.25, Vec3::Y, Vec3::NEG_Y, 1.0).unwrap().n; @@ -1516,7 +1608,8 @@ mod tests { project.texture_sets.push(set); project.display = display.clone(); let coverage = vec![true; (composite.resolution * composite.resolution) as usize]; - let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &Default::default(), coverage: &coverage, mesh_name: "sphere" }; + let input = + ExportInput { project: &project, ts: 0, composite: &composite, baked: &Default::default(), coverage: &coverage, seams: None, mesh_name: "sphere" }; let f0 = |component| SourceRef::Virtual { map: VirtualMap::F0, component }; let channels = vec![(Dest::R, f0(0)), (Dest::G, f0(1)), (Dest::B, f0(2))]; let map = MapSpec { file: "f0".into(), format: FileFormat::Exr, bit_depth: 32, channels, inverted: Vec::new() }; diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 751d4c0b..ffecb883 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,6 +1,6 @@ use texturecraft_compose::{DisplayKind, ImageRes}; use texturecraft_core::DisplaySettings; -use texturecraft_geom::glam::Vec3; +use texturecraft_geom::glam::{Quat, Vec3}; use texturecraft_geom::{OrbitCamera, primitives}; use texturecraft_render::headless::Headless; use texturecraft_render::renderer::TAA_SAMPLES; @@ -47,16 +47,26 @@ impl Img { /// The id `setup` uploads the material ball under const MESH_ID: u64 = 1; -/// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). -fn setup() -> Option<(Headless, Frame)> { - let Ok(mut h) = Headless::new() else { +const TEST_TEXTURE_RESOLUTION: u32 = 256; + +fn headless_renderer() -> Option { + let Ok(headless) = Headless::new() else { eprintln!("skipping: no GPU adapter"); return None; }; - eprintln!("headless adapter: {:?}", h.device.adapter_info()); + + eprintln!("headless adapter: {:?}", headless.device.adapter_info()); + Some(headless) +} + +/// A headless renderer with the material ball framed in a 480×360 view (None without a GPU). +fn setup() -> Option<(Headless, Frame)> { + let mut h = headless_renderer()?; let mesh = primitives::material_ball(); h.renderer.set_mesh(&h.device, &h.queue, &mesh, MESH_ID); - h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0), ((256, 256), 1)], 2); + let dimensions = (TEST_TEXTURE_RESOLUTION, TEST_TEXTURE_RESOLUTION); + h.renderer.set_texture_sets(&h.device, &h.queue, &[(dimensions, 0), (dimensions, 1)], 2); + let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); cam.frame(lo, hi); @@ -261,6 +271,44 @@ fn the_combined_normal_view_shows_the_shading_normal_unlit() { assert_eq!(a.px, b.px, "a data view ignores exposure"); } +#[test] +fn the_height_y_factor_steepens_slopes_down_the_texture_only() { + let Some(mut headless) = headless_renderer() else { return }; + + // An orthographic plane gives both ramps a uniform UV footprint + let resolution = TEST_TEXTURE_RESOLUTION; + let mesh = primitives::plane(2.0, 1); + headless.renderer.set_mesh(&headless.device, &headless.queue, &mesh, MESH_ID); + headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[((resolution, resolution), 0)], 1); + let camera = OrbitCamera { free: true, orient: Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2), ortho: true, distance: 2.0, ..OrbitCamera::default() }; + let normal_view = Frame { + view_id: 1, + size: [resolution; 2], + kind: ViewKind::Scene, + camera, + shade: Shade { view_mode: 4, ..Shade::default() }, + visible: vec![true], + overlay: Vec::new(), + }; + let doubled = shaded(&normal_view, |shade| shade.height_y_factor = 2.0); + let center = resolution / 2; + let flat = render(&mut headless, &normal_view, "height_flat").at(center, center); + + upload_height_to_sets(&mut headless, &[0], |x, _| [x as f32 / resolution as f32, 0.0, 0.0, 0.0]); + let across = render(&mut headless, &normal_view, "height_across"); + let across_doubled = render(&mut headless, &doubled, "height_across_y_doubled"); + + assert_ne!(across.at(center, center)[0], flat[0], "the horizontal ramp tilts the normal"); + assert_same(&across, &across_doubled, "a slope across the texture keeps its tilt"); + + upload_height_to_sets(&mut headless, &[0], |_, y| [y as f32 / resolution as f32, 0.0, 0.0, 0.0]); + let vertical_tilt = |image: Img| image.at(center, center)[2].abs_diff(flat[2]); + let down = vertical_tilt(render(&mut headless, &normal_view, "height_down")); + let down_doubled = vertical_tilt(render(&mut headless, &doubled, "height_down_y_doubled")); + + assert!(down > 0 && down_doubled > down, "the vertical ramp tilts farther from flat ({down} → {down_doubled})"); +} + #[test] fn post_effects() { let Some((mut h, frame)) = setup() else { return }; @@ -739,10 +787,21 @@ fn bench_1080p() { /// Fill the height texture of both 256² sets: `f(x, y)` → (height, F0 r, g, b). fn upload_height(h: &mut Headless, f: impl Fn(u32, u32) -> [f32; 4]) { - for ts in 0..2 { - for (tx, ty) in (0..16).map(|i| (i % 4, i / 4)) { - let bytes: Vec = (0..64 * 64).flat_map(|i| f(tx * 64 + i % 64, ty * 64 + i / 64)).flat_map(|v| half::f16::from_f32(v).to_le_bytes()).collect(); - h.renderer.upload_tile(&h.device, &h.queue, ts, DisplayKind::Height, tx, ty, &bytes); + upload_height_to_sets(h, &[0, 1], f); +} + +fn upload_height_to_sets(headless: &mut Headless, sets: &[usize], texel: impl Fn(u32, u32) -> [f32; 4]) { + use texturecraft_texel::TILE; + + let tiles_per_side = TEST_TEXTURE_RESOLUTION / TILE; + for (tile_x, tile_y) in (0..tiles_per_side.pow(2)).map(|index| (index % tiles_per_side, index / tiles_per_side)) { + let bytes: Vec = (0..TILE * TILE) + .flat_map(|index| texel(tile_x * TILE + index % TILE, tile_y * TILE + index / TILE)) + .flat_map(|value| half::f16::from_f32(value).to_le_bytes()) + .collect(); + + for &texture_set in sets { + headless.renderer.upload_tile(&headless.device, &headless.queue, texture_set, DisplayKind::Height, tile_x, tile_y, &bytes); } } } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5b85a7fe..972652cb 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -12,7 +12,8 @@ workspace = true chrono = { workspace = true } texturecraft-engine = { workspace = true } texturecraft-render = { workspace = true } -eframe = { workspace = true, features = ["default_fonts", "wgpu", "persistence"] } +# egui's default fonts: on desktop from egui; the web build uses craft-ui's deflated copies (`fonts::egui_default_definitions`). +eframe = { workspace = true, features = ["wgpu", "persistence"] } egui = { workspace = true } craft-ui = { workspace = true } craft-behavior = { workspace = true } @@ -32,6 +33,7 @@ craft-image-codecs = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] +eframe = { workspace = true, features = ["default_fonts"] } sys-locale = "0.3" # Help > Check for Updates and the check at start (updates_ui.rs). craft-update = { workspace = true } @@ -41,6 +43,10 @@ tempfile = "3" # Whether the app runs in a real window, where an eyedropper pick may take clicks outside it (screen_pick). raw-window-handle = "0.6" +[target.'cfg(all(not(unix), not(target_arch = "wasm32")))'.dependencies] +# Compare filesystem identities on native platforms without Unix device and inode metadata +same-file = "1" + # An eyedropper click outside the window (screen_pick): a low-level mouse hook and the eyedropper as the system pointer # (winsafe, MIT) and one desktop pixel through GDI (xcap, Apache-2.0). [target.'cfg(windows)'.dependencies] @@ -57,12 +63,16 @@ zbus = { version = "5.19", default-features = false, features = ["async-io", "bl # versions craft-libs' craft-fonts-build subsets with). [build-dependencies] craft-i18n = { workspace = true } +# The web build embeds its fonts and catalogs deflated (build.rs, `fonts::CraftFont`, `i18n`). +flate2 = { workspace = true } skera = "0.8" skrifa = { version = "0.48", default-features = false, features = ["std"] } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] craft-zip = { workspace = true } +# Inflates the embedded fonts and catalogs of the web build. +flate2 = { workspace = true } rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" @@ -70,6 +80,8 @@ js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] } [dev-dependencies] +# build.rs's `i18n_build.rs`, which tests/i18n_build.rs includes. +flate2 = { workspace = true } craft-zip = { workspace = true } zip = { workspace = true } diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 79f33f27..274690a6 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -33,6 +33,7 @@ type Faces = &'static [(&'static str, &'static str)]; fn main() { let catalogs = i18n_build::embed(); + deflate_assets(); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_REQUIRED"); let mut src = String::from("pub static CRAFT_FONTS: &[CraftFont] = &[\n"); @@ -69,8 +70,8 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let wanted = if wasm { web } else { desktop }; let mut out = String::new(); for line in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) { - let f: Vec<&str> = line.split(" | ").map(str::trim).collect(); - let [family, style, file, scripts, ..] = f.as_slice() else { + let fields: Vec<&str> = line.split(" | ").map(str::trim).collect(); + let [family, style, file, scripts, ..] = fields.as_slice() else { return Err(format!("malformed manifest line: {line}")); }; @@ -81,23 +82,31 @@ fn craft_fonts(dir: &std::path::Path, rel: &str, desktop: &[(&str, &str)], web: let mut path = dir.join(file).canonicalize().map_err(|e| format!("{file}: {e}"))?; println!("cargo::rerun-if-changed={}", path.display()); let tags: Vec<&str> = scripts.split(',').map(str::trim).filter(|s| !s.is_empty()).collect(); - // The Latin faces lose their Private Use Area everywhere; a web build also cuts its CJK - // faces to the characters the shipped catalogs use. The desktop keeps its CJK faces whole: - // the same face draws text the app never ships, a user's Japanese file name. + + // Leave the Private Use Area to the icon font + // Desktop CJK fonts also cover user file names outside the catalogs let cut = rel == LATIN_MANIFEST || (wasm && !catalogs.is_empty() && tags.iter().any(|tag| CJK_SCRIPTS.contains(tag))); if cut { let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; let cut = if rel == LATIN_MANIFEST { without_private_use(&bytes) } else { cut_to_catalogs(&bytes, catalogs) }.map_err(|e| format!("{file}: {e}"))?; - let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(path.file_name().unwrap_or_default()); + let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(out_name(file, "")); std::fs::write(&out, cut).map_err(|e| format!("{}: {e}", out.display()))?; path = out; } + // The web build embeds its faces deflated: the wasm is under a download budget and fonts halve. + if wasm { + let bytes = std::fs::read(&path).map_err(|e| format!("{file}: {e}"))?; + let deflated = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join(out_name(file, ".deflate")); + std::fs::write(&deflated, i18n_build::deflate(&bytes)?).map_err(|e| format!("{}: {e}", deflated.display()))?; + path = deflated; + } + let scripts: Vec = tags.iter().map(|s| format!("{s:?}")).collect(); let _ = writeln!( out, - " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], bytes: include_bytes!({:?}) }},", + " CraftFont {{ family: {family:?}, style: {style:?}, scripts: &[{}], data: include_bytes!({:?}), deflated: {wasm} }},", scripts.join(", "), path.display().to_string(), ); @@ -156,3 +165,38 @@ fn subset(font: &FontRef, unicodes: &IntSet) -> Result, String> { ); subset_font(font, &plan).map_err(|e| e.to_string()) } + +/// A face's file name under `OUT_DIR`: its path in the craft-fonts checkout with every separator flattened, so faces +/// that share a file name (`jp/Regular.ttf`, `ar/Regular.ttf`) stay apart. +fn out_name(file: &str, suffix: &str) -> String { + let flat: String = file.chars().map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' }).collect(); + format!("craft-font-{flat}{suffix}") +} + +/// The files a web build embeds deflated (the wasm is under a download budget): the icon font and the studio +/// environment, from this crate's directory to the name they have under `OUT_DIR` (`name.deflate`). The other builds +/// include the files themselves. +const DEFLATED_ASSETS: &[(&str, &str)] = + &[("../../vendor/egui-phosphor/res/Phosphor.ttf", "Phosphor.ttf"), ("../../assets/hdr/studio_small_09_512.hdr", "studio_small_09_512.hdr")]; + +/// Writes [`DEFLATED_ASSETS`] under `OUT_DIR` for the web build. +fn deflate_assets() { + if !std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32") { + return; + } + + let out = PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + let manifest = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default()); + for (source, name) in DEFLATED_ASSETS { + let source = manifest.join(source); + println!("cargo::rerun-if-changed={}", source.display()); + let target = out.join(format!("{name}.deflate")); + let written = std::fs::read(&source) + .map_err(|e| e.to_string()) + .and_then(|bytes| i18n_build::deflate(&bytes)) + .and_then(|d| std::fs::write(&target, d).map_err(|e| e.to_string())); + if let Err(e) = written { + println!("cargo::error={}: {e}", source.display()); + } + } +} diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index 58eaae8b..25de61b3 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -4,14 +4,64 @@ use std::path::Path; /// The catalogs' Rust includes and the distinct characters they use, sorted: the web build cuts /// its CJK interface face to those characters. +#[allow(dead_code)] // used by tests/i18n_build.rs, not by build.rs pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec), String> { - let mut source = String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"); + collect_into(dir, required, None) +} + +/// `bytes` deflated (raw deflate, as `flate2::read::DeflateDecoder` reads it). +pub fn deflate(bytes: &[u8]) -> Result, String> { + use std::io::Write as _; + let mut encoder = flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::best()); + encoder.write_all(bytes).map_err(|e| e.to_string())?; + encoder.finish().map_err(|e| e.to_string()) +} + +/// What the generated source does with the catalogs' text. A web build downloads the wasm, so it embeds each catalog +/// deflated (written under `out`) and inflates all of them on first use; other builds embed the text itself. +const INFLATE_FN: &str = r#" +fn inflate_text(deflated: &[u8]) -> &'static str { + use std::io::Read as _; + let mut text = String::new(); + // A catalog that does not inflate leaves its language without translations, never a panic. + if flate2::read::DeflateDecoder::new(deflated).take(64 << 20).read_to_string(&mut text).is_err() { + text.clear(); + } + Box::leak(text.into_boxed_str()) +} + +pub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded { + static CATALOGS: std::sync::OnceLock<&'static craft_i18n::Embedded> = std::sync::OnceLock::new(); + CATALOGS.get_or_init(|| { + let catalogs: Vec<(&'static str, &'static str, &'static str)> = + CRAFT_I18N_DEFLATED.iter().map(|&(locale, common, app)| (locale, inflate_text(common), inflate_text(app))).collect(); + Box::leak(catalogs.into_boxed_slice()) + }) +} +"#; + +/// [`collect`], embedding the catalogs deflated under the directory `deflated_in` when it is given. +pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Path>) -> Result<(String, Vec), String> { + let mut source = match deflated_in { + Some(_) => String::from("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[\n"), + None => String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"), + }; + let finish_source = |mut source: String| { + source.push_str("];\n"); + source.push_str(if deflated_in.is_some() { + INFLATE_FN + } else { + "\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n" + }); + source + }; + let Some(dir) = dir else { if required { return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into()); } - source.push_str("];\n"); - return Ok((source, Vec::new())); + + return Ok((finish_source(source), Vec::new())); }; if !dir.is_absolute() { @@ -21,6 +71,7 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) let locales = dir.join("locales"); let entries = std::fs::read_dir(&locales).map_err(|e| format!("{}: {e}", locales.display()))?; println!("cargo::rerun-if-changed={}", locales.display()); + let mut paths = Vec::new(); for entry in entries { let entry = entry.map_err(|e| e.to_string())?; @@ -32,7 +83,8 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) paths.sort(); let mut count = 0; let mut catalogs = Vec::new(); - let mut characters = Vec::new(); + let mut characters = std::collections::HashSet::new(); + for path in paths { // Watch directories so adding or removing an app catalog rebuilds the embedding println!("cargo::rerun-if-changed={}", path.display()); @@ -48,10 +100,21 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) let name = file.to_str().ok_or("non-UTF-8 catalog path")?; println!("cargo::rerun-if-changed={name}"); + let include = match deflated_in { + Some(out) => { + let copy = out.join(format!("{locale}.{}.deflate", file.file_stem().and_then(|n| n.to_str()).unwrap_or("catalog"))); + std::fs::write(©, deflate(text.as_bytes())?).map_err(|e| format!("{}: {e}", copy.display()))?; + format!("include_bytes!({:?})", copy.display().to_string()) + } + None => format!("include_str!({name:?})"), + }; + // The shared runtime needs static inputs for this short-lived build process - Ok((format!("include_str!({name:?})"), Box::leak(text.into_boxed_str()))) + Ok((include, Box::leak(text.into_boxed_str()))) }; - let (shared, shared_text) = if common.is_file() { embed(&common)? } else { ("\"\"".into(), "") }; + + let empty = if deflated_in.is_some() { "&[]" } else { "\"\"" }; + let (shared, shared_text) = if common.is_file() { embed(&common)? } else { (empty.into(), "") }; let (app, app_text) = embed(&app)?; characters.extend(shared_text.chars().chain(app_text.chars())); let code: &'static str = Box::leak(locale.to_owned().into_boxed_str()); @@ -59,6 +122,7 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) let _ = writeln!(source, " ({locale:?}, {shared}, {app}),"); count += 1; } + if required && count == 0 { return Err("no TextureCraft translation catalogs found".into()); } @@ -70,10 +134,9 @@ pub fn collect(dir: Option<&Path>, required: bool) -> Result<(String, Vec) return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; "))); } - source.push_str("];\n"); + let mut characters: Vec<_> = characters.into_iter().collect(); characters.sort_unstable(); - characters.dedup(); - Ok((source, characters)) + Ok((finish_source(source), characters)) } /// Write the embedding for both desktop and wasm, reporting optional failures as warnings. @@ -86,7 +149,9 @@ pub fn embed() -> Vec { println!("cargo::rerun-if-env-changed=CRAFT_I18N_REQUIRED"); let dir = std::env::var_os("CRAFT_I18N_DIR").map(std::path::PathBuf::from); let required = std::env::var("CRAFT_I18N_REQUIRED").is_ok_and(|v| v == "1"); - let (source, characters) = match collect(dir.as_deref(), required) { + let out_dir = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()); + let wasm = std::env::var("CARGO_CFG_TARGET_ARCH").is_ok_and(|a| a == "wasm32"); + let (source, characters) = match collect_into(dir.as_deref(), required, wasm.then_some(out_dir.as_path())) { Ok(embedded) => embedded, Err(error) => { if required { @@ -94,13 +159,22 @@ pub fn embed() -> Vec { } else { println!("cargo::warning=building without craft-i18n: {error}"); } - ("pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n".into(), Vec::new()) + (empty_embedding(wasm), Vec::new()) } }; - let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap_or_default()).join("craft_i18n.rs"); + let out = out_dir.join("craft_i18n.rs"); if let Err(error) = std::fs::write(&out, source) { println!("cargo::error=writing {}: {error}", out.display()); } characters } + +/// The embedding of a build without catalogs. +fn empty_embedding(deflated: bool) -> String { + if deflated { + format!("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[];\n{INFLATE_FN}") + } else { + "pub static CRAFT_I18N: &craft_i18n::Embedded = &[];\n\npub fn craft_i18n_catalogs() -> &'static craft_i18n::Embedded {\n CRAFT_I18N\n}\n".into() + } +} diff --git a/crates/ui-egui/src/alpha_choice.rs b/crates/ui-egui/src/alpha_choice.rs new file mode 100644 index 00000000..234601d0 --- /dev/null +++ b/crates/ui-egui/src/alpha_choice.rs @@ -0,0 +1,12 @@ +//! What the brush Alpha slot's picker offers + +use texturecraft_engine::paint::BrushAlpha; + +/// One tile of the Alpha slot's picker: a built-in shape, a library alpha, an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum AlphaChoice { + Shape(BrushAlpha), + Library(&'static str), + Image(String), + Import, +} diff --git a/crates/ui-egui/src/alpha_sheet.rs b/crates/ui-egui/src/alpha_sheet.rs new file mode 100644 index 00000000..1123b2b7 --- /dev/null +++ b/crates/ui-egui/src/alpha_sheet.rs @@ -0,0 +1,297 @@ +//! The Alpha section of a paint tool's Properties: the alpha's slot with its picker, its Parameters beside a picture of the shape they make, and the Text band + +use std::ops::RangeInclusive; + +use egui::{Color32, CornerRadius, Painter, Rect, Stroke, Ui, pos2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::Session; +use texturecraft_engine::core::Channel; +use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; + +use crate::TextureCraftApp; +use crate::alpha_choice::AlphaChoice; +use crate::brush_pictures::alpha_image; +use crate::brush_stroke_preview::BrushStrokePreview; +use crate::i18n::{n_, tr}; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::theme::Tokens; +use crate::tile_picture::TilePicture; + +/// Hardness, Roundness and Size X / Y, in percent +const HARDNESS_PERCENT_RANGE: RangeInclusive = 0.0..=99.9; +const ROUNDNESS_PERCENT_RANGE: RangeInclusive = 0.0..=100.0; +const ALPHA_SIZE_PERCENT_RANGE: RangeInclusive = 5.0..=100.0; + +/// Rows the text box shows before it scrolls +const TEXT_ROWS: usize = 2; + +/// Air inside the text box, around its words +const TEXT_BOX_MARGIN: i8 = 6; + +/// Corner radius of the text box, as the sheet's fields +const TEXT_BOX_ROUNDING: u8 = 3; + +/// Width of the text box's outline +const TEXT_BOX_OUTLINE_WIDTH: f32 = 1.0; + +/// The Alpha section: the alpha's slot, its Parameters band and the Text band +pub(crate) fn alpha_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + alpha_slot(app, sheet); + parameters_band(app, sheet); + + if sheet.band(tr("Text"), false, None, None).open { + text_rows(app, sheet); + } +} + +/// The slot showing the alpha in use; a click opens the picker of shapes, library alphas and images, × goes back to the Round shape +fn alpha_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let ctx = sheet.ui.ctx().clone(); + let current = current_choice(&app.session); + let brush = &app.session.tool.brush; + let hardness = brush.hardness; + let (name, source, texture) = match ¤t { + AlphaChoice::Image(name) => { + let texture = app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image)); + (name.clone(), tr("Imported image"), texture) + } + AlphaChoice::Library(id) => { + let alpha = alphas::find(id); + let texture = alpha.and_then(|alpha| app.thumbs.alpha(&ctx, alpha)); + (alpha.map_or_else(|| (*id).to_owned(), |alpha| tr(&alpha.label).to_owned()), tr("Library alpha"), texture) + } + AlphaChoice::Shape(_) | AlphaChoice::Import => (tr(brush.alpha.label()).to_owned(), tr("Built-in shape"), None), + }; + let shape = brush.alpha; + let thumbnail = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, Color32::BLACK); + match &texture { + Some(texture) => { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + None => crate::thumbs::paint_alpha(painter, rect, shape, hardness), + } + }; + + // The default Round shape has nothing to clear back to + let clearable = current != AlphaChoice::Shape(BrushAlpha::default()); + let slot = sheet.slot(&thumbnail, &name, source, None, clearable, false); + + let popup = sheet.ui.make_persistent_id("brush_alpha_source"); + if slot.pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + let tabs = || alpha_tabs(&app.session, hardness); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), true, tabs) { + Some(AlphaChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(choice) if choice != current => { + app.run("tool.brush", json!({ "alpha": alpha_value(&choice) })); + } + _ => {} + } + if slot.clear { + app.run("tool.brush", json!({ "alpha": BrushAlpha::default().label() })); + } + + // An alpha from the Assets panel, or an image, dropped on the slot becomes the alpha + crate::shelf::drop_target(app, sheet.ui, &slot.pick, crate::shelf::DropZone::Brush); + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.brush", json!({ "alpha": { "image": name } })); + } + sheet.close_card(); +} + +/// The picker's choice the brush's alpha is +fn current_choice(session: &Session) -> AlphaChoice { + let brush = &session.tool.brush; + match (&brush.alpha_image, brush.alpha_library.as_deref().and_then(alphas::find)) { + (Some(name), _) => AlphaChoice::Image(name.clone()), + (None, Some(alpha)) => AlphaChoice::Library(alpha.id.as_str()), + (None, None) => AlphaChoice::Shape(brush.alpha), + } +} + +/// What `tool.brush` takes as `alpha` for `choice` +fn alpha_value(choice: &AlphaChoice) -> Value { + match choice { + AlphaChoice::Shape(shape) => json!(shape.label()), + AlphaChoice::Library(id) => json!({ "library": id }), + AlphaChoice::Image(name) => json!({ "image": name }), + AlphaChoice::Import => Value::Null, + } +} + +/// The picker's one tab: the built-in Shapes at the brush's `hardness`, the library's Alphas in their shelf groups, then Textures with Import... first +fn alpha_tabs(session: &Session, hardness: f32) -> Vec> { + let shapes = BrushAlpha::ALL + .into_iter() + .map(|shape| ResourcePickerItem { + id: AlphaChoice::Shape(shape), + label: tr(shape.label()).to_owned(), + caption: None, + picture: TilePicture::Shape(shape, hardness), + }) + .collect(); + let library = alphas::library() + .iter() + .map(|alpha| ResourcePickerItem { + id: AlphaChoice::Library(alpha.id.as_str()), + label: tr(&alpha.label).to_owned(), + caption: Some(tr(alpha.category)), + picture: TilePicture::Alpha(alpha), + }) + .collect(); + let textures = ResourcePickerItem::textures(session, AlphaChoice::Import, |name| AlphaChoice::Image(name.to_owned())); + let groups = [(n_("Shapes"), shapes), (n_("Alphas"), library), (n_("Textures"), textures)] + .into_iter() + .map(|(header, items)| PickerGroup { header: Some(tr(header)), items }) + .collect(); + vec![PickerTab { icon: ic::CIRCLE_HALF, name: tr("Alphas"), groups }] +} + +/// Hardness and the parameters every alpha shares beside the shape they make; the band's reset puts them all back +fn parameters_band(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let tokens = Tokens::get(sheet.ui.ctx()); + let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); + let fields = |settings: &BrushSettings| (settings.hardness, settings.alpha_params); + let band = sheet.band(tr("Parameters"), true, Some(fields(brush) != fields(&defaults)), None); + if band.reset { + (brush.hardness, brush.alpha_params) = fields(&defaults); + } + if !band.open { + return; + } + + let shown = brush.clone(); + let ctx = sheet.ui.ctx().clone(); + let tint = tokens.text.to_array(); + let picture = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + BrushStrokePreview::paint_picture(&ctx, painter, rect, "brush_alpha_picture", (&shown, image.as_ref()), |_| [tint[0], tint[1], tint[2]], alpha_image); + }; + + // Only the procedural Round shape has a roundness + let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); + let before = [brush.hardness, brush.alpha_params.roundness, brush.alpha_params.size_x, brush.alpha_params.size_y].map(|fraction| fraction * 100.0); + let [mut hardness, mut roundness, mut size_x, mut size_y] = before; + let percent = |label: &'static str, value, range: RangeInclusive| StackSlider { + label: tr(label), + value, + range: range.clone(), + typed: range, + decimals: 0, + suffix: "", + dial: false, + }; + if round { + sheet.picture_sliders( + &picture, + &mut [ + percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE), + percent(n_("Roundness"), &mut roundness, ROUNDNESS_PERCENT_RANGE), + percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE), + percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE), + ], + ); + } else { + sheet.picture_sliders( + &picture, + &mut [ + percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE), + percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE), + percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE), + ], + ); + } + + // Only what moved is written back, so an untouched value keeps its exact fraction + for (after, was, fraction) in [ + (hardness, before[0], &mut brush.hardness), + (roundness, before[1], &mut brush.alpha_params.roundness), + (size_x, before[2], &mut brush.alpha_params.size_x), + (size_y, before[3], &mut brush.alpha_params.size_y), + ] { + if after != was { + *fraction = after / 100.0; + } + } + sheet.slider(tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); + sheet.toggle(tr("Invert"), &mut brush.alpha_params.invert); + *brush = brush.sanitized(); +} + +/// Text drawn in a font, as the brush alpha or a decal (`resource.text`) +fn text_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + if app.ui.text.fonts.is_empty() + && let Some(fonts) = app.run("text.fonts", Value::Null) + { + let installed = fonts["installed"].as_array().into_iter().flatten().map(|font| { + let styles = font["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); + (font["family"].as_str().unwrap_or_default().to_string(), styles) + }); + let built_in = fonts["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|name| (name.to_string(), Vec::new())); + app.ui.text.fonts = installed.chain(built_in).collect(); + } + + // A decal shows the text in the tool's base color; an alpha must stay white + let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); + let tokens = Tokens::get(sheet.ui.ctx()); + let text = &mut app.ui.text; + sheet.embed(|ui: &mut Ui| { + let frame = egui::Frame::NONE + .fill(tokens.field) + .stroke(Stroke::new(TEXT_BOX_OUTLINE_WIDTH, tokens.field_border)) + .corner_radius(CornerRadius::same(TEXT_BOX_ROUNDING)) + .inner_margin(egui::Margin::same(TEXT_BOX_MARGIN)); + frame.show(ui, |ui| { + let edit = + egui::TextEdit::multiline(&mut text.text).frame(egui::Frame::NONE).desired_rows(TEXT_ROWS).desired_width(f32::INFINITY).hint_text(tr("Text")); + ui.add(edit); + }); + }); + + // Index 0 is the default font, then the families in the order `text.fonts` lists them + let family = text.fonts.iter().position(|(family, _)| *family == text.font).map_or(0, |index| index + 1); + let family_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { text.fonts[index - 1].0.clone() }; + let (picked, _) = sheet.dropdown_built(tr("Font"), family, || 0..=text.fonts.len(), family_name, None); + if let Some(index) = picked { + text.font = if index == 0 { String::new() } else { text.fonts[index - 1].0.clone() }; + text.style = String::new(); + } + + let styles = text.fonts.iter().find(|(family, _)| *family == text.font).map(|(_, styles)| styles.clone()).unwrap_or_default(); + if styles.len() > 1 { + let style = styles.iter().position(|style| *style == text.style).map_or(0, |index| index + 1); + let style_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { styles[index - 1].clone() }; + let (picked, _) = sheet.dropdown_built(tr("Style"), style, || 0..=styles.len(), style_name, None); + if let Some(index) = picked { + text.style = if index == 0 { String::new() } else { styles[index - 1].clone() }; + } + } + + let mut params = + json!({"text": text.text, "font": (!text.font.is_empty()).then_some(&text.font), "style": (!text.style.is_empty()).then_some(&text.style)}); + let ready = !text.text.trim().is_empty(); + let alpha = sheet.button_enabled(ic::CIRCLE_HALF, tr("Use as brush alpha"), false, ready).clicked(); + let decal = sheet.button_enabled(ic::STAMP, tr("Place as decal"), false, ready).clicked(); + if decal { + params["color"] = json!(color); + } + if (alpha || decal) + && let Some(name) = app.run("resource.text", params).and_then(|result| result["name"].as_str().map(str::to_string)) + { + if alpha { + app.run("tool.brush", json!({"alpha": {"image": name}})); + } else { + app.run("layer.add.decal", json!({"image": name})); + } + } +} diff --git a/crates/ui-egui/src/autosave_name.rs b/crates/ui-egui/src/autosave_name.rs index 69d0ab4d..8d954593 100644 --- a/crates/ui-egui/src/autosave_name.rs +++ b/crates/ui-egui/src/autosave_name.rs @@ -1,46 +1,67 @@ -//! Where a project's autosave copy goes. Each project has a file of its own, `-copy-.tcraft`: a project's -//! name comes from its mesh file, so the name alone would let projects made from one mesh overwrite each other's copy +//! Where a project's autosave copy goes. Each project has a file of its own, `-copy-.tcraft`, +//! even if several projects share a name or a project is renamed. use std::path::{Path, PathBuf}; +use serde_json::Value; use texturecraft_engine::core::PROJECT_EXT; use texturecraft_engine::formats::export::sanitize_file_stem; -use crate::TextureCraftApp; +use crate::{TextureCraftApp, user_dir}; /// Hex digits of a copy's suffix const SUFFIX_DIGITS: usize = 16; /// Between a copy's stem and its suffix, so a user's own file named like `report-20240115` is not taken for a copy -const COPY_MARK: &str = "-copy-"; +const COPY_MARK: &str = "copy"; /// The longest stem kept, so the suffix and the temporary files of a save still fit a file name const MAX_STEM_CHARS: usize = 170; impl TextureCraftApp { + /// Detach a recovered project because the original can overwrite its autosave copy. + pub(crate) fn detach_autosave_copy(&mut self) -> bool { + let Some(path) = self.session.path.as_deref() else { + return false; + }; + + if !is_copy_in(Path::new(path), &user_dir("autosave")) { + return false; + } + + self.session.path = None; + self.session.modified = true; + true + } + + /// Keep the engine's open reply consistent with the desktop session. + pub(crate) fn recover_file_open(&mut self, command: &str, mut result: Value) -> Value { + if command == "file.open" && self.detach_autosave_copy() { + result["path"] = Value::Null; + result["modified"] = Value::Bool(true); + } + + result + } + /// The open project's autosave file in `folder`. A saved project's copy is named after its file and stays the - /// same across restarts; an unsaved project gets one that no other open project or running instance shares + /// same across restarts; an unsaved project's copy keeps its first autosave name until the project is saved pub(crate) fn autosave_path(&mut self, folder: &Path) -> PathBuf { let Some(saved) = self.session.path.as_deref() else { let project = self.session.project_id; - let suffix = match self.unsaved_autosave_suffix { - Some((owner, suffix)) if owner == project => suffix, - _ => { - let suffix = new_suffix(project); - self.unsaved_autosave_suffix = Some((project, suffix)); - suffix - } - }; - return folder.join(file_name(&self.session.doc.project.name, suffix)); + if let Some((owner, name)) = &self.unsaved_autosave_file + && *owner == project + { + return folder.join(name); + } + + let name = file_name(&self.session.doc.project.name, new_suffix(project)); + let path = folder.join(&name); + self.unsaved_autosave_file = Some((project, name)); + return path; }; let saved = absolute(Path::new(saved)); - - // A project opened from its autosave copy keeps writing there, rather than chaining suffixes - if is_copy_in(&saved, &absolute(folder)) { - return saved; - } - let stem = saved.file_stem().map_or_else(|| self.session.doc.project.name.clone(), |stem| stem.to_string_lossy().into_owned()); folder.join(file_name(&stem, hash(saved.as_os_str().as_encoded_bytes()))) } @@ -48,7 +69,7 @@ impl TextureCraftApp { fn file_name(stem: &str, suffix: u64) -> String { let stem: String = sanitize_file_stem(stem).chars().take(MAX_STEM_CHARS).collect(); - format!("{stem}{COPY_MARK}{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") + format!("{stem}-{COPY_MARK}-{suffix:0SUFFIX_DIGITS$x}.{PROJECT_EXT}") } /// `path` made absolute, as given when that fails @@ -56,17 +77,53 @@ fn absolute(path: &Path) -> PathBuf { std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf()) } -/// `path` with links and, on Windows, the verbatim prefix resolved so two spellings of one folder compare equal; made absolute when that fails -fn resolved(path: &Path) -> PathBuf { - std::fs::canonicalize(path).unwrap_or_else(|_| absolute(path)) +/// Compare device and inode without opening the directory or a possible special file. +#[cfg(unix)] +fn same_location(left: &Path, right: &Path) -> bool { + use std::os::unix::fs::MetadataExt; + + matches!((left.metadata(), right.metadata()), (Ok(left), Ok(right)) if (left.dev(), left.ino()) == (right.dev(), right.ino())) } -/// Whether `path` is an autosave copy of `folder`: a project file there whose name ends in the copy mark and a suffix +#[cfg(not(unix))] +fn same_location(left: &Path, right: &Path) -> bool { + same_file::is_same_file(left, right).unwrap_or(false) +} + +/// Whether the opened file is a generated autosave in the current profile. fn is_copy_in(path: &Path, folder: &Path) -> bool { - let suffix = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once(COPY_MARK)).map(|(_, suffix)| suffix); - path.parent().is_some_and(|parent| resolved(parent) == resolved(folder)) - && path.extension().is_some_and(|extension| extension == PROJECT_EXT) - && suffix.is_some_and(|suffix| suffix.len() == SUFFIX_DIGITS && suffix.bytes().all(|digit| digit.is_ascii_hexdigit())) + let Some(extension) = path.extension().filter(|extension| extension.eq_ignore_ascii_case(PROJECT_EXT)) else { + return false; + }; + + let Some((prefix, suffix)) = path.file_stem().and_then(|stem| stem.to_str()).and_then(|stem| stem.rsplit_once('-')) else { + return false; + }; + + let Some((stem, mark)) = prefix.rsplit_once('-') else { + return false; + }; + + if !mark.eq_ignore_ascii_case(COPY_MARK) || suffix.len() != SUFFIX_DIGITS || !suffix.bytes().all(|digit| digit.is_ascii_hexdigit()) { + return false; + } + + let opened = absolute(path); + let Some(parent) = opened.parent() else { + return false; + }; + + if parent != folder && !same_location(parent, folder) { + return false; + } + + if mark == COPY_MARK && extension == PROJECT_EXT { + return true; + } + + // On a case-sensitive volume the alternate spelling may be a separate user file + let generated_name = format!("{stem}-{COPY_MARK}-{}.{PROJECT_EXT}", suffix.to_ascii_lowercase()); + same_location(path, &folder.join(generated_name)) } /// A suffix for the unsaved project `project`: from this process and the moment, so another instance or a later run @@ -122,6 +179,23 @@ mod tests { assert_ne!(first.autosave_path(folder), one, "a new project of the same name starts its own copy"); } + #[test] + fn renaming_an_unsaved_project_keeps_its_autosave_copy() { + let folder = Path::new("autosave"); + let mut app = app(project("hero")); + let copy = app.autosave_path(folder); + + for name in ["Knight", "Knight final"] { + texturecraft_engine::execute(&mut app.session, "project.rename", &serde_json::json!({"name": name})).unwrap(); + + assert_eq!(app.autosave_path(folder), copy); + } + + app.session.switch_to(project("Knight")); + + assert_ne!(app.autosave_path(folder), copy); + } + #[test] fn a_saved_project_names_its_copy_after_its_file_and_keeps_it_across_restarts() { let folder = Path::new("autosave"); @@ -142,22 +216,28 @@ mod tests { } #[test] - fn a_project_opened_from_its_copy_keeps_writing_to_it() { - let folder = std::env::temp_dir().join("tc-autosave"); + fn only_a_project_opened_from_a_copy_is_detached_from_its_file() { + let folder = user_dir("autosave"); let mut app = app(project("hero")); let copy = app.autosave_path(&folder); + // Ordinary files and copies kept elsewhere retain their save paths + let elsewhere = folder.join("kept").join(name_of(©)); + for project_path in [folder.join("hero.tcraft"), folder.join("hero-20240115.tcraft"), elsewhere] { + let project_path = project_path.display().to_string(); + app.session.path = Some(project_path.clone()); + + app.detach_autosave_copy(); + + assert_eq!(app.session.path, Some(project_path)); + } + app.session.path = Some(copy.display().to_string()); - assert_eq!(app.autosave_path(&folder), copy); - // A file there that is not a copy is the user's own: autosave leaves it alone - let own = folder.join("hero.tcraft"); - app.session.path = Some(own.display().to_string()); - assert_ne!(app.autosave_path(&folder), own); + app.detach_autosave_copy(); - let dated = folder.join("hero-20240115.tcraft"); - app.session.path = Some(dated.display().to_string()); - assert_ne!(app.autosave_path(&folder), dated); + assert_eq!(app.session.path, None, "Save asks for a file"); + assert!(app.session.modified, "closing asks to save the recovered work"); } #[test] diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 2cba0c23..02eea335 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -52,7 +52,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue }; let name = texture_set.name.clone(); - let resolution = texture_set.resolution; + let (resolution, height) = (texture_set.resolution, texture_set.height()); let mut is_enabled = texture_set.bake.common.is_enabled; let visible = texture_set.visible; let tiles: Vec<_> = texture_set @@ -72,7 +72,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { } // The name takes the room the resolution leaves, so it only shortens when the row is too narrow - let resolution_text = format!("{resolution}x{resolution}"); + let resolution_text = format!("{resolution}x{height}"); let name_width = (ui.available_width() - resolution_menu_width(ui, &resolution_text) - ui.spacing().item_spacing.x).max(0.0); let name_size = egui::vec2(name_width, ui.spacing().interact_size.y); let name_button = ui.allocate_ui_with_layout(name_size, egui::Layout::left_to_right(egui::Align::Center), |ui| { diff --git a/crates/ui-egui/src/brush_pictures.rs b/crates/ui-egui/src/brush_pictures.rs new file mode 100644 index 00000000..a4f09487 --- /dev/null +++ b/crates/ui-egui/src/brush_pictures.rs @@ -0,0 +1,154 @@ +//! Pictures of what the brush settings do: the brush's stamp turned to its Angle, a strip of jittered dabs and the alignment modes + +use egui::{ColorImage, Painter, Pos2, Rect, Shape, Stroke, pos2}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::{Alignment, BrushSettings}; + +use crate::preview_image::stroke_strip; +use crate::theme::Tokens; + +/// The stamp's radius in the Orientation picture, as a share of half its side: room for the dial's ring around it +const STAMP_RADIUS_SHARE: f32 = 0.62; + +/// The dial's ring radius, as a share of half the picture's side +const RING_RADIUS_SHARE: f32 = 0.86; + +/// How far the Angle tick reaches in and out of the ring, in points +const TICK_REACH: f32 = 3.0; + +/// The ring's and the tick's line widths, in points +const RING_WIDTH: f32 = 1.0; +const TICK_WIDTH: f32 = 2.0; + +/// How far a dab may reach from the strip's centre line, as a share of half its height +const STRIP_REACH_SHARE: f32 = 0.85; + +/// The least spacing between the strip's dabs, in stamp diameters, so each dab reads on its own +const STRIP_DAB_SPACING: f32 = 1.4; + +/// The brush's own stamp turned to its Angle, alone in a `size` square: jitter, flow and opacity left out so only the shape and its turn show +pub(crate) fn stamp_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let still = BrushSettings { + jitter_size: 0.0, + jitter_angle: 0.0, + jitter_flow: 0.0, + jitter_position: 0.0, + follow_path: false, + flow: 1.0, + opacity: 1.0, + ..brush.clone() + }; + let center = (size[0] as f32 * 0.5, size[1] as f32 * 0.5); + let radius = center.0.min(center.1) * STAMP_RADIUS_SHARE; + + // A curve that stays put lays exactly one stamp + stroke_strip(&still, image, size, |_| radius, |_| center, |x| column_tint(tints, x)) +} + +/// The brush's alpha as its Parameters shape it, upright: the Alpha section's Parameters picture +pub(crate) fn alpha_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + stamp_image(&BrushSettings { angle: 0.0, ..brush.clone() }, image, size, pixels_per_point, tints) +} + +/// A row of the brush's dabs across a `size` strip, scattered by its four jitters; dabs shrink as Position Jitter grows so the scatter stays inside +pub(crate) fn jitter_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let spaced = BrushSettings { spacing: brush.spacing.max(STRIP_DAB_SPACING), follow_path: false, flow: 1.0, opacity: 1.0, ..brush.clone() }; + let (width, middle) = (size[0] as f32, size[1] as f32 * 0.5); + + // A dab lands up to Position Jitter radii from the line, so its radius and that reach together fill the strip's half height + let radius = middle * STRIP_REACH_SHARE / (1.0 + brush.jitter_position.max(0.0)); + let curve = |t: f32| (radius + t * (width - 2.0 * radius), middle); + stroke_strip(&spaced, image, size, |_| radius, curve, |x| column_tint(tints, x)) +} + +fn column_tint(tints: &[[u8; 3]], x: usize) -> [u8; 3] { + tints.get(x).copied().unwrap_or([u8::MAX; 3]) +} + +/// The dial around the Orientation picture's stamp: a ring and an accent tick at `degrees` (counter-clockwise from the right, as the stamp turns) +pub(crate) fn dial_ring(painter: &Painter, rect: Rect, degrees: f32, tokens: &Tokens) { + let center = rect.center(); + let ring = rect.width().min(rect.height()) * 0.5 * RING_RADIUS_SHARE; + painter.circle_stroke(center, ring, Stroke::new(RING_WIDTH, tokens.button_border)); + + let (sin, cos) = degrees.to_radians().sin_cos(); + let at = |reach: f32| pos2(center.x + reach * cos, center.y - reach * sin); + painter.line_segment([at(ring - TICK_REACH), at(ring + TICK_REACH)], Stroke::new(TICK_WIDTH, tokens.accent)); +} + +/// Points along the Alignment picture's surface +const SURFACE_POINTS: usize = 16; + +/// The surface's bulge and the stamp's height above it, as shares of the picture's height +const SURFACE_BULGE_SHARE: f32 = 0.45; +const STAMP_LIFT_SHARE: f32 = 0.12; + +/// Margin inside the Alignment picture, in points +const ALIGNMENT_INSET: f32 = 2.0; + +/// The middle share of the surface the stamp covers +const STAMP_SPAN_SHARE: f32 = 0.6; + +/// How an Alignment lays the stamp on a curved surface: bent along it (Tangent | Wrap) or flat towards the view (Camera) +pub(crate) fn alignment_picture(painter: &Painter, rect: Rect, alignment: Alignment, tokens: &Tokens) { + let rect = rect.shrink(ALIGNMENT_INSET); + let bulge = rect.height() * SURFACE_BULGE_SHARE; + let surface_y = |across: f32| rect.bottom() - bulge * (1.0 - across * across); + let point = |across: f32, lift: f32| pos2(rect.center().x + across * rect.width() * 0.5, surface_y(across) - lift); + let line = |from: f32, to: f32, lift: f32| -> Vec { + (0..=SURFACE_POINTS).map(|step| point(from + (to - from) * step as f32 / SURFACE_POINTS as f32, lift)).collect() + }; + painter.add(Shape::line(line(-1.0, 1.0, 0.0), Stroke::new(RING_WIDTH, tokens.text_dim))); + + let lift = rect.height() * STAMP_LIFT_SHARE; + let stamp = match alignment { + Alignment::Tangent => line(-STAMP_SPAN_SHARE, STAMP_SPAN_SHARE, lift), + Alignment::Camera => { + let top = surface_y(0.0) - lift; + vec![pos2(point(-STAMP_SPAN_SHARE, 0.0).x, top), pos2(point(STAMP_SPAN_SHARE, 0.0).x, top)] + } + }; + painter.add(Shape::line(stamp, Stroke::new(TICK_WIDTH, tokens.accent))); +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::paint::BrushAlpha; + + use super::*; + + const STAMP_SIZE: [usize; 2] = [48, 48]; + const STRIP_SIZE: [usize; 2] = [240, 40]; + + fn white(width: usize) -> Vec<[u8; 3]> { + vec![[u8::MAX; 3]; width] + } + + #[test] + fn the_stamp_turns_with_angle() { + let upright = BrushSettings { alpha: BrushAlpha::Streaks, angle: 0.0, ..BrushSettings::default() }; + let turned = BrushSettings { angle: 45.0, ..upright.clone() }; + + let picture = |brush: &BrushSettings| stamp_image(brush, None, STAMP_SIZE, 1.0, &white(STAMP_SIZE[0])).pixels; + + assert!(picture(&upright).iter().any(|pixel| pixel.a() > 0), "the stamp shows"); + assert_ne!(picture(&upright), picture(&turned)); + } + + #[test] + fn each_jitter_changes_the_strip() { + let steady = BrushSettings { hardness: 1.0, ..BrushSettings::default() }; + let strip = |brush: &BrushSettings| jitter_image(brush, None, STRIP_SIZE, 1.0, &white(STRIP_SIZE[0])).pixels; + let jittered = [ + BrushSettings { jitter_size: 0.8, ..steady.clone() }, + BrushSettings { jitter_flow: 0.8, ..steady.clone() }, + BrushSettings { jitter_angle: 0.8, alpha: BrushAlpha::Streaks, ..steady.clone() }, + BrushSettings { jitter_position: 1.0, ..steady.clone() }, + ]; + + for brush in &jittered { + let unjittered = BrushSettings { jitter_size: 0.0, jitter_flow: 0.0, jitter_angle: 0.0, jitter_position: 0.0, ..brush.clone() }; + assert_ne!(strip(brush), strip(&unjittered), "{brush:?}"); + } + } +} diff --git a/crates/ui-egui/src/brush_sheet.rs b/crates/ui-egui/src/brush_sheet.rs new file mode 100644 index 00000000..cf4a7022 --- /dev/null +++ b/crates/ui-egui/src/brush_sheet.rs @@ -0,0 +1,265 @@ +//! The Brush section of a paint tool's Properties: the Size, Opacity, Orientation, Jitter and Projection bands, grouped and named as the reference groups them + +use std::ops::RangeInclusive; +use std::sync::Arc; + +use egui::{Painter, Rect, Response, Sense, Stroke, StrokeKind, Ui, vec2}; +use serde_json::json; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::{Alignment, BrushSettings}; + +use crate::TextureCraftApp; +use crate::brush_pictures::{alignment_picture, dial_ring, jitter_image, stamp_image}; +use crate::brush_stroke_preview::BrushStrokePreview; +use crate::fill_pictures::backface_picture; +use crate::i18n::tr; +use crate::property_sheet::{PropertySheet, RowLead, StackSlider}; +use crate::theme::{Tokens, caption}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; + +/// Height of the Jitter band's strip of dabs, in points +const JITTER_STRIP_HEIGHT: f32 = 40.0; + +/// Corner radius of the Jitter strip's frame +const JITTER_STRIP_ROUNDING: f32 = 2.0; + +/// Width of the Jitter strip's frame, in points; the dabs are drawn inside it +const JITTER_STRIP_OUTLINE_WIDTH: f32 = 1.0; + +/// What Angle and each Angle fade may be, in degrees +const ANGLE_RANGE: RangeInclusive = -180.0..=180.0; +const ANGLE_FADE_RANGE: RangeInclusive = 0.0..=90.0; + +/// Size's slider, in percent of the largest brush +const SIZE_PERCENT_RANGE: RangeInclusive = 0.05..=100.0; + +/// Spacing's slider, in percent of the stamp's width +const SPACING_PERCENT_RANGE: RangeInclusive = 1.0..=1000.0; + +/// Position Jitter's slider, in percent of the stamp's radius +const POSITION_JITTER_PERCENT_RANGE: RangeInclusive = 0.0..=400.0; + +const PERCENT_RANGE: RangeInclusive = 0.0..=100.0; + +/// The ranges of Stamp depth, Gravity, particles per stamp, and a particle's lifetime in steps +const STAMP_DEPTH_RANGE: RangeInclusive = 0.05..=4.0; +const GRAVITY_RANGE: RangeInclusive = 0.0..=2.0; +const PARTICLE_COUNT_RANGE: RangeInclusive = 1.0..=16.0; +const PARTICLE_LIFETIME_RANGE: RangeInclusive = 1.0..=128.0; + +/// Width of the brush presets list +const PRESETS_WIDTH: f32 = 230.0; + +/// Height the presets list scrolls past +const PRESETS_MAX_HEIGHT: f32 = 380.0; + +/// The Brush section under its caption, whose ≡ button `menu` opens the brush presets +pub(crate) fn brush_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, menu: Option) { + if let Some(menu) = menu { + brush_presets_popover(app, sheet.ui, menu); + } + + let tokens = Tokens::get(sheet.ui.ctx()); + let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned(); + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); + + // Each band's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.size_pressure, settings.min_size, settings.spacing); + let band = sheet.band(tr("Size"), true, Some(size_fields(brush) != size_fields(&defaults)), None); + if band.reset { + (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = size_fields(&defaults); + } + if band.open { + // Every row keeps the pen button's slot, so the three values line up + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if sheet.pen_slider(tr("Size"), &mut size_percent, SIZE_PERCENT_RANGE, 1, Some(&mut brush.size_pressure)).0.is_some() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); + } + let pressure = brush.size_pressure; + sheet.greyed(pressure, Some(tr("Applies only while pen pressure on Size is on")), |sheet| { + pen_percent_slider(sheet, tr("Minimum Size (%)"), &mut brush.min_size, PERCENT_RANGE); + }); + pen_percent_slider(sheet, tr("Spacing"), &mut brush.spacing, SPACING_PERCENT_RANGE); + } + + let opacity_fields = |settings: &BrushSettings| (settings.flow, settings.opacity); + let band = sheet.band(tr("Opacity"), true, Some(opacity_fields(brush) != opacity_fields(&defaults)), None); + if band.reset { + (brush.flow, brush.opacity) = opacity_fields(&defaults); + } + if band.open { + percent_slider(sheet, tr("Flow"), &mut brush.flow, PERCENT_RANGE); + percent_slider(sheet, tr("Stroke opacity"), &mut brush.opacity, PERCENT_RANGE); + } + + let orientation_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + let band = sheet.band(tr("Orientation"), true, Some(orientation_fields(brush) != orientation_fields(&defaults)), None); + if band.reset { + (brush.angle, brush.follow_path) = orientation_fields(&defaults); + } + if band.open { + let shown = brush.clone(); + let ctx = sheet.ui.ctx().clone(); + let tint = tokens.text.to_array(); + let dial = |painter: &Painter, rect: Rect| { + BrushStrokePreview::paint_picture( + &ctx, + painter, + rect, + "brush_stamp_picture", + (&shown, image.as_ref()), + |_| [tint[0], tint[1], tint[2]], + stamp_image, + ); + dial_ring(painter, rect, shown.angle, &tokens); + }; + let angle = StackSlider { label: tr("Angle"), value: &mut brush.angle, range: ANGLE_RANGE, typed: ANGLE_RANGE, decimals: 0, suffix: "°", dial: false }; + sheet.picture_sliders(&dial, &mut [angle]); + sheet.toggle(tr("Follow Path"), &mut brush.follow_path); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_flow, settings.jitter_angle, settings.jitter_position); + let band = sheet.band(tr("Jitter"), true, Some(jitter_fields(brush) != jitter_fields(&defaults)), None); + if band.reset { + (brush.jitter_size, brush.jitter_flow, brush.jitter_angle, brush.jitter_position) = jitter_fields(&defaults); + } + if band.open { + jitter_strip(sheet, brush, image.as_ref(), &tokens); + percent_slider(sheet, tr("Size Jitter"), &mut brush.jitter_size, PERCENT_RANGE); + percent_slider(sheet, tr("Flow Jitter"), &mut brush.jitter_flow, PERCENT_RANGE); + percent_slider(sheet, tr("Angle Jitter"), &mut brush.jitter_angle, PERCENT_RANGE); + percent_slider(sheet, tr("Position Jitter"), &mut brush.jitter_position, POSITION_JITTER_PERCENT_RANGE); + } + + let projection_fields = + |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.screen_space, settings.depth); + let band = sheet.band(tr("Projection"), true, Some(projection_fields(brush) != projection_fields(&defaults)), None); + if band.reset { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.screen_space, brush.depth) = projection_fields(&defaults); + } + if band.open { + projection_rows(sheet, brush, &tokens); + } + + let particles = &mut brush.particles; + let band = sheet.band(tr("Particles"), false, Some(*particles != defaults.particles), None); + if band.reset { + *particles = defaults.particles; + } + if band.open { + sheet.info(tr("Paint slides down the surface")); + sheet.toggle(tr("Particle brush"), &mut particles.enabled); + whole_slider(sheet, tr("Count per stamp"), &mut particles.count, PARTICLE_COUNT_RANGE); + whole_slider(sheet, tr("Lifetime (steps)"), &mut particles.lifetime, PARTICLE_LIFETIME_RANGE); + sheet.slider(tr("Gravity"), &mut particles.gravity, GRAVITY_RANGE, 2); + } + + *brush = brush.sanitized(); +} + +/// Alignment, Backface culling with its Angle fade under it, Size Space and Stamp depth +fn projection_rows(sheet: &mut PropertySheet<'_>, brush: &mut BrushSettings, tokens: &Tokens) { + let alignment_name = |alignment: Alignment| { + match alignment { + Alignment::Tangent => tr("Tangent | Wrap"), + Alignment::Camera => tr("Camera"), + } + .to_owned() + }; + let picture = |painter: &Painter, rect: Rect, alignment: Alignment| alignment_picture(painter, rect, alignment, tokens); + let (picked, _) = sheet.dropdown(tr("Alignment"), brush.alignment, &[Alignment::Tangent, Alignment::Camera], alignment_name, Some(&picture)); + if let Some(alignment) = picked { + brush.alignment = alignment; + } + + let culled = brush.backface_culling; + let picture = |painter: &Painter, rect: Rect| backface_picture(painter, rect, culled, tokens); + sheet.picture_toggle(&picture, tr("Backface culling"), &mut brush.backface_culling); + + // Faces only fade towards their edge while backfaces are culled + sheet.greyed(brush.backface_culling, Some(tr("Fades only while Backface culling is on")), |sheet| { + sheet.angle_led(RowLead::Child(tr("Angle fade from")), &mut brush.angle_fade.0, ANGLE_FADE_RANGE); + sheet.angle_led(RowLead::Child(tr("Angle fade to")), &mut brush.angle_fade.1, ANGLE_FADE_RANGE); + }); + + if let Some(space) = sheet.switch(tr("Size Space"), &[tr("Object"), tr("Viewport")], usize::from(brush.screen_space)) { + brush.screen_space = space == 1; + } + sheet.slider(tr("Stamp depth"), &mut brush.depth, STAMP_DEPTH_RANGE, 2); +} + +/// The brush's dabs scattered by its jitters, across the panel above the Jitter sliders +fn jitter_strip(sheet: &mut PropertySheet<'_>, brush: &BrushSettings, image: Option<&Arc>, tokens: &Tokens) { + let tint = tokens.text.to_array(); + sheet.embed(|ui: &mut Ui| { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), JITTER_STRIP_HEIGHT), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Jitter preview"))); + + let painter = ui.painter(); + painter.rect_filled(rect, JITTER_STRIP_ROUNDING, tokens.field); + painter.rect_stroke(rect, JITTER_STRIP_ROUNDING, Stroke::new(JITTER_STRIP_OUTLINE_WIDTH, tokens.field_border), StrokeKind::Inside); + BrushStrokePreview::paint_picture( + ui.ctx(), + painter, + rect.shrink(JITTER_STRIP_OUTLINE_WIDTH), + "brush_jitter_picture", + (brush, image), + |_| [tint[0], tint[1], tint[2]], + jitter_image, + ); + }); +} + +/// A 0..1 setting shown and typed in whole percent +fn percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32, percent: RangeInclusive) { + let mut shown = *fraction * 100.0; + if sheet.slider(label, &mut shown, percent, 0).is_some() { + *fraction = shown / 100.0; + } +} + +/// [`percent_slider`] in a band whose rows keep the pen button's slot +fn pen_percent_slider(sheet: &mut PropertySheet<'_>, label: &str, fraction: &mut f32, percent: RangeInclusive) { + let mut shown = *fraction * 100.0; + if sheet.pen_slider(label, &mut shown, percent, 0, None).0.is_some() { + *fraction = shown / 100.0; + } +} + +/// A count on a slider of whole numbers +fn whole_slider(sheet: &mut PropertySheet<'_>, label: &str, count: &mut u32, range: RangeInclusive) { + let mut shown = *count as f32; + if sheet.slider(label, &mut shown, range, 0).is_some() { + *count = shown.round() as u32; + } +} + +/// The brush presets, listed under the Brush caption's ≡ button +fn brush_presets_popover(app: &mut TextureCraftApp, ui: &Ui, menu: Response) { + menu.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Brush presets"))); + let menu = menu.on_hover_text(tr("Brush presets")); + let popup_id = ui.make_persistent_id("brush_presets_popup"); + if menu.clicked() { + egui::Popup::toggle_id(ui.ctx(), popup_id); + } + + egui::Popup::from_response(&menu).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.set_min_width(PRESETS_WIDTH); + egui::ScrollArea::vertical().max_height(PRESETS_MAX_HEIGHT).show(ui, |ui| { + let mut category = ""; + for preset in texturecraft_engine::paint::presets::PRESETS.iter() { + if preset.category != category { + category = preset.category; + ui.label(caption(category)); + } + if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() { + app.run("brush.preset.apply", json!({"preset": preset.id})); + } + } + + ui.separator(); + crate::shelf::user_brushes(app, ui, ""); + }); + }); +} diff --git a/crates/ui-egui/src/brush_stroke_preview.rs b/crates/ui-egui/src/brush_stroke_preview.rs new file mode 100644 index 00000000..88af53c3 --- /dev/null +++ b/crates/ui-egui/src/brush_stroke_preview.rs @@ -0,0 +1,237 @@ +//! The live stroke at the top of the paint tool's properties: the current brush's own stamps along a hand-drawn gesture + +use std::sync::{Arc, Weak}; + +use egui::{Color32, ColorImage, Context, Id, Painter, Rect, TextureHandle, TextureOptions, pos2, vec2}; +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::paint::BrushSettings; + +use crate::preview_image::stroke_strip; + +/// The stroke's margin from the edges of its half of the preview, in points +const STROKE_MARGIN: f32 = 6.0; + +/// The gesture the stroke follows, as fractions of its box: a small hook, a dip, a tall arch and a long tail down +const STROKE_PATH: [[f32; 2]; 5] = [[0.0, 0.6], [0.18, 0.3], [0.4, 0.8], [0.65, 0.0], [1.0, 1.0]]; + +/// The gesture's widest width for its height, so a wide preview centres it instead of flattening its arch +const STROKE_ASPECT: f32 = 1.4; + +/// The pen pressure the stroke is drawn with, from its start to its end: it presses harder as it goes, as a hand does +const STROKE_PRESSURE: std::ops::RangeInclusive = 0.35..=1.0; + +/// The stroke's width: [`STROKE_WIDTH_PER_ROOT_SIZE`] points times the root of the brush size, kept inside [`STROKE_WIDTH`]; the root lets small brushes read and big ones still grow +const STROKE_WIDTH_PER_ROOT_SIZE: f32 = 70.0; +const STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=32.0; + +/// The rendered stroke and what it was rendered from, kept in egui's memory behind an `Arc` so a frame with the same brush reuses it without copying it +pub(crate) struct BrushStrokePreview { + brush: BrushSettings, + // A hidden picture keeps its texture without owning the decoded alpha + image: Option>, + tints: Vec<[u8; 3]>, + size: [usize; 2], + pixels_per_point: f32, + texture: TextureHandle, +} + +impl BrushStrokePreview { + /// Paint the brush's stroke across `rect`, each pixel column coloured by `tint` of its position 0..1; it renders again only on a new brush, alpha image, colour or size + pub(crate) fn paint(ctx: &Context, painter: &Painter, rect: Rect, brush: &BrushSettings, image: Option<&Arc>, tint: impl Fn(f32) -> [u8; 3]) { + Self::paint_picture(ctx, painter, rect, "brush_stroke_preview", (brush, image), tint, stroke_image); + } + + /// Paint `render`'s picture of the brush across `rect`, kept under `key` until the brush, alpha image, colour or size change + pub(crate) fn paint_picture( + ctx: &Context, + painter: &Painter, + rect: Rect, + key: &'static str, + (brush, image): (&BrushSettings, Option<&Arc>), + tint: impl Fn(f32) -> [u8; 3], + render: impl FnOnce(&BrushSettings, Option<&ImageRes>, [usize; 2], f32, &[[u8; 3]]) -> ColorImage, + ) { + let pixels_per_point = ctx.pixels_per_point(); + let size = [(rect.width() * pixels_per_point).round().max(1.0) as usize, (rect.height() * pixels_per_point).round().max(1.0) as usize]; + let column_tint = |x: usize| tint((x as f32 + 0.5) / size[0] as f32); + + // The docked panel and the right-click popup draw the same picture at their own widths: one cache each + let id = Id::unique(key).with(painter.layer_id()); + let cached = ctx.data(|data| data.get_temp::>(id)).filter(|preview| { + preview.brush == *brush + && preview.size == size + && preview.pixels_per_point == pixels_per_point + && preview.image.as_ref().map(Weak::as_ptr) == image.map(Arc::as_ptr) + && preview.tints.iter().enumerate().all(|(x, shown)| *shown == column_tint(x)) + }); + + let texture = match cached { + Some(preview) => preview.texture.id(), + None => { + let tints: Vec<[u8; 3]> = (0..size[0]).map(column_tint).collect(); + let picture = render(brush, image.map(|image| &**image), size, pixels_per_point, &tints); + let texture = ctx.load_texture(key, picture, TextureOptions::LINEAR); + let texture_id = texture.id(); + let preview = BrushStrokePreview { brush: brush.clone(), image: image.map(Arc::downgrade), tints, size, pixels_per_point, texture }; + ctx.data_mut(|data| data.insert_temp(id, Arc::new(preview))); + texture_id + } + }; + painter.image(texture, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } +} + +/// The brush's stroke as a `size` image at `pixels_per_point`: a hand-drawn gesture as wide as the brush size, narrowed towards Minimum Size at its light start; column `x` in `tints[x]` +pub(crate) fn stroke_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage { + let (width, height) = (size[0] as f32 / pixels_per_point, size[1] as f32 / pixels_per_point); + let stroke_width = (brush.size.max(0.0).sqrt() * STROKE_WIDTH_PER_ROOT_SIZE).clamp(*STROKE_WIDTH.start(), *STROKE_WIDTH.end()); + let inset = STROKE_MARGIN + stroke_width * 0.5; + let span_y = (height - 2.0 * inset).max(0.0); + let span = vec2((width - 2.0 * inset).clamp(0.0, span_y * STROKE_ASPECT), span_y); + let left = (width - span.x) * 0.5; + let curve = |t: f32| { + let [x, y] = path_point(t); + ((left + x * span.x) * pixels_per_point, (inset + y * span.y) * pixels_per_point) + }; + let radius = |t: f32| { + let pressure = STROKE_PRESSURE.start() + (STROKE_PRESSURE.end() - STROKE_PRESSURE.start()) * t * (2.0 - t); + stroke_width * 0.5 * pixels_per_point * brush.uv_stamp_radius(pressure) / brush.uv_stamp_radius(1.0).max(f32::MIN_POSITIVE) + }; + let tint = |x: usize| tints.get(x).copied().unwrap_or([u8::MAX; 3]); + stroke_strip(brush, image, size, radius, curve, tint) +} + +/// The point at `t` (0..1) along [`STROKE_PATH`], a Catmull-Rom spline through its points +fn path_point(t: f32) -> [f32; 2] { + let last = STROKE_PATH.len() - 1; + let at = t.clamp(0.0, 1.0) * last as f32; + let segment = (at as usize).min(last - 1); + let u = at - segment as f32; + let point = |index: isize| STROKE_PATH[index.clamp(0, last as isize) as usize]; + let [p0, p1, p2, p3] = [-1, 0, 1, 2].map(|offset| point(segment as isize + offset)); + let blend = |axis: usize| { + let (a, b, c, d) = (p0[axis], p1[axis], p2[axis], p3[axis]); + 0.5 * (2.0 * b + (c - a) * u + (2.0 * a - 5.0 * b + 4.0 * c - d) * u * u + (3.0 * b - a - 3.0 * c + d) * u * u * u) + }; + [blend(0), blend(1)] +} + +#[cfg(test)] +mod tests { + use super::*; + + const SIZE: [usize; 2] = [160, 88]; + + fn paint(brush: &BrushSettings) -> ColorImage { + stroke_image(brush, None, SIZE, 1.0, &[[u8::MAX; 3]; SIZE[0]]) + } + + fn painted_pixels(picture: &ColorImage) -> usize { + picture.pixels.iter().filter(|pixel| pixel.a() > 0).count() + } + + fn total_paint(picture: &ColorImage) -> u64 { + picture.pixels.iter().map(|pixel| u64::from(pixel.a())).sum() + } + + #[test] + fn wider_spacing_leaves_gaps_between_dabs() { + let dense = BrushSettings { hardness: 1.0, spacing: 0.1, ..BrushSettings::default() }; + let sparse = BrushSettings { spacing: 3.0, ..dense.clone() }; + + assert!(painted_pixels(&paint(&sparse)) < painted_pixels(&paint(&dense))); + } + + #[test] + fn a_softer_brush_lays_down_less_paint() { + let hard = BrushSettings { hardness: 1.0, ..BrushSettings::default() }; + let soft = BrushSettings { hardness: 0.0, ..hard.clone() }; + + assert!(total_paint(&paint(&soft)) < total_paint(&paint(&hard))); + } + + #[test] + fn a_bigger_brush_paints_a_wider_stroke() { + let small = BrushSettings { size: 0.02, ..BrushSettings::default() }; + let big = BrushSettings { size: 0.1, ..small.clone() }; + + assert!(painted_pixels(&paint(&small)) < painted_pixels(&paint(&big))); + } + + /// Paint in the first and last quarter of the columns the stroke covers + fn paint_at_ends(picture: &ColorImage) -> (u64, u64) { + let [width, _] = picture.size; + let painted = |index: &usize| picture.pixels.iter().skip(*index).step_by(width).any(|pixel| pixel.a() > 0); + let (first, last) = ((0..width).find(painted).unwrap_or(0), (0..width).rfind(painted).unwrap_or(width)); + let quarter = (last - first) / 4; + let paint_in = |columns: std::ops::Range| { + picture.pixels.iter().enumerate().filter(|(index, _)| columns.contains(&(index % width))).map(|(_, pixel)| u64::from(pixel.a())).sum() + }; + (paint_in(first..first + quarter), paint_in(last - quarter..last + 1)) + } + + #[test] + fn the_stroke_starts_light_and_a_lower_minimum_size_thins_its_start() { + let brush = BrushSettings { hardness: 1.0, min_size: 0.05, ..BrushSettings::default() }; + let full = BrushSettings { min_size: 1.0, ..brush.clone() }; + let (start, end) = paint_at_ends(&paint(&brush)); + let (full_start, _) = paint_at_ends(&paint(&full)); + + assert!(start < end, "the stroke widens as the pen presses harder"); + assert!(start < full_start, "Minimum Size bounds how thin the light start gets"); + } + + #[test] + fn without_size_pressure_the_stroke_keeps_its_width() { + let brush = BrushSettings { hardness: 1.0, min_size: 0.05, size_pressure: false, ..BrushSettings::default() }; + let full = BrushSettings { min_size: 1.0, size_pressure: true, ..brush.clone() }; + + assert!(paint(&brush) == paint(&full), "a mouse brush draws no taper"); + } + + #[test] + fn changing_display_scale_redraws_a_stroke_at_the_same_pixel_size() { + let ctx = Context::default(); + let brush = BrushSettings::default(); + let draw = |scale: f32| { + let mut input = egui::RawInput::default(); + input.viewports.entry(egui::ViewportId::ROOT).or_default().native_pixels_per_point = Some(scale); + let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(SIZE[0] as f32, SIZE[1] as f32) / scale); + let mut frame = ctx.run_ui(input, |ui| BrushStrokePreview::paint(&ctx, ui.painter(), rect, &brush, None, |_| [255; 3])); + let upload = frame.textures_delta.set.values().flatten().find(|delta| delta.image.size() == SIZE).map(|delta| delta.image.clone()); + frame.textures_delta.clear(); + upload + }; + + let first = draw(1.0).expect("first picture"); + let scaled = draw(2.0).expect("redrawn picture"); + let reused = draw(2.0); + + let (egui::ImageData::Color(first), egui::ImageData::Color(scaled)) = (first, scaled); + assert_ne!(first.pixels, scaled.pixels, "stroke width and margins follow the display scale"); + assert!(reused.is_none(), "an unchanged display reuses the picture"); + } + + #[test] + fn cached_pictures_release_each_decoded_alpha_when_its_owner_drops_it() { + const ALPHA_SIDE_PX: u32 = 1024; + let ctx = Context::default(); + let brush = BrushSettings::default(); + let rect = Rect::from_min_size(egui::Pos2::ZERO, vec2(48.0, 32.0)); + let mut former_alphas = Vec::new(); + + for (layer_name, gray) in [("docked", 0.25), ("popup", 0.75)] { + let pixels = vec![[gray, gray, gray, 1.0]; (ALPHA_SIDE_PX * ALPHA_SIDE_PX) as usize]; + let alpha = Arc::new(ImageRes::new(ALPHA_SIDE_PX, ALPHA_SIDE_PX, pixels, false)); + let layer = egui::LayerId::new(egui::Order::Middle, Id::unique(layer_name)); + let painter = ctx.layer_painter(layer); + + BrushStrokePreview::paint(&ctx, &painter, rect, &brush, Some(&alpha), |_| [255; 3]); + former_alphas.push(Arc::downgrade(&alpha)); + } + + let retained_bytes: usize = former_alphas.iter().filter_map(|alpha| alpha.upgrade()).map(|alpha| std::mem::size_of_val(alpha.rgba.as_slice())).sum(); + eprintln!("cached pictures retain {retained_bytes} decoded alpha bytes"); + assert_eq!(retained_bytes, 0, "pictures must not own decoded alpha pixels"); + } +} diff --git a/crates/ui-egui/src/channel_manager.rs b/crates/ui-egui/src/channel_manager.rs new file mode 100644 index 00000000..1e47ca88 --- /dev/null +++ b/crates/ui-egui/src/channel_manager.rs @@ -0,0 +1,297 @@ +//! The dialog that adds and removes a texture set's channels: every channel by group, ticked when the set has it + +mod footer_layout; + +use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; +use serde_json::json; +use texturecraft_engine::core::{Channel, ChannelGroup, TextureSet}; + +use self::footer_layout::FooterLayout; +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::property_sheet::{CHECK_SIZE, PropertySheet, paint_check, paint_keyboard_focus}; +use crate::theme::{Tokens, semibold}; + +/// The columns, left to right: which groups each lists, and how wide it is; the User group runs on into the last column +const COLUMNS: [(&[ChannelGroup], f32); 4] = [ + (&[ChannelGroup::Base, ChannelGroup::Specular, ChannelGroup::Transmission, ChannelGroup::Subsurface], GROUP_COLUMN_WIDTH), + (&[ChannelGroup::Coat, ChannelGroup::Sheen, ChannelGroup::Emission, ChannelGroup::ThinFilm], GROUP_COLUMN_WIDTH), + (&[ChannelGroup::Geometry, ChannelGroup::Miscellaneous], GROUP_COLUMN_WIDTH), + (&[ChannelGroup::User], USER_COLUMN_WIDTH), +]; +const GROUP_COLUMN_WIDTH: f32 = 230.0; +const USER_COLUMN_WIDTH: f32 = 140.0; +const USER_ROWS_PER_COLUMN: usize = 16; + +/// Width of the dialog, in points +const DIALOG_WIDTH: f32 = GROUP_COLUMN_WIDTH * 3.0 + USER_COLUMN_WIDTH * 2.0; + +/// The channel columns scroll past this share of the window's height +const MAX_HEIGHT_SHARE: f32 = 0.75; + +/// The title bar: its height, the title's left edge and size +const TITLE_BAR_HEIGHT: f32 = 30.0; +const TITLE_TEXT_LEFT: f32 = 12.0; +const TEXT_SIZE: f32 = 12.0; +const SMALL_TEXT_SIZE: f32 = 11.0; + +/// Air under the title bar, above the footer, around the dialog's edge and between the footer's parts +const BODY_AIR: f32 = 8.0; +const FOOTER_AIR: f32 = 10.0; +const EDGE_AIR: f32 = 12.0; +const CHECK_TO_LABEL: f32 = 8.0; +const LEGEND_GAP: f32 = 24.0; +const LEGEND_GLYPH_TO_TEXT: f32 = 4.0; + +/// Cancel and Apply: their size, the air between them, the dialog's corners +const BUTTON_SIZE: egui::Vec2 = vec2(88.0, 24.0); +const BUTTON_GAP: f32 = 8.0; +const DIALOG_RADIUS: u8 = 4; + +/// An open dialog: the set it edits, each channel's tick (indexed like [`Channel::ALL`]), and whether Apply goes to every set +#[derive(Clone, Debug)] +pub(crate) struct ChannelManager { + ts: usize, + ticked: Vec, + all_sets: bool, + mesh_id: u64, + opener: egui::Id, +} + +impl ChannelManager { + fn id() -> egui::Id { + egui::Id::unique("channel_manager") + } + + /// Open the dialog on texture set `ts`, ticked as the set is + pub(crate) fn open(app: &TextureCraftApp, opener: &egui::Response, ts: usize) { + let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; + let manager = ChannelManager::new(set, ts, app.session.mesh_id, opener.id); + opener.ctx.data_mut(|data| data.insert_temp(Self::id(), Some(manager))); + } + + fn new(set: &TextureSet, ts: usize, mesh_id: u64, opener: egui::Id) -> Self { + let ticked = Channel::ALL.iter().map(|c| set.has_channel(*c)).collect(); + ChannelManager { ts, ticked, all_sets: false, mesh_id, opener } + } + + /// The open dialog, if any; Apply runs one `textureSet.channels` + pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(mut manager) = ctx.data(|data| data.get_temp::>(Self::id())).flatten() else { + // The opener can receive focus again once the modal layer has left egui's focus order + if ctx.memory(|memory| memory.top_modal_layer().is_none()) + && let Some(opener) = ctx.data_mut(|data| data.remove_temp::>(Self::id().with("opener")).flatten()) + { + ctx.memory_mut(|memory| memory.request_focus(opener)); + } + return; + }; + + if manager.mesh_id != app.session.mesh_id || manager.ts >= app.session.set_count() { + ctx.data_mut(|data| data.remove::>(Self::id())); + return; + } + + let opening = ctx.memory(|memory| memory.top_modal_layer().is_none()); + let tokens = Tokens::get(ctx); + let frame = egui::Frame::new() + .fill(tokens.panel) + .stroke(Stroke::new(1.0, tokens.button_border)) + .corner_radius(CornerRadius::same(DIALOG_RADIUS)) + .inner_margin(0); + let modal = egui::Modal::new(Self::id().with("modal")).frame(frame).show(ctx, |ui| { + let width = (ctx.content_rect().width() - 2.0 * EDGE_AIR).clamp(1.0, DIALOG_WIDTH); + ui.set_width(width); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + let footer = FooterLayout::new(ui, &tokens); + let closed = title_bar(ui, &tokens, opening); + ui.add_space(BODY_AIR); + + // Reserve room for the title and footer so Apply stays visible + let window_height = ctx.content_rect().height(); + let room = window_height - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height() - EDGE_AIR; + let max_height = (window_height * MAX_HEIGHT_SHARE).min(room).max(0.0); + egui::ScrollArea::both().auto_shrink([false, true]).min_scrolled_height(0.0).max_height(max_height).show(ui, |ui| manager.columns(ui)); + ui.add_space(FOOTER_AIR); + let (apply, cancel) = manager.footer(ui, &tokens, footer); + ui.add_space(EDGE_AIR); + (apply, cancel || closed) + }); + + let (apply, cancel) = modal.inner; + if apply && let Some(set) = app.session.doc.project.texture_sets.get(manager.ts) { + let (add, remove) = manager.edits(set); + if !add.is_empty() || !remove.is_empty() { + let ids = |list: Vec| list.into_iter().map(Channel::id).collect::>(); + app.run("textureSet.channels", json!({ "ts": manager.ts, "add": ids(add), "remove": ids(remove), "allSets": manager.all_sets })); + } + } + if apply || cancel || modal.should_close() { + ctx.data_mut(|data| { + data.remove::>(Self::id()); + data.insert_temp(Self::id().with("opener"), Some(manager.opener)); + }); + ctx.request_repaint(); + } else { + ctx.data_mut(|data| data.insert_temp(Self::id(), Some(manager))); + } + } + + /// The channels to add and to remove: against `set` alone, or for every set the whole ticked list + fn edits(&self, set: &TextureSet) -> (Vec, Vec) { + let ticked = |c: &Channel| self.ticked.get(c.index()).copied().unwrap_or(false); + let (on, off): (Vec, Vec) = Channel::ALL.into_iter().partition(ticked); + if self.all_sets { + // Other sets may differ from this one: send the whole list so every set ends up the same + return (on, off.into_iter().filter(|c| *c != Channel::BaseColor).collect()); + } + + (on.into_iter().filter(|c| !set.has_channel(*c)).collect(), off.into_iter().filter(|c| set.has_channel(*c)).collect()) + } + + /// The groups side by side, a check per channel; a dim ⊘ marks the material channels our shader doesn't read + fn columns(&mut self, ui: &mut Ui) { + let mut user_rows_top = None; + ui.horizontal_top(|ui| { + for (column, (groups, width)) in COLUMNS.iter().enumerate() { + ui.vertical(|ui| { + ui.set_width(*width); + PropertySheet::show(ui, ("channel_manager", column), |sheet| { + for group in *groups { + sheet.section(tr(group.label()), false); + let channels = group.channels(); + let shown = if *group == ChannelGroup::User { &channels[..USER_ROWS_PER_COLUMN] } else { channels }; + for (row, channel) in shown.iter().enumerate() { + let response = self.check(sheet, *channel); + if *group == ChannelGroup::User && row == 0 { + user_rows_top = Some(response.rect.top()); + } + } + } + }); + }); + } + + // The rest of the User group, its rows level with the first half's + ui.vertical(|ui| { + ui.set_width(USER_COLUMN_WIDTH); + if let Some(top) = user_rows_top { + ui.add_space((top - ui.cursor().top()).max(0.0)); + } + PropertySheet::show(ui, ("channel_manager", COLUMNS.len()), |sheet| { + for channel in &ChannelGroup::User.channels()[USER_ROWS_PER_COLUMN..] { + self.check(sheet, *channel); + } + }); + }); + }); + } + + fn check(&mut self, sheet: &mut PropertySheet<'_>, channel: Channel) -> egui::Response { + let Some(on) = self.ticked.get(channel.index()).copied() else { + return sheet.ui.allocate_response(egui::Vec2::ZERO, Sense::hover()); + }; + + // User channels are the user's own data for export: reading them is never the shader's job, so they carry no mark + let user = ChannelGroup::User.channels().contains(&channel); + let note = (!channel.is_shaded() && !user).then_some(icon::PROHIBIT); + + // Base color stays: every set has it + let fixed = channel == Channel::BaseColor; + let response = sheet.greyed(!fixed, fixed.then(|| tr("Base color can't be removed")), |sheet| sheet.check_noted(tr(channel.label()), Some(on), note)); + if note.is_some() { + sheet.ui.ctx().accesskit_node_builder(response.id, |node| node.set_description(tr("Not used by the shader"))); + } + if response.clicked() + && let Some(tick) = self.ticked.get_mut(channel.index()) + { + *tick = !on; + } + response + } + + /// "Apply to all Texture Sets", the ⊘ legend, then Cancel and Apply at the right; returns (Apply, Cancel) clicked + fn footer(&mut self, ui: &mut Ui, tokens: &Tokens, layout: FooterLayout) -> (bool, bool) { + let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), layout.height()), Sense::hover()); + ui.painter().hline(row.x_range(), row.top() - FOOTER_AIR / 2.0, Stroke::new(1.0, tokens.separator)); + let (check, hit) = layout.checkbox_rects(row); + let response = ui.interact(hit, ui.scope_id().with("all_sets"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.all_sets, layout.checkbox_label)); + if response.clicked() { + self.all_sets = !self.all_sets; + } + paint_check(ui.painter(), tokens, check, Some(self.all_sets), response.hovered()); + paint_keyboard_focus(ui, &response, tokens); + + let (apply, cancel) = layout.paint_labels(ui, tokens, row, check, hit); + (dialog_button(ui, tokens, apply, tr("Apply")), dialog_button(ui, tokens, cancel, tr("Cancel"))) + } +} + +/// The title and × at the right; returns whether × was clicked +fn title_bar(ui: &mut Ui, tokens: &Tokens, opening: bool) -> bool { + let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), TITLE_BAR_HEIGHT), Sense::hover()); + let top = CornerRadius { nw: DIALOG_RADIUS, ne: DIALOG_RADIUS, sw: 0, se: 0 }; + ui.painter().rect_filled(bar, top, tokens.chrome); + let center_y = bar.center().y; + let text = Rect::from_min_max(pos2(bar.left() + TITLE_TEXT_LEFT, bar.top()), pos2(bar.right() - TITLE_BAR_HEIGHT, bar.bottom())); + let label = egui::Label::new(RichText::new(tr("Add or remove channels")).font(semibold(TEXT_SIZE)).color(tokens.text_strong)).truncate(); + ui.scope_builder(egui::UiBuilder::new().max_rect(text).layout(egui::Layout::left_to_right(egui::Align::Center)), |ui| ui.add(label)); + + let close = Rect::from_center_size(pos2(bar.right() - TITLE_BAR_HEIGHT / 2.0, center_y), vec2(TITLE_BAR_HEIGHT, TITLE_BAR_HEIGHT)); + let response = ui.interact(close, ui.scope_id().with("close"), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tr("Close"))); + if opening { + response.request_focus(); + } + let color = if response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(close.center(), Align2::CENTER_CENTER, icon::X, FontId::proportional(TEXT_SIZE), color); + paint_keyboard_focus(ui, &response, tokens); + response.clicked() +} + +fn dialog_button(ui: &mut Ui, tokens: &Tokens, rect: Rect, text: &str) -> bool { + let response = ui.interact(rect, ui.scope_id().with(text), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, text)); + let fill = if response.hovered() { tokens.row_hover } else { tokens.button }; + ui.painter().rect(rect, CornerRadius::same(DIALOG_RADIUS), fill, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + ui.painter().text(rect.center(), Align2::CENTER_CENTER, text, FontId::proportional(TEXT_SIZE), tokens.text); + paint_keyboard_focus(ui, &response, tokens); + response.clicked() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{Channel, TextureSet}; + + use super::ChannelManager; + + fn set() -> TextureSet { + texturecraft_engine::sample_session(128, 64).map(|s| s.doc.project.texture_sets[0].clone()).unwrap() + } + + #[test] + fn apply_sends_only_what_the_ticks_changed() { + let set = set(); + let mut manager = ChannelManager::new(&set, 0, 0, egui::Id::NULL); + assert_eq!(manager.edits(&set), (vec![], vec![]), "an untouched dialog changes nothing"); + + manager.ticked[Channel::Ior.index()] = true; + manager.ticked[Channel::Height.index()] = false; + assert!(set.has_channel(Channel::Height)); + assert_eq!(manager.edits(&set), (vec![Channel::Ior], vec![Channel::Height])); + } + + #[test] + fn apply_to_all_sets_sends_the_whole_list_but_never_removes_base_color() { + // Another set may lack a channel this one has: only the full list makes every set match + let set = set(); + let mut manager = ChannelManager::new(&set, 0, 0, egui::Id::NULL); + manager.all_sets = true; + let (add, remove) = manager.edits(&set); + assert!(set.channels.iter().all(|(c, _)| add.contains(c))); + assert_eq!(add.len() + remove.len(), Channel::ALL.len(), "every channel is sent one way or the other"); + assert!(!remove.contains(&Channel::BaseColor) && !remove.iter().any(|c| set.has_channel(*c))); + } +} diff --git a/crates/ui-egui/src/channel_manager/footer_layout.rs b/crates/ui-egui/src/channel_manager/footer_layout.rs new file mode 100644 index 00000000..34fa5ba4 --- /dev/null +++ b/crates/ui-egui/src/channel_manager/footer_layout.rs @@ -0,0 +1,97 @@ +use std::sync::Arc; + +use egui::{FontId, Galley, Rect, Sense, Ui, pos2, vec2}; +use egui_phosphor::regular as icon; + +use super::{BUTTON_GAP, BUTTON_SIZE, CHECK_SIZE, CHECK_TO_LABEL, EDGE_AIR, LEGEND_GAP, LEGEND_GLYPH_TO_TEXT, SMALL_TEXT_SIZE, TEXT_SIZE}; +use crate::i18n::tr; +use crate::theme::Tokens; + +/// The measured footer, used for both painting and reserving space below the channel list +pub(super) struct FooterLayout { + pub(super) checkbox_label: &'static str, + checkbox_text: Arc, + legend_label: &'static str, + legend_glyph: Arc, + legend_text: Arc, + first_row_height: f32, + legend_row_height: f32, + buttons_row_height: f32, + button_gap: f32, + button_width: f32, +} + +impl FooterLayout { + pub(super) fn new(ui: &Ui, tokens: &Tokens) -> Self { + let content_width = (ui.available_width() - 2.0 * EDGE_AIR).max(0.0); + let checkbox_label = tr("Apply to all Texture Sets"); + let checkbox_text = + ui.painter().layout(checkbox_label.into(), FontId::proportional(TEXT_SIZE), tokens.text, (content_width - CHECK_SIZE - CHECK_TO_LABEL).max(0.0)); + let legend_label = tr("Not used by the shader"); + let legend_font = FontId::proportional(SMALL_TEXT_SIZE); + let legend_glyph = ui.painter().layout_no_wrap(icon::PROHIBIT.into(), legend_font.clone(), tokens.text_dim); + let legend_text_offset = legend_glyph.size().x + LEGEND_GLYPH_TO_TEXT; + let legend_text = ui.painter().layout(legend_label.into(), legend_font, tokens.text_dim, (content_width - legend_text_offset).max(0.0)); + + let left_width = CHECK_SIZE + CHECK_TO_LABEL + checkbox_text.size().x + LEGEND_GAP + legend_text_offset + legend_text.size().x; + let checkbox_height = BUTTON_SIZE.y.max(checkbox_text.size().y); + let legend_height = legend_glyph.size().y.max(legend_text.size().y); + let (first_row_height, legend_row_height) = if left_width > content_width { + (checkbox_height, BUTTON_GAP + BUTTON_SIZE.y.max(legend_height)) + } else { + (checkbox_height.max(legend_height), 0.0) + }; + let buttons_row_height = if left_width + 2.0 * (BUTTON_SIZE.x + BUTTON_GAP) > content_width { BUTTON_GAP + BUTTON_SIZE.y } else { 0.0 }; + let button_gap = BUTTON_GAP.min(content_width); + let button_width = BUTTON_SIZE.x.min((content_width - button_gap) / 2.0); + + Self { + checkbox_label, + checkbox_text, + legend_label, + legend_glyph, + legend_text, + first_row_height, + legend_row_height, + buttons_row_height, + button_gap, + button_width, + } + } + + pub(super) fn height(&self) -> f32 { + self.first_row_height + self.legend_row_height + self.buttons_row_height + } + + pub(super) fn checkbox_rects(&self, row: Rect) -> (Rect, Rect) { + let left = row.left() + EDGE_AIR; + let hit = Rect::from_min_size(pos2(left, row.top()), vec2(CHECK_SIZE + CHECK_TO_LABEL + self.checkbox_text.size().x, self.first_row_height)); + let check = Rect::from_center_size(pos2(left + CHECK_SIZE / 2.0, hit.center().y), vec2(CHECK_SIZE, CHECK_SIZE)); + (check, hit) + } + + pub(super) fn paint_labels(self, ui: &Ui, tokens: &Tokens, row: Rect, check: Rect, hit: Rect) -> (Rect, Rect) { + let paint = |left, center, galley: Arc, color| { + ui.painter().galley(pos2(left, center - galley.size().y / 2.0), galley, color); + }; + paint(check.right() + CHECK_TO_LABEL, hit.center().y, self.checkbox_text, tokens.text); + + let (legend_left, legend_center_y) = if self.legend_row_height > 0.0 { + (check.left(), hit.bottom() + (BUTTON_GAP + self.legend_row_height) / 2.0) + } else { + (hit.right() + LEGEND_GAP, hit.center().y) + }; + let legend_offset = self.legend_glyph.size().x + LEGEND_GLYPH_TO_TEXT; + let legend_height = self.legend_glyph.size().y.max(self.legend_text.size().y); + let legend_rect = + Rect::from_min_size(pos2(legend_left, legend_center_y - legend_height / 2.0), vec2(legend_offset + self.legend_text.size().x, legend_height)); + ui.interact(legend_rect, ui.scope_id().with("legend"), Sense::hover()) + .widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, self.legend_label)); + paint(legend_left, legend_center_y, self.legend_glyph, tokens.text_dim); + paint(legend_left + legend_offset, legend_center_y, self.legend_text, tokens.text_dim); + + let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - self.button_width, row.bottom() - BUTTON_SIZE.y), vec2(self.button_width, BUTTON_SIZE.y)); + let cancel = apply.translate(vec2(-(self.button_width + self.button_gap), 0.0)); + (apply, cancel) + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 8359fbe9..f1d40821 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -35,8 +35,10 @@ impl ControlRequest { } } -fn ok(v: Value) -> Value { - json!({ "ok": true, "result": v }) +fn ok(result: Value) -> Value { + let mut reply = json!({ "ok": true }); + reply["result"] = result; + reply } fn err(e: impl std::fmt::Display) -> Value { @@ -154,9 +156,9 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para return err("A manual project save is already running"); } - let command_params = params.get("params").cloned().unwrap_or(Value::Null); + let command_params = params.get("params").unwrap_or(&Value::Null); let before = app.session.camera; - match texturecraft_engine::execute(&mut app.session, id, &command_params) { + match texturecraft_engine::execute(&mut app.session, id, command_params) { Ok(value) => { if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") { app.thumbs.forget_saved_files(); @@ -177,6 +179,9 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para // A command that moved the camera takes over from a glide in progress; a projection switch joins it app.settle_camera_glide(id, before); + #[cfg(not(target_arch = "wasm32"))] + let value = app.recover_file_open(id, value); + ok(value) } Err(error) => err(error), diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 57c15011..6e9fda2a 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -8,21 +8,21 @@ use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Project, Projection, Sampling, Source, }; -use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST; -use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; +use texturecraft_engine::texel::linear_to_srgb; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; +use crate::brush_stroke_preview::BrushStrokePreview; use crate::i18n::{n_, tr, trf}; use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; +use crate::paint_section::PaintSection; use crate::past_end::PastEnd; use crate::property_sheet::{PropertySheet, SectionScope}; use crate::shelf::{Asset, ShelfDrag}; use crate::source_choice::SourceChoice; -use crate::state::PropsTab; +use crate::tabbed_page::TabbedPage; use crate::theme::{Tokens, caption}; -use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -36,100 +36,7 @@ const TAG_COLORS: [Color32; 8] = [ ]; pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { - // The empty state lists nothing - if !app.session.project_open { - return; - } - - let tk = Tokens::get(ui.ctx()); - let sets: Vec<(String, String, bool)> = app - .session - .doc - .project - .texture_sets - .iter() - .map(|t| { - let res = t.resolution; - let size = match t.uv_tiles.len() { - 0 => format!("{res}x{res}"), - n => format!("{res}x{res}, {n} UDIM"), - }; - (t.name.clone(), size, t.visible) - }) - .collect(); - let active = app.session.ts(); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.menu_button(RichText::new(ic::EYE).size(14.0), |ui| { - for (label, mode) in [(tr("Show all"), "showAll"), (tr("Hide all"), "hideAll"), (tr("Invert show/hide"), "invert")] { - if ui.button(label).clicked() { - app.run("textureSet.visibility", json!({ "mode": mode })); - ui.close(); - } - } - }) - .response - .on_hover_text(tr("Show or hide texture sets")); - let solo = sets.iter().enumerate().all(|(i, s)| s.2 == (i == active)); - if icon_button(ui, ic::FRAME_CORNERS, tr("Focus: show only the active texture set"), solo && sets.len() > 1, 22.0).clicked() { - app.run("textureSet.visibility", json!({ "mode": "solo" })); - } - }); - egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { - for (i, (name, size, visible)) in sets.into_iter().enumerate() { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &name)); - ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(i == active)); - - let p = ui.painter(); - let bg = if i == active { - tk.row_selected - } else if resp.hovered() { - tk.row_hover - } else { - tk.panel - }; - p.rect_filled(rect, 2.0, bg); - if i == active { - p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - if resp.has_focus() { - p.rect_stroke(rect.shrink(2.0), 2.0, Stroke::new(1.0, tk.text_strong), egui::StrokeKind::Inside); - } - - let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0)); - let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set")); - p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text); - - if ui.is_enabled() && (resp.contains_pointer() || eye_resp.contains_pointer()) { - app.next_hovered_texture_set = Some((app.session.project_id, i)); - } - - // Narrow panels drop the shader label, then the resolution, before cutting the name - let cy = rect.center().y; - let mut right = rect.right() - 6.0; - if rect.width() >= 260.0 { - let g = p.layout_no_wrap(tr("Main shader").into(), egui::FontId::proportional(11.0), tk.text_dim); - right -= g.size().x; - p.galley(pos2(right, cy - g.size().y * 0.5), g, tk.text_dim); - right -= 10.0; - } - if rect.width() >= 170.0 { - let g = p.layout_no_wrap(size, egui::FontId::proportional(11.0), tk.text_dim); - let x = (rect.left() + rect.width() * 0.48).min(right - g.size().x); - p.galley(pos2(x, cy - g.size().y * 0.5), g, tk.text_dim); - right = x - 8.0; - } - let color = if i == active { tk.text_strong } else { tk.text }; - let g = elided(p, name, 12.0, color, right - rect.left() - 26.0); - p.galley(pos2(rect.left() + 26.0, cy - g.size().y * 0.5), g, color); - if eye_resp.clicked() { - app.run("textureSet.visible", json!({"ts": i})); - } else if resp.clicked() { - app.run("textureSet.select", json!({"ts": i})); - } - } - }); + crate::texture_set_list::show(app, ui); } // --------------------------------------------------------------------------------------------- @@ -1522,170 +1429,8 @@ fn mask_management_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, m // --------------------------------------------------------------------------------------------- // Texture set settings -/// Size of a channel's remove button, and of the room Base color keeps for one -const CHANNEL_REMOVE_SIZE: f32 = 18.0; - -/// The sizes a texture set and each of its UV tiles can take -const TEXTURE_SET_RESOLUTIONS: [u32; 6] = [256, 512, 1024, 2048, 4096, 8192]; - -/// Air between the General properties grid's columns and rows -const GENERAL_GRID_SPACING: egui::Vec2 = vec2(8.0, 6.0); - -/// Air above the Channels and Mesh maps captions -const SECTION_GAP: f32 = 8.0; - -/// Air between the channel list and the height and normal settings -const CHANNEL_SETTINGS_GAP: f32 = 6.0; - -/// Range of the Height to normal strength slider -const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; - -/// A mesh map row's colour square, its corner radius, the size of its file name and of its menu's dots -const MESH_MAP_SWATCH_SIZE: f32 = 26.0; -const MESH_MAP_SWATCH_RADIUS: f32 = 2.0; -const MESH_MAP_FILE_TEXT_SIZE: f32 = 10.5; -const MESH_MAP_MENU_ICON_SIZE: f32 = 13.0; - pub(crate) fn texture_set_settings(app: &mut TextureCraftApp, ui: &mut Ui) { - let tokens = Tokens::get(ui.ctx()); - let set_index = app.session.ts(); - let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; - egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { - ui.label(caption(tr("General properties"))); - egui::Grid::new("tss_grid").num_columns(2).spacing(GENERAL_GRID_SPACING).show(ui, |ui| { - ui.label(tr("Name")); - ui.label(RichText::new(&set.name).color(tokens.text_strong)); - ui.end_row(); - - ui.label(tr("Size")); - egui::ComboBox::from_id_salt("ts_size").selected_text(format!("{}", set.resolution)).show_ui(ui, |ui| { - for resolution in TEXTURE_SET_RESOLUTIONS { - if ui.selectable_label(resolution == set.resolution, format!("{resolution}")).clicked() { - app.start_resize(set_index, resolution); - } - } - }); - ui.end_row(); - - ui.label(tr("UV tiles (UDIM)")); - let mut tiled = !set.uv_tiles.is_empty(); - if ui.checkbox(&mut tiled, "").changed() { - app.run("textureSet.uvTiles", json!({"ts": set_index, "enabled": tiled})); - } - ui.end_row(); - - // Each tile's own size - for &udim in &set.uv_tiles { - let tile_resolution = set.tile_resolution(udim); - ui.label(RichText::new(format!(" {udim}")).color(tokens.text_dim)); - egui::ComboBox::from_id_salt(("ts_tile", udim)).selected_text(format!("{tile_resolution}")).show_ui(ui, |ui| { - for resolution in TEXTURE_SET_RESOLUTIONS { - if ui.selectable_label(resolution == tile_resolution, format!("{resolution}")).clicked() { - app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": udim, "resolution": resolution})); - } - } - }); - ui.end_row(); - } - - ui.label(tr("Shader instance")); - ui.label(tr("Main shader")); - ui.end_row(); - }); - - ui.add_space(SECTION_GAP); - ui.horizontal(|ui| { - ui.label(caption(tr("Channels"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(tr("Add channel"), |ui| { - for channel in Channel::ALL { - if !set.has_channel(channel) && ui.button(tr(channel.label())).clicked() { - app.run("textureSet.channel.add", json!({"ts": set_index, "channel": channel.id()})); - ui.close(); - } - } - }); - }); - }); - - for (channel, format) in &set.channels { - ui.horizontal(|ui| { - ui.label(RichText::new(tr(channel.label())).strong()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Base color can't be removed: its × room stays, so every format ends on one column - if *channel == Channel::BaseColor { - ui.allocate_exact_size(vec2(CHANNEL_REMOVE_SIZE, CHANNEL_REMOVE_SIZE), Sense::hover()); - } else if icon_button(ui, ic::X, tr("Remove channel"), false, CHANNEL_REMOVE_SIZE).clicked() { - app.run("textureSet.channel.remove", json!({"ts": set_index, "channel": channel.id()})); - } - ui.label(RichText::new(format.label()).color(tokens.text_dim)); - }); - }); - } - - ui.add_space(CHANNEL_SETTINGS_GAP); - let mut height_strength = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut height_strength, HEIGHT_STRENGTH_RANGE, 2) { - app.run("textureSet.settings", json!({"ts": set_index, "heightStrength": height_strength, "merge": merge})); - } - - let directx = app.session.doc.project.normal_format == texturecraft_engine::core::NormalFormat::DirectX; - combo(ui, tr("Normal map format"), if directx { "DirectX" } else { "OpenGL" }, |ui| { - for (id, label, on) in [("openGl", "OpenGL", !directx), ("directX", "DirectX", directx)] { - if ui.selectable_label(on, label).clicked() && !on { - app.run("textureSet.settings", json!({"ts": set_index, "normalFormat": id})); - } - } - }) - .on_hover_text(tr( - "For the whole project: how normal map images set as mesh maps are read (set them again after a change), and the default for export", - )); - - ui.add_space(SECTION_GAP); - ui.horizontal(|ui| { - ui.label(caption(tr("Mesh maps"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Bake Mesh Maps")).clicked() { - app.ui.mode = crate::state::Mode::Baking; - } - }); - }); - for map in BakedMap::ALL { - let present = app.session.doc.baked.get(&set_index).is_some_and(|baked| baked.maps.contains_key(&map)); - let row = ui.horizontal(|ui| { - let (swatch, _) = ui.allocate_exact_size(vec2(MESH_MAP_SWATCH_SIZE, MESH_MAP_SWATCH_SIZE), Sense::hover()); - ui.painter().rect_filled(swatch, MESH_MAP_SWATCH_RADIUS, if present { mesh_map_color(map) } else { tokens.button }); - ui.vertical(|ui| { - ui.label(RichText::new(tr(crate::i18n::baked_map_label(map))).strong()); - ui.label( - RichText::new(if present { format!("{}_{}", set.name, map.id()) } else { tr("Missing (bake to create)").into() }) - .size(MESH_MAP_FILE_TEXT_SIZE) - .color(tokens.text_dim), - ); - }); - - // An image resource instead of a bake, or no map - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.menu_button(RichText::new(ic::DOTS_THREE).size(MESH_MAP_MENU_ICON_SIZE), |ui| { - if let Some(name) = image_menu(app, ui) { - app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); - } - ui.separator(); - if ui.add_enabled(present, egui::Button::new(tr("Clear"))).clicked() { - app.run("textureSet.meshMap.clear", json!({"ts": set_index, "map": map.id()})); - ui.close(); - } - }); - }); - }); - - // A shelf image dropped on the row becomes this mesh map - let response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as this mesh map")); - if let Some(name) = image_drop(ui, &response) { - app.run("textureSet.meshMap.set", json!({"ts": set_index, "map": map.id(), "image": name})); - } - } - }); + crate::texture_set_settings::show(app, ui); } /// Menu listing the decoded image resources with a name filter and thumbnails, then Import...: the @@ -1895,9 +1640,10 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { // A floating scroll bar would cover the right-aligned slider values and section reset icons ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); let scope = SectionScope::Docked; - if let Some(tabs) = properties_fill_tabs(app) { + if let Some(tabs) = properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, 0, &tabs); } + pinned_brush_preview(app, ui); let selection = properties_selection(app); crate::property_sheet::in_scope(ui, scope, |ui| { @@ -1936,20 +1682,42 @@ pub(crate) fn properties_scrolled(app: &mut TextureCraftApp, ui: &mut Ui, area: output.state.clamped_offset().y } -/// The tabs over the panel when it shows a fill layer's or a mask fill effect's sections, which they jump between -pub(crate) fn properties_fill_tabs(app: &TextureCraftApp) -> Option<[(&'static str, &'static str); 3]> { - if app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { +/// The tabs over the panel when it shows a fill layer's, a mask fill effect's or a paint tool's sections, which they jump between +pub(crate) fn properties_tabs(app: &TextureCraftApp) -> Option> { + Some(match tabbed_page(app)? { + TabbedPage::Fill { mask } => crate::fill_panel::fill_tabs(mask).to_vec(), + TabbedPage::Tool => tool_sections(app).into_iter().map(|section| (section.icon(), section.title())).collect(), + }) +} + +/// The page under the panel's jump tabs, if it shows one +fn tabbed_page(app: &TextureCraftApp) -> Option { + if !app.session.project_open || app.session.tool.tool == Tool::PolygonFill && app.session.tool_usable(Tool::PolygonFill) { return None; } let project = &app.session.doc.project; - match app.session.target { - StackTarget::Content => { - let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id))?; - matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then(|| crate::fill_panel::fill_tabs(false)) + let layer = app.session.selected_layer().and_then(|id| project.layers.get(&id)); + let tool_shown = match (layer, app.session.target) { + (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { + return matches!(&layer.kind, LayerKind::Fill(fill) if fill.projection.placed().is_none()).then_some(TabbedPage::Fill { mask: false }); } - StackTarget::Effect(effect) => mask_fill_of(project, effect).map(|_| crate::fill_panel::fill_tabs(true)), - _ => None, + (Some(_), StackTarget::Effect(effect)) => match project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Paint | EffectKind::Path(_)) => true, + _ => return mask_fill_of(project, effect).map(|_| TabbedPage::Fill { mask: true }), + }, + (Some(layer), StackTarget::Content) => !layer.is_group() && layer.instance_source().is_none(), + _ => true, + }; + + // Everything else shows the tool's sections where the tool can paint + (tool_shown && app.session.tool_usable(app.session.tool.tool)).then_some(TabbedPage::Tool) +} + +/// The brush preview under the tool's jump tabs: it stays in view while the sections scroll under it +pub(crate) fn pinned_brush_preview(app: &TextureCraftApp, ui: &mut Ui) { + if tabbed_page(app) == Some(TabbedPage::Tool) { + legacy_body(ui, |ui| brush_preview(app, ui)); } } @@ -1991,10 +1759,6 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { (Some(layer), StackTarget::Effect(effect)) => { let snapshot = layer.clone(); effect_properties(app, ui, &snapshot, effect); - let painted = app.session.doc.project.effect(effect).is_some_and(|(_, effect)| matches!(effect.kind, EffectKind::Paint | EffectKind::Path(_))); - if painted && grayscale_tab_open(app) { - crate::mask_paint_panel::grayscale_sheet(app, ui); - } } (Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => { let snapshot = layer.clone(); @@ -2007,35 +1771,27 @@ pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) { } (Some(layer), StackTarget::Mask) => { let layer_id = layer.id; - legacy_body(ui, |ui| { - // Saved height masks can still be turned off here - let height_shown = app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled); - if height_shown { + + // Saved height masks can still be turned off here + if app.session.doc.project.content_layer(layer_id).is_some_and(|content| content.height_mask.enabled) { + legacy_body(ui, |ui| { height_mask_section(app, ui, layer_id); - } - if tool_usable { - if height_shown { + if tool_usable { ui.separator(); } - tool_properties(app, ui); - } - }); - if tool_usable && grayscale_tab_open(app) { - crate::mask_paint_panel::grayscale_sheet(app, ui); + }); + } + if tool_usable { + tool_properties(app, ui); } } (None, _) if !tool_usable => legacy_body(ui, |ui| { ui.label(RichText::new(tr("Select a layer to paint on")).color(tokens.text_dim)); }), - _ => legacy_body(ui, |ui| tool_properties(app, ui)), + _ => tool_properties(app, ui), } } -/// Whether the tool panel's third tab is open while a mask is painted: its Grayscale tab, drawn under the tool's rows -fn grayscale_tab_open(app: &TextureCraftApp) -> bool { - app.ui.props_tab == PropsTab::Material && !targets_content(app) -} - /// Mask with height: the layer's height shapes its mask transitions. fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { let height_mask = app.session.project().content_layer(layer).map(|source| source.height_mask).unwrap_or_default(); @@ -2066,97 +1822,69 @@ fn height_mask_section(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId) { const BRUSH_PREVIEW_HEIGHT: f32 = 88.0; const BRUSH_PREVIEW_CORNER_RADIUS: f32 = 2.0; -/// The preview stroke: its segments, its margin from the preview's left (each side of its half), its wave's phase span in radians and its swing -const PREVIEW_STROKE_STEPS: usize = 40; -const PREVIEW_STROKE_MARGIN: f32 = 14.0; -const PREVIEW_STROKE_WAVE: f32 = 9.0; -const PREVIEW_STROKE_SWING: f32 = 18.0; - -/// The preview stroke's width: [`PREVIEW_STROKE_WIDTH_SCALE`] points for each [`PREVIEW_SIZE_UNIT`] of brush size, kept inside [`PREVIEW_STROKE_WIDTH`] -const PREVIEW_SIZE_UNIT: f32 = 0.25; -const PREVIEW_STROKE_WIDTH_SCALE: f32 = 60.0; -const PREVIEW_STROKE_WIDTH: std::ops::RangeInclusive = 2.0..=30.0; - -/// Faintest the preview stroke draws, so a low flow or opacity still shows -const PREVIEW_STROKE_MIN_ALPHA: u8 = 30; - -/// Radius of the preview's material sphere, and the colour it shows when the tool has no base colour +/// Radius of the preview's material sphere, and the material it shows for channels the tool doesn't paint const PREVIEW_SPHERE_RADIUS: f32 = 36.0; const PREVIEW_FALLBACK_BASE_COLOR: [f32; 3] = [0.8; 3]; -/// Gap between the brush preview and the tab buttons +/// Samples an image-backed mask's gray is read at across the preview stroke +const STROKE_GRAY_SAMPLES: u32 = 64; + +/// Gap under the brush preview const BRUSH_PREVIEW_GAP: f32 = 4.0; -fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The brush's stroke in its target's tint, with a material sphere for content targets +fn brush_preview(app: &TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); let content = targets_content(app); - - // Brush preview: a stroke and a sphere with the tool's material - let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), BRUSH_PREVIEW_HEIGHT), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, tr("Brush preview"))); let painter = ui.painter(); painter.rect_filled(rect, BRUSH_PREVIEW_CORNER_RADIUS, tokens.viewport); let half_width = rect.width() * 0.5; - let brush = &app.session.tool.brush; - let mut points = Vec::new(); - for step in 0..=PREVIEW_STROKE_STEPS { - let fraction = step as f32 / PREVIEW_STROKE_STEPS as f32; - let x = rect.left() + PREVIEW_STROKE_MARGIN + fraction * (half_width - 2.0 * PREVIEW_STROKE_MARGIN); - points.push(pos2(x, rect.center().y + (fraction * PREVIEW_STROKE_WAVE).sin() * PREVIEW_STROKE_SWING)); + let stroke_rect = Rect::from_min_size(rect.min, vec2(half_width, rect.height())); + let tool = &app.session.tool; + let brush = &tool.brush; + let image = brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)); + + let channel_value = |channel| if tool.enabled.contains(&channel) { tool.values.get(&channel).copied() } else { None }; + let base_color = content.then(|| channel_value(Channel::BaseColor).unwrap_or(PREVIEW_FALLBACK_BASE_COLOR)); + + if app.session.quick_mask.editing { + // The quick mask stores coverage independently of the tool's material and mask gray + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| [u8::MAX; 3]); + } else if let Some(base_color) = base_color { + let srgb = base_color.map(|linear| (linear_to_srgb(linear) * 255.0 + 0.5) as u8); + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, |_| srgb); + } else { + // A mask paints gray: an image-backed one is read across the stroke + let gray = app.session.mask_gray(); + let mask_tint = |across: f32| { + let gray = (gray.at((across * STROKE_GRAY_SAMPLES as f32) as u32, 0, (STROKE_GRAY_SAMPLES, 1)) * 255.0).round() as u8; + [gray; 3] + }; + BrushStrokePreview::paint(ui.ctx(), painter, stroke_rect, brush, image, mask_tint); } - let stroke_width = (brush.size / PREVIEW_SIZE_UNIT * PREVIEW_STROKE_WIDTH_SCALE).clamp(*PREVIEW_STROKE_WIDTH.start(), *PREVIEW_STROKE_WIDTH.end()); - let alpha = (brush.flow * brush.opacity * 255.0) as u8; - - let preview_stroke = |gray: f32| { - let gray = (gray.clamp(0.0, 1.0) * 255.0).round() as u8; - Stroke::new(stroke_width, Color32::from_rgba_unmultiplied(gray, gray, gray, alpha.max(PREVIEW_STROKE_MIN_ALPHA))) - }; - - // Sample image-backed masks along the preview stroke - let gray = if content { texturecraft_engine::compose::MaskGray::Value(1.0) } else { app.session.mask_gray() }; - match gray { - texturecraft_engine::compose::MaskGray::Value(value) => { - painter.add(egui::Shape::line(points, preview_stroke(value))); - } - texturecraft_engine::compose::MaskGray::Image { .. } => { - let size = PREVIEW_STROKE_STEPS as u32; - for (index, segment) in points.windows(2).enumerate() { - let value = gray.at(index as u32, size / 2, (size, size)); - painter.line_segment([segment[0], segment[1]], preview_stroke(value)); - } - } - } - - if content { - let base_color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or(PREVIEW_FALLBACK_BASE_COLOR); - + if let Some(base_color) = base_color { // The sphere sits in the middle of the preview's right half - crate::thumbs::paint_sphere(painter, pos2(rect.left() + half_width * 1.5, rect.center().y), PREVIEW_SPHERE_RADIUS, base_color); + let metallic = channel_value(Channel::Metallic).map_or(crate::thumbs::SPHERE_DEFAULT_METALLIC, |metallic| metallic[0]); + let roughness = channel_value(Channel::Roughness).map_or(crate::thumbs::SPHERE_DEFAULT_ROUGHNESS, |roughness| roughness[0]); + let center = pos2(rect.left() + half_width * 1.5, rect.center().y); + crate::thumbs::paint_material_sphere(painter, center, PREVIEW_SPHERE_RADIUS, base_color, metallic, roughness); } + ui.add_space(BRUSH_PREVIEW_GAP); +} - ui.horizontal(|ui| { - let button_size = ui.spacing().interact_size.y; - - // Painting a mask, the material tab becomes the Grayscale tab - let material = if content { (ic::SPHERE, tr("Material")) } else { (ic::SQUARE_HALF, tr("Grayscale")) }; - for (tab, icon, tip) in - [(PropsTab::Brush, ic::PAINT_BRUSH, tr("Brush")), (PropsTab::Alpha, ic::CIRCLE_HALF, tr("Alpha")), (PropsTab::Material, material.0, material.1)] - { - if icon_button(ui, icon, tip, app.ui.props_tab == tab, button_size).clicked() { - app.ui.props_tab = tab; - } - } - }); - ui.separator(); - +/// What only this tool has, above the sections every brush tool shares +fn tool_header(app: &mut TextureCraftApp, ui: &mut Ui) { + let tokens = Tokens::get(ui.ctx()); if app.session.quick_mask.editing { ui.label(RichText::new(tr("Editing the quick mask: strokes paint where painting is allowed. Press U to finish.")).color(tokens.text_dim)); ui.separator(); } let tool_section: Option = match app.session.tool.tool { - Tool::Projection => Some(stencil_section), Tool::Clone => Some(clone_section), Tool::Smudge => Some(smudge_section), Tool::Path => Some(path_section), @@ -2167,75 +1895,32 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { section(app, ui); ui.separator(); } - - match app.ui.props_tab { - PropsTab::Brush => brush_section(app, ui), - PropsTab::Alpha => alpha_section(app, ui), - PropsTab::Material if content => material_section(app, ui), - // A mask's Grayscale tab is a property sheet, drawn by the caller past this panel's margins - PropsTab::Material => {} - } } -/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) -const STENCIL_POSITION_RANGE: f32 = 2.0; - -fn stencil_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(caption(tr("Stencil"))); - let names: Vec = app.session.doc.resources.keys().cloned().collect(); - let current = app.session.tool.stencil.as_ref().map(|s| s.image.clone()).unwrap_or_else(|| tr("None").into()); - let row = ui.horizontal(|ui| { - egui::ComboBox::from_id_salt("stencil_img").width(170.0).selected_text(current.clone()).show_ui(ui, |ui| { - if ui.selectable_label(app.session.tool.stencil.is_none(), tr("None")).clicked() { - app.run("tool.stencil", json!({"clear": true})); +/// The tool's sections, one page under the panel's jump tabs +fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) { + legacy_body(ui, |ui| tool_header(app, ui)); + PropertySheet::show(ui, "tool_sheet", |sheet| { + for section in tool_sections(app) { + // The Stencil caption carries its own reset + let menu = if section == PaintSection::Stencil { None } else { sheet.section(section.title(), section == PaintSection::Brush) }; + match section { + PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu), + PaintSection::Alpha => crate::alpha_sheet::alpha_section(app, sheet), + PaintSection::Stencil => crate::stencil_sheet::stencil_section(app, sheet), + PaintSection::Material => crate::material_sheet::material_section(app, sheet), + PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet), } - for n in &names { - if ui.selectable_label(*n == current, n).clicked() { - app.run("tool.stencil", json!({"image": n})); - } - } - }); - import_button(app, ui); - }); - - // An image from the Assets panel dropped on the row becomes the stencil - let row_response = row.response.interact(Sense::hover()).on_hover_text(tr("Drop an image from the Assets panel here to use it as the stencil")); - if let Some(name) = image_drop(ui, &row_response) { - app.run("tool.stencil", json!({"image": name})); - } - if names.is_empty() { - ui.label(RichText::new(tr("Import an image (File > Import resources) to project it onto the mesh.")).color(tk.text_dim)); - return; - } - - if let Some(st) = app.session.tool.stencil.as_mut() { - slider(ui, tr("Scale"), &mut st.scale, 0.05..=4.0, 2); - slider(ui, tr("Rotation"), &mut st.rotation, 0.0..=360.0, 0); - slider(ui, tr("Position X"), &mut st.center[0], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); - slider(ui, tr("Position Y"), &mut st.center[1], -STENCIL_POSITION_RANGE..=STENCIL_POSITION_RANGE, 2); - if ui.button(tr("Reset stencil")).on_hover_text(tr("Put the stencil back in the middle of the view at its starting size and rotation")).clicked() { - st.reset_placement(); } - slider(ui, tr("Overlay opacity"), &mut st.opacity, 0.0..=1.0, 2); - ui.checkbox(&mut st.tile, tr("Tile")); - ui.label( - RichText::new(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves; or use Position X / Y.")) - .size(10.5) - .color(tk.text_dim), - ); - } + }); } -fn import_button(app: &mut TextureCraftApp, ui: &mut Ui) { - if ui.small_button(tr("Import...")).clicked() { - let ctx = ui.ctx().clone(); - crate::menus::invoke(app, &ctx, "resource.import"); - } +/// The sections of [`tool_properties`]: Stencil for the brush tools it shapes, except while they paint the quick mask +fn tool_sections(app: &TextureCraftApp) -> Vec { + PaintSection::page(crate::viewport::stencil_applies(app), targets_content(app)) } fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Clone"))); ui.horizontal(|ui| { ui.label(tr("Copy from")); @@ -2248,6 +1933,7 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { } } }); + let mut aligned = app.session.tool.clone_aligned; if ui .checkbox(&mut aligned, tr("Aligned")) @@ -2256,39 +1942,47 @@ fn clone_section(app: &mut TextureCraftApp, ui: &mut Ui) { { app.run("tool.brush", json!({"cloneAligned": aligned})); } - let Some(src) = app.session.tool.clone_source else { - ui.label(RichText::new(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")).color(tk.text_dim)); + + let Some(source) = app.session.tool.clone_source else { + ui.label(tr("Source: none")).on_hover_text(tr("Hold V and click the mesh to set the source, then paint elsewhere to copy it.")); return; }; - ui.horizontal(|ui| { - ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", src.uv[0])), ("v", &format!("{:.3}", src.uv[1]))])); - if ui.small_button(tr("Clear")).clicked() { - app.run("tool.cloneSource", json!({"clear": true})); - } - }); let hint = if !app.session.tool.clone_aligned { tr("Not aligned: every stroke starts at the source. V + click sets a new source.") - } else if src.offset.is_some() { + } else if source.offset.is_some() { tr("Aligned: the offset set by the first stroke is kept. V + click sets a new source.") } else { tr("The first stroke sets the offset from the source.") }; - ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); + ui.horizontal(|ui| { + ui.label(trf("Source U {u} V {v}", &[("u", &format!("{:.3}", source.uv[0])), ("v", &format!("{:.3}", source.uv[1]))])).on_hover_text(hint); + if ui.small_button(tr("Clear")).clicked() { + app.run("tool.cloneSource", json!({"clear": true})); + } + }); } +/// Space between the smudge strength and the channels it drags +const SMUDGE_CHANNELS_GAP: f32 = 4.0; + +/// Full value of the smudge strength slider, the 0..100 scale `tool.brush` takes +const SMUDGE_STRENGTH_PERCENT: f32 = 100.0; + fn smudge_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); ui.label(caption(tr("Smudge"))); - let mut v = app.session.tool.smudge_strength * 100.0; - if slider(ui, tr("Strength"), &mut v, 0.0..=100.0, 0).changed() { - app.session.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0); + + let mut strength_percent = app.session.tool.smudge_strength * SMUDGE_STRENGTH_PERCENT; + let strength = slider(ui, tr("Strength"), &mut strength_percent, 0.0..=SMUDGE_STRENGTH_PERCENT, 0); + if strength.on_hover_text(tr("Drags the layer stack's values along the stroke into the selected layer.")).changed() { + app.run("tool.brush", json!({"smudgeStrength": strength_percent})); } - ui.label(RichText::new(tr("Drags the layer stack's values along the stroke into the selected layer.")).size(10.5).color(tk.text_dim)); - ui.add_space(4.0); - ui.label(tr("Channels dragged")); + + ui.add_space(SMUDGE_CHANNELS_GAP); + ui.label(tr("Channels dragged")).on_hover_text(tr( + "These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.", + )); material_channel_chips(app, ui); - ui.label(RichText::new(tr("These are the brush's material channels, the same ones Paint writes and the Material tab shows. A channel the selected layer does not have is skipped.")).size(10.5).color(tk.text_dim)); } fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { @@ -2303,34 +1997,6 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } -/// Popover for built-in and saved brush presets -fn brush_presets_popover(app: &mut TextureCraftApp, ui: &mut Ui) { - let response = ui.button(format!("{} {}", ic::PAINT_BRUSH_BROAD, tr("Brush presets"))); - let popup_id = ui.make_persistent_id("brush_presets_popup"); - if response.clicked() { - egui::Popup::toggle_id(ui.ctx(), popup_id); - } - - egui::Popup::from_response(&response).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(230.0); - egui::ScrollArea::vertical().max_height(380.0).show(ui, |ui| { - let mut category = ""; - for preset in texturecraft_engine::paint::presets::PRESETS.iter() { - if preset.category != category { - category = preset.category; - ui.label(caption(category)); - } - if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() { - app.run("brush.preset.apply", json!({"preset": preset.id})); - } - } - - ui.separator(); - crate::shelf::user_brushes(app, ui, ""); - }); - }); -} - /// Width of the label column in polygon fill's properties const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0; @@ -2429,298 +2095,16 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result { } } -/// Font size of the dim hint line under the Brush caption -const HINT_TEXT_SIZE: f32 = 10.5; - -fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.label(caption(tr("Brush"))); - brush_presets_popover(app, ui); - }); - - let brush = &mut app.session.tool.brush; - let defaults = BrushSettings::default(); - let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); - ui.label(RichText::new(tr("Ctrl+Shift+right-drag: size and hardness in fine steps.")).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); - - // Each section's reset puts back only the fields it shows - let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); - if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { - let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; - if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { - brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); - } - - let mut min_size_percent = brush.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { - brush.min_size = min_size_percent / 100.0; - } - - ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); - }) { - (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); - } - - let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing); - if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { - let mut flow_percent = brush.flow * 100.0; - if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { - brush.flow = flow_percent / 100.0; - } - - let mut opacity_percent = brush.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { - brush.opacity = opacity_percent / 100.0; - } - - let mut spacing_percent = brush.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { - brush.spacing = spacing_percent / 100.0; - } - }) { - (brush.flow, brush.opacity, brush.spacing) = flow_fields(&defaults); - } - - let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); - if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { - slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); - ui.checkbox(&mut brush.follow_path, tr("Follow path")); - }) { - (brush.angle, brush.follow_path) = angle_fields(&defaults); - } - - let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); - if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { - let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; - for (label, jitter) in jitters { - let mut jitter_percent = *jitter * 100.0; - if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { - *jitter = jitter_percent / 100.0; - } - } - - let mut position_jitter_percent = brush.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { - brush.jitter_position = position_jitter_percent / 100.0; - } - }) { - (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); - } - - let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); - if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { - use texturecraft_engine::paint::Alignment; - let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); - combo(ui, tr("Alignment"), shown, |ui| { - for (alignment, label) in alignments { - ui.selectable_value(&mut brush.alignment, alignment, label); - } - }); - - ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); - }) { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); - } - - if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { - let particles = &mut brush.particles; - ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); - - let mut count = particles.count as f32; - if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - particles.count = count as u32; - } - - let mut lifetime_steps = particles.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { - particles.lifetime = lifetime_steps as u32; - } - - slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); - }) { - brush.particles = defaults.particles; - } - - 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); - }) { - brush.lazy = defaults.lazy; - } - - *brush = brush.sanitized(); -} - -/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. -fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Painter, Rect)) -> egui::Response { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(52.0, 64.0), Sense::click()); - let p = ui.painter(); - p.rect_filled(rect, 3.0, tk.viewport); - if on { - p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); - } - paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0))); - let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0); - p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text); - resp.on_hover_text(label) -} - -fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.horizontal(|ui| { - ui.label(caption(tr("Alpha"))); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| import_button(app, ui)); - }); - let brush = &app.session.tool.brush; - let (current, image, hardness) = (brush.alpha, brush.alpha_image.clone(), brush.hardness); - let library = if image.is_none() { brush.alpha_library.as_deref().and_then(alphas::find) } else { None }; - let mut pick = None; - let zone = ui.horizontal_wrapped(|ui| { - for a in BrushAlpha::ALL { - let on = image.is_none() && library.is_none() && current == a; - if alpha_tile(ui, on, tr(a.label()), |p, r| crate::thumbs::paint_alpha(p, r, a, hardness)).clicked() { - pick = Some(json!(a.label())); - } - } - - // The library alpha in use (picked from the shelf's Alphas tab) - if let Some(a) = library { - let tex = app.thumbs.alpha(ui.ctx(), a); - alpha_tile(ui, true, &a.label, |p, r| { - if let Some(t) = tex { - p.image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - } - }); - } - - // Imported images, sampled as grayscale - for name in app.session.doc.resources.keys() { - let Some(img) = app.session.images.get(name) else { continue }; - let tex = app.thumbs.image(ui.ctx(), name, img); - let on = image.as_deref() == Some(name.as_str()); - if alpha_tile(ui, on, name, |p, r| { - p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); - }) - .clicked() - { - pick = Some(json!({ "image": name })); - } - } - }); - if let Some(alpha) = pick { - app.run("tool.brush", json!({ "alpha": alpha })); - } - ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim)); - crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush); - alpha_parameters(&mut app.session.tool.brush, ui); - section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui)); -} - -/// Hardness and the parameters every alpha shares, under a header whose reset puts them back -fn alpha_parameters(brush: &mut BrushSettings, ui: &mut Ui) { - let defaults = BrushSettings::default(); - let at_defaults = brush.hardness == defaults.hardness && brush.alpha_params == defaults.alpha_params; - let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none(); - let percent_slider = |ui: &mut Ui, label: &str, value: &mut f32, min: f32, max: f32| { - let mut percent = *value * 100.0; - if slider(ui, label, &mut percent, min..=max, 0).changed() { - *value = percent / 100.0; - } - }; - - let reset = section_with_reset(ui, "sec_alpha_params", tr("Parameters"), true, at_defaults, |ui| { - percent_slider(ui, tr("Hardness"), &mut brush.hardness, 0.0, 99.9); - percent_slider(ui, tr("Size X"), &mut brush.alpha_params.size_x, 5.0, 100.0); - percent_slider(ui, tr("Size Y"), &mut brush.alpha_params.size_y, 5.0, 100.0); - - // Only the procedural Round shape has a roundness - ui.add_enabled_ui(round, |ui| percent_slider(ui, tr("Roundness"), &mut brush.alpha_params.roundness, 0.0, 100.0)); - slider(ui, tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2); - ui.checkbox(&mut brush.alpha_params.invert, tr("Invert")); - }); - if reset { - (brush.hardness, brush.alpha_params) = (defaults.hardness, defaults.alpha_params); - } - *brush = brush.sanitized(); -} - -/// Text drawn in a font, as the brush alpha or a decal (`resource.text`). -fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) { - if app.ui.text.fonts.is_empty() - && let Some(f) = app.run("text.fonts", Value::Null) - { - let installed = f["installed"].as_array().into_iter().flatten().map(|v| { - let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect(); - (v["family"].as_str().unwrap_or_default().to_string(), styles) - }); - let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new())); - app.ui.text.fonts = installed.chain(built_in).collect(); - } - // A decal shows the text in the tool's base color; an alpha must stay white. - let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]); - let t = &mut app.ui.text; - ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text"))); - let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() }; - combo(ui, tr("Font"), shown, |ui| { - if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() { - (t.font, t.style) = (String::new(), String::new()); - } - for (family, _) in &t.fonts { - if ui.selectable_label(t.font == *family, family).clicked() { - (t.font, t.style) = (family.clone(), String::new()); - } - } - }); - let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default(); - if styles.len() > 1 { - let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() }; - combo(ui, tr("Style"), shown, |ui| { - for s in styles { - ui.selectable_value(&mut t.style, s.clone(), s); - } - }); - } - let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)}); - let ready = !t.text.trim().is_empty(); - ui.horizontal_wrapped(|ui| { - let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked(); - let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked(); - if decal { - params["color"] = json!(color); - } - if (alpha || decal) - && let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string)) - { - match alpha { - true => app.run("tool.brush", json!({"alpha": {"image": name}})), - false => app.run("layer.add.decal", json!({"image": name})), - }; - } - }); -} - /// Tooltip of the material channel chips. pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only"; -/// The tool's material under a "Material" heading -fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(caption(tr("Material"))); - material_controls(app, ui); -} - /// Space between the tool's channel chips and the first channel value const CHIPS_GAP: f32 = 4.0; /// Room right of the tool's colour swatch, like a linked material's const TOOL_SWATCH_RIGHT_MARGIN: f32 = LINK_SWATCH_RIGHT_MARGIN; -/// One chip per channel of the texture set, on while the tool's material has it enabled; returns the channels. -/// The Material tab and the Smudge panel both draw these, so they share one set of flags. +/// One chip per channel of the texture set, on while the tool's material has it enabled (the flags the Material section's pills show); returns the channels fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec { let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default(); ui.horizontal_wrapped(|ui| { @@ -2735,7 +2119,7 @@ fn material_channel_chips(app: &mut TextureCraftApp, ui: &mut Ui) -> Vec crate::anchor_properties::anchor_properties(app, ui, effect_id, &effect.name), - EffectKind::Paint => legacy_body(ui, |ui| { - let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { - tr("Paint on the mesh to edit the layer content.") - } else { - tr("Paint on the mesh to edit this mask.") - }; - ui.label(RichText::new(hint).color(tokens.text_dim)); + EffectKind::Paint => { + legacy_body(ui, |ui| { + let hint = if layer.content_effects.iter().any(|content| content.id == effect_id) { + tr("Paint on the mesh to edit the layer content.") + } else { + tr("Paint on the mesh to edit this mask.") + }; + ui.label(RichText::new(hint).color(tokens.text_dim)); + }); if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - }), - EffectKind::Path(paths) => legacy_body(ui, |ui| { - ui.label( + } + EffectKind::Path(paths) => { + legacy_body(ui, |ui| { + ui.label( RichText::new(tr("Paths stay editable: pick one to move its points or change its brush and material, and the sublayer repaints at once. Add paths with the Path tool.")) .color(tokens.text_dim), ); - let editing = app.session.tool.path.editing; - for index in 0..paths.len() { - ui.horizontal(|ui| { - let selected = editing == Some((effect_id, index)); - if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { - if selected { - app.run("tool.path", json!({"clear": true})); - } else { - app.run("path.edit", json!({"effect": id, "index": index})); + let editing = app.session.tool.path.editing; + for index in 0..paths.len() { + ui.horizontal(|ui| { + let selected = editing == Some((effect_id, index)); + if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() { + if selected { + app.run("tool.path", json!({"clear": true})); + } else { + app.run("path.edit", json!({"effect": id, "index": index})); + } } - } - if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { - app.run("path.remove", json!({"effect": id, "index": index})); - } - }); - } + if icon_button(ui, ic::TRASH, tr("Remove"), false, ICON_BUTTON_SIZE).clicked() { + app.run("path.remove", json!({"effect": id, "index": index})); + } + }); + } + }); if app.session.tool_usable(app.session.tool.tool) { tool_properties(app, ui); } - }), + } EffectKind::Filter(filter) => crate::filter_properties::filter_properties(app, ui, effect_id, filter), EffectKind::ColorSelection(selection) => crate::color_selection_editor::color_selection_properties(app, ui, effect_id, selection), EffectKind::Compare { op, value, tolerance, left, right, channel, hardness } => { diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 66bab1aa..6f5929ca 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -173,10 +173,12 @@ pub fn default_workspace() -> Workspace { // The Assets split keeps four tiles visible at the reference window width const ASSETS_SPLIT_RATIO: f32 = 0.16; const VIEWPORT_SPLIT_RATIO: f32 = 0.80; - const TEXTURE_SET_SPLIT_RATIO: f32 = 0.125; + + // Three texture set rows show at the default window height + const TEXTURE_SET_SPLIT_RATIO: f32 = 0.2; // Leave room for three layer rows and the fill's channel controls - const LAYERS_SPLIT_RATIO: f32 = 0.31; + const LAYERS_SPLIT_RATIO: f32 = 0.34; let column = split( Axis::Y, @@ -616,12 +618,13 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - // Properties draws full-width bands and tabs and History and Log full-width rows, so they draw their own side margins + // Let panels with full-width content set their own side margins let margin = match panel { Panel::Properties => Margin::ZERO, Panel::History | Panel::Log => LIST_PANEL_MARGIN, _ => PANEL_BODY_MARGIN, }; + egui::Frame::new().inner_margin(margin).show(ui, |ui| match panel { Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), Panel::Assets => crate::shelf::body(app, ui), @@ -634,7 +637,7 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), Panel::Properties => crate::dock::properties(app, ui), - // Display and Shader Settings scroll one page under their section tabs; History and Log scroll their own lists + // Each of these panels owns its scroll area Panel::Display => crate::display_settings::body(app, ui), Panel::Shader => crate::shader_settings::body(app, ui), Panel::History => crate::windows::history(app, ui), diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index aa7f223d..014a7c42 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -889,15 +889,13 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) { fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { let look = ExportLook::get(ui.ctx()); let tokens = Tokens::get(ui.ctx()); - let (mut preset, editable) = match (&app.ui.export.draft, selected(app)) { - (Some(d), _) => (d.clone(), true), - (None, Some(b)) => (b, false), - (None, None) => { - MapPreviewCache::clear(ui.ctx()); - drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); - return; - } + let editable = app.ui.export.draft.is_some(); + let Some(mut preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { + MapPreviewCache::clear(ui.ctx()); + drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); + return; }; + let params = plan_params(app, &preset); let preview = match ¶ms { Ok(params) => MapPreviewCache::plan(app, ui.ctx(), params), @@ -1043,9 +1041,10 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { if acted { pending = None; } - let e = &mut app.ui.export; - e.draft_split = split; - e.pending_drop = pending; + + app.ui.export.draft_split = split; + app.ui.export.pending_drop = pending; + if acted || changed { commit(app, preset, origin); } @@ -1119,7 +1118,7 @@ fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result display_name.to_owned(), }, tiled, - size: file.get("size").and_then(Value::as_u64).unwrap_or(0), + dimensions: (file["size"].as_u64().unwrap_or(0), file["height"].as_u64().unwrap_or(0)), format: file.get("format").and_then(Value::as_str).and_then(FileFormat::from_extension), bit_depth: file.get("bitDepth").and_then(Value::as_u64).and_then(|depth| u8::try_from(depth).ok()).unwrap_or(0), dithering: file.get("dithering").and_then(Value::as_bool).unwrap_or(false), @@ -1508,7 +1507,8 @@ fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&Pla let file_type = planned.format.map_or("", FileFormat::extension); let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); - let details = if planned.tiled { format!("{file_type} {depth}") } else { format!("{size} x {size} · {file_type} {depth}", size = planned.size) }; + let (width, height) = planned.dimensions; + let details = if planned.tiled { format!("{file_type} {depth}") } else { format!("{width} x {height} · {file_type} {depth}") }; ui.label(RichText::new(details).color(tokens.text_dim)); } @@ -1782,7 +1782,8 @@ fn source_channel_popup(ui: &Ui, pending: &mut Option, maps: &mut [ /// The maps the selected template's outputs read, with their colours, for the panes' markers fn marked_sources(app: &TextureCraftApp) -> Vec<(SourceRef, Color32)> { - let Some(preset) = app.ui.export.draft.clone().or_else(|| selected(app)) else { return Vec::new() }; + let draft = app.ui.export.draft.as_ref().map(std::borrow::Cow::Borrowed); + let Some(preset) = draft.or_else(|| selected(app).map(std::borrow::Cow::Owned)) else { return Vec::new() }; let sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); sources.filter_map(|source| source_color(source).map(|color| (source.clone(), color))).collect() @@ -1894,6 +1895,7 @@ mod tests { let mut harness = Harness::builder().with_context_setup(crate::framework::install_headless).build_eframe(|cc| TextureCraftApp::new(cc, session)); let app = harness.state_mut(); let ts = app.session.ts(); + app.session.doc.project.texture_sets[ts].set_size(256, 128); let saved = app.session.export_preset("Unreal Engine (Packed)").unwrap(); let mut draft = saved.clone(); draft.maps = vec![saved.maps[1].clone(), new_map(Layout::Gray, "New"), saved.maps[0].clone()]; @@ -1915,7 +1917,7 @@ mod tests { let outputs = planned_outputs(app, ¶ms).unwrap(); assert!(outputs[0].is_none(), "the disabled map stays disabled in its new position"); - assert_eq!(outputs[2].as_ref().unwrap().size, 128); + assert_eq!(outputs[2].as_ref().unwrap().dimensions, (128, 64)); assert_eq!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); } diff --git a/crates/ui-egui/src/export_templates/map_lists.rs b/crates/ui-egui/src/export_templates/map_lists.rs index f190370c..7fd30b1d 100644 --- a/crates/ui-egui/src/export_templates/map_lists.rs +++ b/crates/ui-egui/src/export_templates/map_lists.rs @@ -28,40 +28,56 @@ fn missing(name: &'static str) -> MapEntry { /// Input maps in the OpenPBR parameter groups, then TextureCraft's channels outside OpenPBR pub static INPUT_MAPS: LazyLock> = LazyLock::new(|| { vec![ - (n_("Base"), vec![missing(n_("Base weight")), channel(Channel::BaseColor), channel(Channel::Metallic), missing(n_("Base diffuse roughness"))]), + (n_("Base"), vec![channel(Channel::BaseWeight), channel(Channel::BaseColor), channel(Channel::Metallic), channel(Channel::BaseDiffuseRoughness)]), ( n_("Specular"), vec![ - missing(n_("Specular weight")), - missing(n_("Specular color")), + channel(Channel::SpecularWeight), + channel(Channel::SpecularColor), channel(Channel::Roughness), channel(Channel::SpecularLevel), channel(Channel::AnisotropyLevel), channel(Channel::AnisotropyAngle), ], ), - (n_("Transmission"), vec![channel(Channel::Transmission), missing(n_("Transmission color"))]), - (n_("Subsurface"), vec![channel(Channel::ScatterWeight), missing(n_("Subsurface color")), missing(n_("Subsurface radius"))]), + (n_("Transmission"), vec![channel(Channel::Transmission), channel(Channel::TransmissionColor)]), + (n_("Subsurface"), vec![channel(Channel::ScatterWeight), channel(Channel::SubsurfaceColor), channel(Channel::SubsurfaceRadiusScale)]), ( n_("Coat"), vec![ channel(Channel::CoatWeight), - missing(n_("Coat color")), + channel(Channel::CoatColor), channel(Channel::CoatRoughness), - missing(n_("Coat roughness anisotropy")), + channel(Channel::CoatAnisotropy), missing(n_("Coat IOR")), + channel(Channel::CoatSpecularLevel), channel(Channel::CoatNormal), - missing(n_("Coat tangent")), + channel(Channel::CoatTangent), ], ), (n_("Sheen"), vec![channel(Channel::SheenWeight), channel(Channel::SheenColor), channel(Channel::SheenRoughness)]), (n_("Emission"), vec![channel(Channel::Emissive)]), - (n_("Thin film"), vec![missing(n_("Thin film weight")), missing(n_("Thin film thickness"))]), + (n_("Thin film"), vec![channel(Channel::ThinFilmWeight), missing(n_("Thin film thickness"))]), ( n_("Geometry"), - vec![channel(Channel::Opacity), channel(Channel::Height), channel(Channel::Normal), missing(n_("Tangent")), channel(Channel::AmbientOcclusion)], + vec![channel(Channel::Opacity), channel(Channel::Height), channel(Channel::Normal), channel(Channel::Tangent), channel(Channel::AmbientOcclusion)], ), - (n_("Other"), vec![channel(Channel::Glossiness), channel(Channel::Specular)]), + ( + n_("Other"), + [ + Channel::BlendingMask, + Channel::Diffuse, + Channel::Displacement, + Channel::Glossiness, + Channel::Ior, + Channel::Reflection, + Channel::Specular, + Channel::Transmissive, + ] + .map(channel) + .to_vec(), + ), + (n_("User"), Channel::ALL.into_iter().filter(|c| c.id().starts_with("user")).map(channel).collect()), ] }); diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs index 6c5bcf37..af802e7e 100644 --- a/crates/ui-egui/src/export_templates/planned_output.rs +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -6,8 +6,8 @@ pub(super) struct PlannedOutput { pub(super) file: String, /// The picture shows the full atlas while export writes individual tiles pub(super) tiled: bool, - /// Pixels per side (export.plan never plans an atlas, so every file is square) - pub(super) size: u64, + /// Planned file width and height in pixels + pub(super) dimensions: (u64, u64), pub(super) format: Option, pub(super) bit_depth: u8, pub(super) dithering: bool, diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c346d033..aa3fc82b 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -400,9 +400,15 @@ fn size_label(size: u32) -> String { } } -/// A size as a texture set page shows it: "1024x1024", marked when it is the set's own -fn set_size_label(size: u32, own: u32) -> String { - if size == own { trf("{n}x{n} (Texture Set size)", &[("n", &size)]) } else { format!("{size}x{size}") } +/// The displayed block dimensions at an export width +fn scaled_block_size(width: u32, native: (u32, u32)) -> (u32, u32) { + (width, texturecraft_engine::formats::export::scale_export_side(native.1, native.0, Some(width))) +} + +/// Display both dimensions and mark the texture set's own size +fn set_size_label(size: (u32, u32), native: (u32, u32)) -> String { + let (width, height) = size; + if size == native { trf("{width}x{height} (Texture Set size)", &[("width", &width), ("height", &height)]) } else { format!("{width}x{height}") } } /// The largest texture set's resolution @@ -448,22 +454,22 @@ fn start_export(app: &mut TextureCraftApp) { texturecraft_engine::formats::export::validate_export_paths(paths).err().map(|error| trf("Export stopped: {error}", &[("error", &error)])) }); - let e = &mut app.ui.export; - e.tab = 2; - e.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; + let export = &mut app.ui.export; + export.tab = 2; + export.console = vec![ConsoleLine::Step(tr("Preparing texture export").into())]; if let Some(error) = error { - e.console.push(ConsoleLine::Step(error.clone())); + export.console.push(ConsoleLine::Step(error.clone())); app.toast(error, true); return; } - e.job = Some(crate::state::ExportJob { + export.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, - usd_asset: e.usd_asset, - shader_parameters: e.shader_parameters, + usd_asset: export.usd_asset, + shader_parameters: export.shader_parameters, ..Default::default() }); } @@ -493,8 +499,8 @@ fn planned_names(plan: &serde_json::Value) -> impl Iterator { plan.as_array().into_iter().flatten().filter_map(|file| file.get("file").and_then(serde_json::Value::as_str)) } -fn planned_file_shapes(plan: &serde_json::Value) -> impl Iterator { - plan.as_array().into_iter().flatten().map(|file| (&file["file"], &file["size"])) +fn planned_file_shapes(plan: &serde_json::Value) -> impl Iterator { + plan.as_array().into_iter().flatten().map(|file| [&file["file"], &file["size"], &file["height"]]) } /// In the browser the textures download (one zip for several files). @@ -774,6 +780,8 @@ fn map_rows(app: &TextureCraftApp, ts: usize) -> Vec { /// The Output maps section of texture set `ts`'s page: its header, then its rows scrolling in `area` fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, area: egui::Rect) { let look = ExportLook::get(ui.ctx()); + let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; + let native = set.block_size(); let rows = map_rows(app, ts); let template = set_template(app, ts); let overrides = app.ui.export.sets.entry(ts).or_default(); @@ -806,7 +814,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePla let (rows_rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); for (index, row) in rows.iter().enumerate() { let y = rows_rect.top() + (index as f32 + 0.5) * MAP_ROW_PITCH; - map_row(ui, place, y, ts, row, overrides.maps.entry(row.map).or_default()); + map_row(ui, place, y, ts, native, row, overrides.maps.entry(row.map).or_default()); } }); }); @@ -826,7 +834,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePla } /// One Output maps row at `y`: tick, file name cut at the front, override pen, file type, the map's own size -fn map_row(ui: &mut Ui, place: PagePlace, y: f32, ts: usize, row: &MapRow, map_export: &mut MapExport) { +fn map_row(ui: &mut Ui, place: PagePlace, y: f32, ts: usize, native: (u32, u32), row: &MapRow, map_export: &mut MapExport) { let look = ExportLook::get(ui.ctx()); let check_left = place.x(MAP_CHECK_LEFT); let hit = egui::Rect::from_center_size(egui::pos2(check_left + CHECK_HIT_SIZE / 2.0 - CHECK_HIT_OVERHANG, y), vec2(CHECK_HIT_SIZE, CHECK_HIT_SIZE)); @@ -853,7 +861,7 @@ fn map_row(ui: &mut Ui, place: PagePlace, y: f32, ts: usize, row: &MapRow, map_e } None => inherited_file_type(ui, place, y, &row.inherited), } - map_size_combo(ui, size_rect, ("exp_map_size", ts, row.map), &mut map_export.size); + map_size_combo(ui, size_rect, ("exp_map_size", ts, row.map), native, &mut map_export.size); } /// A map's inherited file type: "png" and "8 bits" in their columns, one text to assistive technology @@ -869,13 +877,17 @@ fn inherited_file_type(ui: &mut Ui, place: PagePlace, y: f32, inherited: &FileTy } /// An output map's size in `rect`: the export's, or its own, which wins over it -fn map_size_combo(ui: &mut Ui, rect: egui::Rect, id: (&str, usize, usize), size: &mut Option) { - let shown = size.map_or_else(|| tr("Export size").to_string(), |side| format!("{side}x{side}")); +fn map_size_combo(ui: &mut Ui, rect: egui::Rect, id: (&str, usize, usize), native: (u32, u32), size: &mut Option) { + let label = |width| { + let (_, height) = scaled_block_size(width, native); + format!("{width}x{height}") + }; + let shown = size.map_or_else(|| tr("Export size").to_string(), label); drawn::combo(ui, rect, id, shown, |ui| { ui.selectable_value(size, None, tr("Export size")); ui.separator(); for side in SIZES { - ui.selectable_value(size, Some(side), format!("{side}x{side}")); + ui.selectable_value(size, Some(side), label(side)); } }) .response @@ -1227,17 +1239,14 @@ fn toggle(o: &mut SetExport, row: usize, from: &InheritedSettings) { /// A texture set's page from `place`: its overrides, then its output maps scrolling down to `bottom` fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, bottom: f32, builtins: &[ExportPreset]) { let Some(set) = app.session.doc.project.texture_sets.get(ts) else { return }; - let own = set.block_resolution(); - let mut from = InheritedSettings::for_texture_set(app, own); + let native = set.block_size(); + let mut from = InheritedSettings::for_texture_set(app, native.0); let (first, rest) = template_groups(app, builtins); let first: Vec<(&str, bool)> = first.into_iter().filter(|(name, _)| !NOT_PER_SET.contains(name)).collect(); let global = &app.ui.export; let inherited_file_type = if global.format.is_empty() { tr("Based on output template").to_string() } else { file_type_text(&from.file_type) }; - let inherited_size = match global.size { - 0 => set_size_label(own, own), - _ => set_size_label(from.size, own), - }; + let inherited_size = set_size_label(scaled_block_size(from.size, native), native); let inherited_padding = tr(padding_label(&global.padding)).to_string(); let look = ExportLook::get(ui.ctx()); @@ -1274,9 +1283,9 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, } if override_row(ui, place, row_y(2), tr("Size"), overrides.size.is_some(), &inherited_size, |ui, rect| { if let Some(size) = &mut overrides.size { - drawn::combo(ui, rect, "exp_set_size", set_size_label(*size, own), |ui| { + drawn::combo(ui, rect, "exp_set_size", set_size_label(scaled_block_size(*size, native), native), |ui| { for side in SIZES { - ui.selectable_value(size, side, set_size_label(side, own)); + ui.selectable_value(size, side, set_size_label(scaled_block_size(side, native), native)); } }); } @@ -1340,9 +1349,9 @@ fn success(tk: &Tokens) -> egui::Color32 { } /// The LIST OF EXPORTS tab in `body`: the file tree with each file's path as tooltip, the fold strip and the console -fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { +fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect, idle_plans: Option<&[ExportSetPlan]>) { let look = ExportLook::get(ui.ctx()); - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; // The console keeps at least its least width, the tree at least its own @@ -1353,7 +1362,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { let tree = egui::Rect::from_min_max(egui::pos2(body.left(), body.top() + 1.0), egui::pos2(strip.left() - STRIP_GAP, body.bottom())); ui.painter().rect_filled(tree, 0.0, look.chrome); ui.scope_builder(egui::UiBuilder::new().max_rect(tree), |ui| { - egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); + egui::ScrollArea::both().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tokens, idle_plans)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it @@ -1391,8 +1400,8 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui, body: egui::Rect) { for (index, line) in app.ui.export.console.iter().enumerate() { let response = match line { ConsoleLine::Step(text) => ui.label(text), - ConsoleLine::Done(text) => ui.label(RichText::new(text).color(success(&tk))), - ConsoleLine::Set(name) => ui.label(set_line(ui, name, &tk)), + ConsoleLine::Done(text) => ui.label(RichText::new(text).color(success(&tokens))), + ConsoleLine::Set(name) => ui.label(set_line(ui, name, &tokens)), }; if index + 1 == app.ui.export.console.len() { @@ -1417,19 +1426,30 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { } /// One foldable node per ticked texture set, a row per file; the columns start after the longest file name -fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { - let (sets, directory): (Vec<(usize, ExportSetPlan)>, String) = match &app.ui.export.job { - Some(job) if !job.preview.is_empty() => (job.preview.iter().cloned().enumerate().collect(), job.directory.clone()), +fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens, idle_plans: Option<&[ExportSetPlan]>) { + let planned: Vec; + let (sets, directory) = match (&app.ui.export.job, idle_plans) { + (Some(job), _) if !job.preview.is_empty() => (job.preview.as_slice(), job.directory.as_str()), + (_, Some(plans)) => (plans, app.ui.export.dir.as_str()), _ => { - let planned = export_selection(app).into_iter().filter_map(|ts| { - let params = set_params(app, ts); - plan_set(app, ts, ¶ms).map(|set| (ts, set)) - }); - (planned.collect(), app.ui.export.dir.clone()) + planned = selected_plans(app); + (planned.as_slice(), app.ui.export.dir.as_str()) } }; - let rows: Vec> = sets.iter().map(|(_, set)| tree_files(set, &directory)).collect(); - let longest = |text: fn(&TreeFile) -> &str| rows.iter().flatten().map(|file| drawn::text_width(ui, text(file), false)).fold(0.0, f32::max); + + let rows: Vec> = sets.iter().map(|set| tree_files(set, directory)).collect(); + let longest = |column: fn(&TreeFile) -> &str| { + let mut widest = 0.0_f32; + let mut previous = None; + for value in rows.iter().flatten().map(column) { + if previous != Some(value) { + widest = widest.max(drawn::text_width(ui, value, false)); + previous = Some(value); + } + } + + widest + }; let columns = { let size = TREE_FILE_INDENT + longest(|f| &f.name) + TREE_COLUMN_GAP; let format = size + longest(|f| &f.size) + TREE_COLUMN_GAP; @@ -1437,27 +1457,38 @@ fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { }; // Each set takes its header row, its files when open and a blank row - let open: Vec = sets.iter().map(|(index, _)| ui.data(|d| d.get_temp::(tree_id(ui, *index))).unwrap_or(true)).collect(); + let disclosure: Vec<_> = sets + .iter() + .enumerate() + .map(|(row, set)| { + let id = match set.index { + Some(index) => ui.scope_id().with(("exp_tree", index)), + None => ui.scope_id().with(("removed_export_set", row)), + }; + let open = ui.data(|data| data.get_temp::(id)).unwrap_or(true); + (id, open) + }) + .collect(); let row_count: usize = sets .iter() .zip(&rows) - .zip(&open) - .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) + .zip(&disclosure) + .map(|((set, files), (_, open))| 2 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) .sum(); let width = ui.available_width().max(columns[2] + longest(|file| &file.bits) + TREE_BITS_GAP); let height = TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT; let (area, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); let mut y = area.top() + TREE_TOP_PADDING; - for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { + for ((set, files), (id, open)) in sets.iter().zip(&rows).zip(disclosure) { let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); - if tree_header(ui, header, &set.name, open, tree_id(ui, *index)) { - ui.data_mut(|d| d.insert_temp(tree_id(ui, *index), !open)); + if tree_header(ui, header, &set.name, open, id) { + ui.data_mut(|data| data.insert_temp(id, !open)); } y += TREE_ROW_HEIGHT; if open { if let Err(error) = &set.files { - drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tk.danger, false); + drawn::label_at(ui, area.left() + TREE_FILE_INDENT, y + TREE_ROW_HEIGHT / 2.0, error, tokens.danger, false); y += TREE_ROW_HEIGHT; } for file in files { @@ -1469,6 +1500,16 @@ fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { } } +fn selected_plans(app: &mut TextureCraftApp) -> Vec { + export_selection(app) + .into_iter() + .filter_map(|index| { + let params = set_params(app, index); + plan_set(app, index, ¶ms) + }) + .collect() +} + fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) -> Option { let set = app.session.doc.project.texture_sets.get(index)?; let name = set.name.clone(); @@ -1477,11 +1518,6 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) Some(ExportSetPlan { index: Some(index), name, files }) } -/// Where a texture set's node keeps whether it is open -fn tree_id(ui: &Ui, index: usize) -> egui::Id { - ui.scope_id().with(("exp_tree", index)) -} - /// The texts of each file `set` plans: name, size, file type, bit depth and its whole path fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { let Ok(files) = &set.files else { return Vec::new() }; @@ -1491,8 +1527,10 @@ fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { let format = FileFormat::from_extension(output.get("format").and_then(serde_json::Value::as_str).unwrap_or_default()); let depth = output.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; let dithering = output.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let size = output["size"].as_u64().unwrap_or_default() as u32; - let source_size = output["sourceSize"].as_u64().unwrap_or_default() as u32; + let dimension = |key: &str| output[key].as_u64().unwrap_or_default() as u32; + let size = (dimension("size"), dimension("height")); + let source_size = (dimension("sourceSize"), dimension("sourceHeight")); + TreeFile { name: file.to_string(), size: set_size_label(size, source_size), @@ -1511,6 +1549,7 @@ fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui:: // Expose the hand-drawn header as a disclosure control response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); let y = rect.center().y; let chevron = if open { @@ -1734,7 +1773,7 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { } /// The bottom bar: Export, Save settings, Cancel and the texture count, Reset all on SETTINGS; while exporting, progress -fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) { +fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do_export: &mut bool, canceled: &mut bool) -> Option> { let slot = |k: f32| { let right = window.right() - RIGHT_MARGIN - k * (FOOTER_BUTTON_WIDTH + FOOTER_BUTTON_GAP); drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, y) @@ -1749,7 +1788,7 @@ fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do let look = ExportLook::get(ui.ctx()); let response = ui.put(bar, egui::ProgressBar::new(progress).fill(look.outline).text(format!("{:.0}%", progress * 100.0))); ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(egui::accesskit::Live::Polite)); - return; + return None; } // OUTPUT TEMPLATES shows no count; a template edit that does not validate holds Save and Export @@ -1770,9 +1809,20 @@ fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do if cancel.on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { *canceled = true; } + let list_plans = (app.ui.export.tab == 2).then(|| selected_plans(app)); if !templates_tab { + let texture_count = match &list_plans { + Some(plans) => plans + .iter() + .try_fold(0, |count, set| { + let files = set.files.as_ref().ok()?; + Some(count + files.as_array().map_or(0, Vec::len)) + }) + .unwrap_or(0), + None => selected_texture_count(app), + }; let look = ExportLook::get(ui.ctx()); - let count = trf("{n} textures selected for export", &[("n", &selected_texture_count(app))]); + let count = trf("{n} textures selected for export", &[("n", &texture_count)]); let left = slot(2.0).left() - COUNT_GAP - drawn::text_width(ui, &count, false); drawn::label_at(ui, left, y, &count, look.text_dim, false); } @@ -1782,10 +1832,12 @@ fn footer(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, y: f32, do && drawn::button(ui, reset_rect, tr("Reset all"), false, true).on_hover_text(tr("Restore the export defaults and select every texture")).clicked() { // Keep ownership so Cancel can restore the opening settings - let e = &mut app.ui.export; - let (opened_with, owner, owner_id) = (e.opened_with.take(), std::mem::take(&mut e.owner), e.owner_id); + let export = &mut app.ui.export; + let (opened_with, owner, owner_id) = (export.opened_with.take(), std::mem::take(&mut export.owner), export.owner_id); app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; } + + list_plans } /// The SETTINGS tab in `body`: the texture set list, a divider, then the selected page @@ -1826,13 +1878,13 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { crate::export_templates::clear_map_previews(ctx); // The window opens on SETTINGS again; an export stops with it - let e = &mut app.ui.export; - e.job = None; - e.ask = None; - e.pending_drop = None; - e.opened_with = None; - e.tab = 0; - e.page = None; + let export = &mut app.ui.export; + export.job = None; + export.ask = None; + export.pending_drop = None; + export.opened_with = None; + export.tab = 0; + export.page = None; return; } @@ -1921,7 +1973,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let footer_y = window.bottom() - FOOTER_MIDDLE_FROM_BOTTOM; drawn::divider(ui, egui::Rect::from_min_max(body.left_bottom(), body.right_bottom() + vec2(0.0, 1.0))); - footer(app, ui, window, footer_y, &mut do_export, &mut canceled); + let list_plans = footer(app, ui, window, footer_y, &mut do_export, &mut canceled); // The tabs lay out from the body; a child clips what an overflow would draw past it let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); @@ -1929,7 +1981,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let ui = &mut body_ui; match app.ui.export.tab { 1 => crate::export_templates::tab(app, ui, body, presets), - 2 => list_tab(app, ui, body), + 2 => list_tab(app, ui, body, list_plans.as_deref()), _ => settings_tab(app, ui, body, presets), } }); diff --git a/crates/ui-egui/src/filter_properties.rs b/crates/ui-egui/src/filter_properties.rs index 1de8341b..d962d2c2 100644 --- a/crates/ui-egui/src/filter_properties.rs +++ b/crates/ui-egui/src/filter_properties.rs @@ -86,7 +86,7 @@ fn attributes(app: &TextureCraftApp, sheet: &mut PropertySheet<'_>, def: Option< sheet.attribute(tr("Tags"), &about.tags.iter().map(|tag| tr(tag)).collect::>().join(", ")); } if let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) { - sheet.attribute(tr("Size"), &format!("{0} × {0}", texture_set.resolution)); + sheet.attribute(tr("Size"), &format!("{} × {}", texture_set.resolution, texture_set.height())); } } diff --git a/crates/ui-egui/src/fonts.rs b/crates/ui-egui/src/fonts.rs index 2bf2dba0..88909259 100644 --- a/crates/ui-egui/src/fonts.rs +++ b/crates/ui-egui/src/fonts.rs @@ -23,11 +23,109 @@ pub struct CraftFont { pub style: &'static str, /// ISO 15924 scripts the font is for, e.g. `"Jpan"`. pub scripts: &'static [&'static str], - pub bytes: &'static [u8], + /// The font file; deflated in a web build, where the data is part of the download (see `deflated`). + data: &'static [u8], + deflated: bool, +} + +impl CraftFont { + /// Whether this build carries no data for the font. + pub fn is_empty(&self) -> bool { + self.data.is_empty() + } + + /// The font file's bytes: borrowed as embedded, or inflated from the web build's copy. Data that does not inflate + /// gives no bytes (the font is left out), never a panic. + pub fn bytes(&self) -> std::borrow::Cow<'static, [u8]> { + if self.deflated { std::borrow::Cow::Owned(inflate(self.data)) } else { std::borrow::Cow::Borrowed(self.data) } + } + + /// The font as egui takes it, without copying an embedded one. + pub fn font_data(&self) -> FontData { + match self.bytes() { + std::borrow::Cow::Borrowed(bytes) => FontData::from_static(bytes), + std::borrow::Cow::Owned(bytes) => FontData::from_owned(bytes), + } + } } include!(concat!(env!("OUT_DIR"), "/craft_fonts.rs")); +/// Inflates a font the web build embeds deflated. Empty when the data does not inflate. +#[cfg(target_arch = "wasm32")] +fn inflate(deflated: &[u8]) -> Vec { + use std::io::Read as _; + // The largest face is under 1 MB; the bound keeps corrupt data from growing without limit. + const MAX_INFLATED_BYTES: u64 = 64 << 20; + let mut out = Vec::new(); + match flate2::read::DeflateDecoder::new(deflated).take(MAX_INFLATED_BYTES + 1).read_to_end(&mut out) { + Ok(_) if out.len() as u64 <= MAX_INFLATED_BYTES => out, + _ => Vec::new(), + } +} + +/// Adds the Phosphor icon font to `fonts`: the font itself on desktop, the web build's deflated copy there (the icon +/// font is half a megabyte of the download). Icons draw as missing-glyph boxes if the copy does not inflate. +pub(crate) fn add_icon_font(fonts: &mut egui::FontDefinitions) { + #[cfg(not(target_arch = "wasm32"))] + egui_phosphor::add_to_fonts(fonts, egui_phosphor::Variant::Regular); + #[cfg(target_arch = "wasm32")] + { + static PHOSPHOR: std::sync::OnceLock<&'static [u8]> = std::sync::OnceLock::new(); + let bytes = PHOSPHOR.get_or_init(|| Vec::leak(inflate(include_bytes!(concat!(env!("OUT_DIR"), "/Phosphor.ttf.deflate"))))); + if bytes.is_empty() { + log::warn!("the icon font did not inflate; icons show as boxes"); + } else { + egui_phosphor::add_font_bytes_to_fonts(fonts, "phosphor", bytes); + } + } +} + +/// egui's default fonts (Hack, Ubuntu Light and egui's icons, in egui's family order). The web build takes them from +/// craft-ui's deflated copies instead of egui's `default_fonts` feature, which would embed a second, raw copy, and it +/// hands the engine its built-in text fonts from the same copies. +pub(crate) fn egui_default_definitions() -> egui::FontDefinitions { + #[cfg(not(target_arch = "wasm32"))] + { + egui::FontDefinitions::default() + } + #[cfg(target_arch = "wasm32")] + { + texturecraft_engine::text_cmds::provide_built_in_fonts(engine_fonts); + let mut fonts = craft_ui::fonts::deflated_default_definitions(); + // craft-ui's Inter: TextureCraft adds its own (`theme::font_definitions`) and its own semibold family. + for name in ["Inter-Regular", "Inter-SemiBold"] { + fonts.font_data.remove(name); + } + fonts.families.remove(&FontFamily::Name(craft_ui::fonts::SEMIBOLD.into())); + let known: Vec = fonts.font_data.keys().cloned().collect(); + for list in fonts.families.values_mut() { + list.retain(|name| known.contains(name)); + } + fonts + } +} + +/// The engine's built-in text fonts, Ubuntu Light and Hack, copied once from the deflated defaults. Empty when a face +/// is unavailable (the text command then reports the font as unusable). +#[cfg(target_arch = "wasm32")] +fn engine_fonts() -> [&'static [u8]; 2] { + let fonts = craft_ui::fonts::deflated_default_definitions(); + let face = |name: &str| -> &'static [u8] { + match fonts.font_data.get(name) { + Some(data) => Vec::leak((*data.font).as_ref().to_vec()), + None => &[], + } + }; + [face("Ubuntu-Light"), face("Hack")] +} + +/// Only the web build embeds deflated data. +#[cfg(not(target_arch = "wasm32"))] +fn inflate(_deflated: &[u8]) -> Vec { + Vec::new() +} + /// Skip absurdly large files (a corrupt or non-font path must not eat memory). #[cfg(not(target_arch = "wasm32"))] const MAX_FONT_BYTES: u64 = 128 << 20; @@ -186,8 +284,8 @@ impl UiFonts { /// The first available font for `script`: craft-fonts' (embedded), then the system's. fn load(script: Script) -> Option { - if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.bytes.is_empty()) { - return Some(aligned(FontData::from_static(f.bytes))); + if let Some(f) = CRAFT_FONTS.iter().find(|f| f.scripts.contains(&script.iso()) && f.style == "Regular" && !f.is_empty()) { + return Some(aligned(f.font_data())); } #[cfg(not(target_arch = "wasm32"))] for (path, index) in script.system_files() { diff --git a/crates/ui-egui/src/framework.rs b/crates/ui-egui/src/framework.rs index 22c87109..7a08c986 100644 --- a/crates/ui-egui/src/framework.rs +++ b/crates/ui-egui/src/framework.rs @@ -122,6 +122,10 @@ impl TextureCraftApp { Brightness::Dark | Brightness::MediumDark => craft_theme::Mode::Dark, }; let mut root = RootEnv::new().mode(mode).scale(Scale::new(scale)); + if let Some(theme) = crate::library_theme::library_theme(ctx, &crate::theme::Tokens::get(ctx)) { + root = root.library_theme(theme); + } + // Hide UI on another key leaves Tab to focus traversal and the shortcuts root.tab_toggles_chrome = crate::keymap::shortcut_of(&self.ui.keymap, "ui.hideUi") == Some("Tab"); let app_modal = crate::docking::input_blocked(self, ctx).then_some(ViewportId::ROOT); diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index e9460184..87e7e17f 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -9,7 +9,7 @@ use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor use rayon::prelude::*; use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, kinds_for, tile_bytes}; -use texturecraft_engine::core::{BakedMap, Channel, LayerId}; +use texturecraft_engine::core::{AoMixing, BakedMap, Channel, LayerId}; use texturecraft_engine::geom::Mesh; use texturecraft_render::{BakeVisualization, CageGeometry, Frame, Renderer, wgpu}; @@ -260,6 +260,7 @@ impl GpuLink { let empty = Default::default(); let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); let composite = &cache.composite; + let ao_mixing = session.doc.project.texture_sets.get(texture_set).map_or(AoMixing::Multiply, |set| set.ao_mixing); let channels: Vec = composite.channels.keys().copied().collect(); let sent = self.sent.entry(texture_set).or_default(); let kinds: Vec = @@ -271,7 +272,7 @@ impl GpuLink { let bytes: Vec<_> = chunk .par_iter() .flat_map_iter(|&(tile_x, tile_y)| kinds.iter().map(move |&kind| (kind, tile_x, tile_y))) - .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, kind, tile_x, tile_y))) + .map(|(kind, tile_x, tile_y)| (texture_set, kind, tile_x, tile_y, tile_bytes(composite, baked, ao_mixing, kind, tile_x, tile_y))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index e9cc27f4..dc239fe8 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -9,7 +9,7 @@ include!(concat!(env!("OUT_DIR"), "/craft_i18n.rs")); static I18N: LazyLock = LazyLock::new(|| { let offered: Vec<_> = LANGUAGES.iter().map(|l| l.code).collect(); - let (i18n, problems) = craft_i18n::I18n::new(CRAFT_I18N, &offered); + let (i18n, problems) = craft_i18n::I18n::new(craft_i18n_catalogs(), &offered); for problem in problems { log::warn!("translation catalog: {problem}"); } @@ -377,7 +377,7 @@ mod tests", let keys = keys(); assert!(keys.len() > 300, "found only {} keys", keys.len()); let used: BTreeSet<_> = keys.iter().map(String::as_str).collect(); - for &(locale, common, app) in CRAFT_I18N { + for &(locale, common, app) in craft_i18n_catalogs() { let Some(lang) = I18N.from_code(locale) else { continue }; let missing: Vec<_> = keys.iter().filter(|key| I18N.get(lang, "", key).is_none()).collect(); diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 7d9be266..cdf46547 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -698,9 +698,9 @@ pub fn fixed_gestures() -> Vec<(String, String)> { (tr("Ctrl + RMB drag").into(), tr("Brush size (left/right) and hardness (up/down)").into()), (tr("Ctrl + LMB drag").into(), tr("Brush flow (left/right) and angle (up/down)").into()), (tr("Ctrl + Shift + RMB drag").into(), tr("Brush size and hardness in fine steps").into()), - (keyed("{key} + LMB drag"), tr("Projection: rotate the stencil").into()), - (keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()), - (keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()), + (keyed("{key} + LMB drag"), tr("Rotate the stencil").into()), + (keyed("{key} + RMB drag"), tr("Scale the stencil").into()), + (keyed("{key} + MMB drag"), tr("Move the stencil").into()), (trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()), (tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()), (tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()), @@ -733,7 +733,7 @@ mod tests { let rows = fixed_gestures(); let has = |gesture: &str, what: &str| rows.iter().any(|(g, w)| g == gesture && w.contains(what)); let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name()); - assert!(has(&format!("{s} + LMB drag"), "rotate") && has(&format!("{s} + RMB drag"), "scale") && has(&format!("{s} + MMB drag"), "move")); + assert!(has(&format!("{s} + LMB drag"), "Rotate") && has(&format!("{s} + RMB drag"), "Scale") && has(&format!("{s} + MMB drag"), "Move")); assert!(has(&format!("{v} + LMB"), "Clone")); for (gesture, what) in [ ("Shift + LMB", "straight line"), diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 83e028db..957293af 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -22,11 +22,11 @@ mod item_icon; mod menu_icon; mod pick; -use add_item::AddItem; +pub(crate) use add_item::AddItem; use bitmap_choice::BitmapChoice; -use item_icon::ItemIcon; -use menu_icon::MenuIcon; -use pick::Pick; +pub(crate) use item_icon::ItemIcon; +pub(crate) use menu_icon::MenuIcon; +pub(crate) use pick::Pick; /// The row's height and its controls' height const BAR_HEIGHT: f32 = 40.0; @@ -64,7 +64,7 @@ const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP; const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; /// A hanging menu: its caption, rows, icon and text columns and its smallest width -const MENU_PADDING: f32 = 4.0; +pub(crate) const MENU_PADDING: f32 = 4.0; const MENU_CAPTION_HEIGHT: f32 = 22.0; const MENU_CAPTION_X: f32 = 12.0; const MENU_CAPTION_SIZE: f32 = 10.0; @@ -201,7 +201,15 @@ const TAB_SEAM_COVER: f32 = 2.5; const TAB_BORDER_WIDTH: f32 = 1.0; /// A button with its icon and a caret whose menu hangs from it (caption, then the `items` built while it is open); the item picked -fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &str, items: impl FnOnce() -> Vec, tokens: &Tokens) -> Option { +pub(crate) fn menu_button( + ui: &mut Ui, + rect: Rect, + label: &str, + icon: MenuIcon, + caption: &str, + items: impl FnOnce() -> Vec, + tokens: &Tokens, +) -> Option { let response = tip_above(ui.interact(rect, ui.scope_id().with(("layer_toolbar_menu", label)), Sense::click()), label); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); let popup = ui.scope_id().with(("layer_toolbar_menu_popup", label)); @@ -215,11 +223,7 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s // A click opens the menu this frame let items = if open || response.clicked() { items() } else { Vec::new() }; let width = menu_width(ui, &items); - let frame = Frame::NONE - .fill(tokens.chrome) - .stroke(Stroke::new(1.0, tokens.field_border)) - .corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) }) - .shadow(Shadow { offset: SHADOW_OFFSET, blur: 0, spread: 0, color: HARD_SHADOW }); + let frame = menu_frame(tokens).corner_radius(CornerRadius { nw: 0, ..CornerRadius::same(MENU_ROUNDING) }); let mut picked = None; let shown = egui::Popup::menu(&response).id(popup).align(egui::RectAlign::BOTTOM_START).gap(MENU_TAB_OVERLAP).frame(frame).width(width).show(|ui| { ui.set_width(width); @@ -256,6 +260,16 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s picked } +/// The toolbar menus' frame: chrome fill, field border, hard shadow +pub(crate) fn menu_frame(tokens: &Tokens) -> Frame { + Frame::NONE.fill(tokens.chrome).stroke(Stroke::new(1.0, tokens.field_border)).corner_radius(CornerRadius::same(MENU_ROUNDING)).shadow(Shadow { + offset: SHADOW_OFFSET, + blur: 0, + spread: 0, + color: HARD_SHADOW, + }) +} + /// A menu button's icon and caret fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) { let icon_at = pos2(rect.left() + MENU_ICON_X, rect.center().y); @@ -269,7 +283,7 @@ fn button_face(painter: &Painter, rect: Rect, icon: MenuIcon, tokens: &Tokens) { } /// The menu's width: its longest item, with room for the icons and the right edge -fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { +pub(crate) fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { let widest = items .iter() .map(|item| ui.fonts_mut(|fonts| fonts.layout_no_wrap(tr(item.short).to_owned(), FontId::proportional(TEXT_SIZE), Color32::WHITE).size().x)) @@ -278,7 +292,7 @@ fn menu_width(ui: &Ui, items: &[AddItem]) -> f32 { } /// One menu row: hover face, icon, name; dim and unclickable when it can't go where the selection is -fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response { +pub(crate) fn menu_row(ui: &mut Ui, width: f32, item: &AddItem, tokens: &Tokens) -> Response { let sense = if item.enabled { Sense::click() } else { Sense::hover() }; let (rect, response) = ui.allocate_exact_size(vec2(width, MENU_ROW), sense); let label = tr(item.short); diff --git a/crates/ui-egui/src/layer_toolbar/add_item.rs b/crates/ui-egui/src/layer_toolbar/add_item.rs index 8e44a94c..004940bb 100644 --- a/crates/ui-egui/src/layer_toolbar/add_item.rs +++ b/crates/ui-egui/src/layer_toolbar/add_item.rs @@ -3,12 +3,12 @@ use serde_json::Value; use super::ItemIcon; /// One item of the Add effect or Add mask menu -pub(super) struct AddItem { - pub(super) icon: ItemIcon, +pub(crate) struct AddItem { + pub(crate) icon: ItemIcon, /// The toolbar menu's name (the button says "Add effect" / "Add mask") and the layer context menu's - pub(super) short: &'static str, - pub(super) long: &'static str, - pub(super) command: &'static str, - pub(super) params: Value, - pub(super) enabled: bool, + pub(crate) short: &'static str, + pub(crate) long: &'static str, + pub(crate) command: &'static str, + pub(crate) params: Value, + pub(crate) enabled: bool, } diff --git a/crates/ui-egui/src/layer_toolbar/item_icon.rs b/crates/ui-egui/src/layer_toolbar/item_icon.rs index b5875428..3a7e301f 100644 --- a/crates/ui-egui/src/layer_toolbar/item_icon.rs +++ b/crates/ui-egui/src/layer_toolbar/item_icon.rs @@ -1,6 +1,6 @@ /// What an Add menu item shows at its left #[derive(Clone, Copy)] -pub(super) enum ItemIcon { +pub(crate) enum ItemIcon { Glyph(&'static str), /// A gray swatch (Add mask's White and Black) Swatch(u8), diff --git a/crates/ui-egui/src/layer_toolbar/menu_icon.rs b/crates/ui-egui/src/layer_toolbar/menu_icon.rs index adfcff01..1ef5b5aa 100644 --- a/crates/ui-egui/src/layer_toolbar/menu_icon.rs +++ b/crates/ui-egui/src/layer_toolbar/menu_icon.rs @@ -1,6 +1,6 @@ /// The icon of a menu button #[derive(Clone, Copy)] -pub(super) enum MenuIcon { +pub(crate) enum MenuIcon { Glyph(&'static str), /// Add mask's square, half of it filled corner to corner Mask, diff --git a/crates/ui-egui/src/layer_toolbar/pick.rs b/crates/ui-egui/src/layer_toolbar/pick.rs index 743293e0..4c5b189c 100644 --- a/crates/ui-egui/src/layer_toolbar/pick.rs +++ b/crates/ui-egui/src/layer_toolbar/pick.rs @@ -1,7 +1,7 @@ use serde_json::Value; /// What a click in one of the row's menus asks for, done once the menu has closed -pub(super) enum Pick { +pub(crate) enum Pick { Run { command: &'static str, params: Value }, Bitmap, } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index bb25f49c..cec3e28b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,8 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod alpha_choice; +mod alpha_sheet; mod anchor_properties; mod angle_dial; mod ask; @@ -20,6 +22,10 @@ pub mod bake_presets; mod bake_report; mod bake_scene; pub mod baking_log; +mod brush_pictures; +mod brush_sheet; +mod brush_stroke_preview; +mod channel_manager; mod color_management; mod color_picker; mod color_selection_editor; @@ -79,6 +85,7 @@ mod levels_display; mod levels_editor; mod levels_handle; mod levels_properties; +mod library_theme; mod line_snap; mod list_action; pub mod log_panel; @@ -90,6 +97,7 @@ mod mask_preview_image; mod mask_source_choice; mod material_orb; mod material_preview_image; +mod material_sheet; pub mod menus; mod mesh_export_options; #[cfg(not(target_arch = "wasm32"))] @@ -109,6 +117,7 @@ pub mod orb_previews; mod orb_shape; /// The channel's OS identity (app id, window and app names) — see its module docs. pub mod os_window; +mod paint_section; mod pane_split; pub mod parity; mod past_end; @@ -185,8 +194,13 @@ mod soft_box; mod source_choice; mod source_slot; pub mod state; +mod stencil_choice; +mod stencil_sheet; mod surface_paint_point; pub mod symmetry; +mod tabbed_page; +mod texture_set_list; +mod texture_set_settings; pub mod theme; pub mod thumbs; mod tile_edits; @@ -383,9 +397,12 @@ pub struct TextureCraftApp { /// When the next autosave is due (seconds of app time; desktop only). #[cfg_attr(target_arch = "wasm32", allow(dead_code))] next_autosave: f64, - /// The unsaved project (its id) and the suffix of its autosave copy. + /// The unsaved project (its id) and the stable filename of its autosave copy. #[cfg(not(target_arch = "wasm32"))] - unsaved_autosave_suffix: Option<(u64, u64)>, + unsaved_autosave_file: Option<(u64, String)>, + /// The dialog opening that owns the Project name widget's undo state. + #[cfg(not(target_arch = "wasm32"))] + project_name_editor_opening: Option, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -537,7 +554,9 @@ impl TextureCraftApp { last_time: 0.0, next_autosave, #[cfg(not(target_arch = "wasm32"))] - unsaved_autosave_suffix: None, + unsaved_autosave_file: None, + #[cfg(not(target_arch = "wasm32"))] + project_name_editor_opening: None, styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] @@ -585,6 +604,9 @@ impl TextureCraftApp { } } + // The desktop launcher can supply an already-open autosave copy + app.detach_autosave_copy(); + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); @@ -666,6 +688,9 @@ impl TextureCraftApp { None => self.settle_camera_glide(id, before), } + #[cfg(not(target_arch = "wasm32"))] + let value = self.recover_file_open(id, value); + Some(value) } Err(error) => { @@ -1055,14 +1080,22 @@ impl TextureCraftApp { } } - /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when - /// it is done, as one undo step). - pub fn start_resize(&mut self, ts: usize, resolution: u32) { + /// Resize texture set `ts` to `width` texels across on a worker thread, keeping its shape: one undo step once done + pub fn start_resize(&mut self, ts: usize, width: u32) { + let height = self.session.doc.project.texture_set(ts).map_or(width, |set| { + let scaled = u64::from(set.height()) * u64::from(width) / u64::from(set.resolution.max(1)); + u32::try_from(scaled).unwrap_or(u32::MAX) + }); + self.start_resize_to(ts, width, height); + } + + /// [`Self::start_resize`] to `width` by `height` + pub fn start_resize_to(&mut self, ts: usize, width: u32, height: u32) { if self.resize.is_some() { return; } - match self.session.resize_task(ts, resolution) { + match self.session.resize_task_to(ts, width, height) { Ok(task) => { let progress = Arc::new(Progress::new()); let p = progress.clone(); diff --git a/crates/ui-egui/src/library_theme.rs b/crates/ui-egui/src/library_theme.rs new file mode 100644 index 00000000..38f24b65 --- /dev/null +++ b/crates/ui-egui/src/library_theme.rs @@ -0,0 +1,52 @@ +//! TextureCraft's colours handed to craft-ui, so the dock's frames, tab strips and splitters draw in our theme instead of the suite's default grey + +use std::sync::Arc; + +use craft_theme::{ColorToken, ModePins, Pins, Rgba, SUITE_DEFAULT, ThemeDef, ThemeId, builtins}; +use egui::{Color32, Context, Id}; + +use crate::theme::Tokens; + +/// The id of TextureCraft's theme, apart from every built-in one +const THEME_ID: &str = "texturecraft.app"; + +/// The theme craft-ui resolves its tokens from (`RootEnv::library_theme`), kept while the tokens stay the same so it resolves once per theme change +pub(crate) fn library_theme(ctx: &Context, tokens: &Tokens) -> Option> { + let pins = app_pins(tokens); + let memory_id = Id::unique(THEME_ID); + let kept: Option> = ctx.data(|data| data.get_temp(memory_id)); + if let Some(def) = kept.filter(|def| def.pins.dark == pins) { + return Some(def); + } + + let def = Arc::new(app_def(pins)?); + ctx.data_mut(|data| data.insert_temp(memory_id, Arc::clone(&def))); + Some(def) +} + +/// The suite default with TextureCraft's colours pinned in both modes (the root's mode picks one); `None` if the suite default is missing +fn app_def(pins: Pins) -> Option { + let mut def = builtins().iter().find(|theme| theme.id.as_str() == SUITE_DEFAULT)?.clone(); + def.id = ThemeId::parse(THEME_ID).ok()?; + def.pins = ModePins { light: pins.clone(), dark: pins }; + Some(def) +} + +fn app_pins(tokens: &Tokens) -> Pins { + [ + (ColorToken::SurfaceBackground, rgba(tokens.chrome)), + (ColorToken::SurfacePanel, rgba(tokens.panel)), + (ColorToken::LineBorder, rgba(tokens.separator)), + (ColorToken::AccentSolid, rgba(tokens.accent)), + // The shown tab's name is brighter than the others, as on the panel headers + (ColorToken::TextNormal, rgba(tokens.text_strong)), + (ColorToken::TextMuted, rgba(tokens.text_dim)), + ] + .into_iter() + .collect() +} + +fn rgba(color: Color32) -> Rgba { + let [r, g, b, a] = color.to_srgba_unmultiplied(); + Rgba([r, g, b, a]) +} diff --git a/crates/ui-egui/src/link_import.rs b/crates/ui-egui/src/link_import.rs index d245ecc5..063584fe 100644 --- a/crates/ui-egui/src/link_import.rs +++ b/crates/ui-egui/src/link_import.rs @@ -18,7 +18,8 @@ pub(super) struct LinkImport { mesh: u64, canceled: Arc, set: usize, - resolution: u32, + /// The set's size when the import started: a resize cancels it + size: (u32, u32), place: Place, result: Receiver>, } @@ -53,7 +54,7 @@ impl TextureCraftApp { ), explicit => explicit, }; - let resolution = texture_set.resolution; + let (resolution, size) = (texture_set.resolution, texture_set.size()); let baked = self.session.baked(set).cloned(); let path = PathBuf::from(path); let canceled = Arc::new(AtomicBool::new(false)); @@ -65,7 +66,7 @@ impl TextureCraftApp { // A pending installation only needs its source package and cooked outputs Ok((source.package, source.source_ext, cooked)) }); - self.link_imports.push(LinkImport { project: self.session.project_id, mesh: self.session.mesh_id, canceled, set, resolution, place, result: rx }); + self.link_imports.push(LinkImport { project: self.session.project_id, mesh: self.session.mesh_id, canceled, set, size, place, result: rx }); self.toast("Cooking MaterialCraft material", false); Some(json!({"pending":true})) } @@ -83,7 +84,7 @@ impl TextureCraftApp { for mut job in std::mem::take(&mut self.link_imports) { if job.project != self.session.project_id || job.mesh != self.session.mesh_id - || !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.resolution == job.resolution) + || !self.session.doc.project.texture_set(job.set).is_ok_and(|set| set.size() == job.size) { self.toast("Material import canceled because the target texture set changed", true); continue; diff --git a/crates/ui-egui/src/log_panel.rs b/crates/ui-egui/src/log_panel.rs index 06134c0e..bfb1d16e 100644 --- a/crates/ui-egui/src/log_panel.rs +++ b/crates/ui-egui/src/log_panel.rs @@ -25,7 +25,7 @@ const LIST_SCROLLBAR_INNER_MARGIN: f32 = 1.0; /// A newly focused row of a list scrolls in with a neighbour on each side: only shown rows are laid out, so Tab needs the next one there pub(crate) fn reveal_focused_row(ui: &Ui, response: &egui::Response, row: egui::Rect) { if response.gained_focus() { - // The shown width, so the list never moves sideways + // Restrict focus reveal to vertical scrolling let around = egui::Rect::from_x_y_ranges(ui.clip_rect().x_range(), row.y_range()).expand2(egui::vec2(0.0, row.height())); ui.scroll_to_rect_animation(around, None, egui::style::ScrollAnimation::none()); } @@ -52,7 +52,7 @@ pub(crate) fn panel_rows( let visuals = ui.visuals_mut(); visuals.extreme_bg_color = tokens.field; - // The thumb stands 3:1 or more off its track in every theme, brighter under the pointer + // Use text colors to keep the thumb distinct from the track visuals.widgets.inactive.bg_fill = tokens.text_dim; visuals.widgets.hovered.bg_fill = tokens.text; visuals.widgets.active.bg_fill = tokens.text; @@ -81,13 +81,14 @@ const LINE_TEXT_LEFT: f32 = 6.0; /// The General and Assets tabs, splitting the panel's width; returns the open tab's rectangle fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) -> Rect { - // The panel's own margin is above the tabs; the strip adds the rest of the inset + // Count the panel margin toward the tab inset ui.add_space(PANEL_INSET - f32::from(crate::docking::LIST_PANEL_MARGIN.top)); let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), TAB_HEIGHT), Sense::hover()); let strip = strip.shrink2(vec2(PANEL_INSET, 0.0)); let tab_width = strip.width() / LogChannel::ALL.len() as f32; let outline = Stroke::new(1.0, tokens.field_border); let mut open_tab = strip; + for (slot, channel) in LogChannel::ALL.into_iter().enumerate() { let rect = Rect::from_min_size(strip.min + vec2(slot as f32 * tab_width, 0.0), vec2(tab_width, TAB_HEIGHT)); let response = ui.interact(rect, ui.make_persistent_id(("log-tab", channel.name())), Sense::click()); @@ -115,16 +116,16 @@ fn channel_tabs(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) -> Rect open_tab } -/// A line as its row shows it: a message's line breaks become spaces, so it stays on its one row -fn row_text(entry: &LogEntry) -> String { - entry.line().replace(['\r', '\n'], " ") +/// Flatten embedded line breaks for layout while leaving the stored message intact for copy +fn row_text(line: String) -> String { + if line.contains(['\r', '\n']) { line.replace(['\r', '\n'], " ") } else { line } } /// One Log line across the list: one row, never wrapped, banded while selected fn log_line(ui: &mut Ui, tokens: &Tokens, index: usize, entry: &LogEntry, selected: bool) -> egui::Response { let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), LINE_HEIGHT), Sense::hover()); - // A row is as wide as the widest line: only its shown part takes clicks, so its middle is on screen + // Hit testing and accessibility bounds use the visible portion of a wide row let response = ui.interact(rect.intersect(ui.clip_rect()), ui.make_persistent_id(("log-line", index)), Sense::click()); let line = entry.line(); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &line)); @@ -138,7 +139,7 @@ fn log_line(ui: &mut Ui, tokens: &Tokens, index: usize, entry: &LogEntry, select painter.rect_filled(rect, 0.0, tokens.accent_dim); } let text_at = egui::pos2(rect.left() + LINE_TEXT_LEFT, rect.center().y); - painter.text(text_at, Align2::LEFT_CENTER, row_text(entry), egui::FontId::proportional(LINE_TEXT_SIZE), level_color(tokens, entry.level)); + painter.text(text_at, Align2::LEFT_CENTER, row_text(line), egui::FontId::proportional(LINE_TEXT_SIZE), level_color(tokens, entry.level)); if response.has_focus() { crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); } @@ -283,12 +284,14 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.ui.log_anchor = None; } - // The list's box overlaps the tabs' bottom line, which is then cleared under the open tab; the panel's own margin is below it + // Overlap the tab border and count the panel margin toward the bottom inset let inset = PANEL_INSET as i8; let outer = egui::Margin { left: inset, right: inset, top: -1, bottom: inset - crate::docking::LIST_PANEL_MARGIN.bottom }; - // The 1 px inner margin keeps the rows and scrollbars off the frame's line + + // Keep rows and scrollbars clear of the frame stroke let frame = egui::Frame::new().fill(tokens.field).stroke(Stroke::new(1.0, tokens.field_border)).inner_margin(1).outer_margin(outer); frame.show(ui, |ui| entries(app, ui, &tokens)); + let joint = Rect::from_min_max(open_tab.left_bottom() + vec2(1.0, -1.0), open_tab.right_bottom() + vec2(-1.0, 0.0)); ui.painter().rect_filled(joint, 0.0, tokens.field); } @@ -307,7 +310,7 @@ fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { let shown = app.ui.log_channel; let rows = listed(app, shown); - // The empty space under the lines has the same menu as a line; the lines sit on top of it + // Put the background menu behind the row hit targets let area = ui.available_rect_before_wrap(); let pass = ui.ctx().cumulative_pass_nr(); ui.ctx().data_mut(|data| data.insert_temp(rect_id(), (area, ui.layer_id(), pass))); @@ -320,15 +323,21 @@ fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { } } - // Lines never wrap: the list is as wide as its widest line and scrolls sideways + // Measure the widest line to size the horizontal scroll area let font = egui::FontId::proportional(LINE_TEXT_SIZE); - let measure = |entry: &LogEntry| ui.painter().layout_no_wrap(row_text(entry), font.clone(), tokens.text).size().x; + let measure = |entry: &LogEntry| ui.painter().layout_no_wrap(row_text(entry.line()), font.clone(), tokens.text).size().x; let widest = app.ui.log_widths.widest(&app.session.log, app.session.log_id, ui.ctx().pixels_per_point(), font_key(ui), shown, measure); - let scroll_area = egui::ScrollArea::both().id_salt(("log", shown.name())).auto_shrink([false, false]).stick_to_bottom(true); + let scroll_area = egui::ScrollArea::both() + .id_salt(("log", shown.name())) + .auto_shrink([false, false]) + .stick_to_bottom(true) + .horizontal_scroll_bar_label(tr("Log horizontal scrollbar")) + .vertical_scroll_bar_label(tr("Log vertical scrollbar")); panel_rows(ui, scroll_area, LINE_HEIGHT, rows.len(), |ui, range| { ui.set_min_width(widest + 2.0 * LINE_TEXT_LEFT); for index in rows[range].iter().copied() { let Some(entry) = app.session.log.get(index) else { continue }; + let response = log_line(ui, tokens, index, entry, app.ui.log_selection.contains(&index)); if response.clicked() || response.secondary_clicked() && !app.ui.log_selection.contains(&index) { let modifiers = ui.input(|input| input.modifiers); diff --git a/crates/ui-egui/src/log_panel/log_width_cache.rs b/crates/ui-egui/src/log_panel/log_width_cache.rs index 808dd651..702759d5 100644 --- a/crates/ui-egui/src/log_panel/log_width_cache.rs +++ b/crates/ui-egui/src/log_panel/log_width_cache.rs @@ -12,7 +12,7 @@ pub struct LogWidthCache { /// The newest measured line's occurrence id (ids are never reused within a log) last_occurrence: u64, /// How many lines of both tabs were measured: fewer lines in the log means some were cleared - measured: usize, + measured_entries: usize, widest: [f32; LogChannel::ALL.len()], } @@ -27,9 +27,9 @@ impl LogWidthCache { channel: LogChannel, measure: impl Fn(&LogEntry) -> f32, ) -> f32 { - let added = log.entries_after(self.last_occurrence).count(); + let appended_entries = log.entries_after(self.last_occurrence).count(); let same_measure = self.pixels_per_point == pixels_per_point && self.font_key == font_key; - if self.log_id != log_id || !same_measure || self.measured + added != log.len() { + if self.log_id != log_id || !same_measure || self.measured_entries + appended_entries != log.len() { *self = LogWidthCache { log_id, pixels_per_point, font_key, ..LogWidthCache::default() }; } @@ -37,8 +37,9 @@ impl LogWidthCache { let widest = &mut self.widest[channel_of(entry) as usize]; *widest = widest.max(measure(entry)); self.last_occurrence = occurrence; - self.measured += 1; + self.measured_entries += 1; } + self.widest[channel as usize] } } @@ -60,6 +61,7 @@ mod tests { let wide = cache.widest(&log, 1, 1.0, 1, LogChannel::General, width); log.retain(|entry| !entry.line().contains("longer")); + assert!(cache.widest(&log, 1, 1.0, 1, LogChannel::General, width) < wide); } @@ -72,6 +74,7 @@ mod tests { let mut next = SessionLog::new(); next.info("Project", "short"); + assert!(cache.widest(&next, 2, 1.0, 1, LogChannel::General, width) < wide); } @@ -83,6 +86,7 @@ mod tests { let narrow = cache.widest(&log, 1, 1.0, 1, LogChannel::General, width); let wider = |entry: &LogEntry| 2.0 * width(entry); + assert!(cache.widest(&log, 1, 1.0, 2, LogChannel::General, wider) > narrow); } } diff --git a/crates/ui-egui/src/mask_paint_panel.rs b/crates/ui-egui/src/mask_paint_panel.rs index cf12f191..7ecdfba4 100644 --- a/crates/ui-egui/src/mask_paint_panel.rs +++ b/crates/ui-egui/src/mask_paint_panel.rs @@ -1,6 +1,5 @@ -//! The paint tools' Grayscale tab while a mask is painted: the GRAYSCALE section with the slot of the gray a stroke lays down +//! The paint tools' Grayscale section while a mask is painted: the slot of the gray a stroke lays down -use egui::Ui; use egui_phosphor::regular as ic; use serde_json::json; use texturecraft_engine::Session; @@ -20,58 +19,55 @@ use crate::theme::Tokens; use crate::tile_picture::TilePicture; /// The GRAYSCALE section: a slot card for one gray (with its ramp and invert) or an image whose gray is painted -pub(crate) fn grayscale_sheet(app: &mut TextureCraftApp, ui: &mut Ui) { - PropertySheet::show(ui, "mask_paint_sheet", |sheet| { - sheet.section(tr("Grayscale"), false); - let gray = app.session.tool.mask_value; - let source = match &app.session.tool.mask_image { - Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, - None => Source::Uniform([gray; 3]), - }; - let tokens = Tokens::get(sheet.ui.ctx()); - let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); - let line = source_line(app, &source); - let image = app.session.tool.mask_image.is_some(); - let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); +pub(crate) fn grayscale_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let gray = app.session.tool.mask_value; + let source = match &app.session.tool.mask_image { + Some(name) => Source::Image { name: name.clone(), normal_format: NormalFormat::default() }, + None => Source::Uniform([gray; 3]), + }; + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source); + let line = source_line(app, &source); + let image = app.session.tool.mask_image.is_some(); + let slot = sheet.slot(&|painter, rect| paint_thumbnail(painter, rect, &picture, &tokens), tr("Grayscale"), &line, None, image, false); - let popup = sheet.ui.make_persistent_id("mask_paint_source"); - if slot.pick.clicked() { - resource_picker::toggle(sheet.ui.ctx(), popup); - } - let current = match &app.session.tool.mask_image { - Some(name) => MaskSourceChoice::Image(name.clone()), - None => MaskSourceChoice::Uniform, - }; - let ctx = sheet.ui.ctx().clone(); - let tabs = || source_tabs(&app.session, shown_color([gray; 3])); - match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { - Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), - Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { - app.run("tool.material", json!({"maskImage": name})); - } - Some(MaskSourceChoice::Uniform) if image => { - app.run("tool.material", json!({"maskImage": null})); - } - _ => {} - } - if slot.clear { - app.run("tool.material", json!({"maskImage": null})); - } - if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + let popup = sheet.ui.make_persistent_id("mask_paint_source"); + if slot.pick.clicked() { + resource_picker::toggle(sheet.ui.ctx(), popup); + } + let current = match &app.session.tool.mask_image { + Some(name) => MaskSourceChoice::Image(name.clone()), + None => MaskSourceChoice::Uniform, + }; + let ctx = sheet.ui.ctx().clone(); + let tabs = || source_tabs(&app.session, shown_color([gray; 3])); + match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(¤t), image, tabs) { + Some(MaskSourceChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(MaskSourceChoice::Image(name)) if app.session.tool.mask_image.as_deref() != Some(name.as_str()) => { app.run("tool.material", json!({"maskImage": name})); } - - if !image { - let mut value = gray; - let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); - if edit.invert { - app.run("tool.material", json!({"maskValue": 1.0 - gray})); - } else if edit.changed.is_some() { - app.run("tool.material", json!({"maskValue": value})); - } + Some(MaskSourceChoice::Uniform) if image => { + app.run("tool.material", json!({"maskImage": null})); } - sheet.close_card(); - }); + _ => {} + } + if slot.clear { + app.run("tool.material", json!({"maskImage": null})); + } + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) { + app.run("tool.material", json!({"maskImage": name})); + } + + if !image { + let mut value = gray; + let edit = sheet.ramp(tr("Grayscale"), &mut value, 0.0..=1.0); + if edit.invert { + app.run("tool.material", json!({"maskValue": 1.0 - gray})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"maskValue": value})); + } + } + sheet.close_card(); } /// The picker's one Resources tab: Textures (Import... first, then the project's images) and Uniform diff --git a/crates/ui-egui/src/material_sheet.rs b/crates/ui-egui/src/material_sheet.rs new file mode 100644 index 00000000..6ff7c5d4 --- /dev/null +++ b/crates/ui-egui/src/material_sheet.rs @@ -0,0 +1,71 @@ +//! The Material section of a brush tool's Properties: the channel strip, then one card per channel that is on with the value the brush paints there + +use serde_json::json; +use texturecraft_engine::Tool; +use texturecraft_engine::core::{Channel, ChannelKind, Source}; + +use crate::TextureCraftApp; +use crate::fill_material_panel::{pill_name, take_color_pick}; +use crate::i18n::tr; +use crate::property_sheet::PropertySheet; +use crate::slot_thumbnail::{paint_thumbnail, thumbnail}; +use crate::source_slot::SourceSlot; +use crate::theme::Tokens; + +/// The channel strip (the fill layer's pills), then a card per channel that is on; the eraser only picks channels +pub(crate) fn material_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); + let names: Vec<&str> = channels.iter().map(|channel| tr(pill_name(*channel))).collect(); + let enabled: Vec = channels.iter().map(|channel| app.session.tool.enabled.contains(channel)).collect(); + if let Some((index, solo)) = sheet.channel_pills(&names, &enabled) + && let Some(channel) = channels.get(index) + { + let enable = solo || !enabled.get(index).copied().unwrap_or(false); + app.run("tool.material", json!({"channel": channel.id(), "enabled": enable, "solo": solo})); + } + if app.session.tool.tool == Tool::Eraser { + return; + } + + let shown: Vec = channels.into_iter().filter(|channel| app.session.tool.enabled.contains(channel)).collect(); + for channel in shown { + channel_card(app, sheet, channel); + } +} + +/// One channel's card: its swatch, name and source, the ⟲ back to the channel's default, then its colour bar or gray ramp (a normal paints flat and has none) +fn channel_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, channel: Channel) { + let slot_of = SourceSlot::Channel(channel); + let kind = channel.kind(); + let default = channel.default_value(); + let value = if kind == ChannelKind::NormalMap { default } else { app.session.tool.values.get(&channel).copied().unwrap_or(default) }; + + let tokens = Tokens::get(sheet.ui.ctx()); + let picture = thumbnail(app, &sheet.ui.ctx().clone(), &Source::Uniform(value)); + let thumb = |painter: &egui::Painter, rect: egui::Rect| paint_thumbnail(painter, rect, &picture, &tokens); + let line = if kind == ChannelKind::NormalMap { tr("Flat") } else { tr("Uniform") }; + if sheet.slot_fixed(&thumb, slot_of.name(), line, value != default).reset { + app.run("tool.material", json!({"channel": channel.id(), "value": default})); + } + + match kind { + ChannelKind::Color => { + let pick = sheet.color_bar(slot_of.name(), value, app.picking_color, &app.session.doc.project.swatches); + if let Some(color) = take_color_pick(app, pick) { + app.run("tool.material", json!({"channel": channel.id(), "color": color})); + } + } + ChannelKind::Scalar | ChannelKind::Signed => { + let mut gray = value[0]; + let edit = sheet.ramp(slot_of.name(), &mut gray, slot_of.range()); + if edit.invert { + let inverted = if kind == ChannelKind::Signed { -gray } else { 1.0 - gray }; + app.run("tool.material", json!({"channel": channel.id(), "value": inverted})); + } else if edit.changed.is_some() { + app.run("tool.material", json!({"channel": channel.id(), "value": gray})); + } + } + ChannelKind::NormalMap => {} + } + sheet.close_card(); +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5e5ced92..82025444 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -468,8 +468,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // A plain Escape or Enter while no widget of TextureCraft's has the keyboard is the window's cancel or submit: back - // in egui's input, it runs the Escape and Enter handlers below, the shortcuts and the Path tool's keys + // Route unhandled window actions back through the shortcuts and Path tool for (key, taken) in [(Key::Escape, crate::framework::take_window_cancel(ctx)), (Key::Enter, crate::framework::take_window_submit(ctx))] { if taken { let escape = craft_ui::runtime::keys::escape_mods(ctx).filter(|_| key == Key::Escape); @@ -496,13 +495,18 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { }); // Let the innermost popup consume Escape before cancelling the active tool - // (the drop popup of the Output templates tab is open without registering with egui, and reads Escape itself) + // The Output templates drop popup handles Escape outside egui's popup registry let popup_open = egui::Popup::is_any_open(ctx) || app.ui.export.pending_drop.is_some(); let point_pick_armed = crate::generator_point_pick::armed(ctx).is_some(); let mut cancel_point_pick = false; let picker_open = crate::color_picker::open_window(ctx).is_some(); let nothing_focused = !crate::framework::widget_has_keyboard(ctx); + + // A dialog closes on Escape itself + let modal_open = ctx.memory(|memory| memory.top_modal_layer().is_some()); + let over_set_list = crate::texture_set_list::pointer_over(ctx); + let mut set_list_keys = (false, false); let log_copies = crate::log_panel::takes_copy(app, ctx); let commands_to_invoke = ctx.input_mut(|input| { // egui's label selection copies on these events at the end of the frame @@ -521,6 +525,13 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if app.ui.windows.export && app.ui.export.tab == 1 && app.ui.export.ask.is_none() && input.consume_key(Modifiers::NONE, Key::F2) { app.ui.export.rename_key = true; } + + // Keep the texture set list's shortcuts inactive behind a dialog + if over_set_list && !modal_open { + let menu = input.consume_key(Modifiers::SHIFT, Key::F10) || input.consume_key(Modifiers::NONE, Key::Menu); + set_list_keys = (input.consume_key(Modifiers::NONE, Key::F2), menu); + } + let commands = app.bindings.dispatch(input); for copy in copies { if !input.events.contains(©) { @@ -538,7 +549,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } let export = &app.ui.export; - let escape_is_free = !popup_open && !picker_open; + let escape_is_free = !popup_open && !picker_open && !modal_open; // Local export inputs handle Escape during drawing let export_input_active = app.ui.windows.export && (export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some()); @@ -554,8 +565,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { } else if app.ui.windows.import_resources.is_some() { #[cfg(not(target_arch = "wasm32"))] crate::import_resources::keys_in(app, input, nothing_focused, popup_open); - } else if popup_open || export_input_active { - // The open list or export input handles the key + } else if popup_open || modal_open || export_input_active { + // The open list, dialog or export input handles the key } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { @@ -582,6 +593,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if cancel_point_pick { crate::generator_point_pick::set(ctx, None); } + crate::texture_set_list::take_keys(ctx, set_list_keys.0, set_list_keys.1); for id in &commands_to_invoke { run_shortcut(app, ctx, id); diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs index d74186f0..5a2699b1 100644 --- a/crates/ui-egui/src/orb_environment.rs +++ b/crates/ui-egui/src/orb_environment.rs @@ -7,7 +7,11 @@ use texturecraft_engine::geom::glam::Vec3; use texturecraft_render::ibl::{self, EnvImage}; /// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR +#[cfg(not(target_arch = "wasm32"))] const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/hdr/studio_small_09_512.hdr"); +/// The same file deflated by build.rs: the web build's wasm is under a download budget +#[cfg(target_arch = "wasm32")] +const STUDIO_HDR_DEFLATED: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/studio_small_09_512.hdr.deflate")); /// Prefiltered levels from mirror (0) to fully rough (last) const LEVELS: u32 = 6; @@ -15,6 +19,23 @@ const LEVELS: u32 = 6; /// How far the studio is turned about the vertical axis (radians) so its key soft box lights the orb from the upper left const TURN: f32 = 4.4; +/// The bundled file's bytes +#[cfg(not(target_arch = "wasm32"))] +fn studio_hdr() -> std::borrow::Cow<'static, [u8]> { + std::borrow::Cow::Borrowed(STUDIO_HDR) +} + +/// The bundled file's bytes, inflated; none if the copy does not inflate (the studio falls back) +#[cfg(target_arch = "wasm32")] +fn studio_hdr() -> std::borrow::Cow<'static, [u8]> { + use std::io::Read as _; + let mut out = Vec::new(); + match flate2::read::DeflateDecoder::new(STUDIO_HDR_DEFLATED).take(64 << 20).read_to_end(&mut out) { + Ok(_) => std::borrow::Cow::Owned(out), + Err(_) => std::borrow::Cow::Owned(Vec::new()), + } +} + /// The prefiltered studio pub(crate) struct OrbEnvironment { /// Level `l` holds reflections for roughness `l / (LEVELS - 1)` @@ -27,7 +48,7 @@ impl OrbEnvironment { /// The studio, decoded and prefiltered by the first caller (about a tenth of a second in release) pub(crate) fn get() -> &'static OrbEnvironment { static STUDIO: OnceLock = OnceLock::new(); - STUDIO.get_or_init(|| OrbEnvironment::from_hdr(STUDIO_HDR).unwrap_or_else(OrbEnvironment::fallback)) + STUDIO.get_or_init(|| OrbEnvironment::from_hdr(&studio_hdr()).unwrap_or_else(OrbEnvironment::fallback)) } fn from_hdr(bytes: &[u8]) -> Option { diff --git a/crates/ui-egui/src/paint_section.rs b/crates/ui-egui/src/paint_section.rs new file mode 100644 index 00000000..4648658f --- /dev/null +++ b/crates/ui-egui/src/paint_section.rs @@ -0,0 +1,50 @@ +//! The sections of a paint tool's Properties, each with its jump tab + +use egui_phosphor::regular as ic; + +use crate::i18n::tr; + +/// One section of a paint tool's Properties page +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PaintSection { + Brush, + Alpha, + Stencil, + Material, + /// The Material section's place while a mask is painted + Grayscale, +} + +impl PaintSection { + /// The sections in page order: Stencil only for a tool that `uses_stencil`, Grayscale instead of Material unless `content` is painted + pub(crate) fn page(uses_stencil: bool, content: bool) -> Vec { + let mut sections = vec![PaintSection::Brush, PaintSection::Alpha]; + if uses_stencil { + sections.push(PaintSection::Stencil); + } + sections.push(if content { PaintSection::Material } else { PaintSection::Grayscale }); + sections + } + + /// The section's caption and tab name + pub(crate) fn title(self) -> &'static str { + match self { + PaintSection::Brush => tr("Brush"), + PaintSection::Alpha => tr("Alpha"), + PaintSection::Stencil => tr("Stencil"), + PaintSection::Material => tr("Material"), + PaintSection::Grayscale => tr("Grayscale"), + } + } + + /// The tab's icon + pub(crate) fn icon(self) -> &'static str { + match self { + PaintSection::Brush => ic::PAINT_BRUSH, + PaintSection::Alpha => ic::CIRCLE_HALF, + PaintSection::Stencil => ic::FRAME_CORNERS, + PaintSection::Material => ic::SPHERE, + PaintSection::Grayscale => ic::SQUARE_HALF, + } + } +} diff --git a/crates/ui-egui/src/parity.rs b/crates/ui-egui/src/parity.rs index 23316b2b..c452c978 100644 --- a/crates/ui-egui/src/parity.rs +++ b/crates/ui-egui/src/parity.rs @@ -18,7 +18,7 @@ pub const HEADLESS: &[(&str, &str, &str, &str)] = &[ ("ui.saveAsTemplate", "partial", "window", "the dialog is desktop-only; `project.template.save` saves it"), ("ui.export", "partial", "window", "the dialog is desktop-only; `file.exportTextures` exports"), ("ui.saveReduced", "no", "engine-gap", "a smaller save could be a command"), - ("ui.projectConfig", "no", "engine-gap", "project settings could be set by a command"), + ("ui.projectConfig", "partial", "window", "the dialog is desktop-only; `project.rename` sets the project name"), ("ui.recent.clear", "no", "window", "the desktop recent-projects list"), ("ui.quit", "no", "window", "quits the desktop app"), ("ui.settings", "no", "window", "the desktop settings window"), @@ -51,12 +51,15 @@ pub fn headless_of(id: &str, in_engine: bool) -> (&'static str, Option<&'static if in_engine { return ("yes", None, ""); } + if let Some(m) = HEADLESS.iter().find(|m| m.0 == id) { return (m.1, Some(m.2), m.3); } + if WINDOW_PREFIXES.iter().any(|p| id.starts_with(p)) { return ("no", Some("window"), "a desktop panel or toolbar"); } + ("unknown", None, "") } diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index b078e520..b1a8a9f7 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -158,19 +158,12 @@ pub fn image_preview(img: &ImageRes, size: usize) -> ColorImage { /// Preview the brush along an S curve in a `size_px` square pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&ImageRes>) -> ColorImage { - // Leave room around the S curve and cap work for a single preview + // Leave room around the S curve const STROKE_RADIUS_FRACTION: f32 = 0.11; - const CURVE_SAMPLE_STEP: f32 = 0.002; - const MIN_STAMP_SPACING_PX: f32 = 0.5; - const MAX_STAMPS: u32 = 2000; const CURVE_HORIZONTAL_INSET: f32 = 0.15; const CURVE_HORIZONTAL_SPAN: f32 = 0.7; const CURVE_WAVE_AMPLITUDE: f32 = 0.22; - let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); - let radius = size_px as f32 * STROKE_RADIUS_FRACTION; - let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius); - // The horizontal inset and vertical wave keep the S curve inside the swatch let curve = |t: f32| { ( @@ -178,48 +171,90 @@ pub fn stroke_preview(brush: &BrushSettings, size_px: usize, image: Option<&Imag size_px as f32 * (0.5 - CURVE_WAVE_AMPLITUDE * (t * std::f32::consts::TAU).sin()), ) }; - let mut cover = vec![0f32; size_px * size_px]; + let cover = stamp_coverage(brush, image, [size_px, size_px], |_| size_px as f32 * STROKE_RADIUS_FRACTION, curve); + ColorImage::new([size_px, size_px], cover.into_iter().map(|coverage| Color32::from_gray((coverage * brush.opacity * 255.0 + 0.5) as u8)).collect()) +} + +/// The brush's stroke along `curve` (0..1 to pixels) in a `size` strip, stamps `radius` (0..1 to pixels) wide, columns in `tint`'s colour; missed pixels stay transparent +pub fn stroke_strip( + brush: &BrushSettings, + image: Option<&ImageRes>, + size: [usize; 2], + radius: impl Fn(f32) -> f32, + curve: impl Fn(f32) -> (f32, f32), + tint: impl Fn(usize) -> [u8; 3], +) -> ColorImage { + let cover = stamp_coverage(brush, image, size, radius, curve); + let pixels = cover + .into_iter() + .enumerate() + .map(|(index, coverage)| { + let [r, g, b] = tint(index % size[0]); + Color32::from_rgba_unmultiplied(r, g, b, (coverage * brush.opacity * 255.0 + 0.5) as u8) + }) + .collect(); + ColorImage::new(size, pixels) +} + +/// Paint coverage 0..1 of the brush's stamps (`radius` 0..1 to pixels, its alpha, hardness, spacing, flow, angle and jitters) along `curve` in a `width` × `height` image +fn stamp_coverage( + brush: &BrushSettings, + image: Option<&ImageRes>, + [width, height]: [usize; 2], + radius: impl Fn(f32) -> f32, + curve: impl Fn(f32) -> (f32, f32), +) -> Vec { + // Cap work for a single preview + const CURVE_SAMPLE_STEP: f32 = 0.002; + const MIN_STAMP_SPACING_PX: f32 = 0.5; + const MAX_STAMPS: u32 = 2000; + + let library = brush.alpha_library.as_deref().and_then(alphas::find).map(alphas::LibraryAlpha::image); + let shape = Shape { alpha: brush.alpha, image, library, params: brush.alpha_params, level: 0 }.at_radius(radius(1.0)); + let mut cover = vec![0f32; width * height]; // Odd multipliers decorrelate reproducible jitter across stamps and channels let jitter_sample = |stamp_index: u32, channel: u32| { (stamp_index.wrapping_mul(0x9E37_79B9) ^ channel.wrapping_mul(0x85EB_CA6B)).wrapping_mul(0xC2B2_AE35) as f32 / u32::MAX as f32 }; - let step = (brush.spacing * 2.0 * radius).max(MIN_STAMP_SPACING_PX); - let (mut t, mut travelled, mut i) = (0.0f32, step, 0u32); + + // Spacing follows the stamp's own radius, as on the model + let step = |t: f32| (brush.spacing * 2.0 * radius(t)).max(MIN_STAMP_SPACING_PX); + let (mut t, mut travelled, mut stamp_index) = (0.0f32, step(0.0), 0u32); let mut last = curve(0.0); - while t <= 1.0 && i < MAX_STAMPS { - let p = curve(t); - travelled += (p.0 - last.0).hypot(p.1 - last.1); - last = p; + while t <= 1.0 && stamp_index < MAX_STAMPS { + let point = curve(t); + travelled += (point.0 - last.0).hypot(point.1 - last.1); + last = point; t += CURVE_SAMPLE_STEP; - if travelled < step { + if travelled < step(t) { continue; } travelled = 0.0; - i += 1; - let stamp_radius = radius * (1.0 - brush.jitter_size * jitter_sample(i, 1)); - let tangent = if brush.follow_path { (curve(t).1 - p.1).atan2(curve(t).0 - p.0) } else { 0.0 }; - let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(i, 2); - let (cx, cy) = ( - p.0 + brush.jitter_position * radius * (jitter_sample(i, 3) * 2.0 - 1.0), - p.1 + brush.jitter_position * radius * (jitter_sample(i, 4) * 2.0 - 1.0), + stamp_index += 1; + let stamp_radius = radius(t) * (1.0 - brush.jitter_size * jitter_sample(stamp_index, 1)); + let tangent = if brush.follow_path { (curve(t).1 - point.1).atan2(curve(t).0 - point.0) } else { 0.0 }; + let angle = brush.angle.to_radians() + tangent + brush.jitter_angle * std::f32::consts::TAU * jitter_sample(stamp_index, 2); + let (center_x, center_y) = ( + point.0 + brush.jitter_position * radius(t) * (jitter_sample(stamp_index, 3) * 2.0 - 1.0), + point.1 + brush.jitter_position * radius(t) * (jitter_sample(stamp_index, 4) * 2.0 - 1.0), ); - let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(i, 5)); + let flow = brush.flow * (1.0 - brush.jitter_flow * jitter_sample(stamp_index, 5)); let (sin, cos) = angle.sin_cos(); - let (x0, x1) = ((cx - stamp_radius).floor().max(0.0) as usize, ((cx + stamp_radius).ceil() as usize).min(size_px)); - let (y0, y1) = ((cy - stamp_radius).floor().max(0.0) as usize, ((cy + stamp_radius).ceil() as usize).min(size_px)); + let (x0, x1) = ((center_x - stamp_radius).floor().max(0.0) as usize, ((center_x + stamp_radius).ceil() as usize).min(width)); + let (y0, y1) = ((center_y - stamp_radius).floor().max(0.0) as usize, ((center_y + stamp_radius).ceil() as usize).min(height)); for y in y0..y1 { for x in x0..x1 { - let (dx, dy) = ((x as f32 + 0.5 - cx) / stamp_radius, (cy - y as f32 - 0.5) / stamp_radius); - let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, i) * flow; - let coverage = &mut cover[y * size_px + x]; + let (dx, dy) = ((x as f32 + 0.5 - center_x) / stamp_radius, (center_y - y as f32 - 0.5) / stamp_radius); + let alpha = shape.sample(dx * cos + dy * sin, -dx * sin + dy * cos, brush.hardness, stamp_index) * flow; + let coverage = &mut cover[y * width + x]; *coverage = 1.0 - (1.0 - *coverage) * (1.0 - alpha.clamp(0.0, 1.0)); } } } - ColorImage::new([size_px, size_px], cover.into_iter().map(|v| Color32::from_gray((v * brush.opacity * 255.0 + 0.5) as u8)).collect()) + cover } /// Environment `name`'s panorama across a `size²` swatch, transparent above and below diff --git a/crates/ui-egui/src/project_config.rs b/crates/ui-egui/src/project_config.rs index a399aa4e..e88413f2 100644 --- a/crates/ui-egui/src/project_config.rs +++ b/crates/ui-egui/src/project_config.rs @@ -1,13 +1,15 @@ //! Edit > Project Configuration...: the project's settings in sections. 3D MESH picks another mesh -//! file for the project or reads the current one again; PROJECT SETTINGS sets the normal map format -//! and shows the UV tiles. Settings TextureCraft does not have yet (tangent space per fragment, -//! physical size, OpenColorIO, import options other than stroke preservation) are shown disabled. +//! file for the project or reads the current one again; PROJECT SETTINGS sets the project name and +//! normal map format and shows the UV tiles. Unsupported options such as tangent space per fragment, +//! physical size and OpenColorIO are shown disabled. +use std::borrow::Cow; use std::sync::atomic::{AtomicU64, Ordering}; use egui::{Key, Modifiers}; use serde_json::{Value, json}; use texturecraft_engine::core::NormalFormat; +use texturecraft_engine::project_cmds::{MAX_PROJECT_NAME_CHARS, validate_project_name}; use crate::TextureCraftApp; use crate::dock::info_icon; @@ -33,6 +35,7 @@ const MIN_FIELD_WIDTH_POINTS: f32 = 60.0; const DEFAULT_DIALOG_WIDTH_POINTS: f32 = 560.0; /// Leave space around the centered dialog on short viewports. const DIALOG_VIEWPORT_MARGIN_POINTS: f32 = 32.0; +const PROJECT_NAME_FIELD_ID: &str = "project_config_name"; /// Opens the window on the current project, with nothing chosen yet. pub(crate) fn open(app: &mut TextureCraftApp) { @@ -44,6 +47,7 @@ pub(crate) fn open(app: &mut TextureCraftApp) { mesh: None, reimport: false, preserve: true, + draft_name: None, normal_format: None, color_management: crate::project_form::ColorManagement::Legacy, confirm: false, @@ -115,14 +119,23 @@ fn format_name(format: NormalFormat) -> &'static str { } } -pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { - let Some(mut config) = app.ui.windows.project_config.take() else { return }; - - // Choices for another project cannot be applied here - if config.project != app.session.project_id { +fn sync_name_editor(app: &mut TextureCraftApp, ctx: &egui::Context, opening: Option) { + if app.project_name_editor_opening == opening { return; } + // Egui keeps widget undo data after the dialog closes + app.project_name_editor_opening = opening; + ctx.data_mut(|data| data.remove::(egui::Id::unique(PROJECT_NAME_FIELD_ID))); +} + +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + // Choices for another project cannot be applied here + let config = app.ui.windows.project_config.take().filter(|config| config.project == app.session.project_id); + sync_name_editor(app, ctx, config.as_ref().map(|config| config.opening_id)); + + let Some(mut config) = config else { return }; + let project = &app.session.doc.project; let current_mesh_path = &project.mesh_path; @@ -137,7 +150,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut open = true; let (mut ok, mut cancel, mut select) = (std::mem::take(&mut config.confirm), false, false); - // Start with a form that fits the viewport; subsequent sizes follow the user's resize + // Fit the first frame to the viewport and follow the user's resize after that let form_height = (ctx.content_rect().height() - DIALOG_VIEWPORT_MARGIN_POINTS - DIALOG_CHROME_HEIGHT_POINTS) .clamp(crate::project_form::MIN_FORM_HEIGHT_POINTS, crate::project_form::FORM_HEIGHT_POINTS); let dialog = crate::windows::dialog(ctx, "project_config", tr("Project Configuration"), &mut open) @@ -211,6 +224,20 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.add_space(12.0); ui.label(caption(tr("PROJECT SETTINGS"))); ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(ROW_INDENT_POINTS); + let label = ui.label(tr("Project name")).id; + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + info_icon(ui, tr("The name $project stands for in export file names. The project file keeps its own name.")); + let was_edited = config.draft_name.is_some(); + let mut name = config.draft_name.take().map_or(Cow::Borrowed(project.name.as_str()), Cow::Owned); + let field = egui::TextEdit::singleline(&mut name).id(egui::Id::unique(PROJECT_NAME_FIELD_ID)).desired_width(FIELD_WIDTH_POINTS); + if ui.add(field).labelled_by(label).changed() || was_edited { + config.draft_name = Some(name.into_owned()); + } + }); + }); + let shown_format = config.normal_format.unwrap_or(current_normal_format); row( ui, @@ -284,7 +311,6 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { physical_size(ui, "project_config_physical_size", false); color_management(ui, "project_config_color_management", &mut config.color_management); }); - }); }); }); @@ -303,9 +329,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); } - // Apply the mesh first so a failed mesh change leaves the format untouched + let confirming = ok && !cancel && open; + + // Reject invalid drafts before applying mesh or format changes + if confirming && config.draft_name.as_deref().is_some_and(|name| validate_project_name(name).is_err()) { + app.toast(trf("Project name must be 1 to {max} characters after trimming, without control characters.", &[("max", &MAX_PROJECT_NAME_CHARS)]), true); + app.announce_latest_toast(); + app.ui.windows.project_config = Some(config); + return; + } + + // Apply the mesh first so a failed mesh change leaves the remaining settings untouched let mut mesh_applied = false; - let done = ok && !cancel && open && { + let done = confirming && { let reimport = config.reimport.then(|| app.session.remembered_mesh_path().map(str::to_string)).flatten(); mesh_applied = if config.reimport && chosen_mesh.is_none() && reimport.is_none() { // Drop a stale reimport tick so the user can retry the remaining settings @@ -328,15 +364,21 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } None => true, } + && match config.draft_name.as_deref() { + Some(name) => app.run("project.rename", json!({"name": name})).is_some(), + None => true, + } }; if !done && !cancel && open { - // A format retry must not reimport an already changed mesh + // A retry must not reimport an already changed mesh if ok && mesh_applied { (config.mesh, config.reimport) = (None, false); } app.ui.windows.project_config = Some(config); + } else { + sync_name_editor(app, ctx, None); } } diff --git a/crates/ui-egui/src/properties_popup.rs b/crates/ui-egui/src/properties_popup.rs index 291d50d9..1d59fdc1 100644 --- a/crates/ui-egui/src/properties_popup.rs +++ b/crates/ui-egui/src/properties_popup.rs @@ -85,9 +85,10 @@ pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { // The docked panel's jump tabs on the top edge stay put while the sections scroll under them let scope = SectionScope::Popup; - if let Some(tabs) = crate::dock::properties_fill_tabs(app) { + if let Some(tabs) = crate::dock::properties_tabs(app) { crate::property_sheet::section_tabs(ui, scope, ui.style().visuals.menu_corner_radius.nw, &tabs); } + crate::dock::pinned_brush_preview(app, ui); crate::property_sheet::in_scope(ui, scope, |ui| { // A popup that fits its rows keeps its size; one that scrolls goes on until its last section's top let area = egui::ScrollArea::vertical().id_salt("properties_popup_scroll"); diff --git a/crates/ui-egui/src/property_sheet/axis_rows.rs b/crates/ui-egui/src/property_sheet/axis_rows.rs index c534afc3..c74a956a 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -2,7 +2,7 @@ use std::ops::RangeInclusive; -use egui::{Align2, Color32, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Painter, Rect, Response, Role, Sense, Stroke, StrokeKind, WidgetInfo, pos2, vec2}; use super::row::SECTION_CAPTION_CENTER; use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS}; @@ -45,6 +45,9 @@ const PICTURE_TOP: f32 = 4.0; const PICTURE_SHORTER: f32 = 10.0; const PICTURE_TO_COLUMN: f32 = 6.0; +/// Width of the line around the picture +const PICTURE_OUTLINE_WIDTH: f32 = 1.0; + impl PropertySheet<'_> { /// A section caption with its on/off switch at the right edge pub(crate) fn section_switch(&mut self, title: &str, on: bool) -> Response { @@ -135,32 +138,35 @@ impl PropertySheet<'_> { Self::apply_typed(value, typed, dragged) } - /// Draw a picture beside captioned sliders and report the edit on each slider. + /// Draw a picture beside captioned sliders and report the edit on each slider pub(crate) fn picture_sliders(&mut self, picture: &dyn Fn(&Painter, Rect), sliders: &mut [StackSlider<'_>; N]) -> [Option; N] { let count = sliders.len().max(1) as f32; let height = count * (STACK_CAPTION_LINE + STACK_PART_LINE) + (count - 1.0) * STACK_GAP; self.space(BLOCK_MARGIN); let block = self.take(height); - let x0 = self.column(); - let side = (height - PICTURE_SHORTER).min(x0 - self.left - PICTURE_TO_COLUMN).max(1.0); + + let column_x = self.column(); + let side = (height - PICTURE_SHORTER).min(column_x - self.left - PICTURE_TO_COLUMN).max(1.0); let square = Rect::from_min_size(pos2(self.left, block.top() + PICTURE_TOP), vec2(side, side)); picture(self.ui.painter(), square); - self.ui.painter().rect_stroke(square, 0, Stroke::new(1.0, self.tokens.field_border), StrokeKind::Inside); + self.ui.painter().rect_stroke(square, CornerRadius::ZERO, Stroke::new(PICTURE_OUTLINE_WIDTH, self.tokens.field_border), StrokeKind::Inside); + let caption_color = self.tokens.text_dim; let mut edits = [None; N]; let mut y = block.top(); for (edit, slider) in edits.iter_mut().zip(sliders) { - let dim = self.tokens.text_dim; - let caption = pos2(x0, y + STACK_CAPTION_LINE / 2.0); - self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), dim); + let caption = pos2(column_x, y + STACK_CAPTION_LINE / 2.0); + self.ui.painter().text(caption, Align2::LEFT_CENTER, slider.label, FontId::proportional(SMALL_TEXT_SIZE), caption_color); + let center_y = y + STACK_CAPTION_LINE + STACK_PART_LINE / 2.0; let id = self.next_id(); let dial_x = self.right - self.used.value_width.max(super::VALUE_MIN_WIDTH) - DIAL_AIR - DIAL_RADIUS; let end = if slider.dial { dial_x - DIAL_RADIUS - DIAL_AIR } else { self.track_end() }; - let track = Track { start: x0 + KNOB_RADIUS, end, center_y, zero: None, ramp: false }; + let track = Track { start: column_x + KNOB_RADIUS, end, center_y, zero: (*slider.range.start() < 0.0).then_some(0.0), ramp: false }; if slider.dial { self.paint_dial(pos2(dial_x, center_y), *slider.value); } + let dragged = self.track(id, slider.label, &track, slider.value, &slider.range); let typed = self.value_field(id, slider.label, center_y, *slider.value, &slider.typed, slider.decimals, slider.suffix); *edit = Self::apply_typed(slider.value, typed, dragged); diff --git a/crates/ui-egui/src/property_sheet/choice.rs b/crates/ui-egui/src/property_sheet/choice.rs index 122857cb..91d6e7eb 100644 --- a/crates/ui-egui/src/property_sheet/choice.rs +++ b/crates/ui-egui/src/property_sheet/choice.rs @@ -77,6 +77,36 @@ const CHOSEN_BAR_RADIUS: u8 = 1; /// The hovered option's eye glyph size const EYE_SIZE: f32 = 13.0; +/// An option's hover fill, the chosen one's accent bar and its keyboard focus outline +fn paint_option(painter: &Painter, rect: Rect, response: &Response, chosen: bool, tokens: &crate::theme::Tokens) { + if response.hovered() { + let fill = Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); + painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); + } + if chosen { + let bar = Rect::from_min_max( + pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), + pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), + ); + painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); + } + if response.has_focus() { + painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(OPTION_FOCUS_WIDTH, tokens.text_strong), StrokeKind::Inside); + } +} + +/// One option of a list drawn outside a sheet (a menu popup), the full width of `ui`, looking like a sheet dropdown's option +pub(crate) fn option_row(ui: &mut egui::Ui, text: &str, chosen: bool) -> Response { + let tokens = crate::theme::Tokens::get(ui.ctx()); + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), OPTION_HEIGHT), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, text)); + let painter = ui.painter(); + paint_option(painter, rect, &response, chosen, &tokens); + let font = if chosen { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) }; + painter.text(pos2(rect.left() + VALUE_INSET, rect.top() + OPTION_HEIGHT / 2.0 - OPTION_TEXT_LIFT), Align2::LEFT_CENTER, text, font, tokens.text); + response +} + impl PropertySheet<'_> { /// A set-once choice whose list hangs from its button; returns the picked and the hovered option pub(crate) fn dropdown( @@ -225,20 +255,8 @@ impl PropertySheet<'_> { response.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, chosen, name(option))); if response.hovered() { hovered = Some(option); - let fill = - Rect::from_min_max(pos2(rect.left() + HOVER_INSET, rect.top()), pos2(rect.right() - HOVER_INSET, rect.bottom() - HOVER_BOTTOM_GAP)); - painter.rect_filled(fill, CornerRadius::same(CONTROL_RADIUS), tokens.button); - } - if chosen { - let bar = Rect::from_min_max( - pos2(rect.left() + CHOSEN_BAR_LEFT, rect.top() + CHOSEN_BAR_TOP), - pos2(rect.left() + CHOSEN_BAR_RIGHT, rect.bottom() - CHOSEN_BAR_BOTTOM), - ); - painter.rect_filled(bar, CornerRadius::same(CHOSEN_BAR_RADIUS), tokens.accent); - } - if response.has_focus() { - painter.rect_stroke(rect, CornerRadius::same(CONTROL_RADIUS), Stroke::new(OPTION_FOCUS_WIDTH, tokens.text_strong), StrokeKind::Inside); } + paint_option(painter, rect, &response, chosen, &tokens); // Align the option text and picture with the button despite the list border let button_left = rect.left() - LIST_BORDER; diff --git a/crates/ui-egui/src/property_sheet/material_rows.rs b/crates/ui-egui/src/property_sheet/material_rows.rs index 14fc9b40..78d4b10a 100644 --- a/crates/ui-egui/src/property_sheet/material_rows.rs +++ b/crates/ui-egui/src/property_sheet/material_rows.rs @@ -82,7 +82,7 @@ impl PropertySheet<'_> { /// Controls the sheet has no row for yet, laid out by egui between the panel's edges pub(crate) fn embed(&mut self, body: impl FnOnce(&mut egui::Ui) -> R) -> R { - let width = self.right - self.left; + let width = (self.right - self.left).max(0.0); let top = self.cursor_y(); let inner = self.ui.horizontal(|ui| { ui.add_space(self.left - ui.cursor().left()); diff --git a/crates/ui-egui/src/property_sheet/mod.rs b/crates/ui-egui/src/property_sheet/mod.rs index acd1f2dd..59a00a04 100644 --- a/crates/ui-egui/src/property_sheet/mod.rs +++ b/crates/ui-egui/src/property_sheet/mod.rs @@ -29,6 +29,7 @@ mod material_rows; mod name_field; mod number_field; mod open_card; +mod pen_slider; mod preview_block; mod preview_edit; mod preview_lower; @@ -46,6 +47,7 @@ mod size_columns; mod size_columns_response; mod slider; mod slot; +mod slot_ends; mod slot_response; mod source_card; mod stack_slider; @@ -62,6 +64,7 @@ mod tests; pub(crate) use action_row_response::ActionRowResponse; pub(crate) use band_response::BandResponse; pub(crate) use button_icon::ButtonIcon; +pub(crate) use choice::option_row; pub(crate) use compare_row_response::CompareRowResponse; pub(crate) use file_list_add::FileListAdd; pub(crate) use file_list_response::FileListResponse; diff --git a/crates/ui-egui/src/property_sheet/number_field.rs b/crates/ui-egui/src/property_sheet/number_field.rs index 36c484ad..11ed89fd 100644 --- a/crates/ui-egui/src/property_sheet/number_field.rs +++ b/crates/ui-egui/src/property_sheet/number_field.rs @@ -8,7 +8,7 @@ use crate::theme::semibold; const FIELD_GAP: f32 = 4.0; /// Room kept at the row's end for the link button, on every row of a group that has one -const LINK_SLOT: f32 = 26.0; +pub(super) const LINK_SLOT: f32 = 26.0; /// Size of the link button pub(super) const LINK_SIZE: f32 = 18.0; diff --git a/crates/ui-egui/src/property_sheet/pen_slider.rs b/crates/ui-egui/src/property_sheet/pen_slider.rs new file mode 100644 index 00000000..23ce262b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/pen_slider.rs @@ -0,0 +1,57 @@ +//! A slider that keeps the link slot at its end, for a pen-pressure button: the Size band's rows + +use std::ops::RangeInclusive; + +use egui::{Align2, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, vec2}; +use egui_phosphor::regular as ic; + +use super::number_field::{LINK_SIZE, LINK_SLOT}; +use super::{CONTROL_RADIUS, ICON_SIZE, PropertySheet, ROW_HEIGHT, RowLead}; +use crate::i18n::{tr, trf}; + +/// Width of the pen button's outline, in points +const PEN_BUTTON_OUTLINE_WIDTH: f32 = 1.0; + +impl PropertySheet<'_> { + /// [`Self::slider`] ending one link slot early so a band's rows line up, with the `pen` button in that slot; returns the edit and whether the pen was clicked (it flips `pen`) + pub(crate) fn pen_slider( + &mut self, + label: &str, + value: &mut f32, + range: RangeInclusive, + decimals: usize, + pen: Option<&mut bool>, + ) -> (Option, bool) { + let right = self.right; + self.right -= LINK_SLOT; + let edit = self.slider_led(RowLead::label(label), value, range, decimals, ""); + self.right = right; + let center = Pos2::new(right - LINK_SIZE / 2.0, self.cursor_y() - ROW_HEIGHT / 2.0); + let clicked = pen.is_some_and(|pressed| self.pen_button(center, label, pressed)); + (edit, clicked) + } + + /// The pen button: lit while pen pressure drives row `label`'s value + fn pen_button(&mut self, center: Pos2, label: &str, pressed: &mut bool) -> bool { + let rect = Rect::from_center_size(center, vec2(LINK_SIZE, LINK_SIZE)); + let id = self.named_id("pen_pressure", label); + let response = self.ui.interact(rect, id, Sense::click()); + + let name = trf("{name} pen pressure", &[("name", &label)]); + let enabled = self.ui.is_enabled(); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, enabled, *pressed, &name)); + let response = self.tip(response, tr("Pen pressure")); + if response.clicked() { + *pressed = !*pressed; + } + + let tokens = self.tokens; + let (fill, border) = if *pressed { (tokens.accent_dim, tokens.accent) } else { (tokens.button, tokens.button_border) }; + let painter = self.ui.painter(); + painter.rect(rect, CornerRadius::same(CONTROL_RADIUS), fill, Stroke::new(PEN_BUTTON_OUTLINE_WIDTH, border), StrokeKind::Inside); + painter.text(rect.center(), Align2::CENTER_CENTER, ic::PEN, FontId::proportional(ICON_SIZE), tokens.text); + self.paint_control_focus(&response); + + response.clicked() + } +} diff --git a/crates/ui-egui/src/property_sheet/slot.rs b/crates/ui-egui/src/property_sheet/slot.rs index 90d2111b..623b6126 100644 --- a/crates/ui-egui/src/property_sheet/slot.rs +++ b/crates/ui-egui/src/property_sheet/slot.rs @@ -1,6 +1,7 @@ use egui::{Align2, CornerRadius, FontId, Painter, Rect, Sense, Stroke, StrokeKind, Vec2, pos2, vec2}; use egui_phosphor::regular as ic; +use super::slot_ends::SlotEnds; use super::switch_control::PILL_SIZE; use super::{ButtonIcon, CONTROL_RADIUS, PropertySheet, ROW_HEIGHT, SlotResponse, TEXT_SIZE}; use crate::theme::semibold; @@ -14,6 +15,9 @@ const SLOT_HEIGHT: f32 = 36.0; /// Size of a slot's thumbnail pub(super) const THUMB_SIZE: f32 = 26.0; +/// Width of the thumbnail's frame, lit while the row is hovered, in points +const THUMB_OUTLINE_WIDTH: f32 = 1.0; + /// Air between the thumbnail and the slot's name const THUMB_TO_NAME: f32 = 10.0; @@ -73,31 +77,32 @@ impl PropertySheet<'_> { self.open_card(); self.scope = self.named_id("slot", name); self.space(SLOT_CARD_TOP); - self.slot_row(thumbnail, name, source, on, clear, reset.then_some(true)) + self.slot_row(thumbnail, name, source, SlotEnds { on, clear, reset: reset.then_some(true), pickable: true }) } /// [`Self::slot`] whose ⟲ always shows beside the ×, faint and inert while what it restores is at its defaults (`changed` false) pub(crate) fn slot_restorable(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { self.open_card(); self.space(SLOT_CARD_TOP); - self.slot_row(thumbnail, name, source, None, true, Some(changed)) + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear: true, reset: Some(changed), pickable: true }) + } + + /// A slot card whose one source can't be swapped (a brush's uniform channel): the row picks nothing, its ⟲ is faint and inert while at the defaults (`changed` false) + pub(crate) fn slot_fixed(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, changed: bool) -> SlotResponse { + self.open_card(); + self.scope = self.named_id("slot", name); + self.space(SLOT_CARD_TOP); + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear: false, reset: Some(changed), pickable: false }) } /// [`Self::slot`]'s row inside the card open now (an input a mode adds, under that mode), not a card of its own pub(crate) fn slot_in_card(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, clear: bool) -> SlotResponse { - self.slot_row(thumbnail, name, source, None, clear, None) + self.slot_row(thumbnail, name, source, SlotEnds { on: None, clear, reset: None, pickable: true }) } - /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list - fn slot_row( - &mut self, - thumbnail: &dyn Fn(&Painter, Rect), - name: &str, - source: &str, - on: Option<&mut bool>, - clear: bool, - reset: Option, - ) -> SlotResponse { + /// A slot row: thumbnail, name over source, then ⟲ (`Some(changed)`), × and the toggle on the right; the row opens the source list when `pickable` + fn slot_row(&mut self, thumbnail: &dyn Fn(&Painter, Rect), name: &str, source: &str, ends: SlotEnds<'_>) -> SlotResponse { + let SlotEnds { on, clear, reset, pickable } = ends; let rect = self.take(SLOT_HEIGHT); let center_y = rect.top() + SLOT_HEIGHT / 2.0; let enabled = on.as_deref().copied().unwrap_or(true); @@ -109,8 +114,16 @@ impl PropertySheet<'_> { // The picker spans the card while the trailing glyphs keep their own hit areas let row = self.bled_row(rect); let pick_id = self.next_id(); - let pick = self.ui.interact(row, pick_id, Sense::click()); - pick.widget_info(|| egui::WidgetInfo { current_text_value: Some(source.to_owned()), ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) }); + let pick = self.ui.interact(row, pick_id, if pickable { Sense::click() } else { Sense::hover() }); + if pickable { + pick.widget_info(|| egui::WidgetInfo { + current_text_value: Some(source.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name) + }); + } else { + // A label's words are its value, so the name and source read as one + pick.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, format!("{name}: {source}"))); + } let mut result = SlotResponse { pick, clear: false, reset: false, toggled: false }; let tokens = self.tokens; @@ -119,15 +132,16 @@ impl PropertySheet<'_> { painter.rect_stroke( thumb, CornerRadius::ZERO, - Stroke::new(1.0, if result.pick.hovered() { tokens.accent } else { tokens.field_border }), + Stroke::new(THUMB_OUTLINE_WIDTH, if pickable && result.pick.hovered() { tokens.accent } else { tokens.field_border }), StrokeKind::Inside, ); let text_x = thumb.right() + THUMB_TO_NAME; + let (name_font, name_color) = if enabled { (semibold(TEXT_SIZE), tokens.text) } else { (FontId::proportional(TEXT_SIZE), tokens.text_dim) }; painter.text(pos2(text_x, center_y - NAME_ABOVE_CENTER), Align2::LEFT_CENTER, name, name_font, name_color); painter.text(pos2(text_x, center_y + SOURCE_BELOW_CENTER), Align2::LEFT_CENTER, source, FontId::proportional(SOURCE_TEXT_SIZE), tokens.text_dim); - for (shown, live, x, glyph, tip, slot) in [ + for (shown, live, x, glyph, tip, clicked) in [ (clear, true, clear_x, ic::X, crate::i18n::n_("Clear"), &mut result.clear), (reset.is_some(), reset.unwrap_or(false), reset_x, ic::CLOCK_COUNTER_CLOCKWISE, crate::i18n::n_("Restore defaults"), &mut result.reset), ] { @@ -138,14 +152,15 @@ impl PropertySheet<'_> { let glyph_rect = Rect::from_center_size(pos2(x, center_y), Vec2::splat(SLOT_GLYPH_BOX)); let id = self.next_id(); - // At the defaults the ⟲ is faint and inert, as on a band: a click there picks the source like the rest of the row + // At the defaults the ⟲ is faint and inert, as on a band: on a pickable row a click there picks the source like the rest of the row let response = if live { self.tip(self.ui.interact(glyph_rect, id, Sense::click()), crate::i18n::tr(tip)) } else { self.ui.interact(glyph_rect, id, Sense::hover()) }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, live, crate::i18n::tr(tip))); - *slot = live && response.clicked(); + *clicked = live && response.clicked(); + let color = self.reset_glyph_color(live, response.hovered(), tokens.text); painter.text(glyph_rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(SLOT_ICON_SIZE), color); } @@ -161,6 +176,7 @@ impl PropertySheet<'_> { response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, *on, name)); self.pill(pill.center(), *on, true); } + self.drawn(thumb.bottom()); result } diff --git a/crates/ui-egui/src/property_sheet/slot_ends.rs b/crates/ui-egui/src/property_sheet/slot_ends.rs new file mode 100644 index 00000000..cfc42cda --- /dev/null +++ b/crates/ui-egui/src/property_sheet/slot_ends.rs @@ -0,0 +1,16 @@ +//! What a slot row offers besides its picture and words + +/// A slot row's toggle, ×, ⟲ and whether the row opens the source list +pub(super) struct SlotEnds<'a> { + /// The on/off pill at the right end, when the slot has one + pub(super) on: Option<&'a mut bool>, + + /// The × back to a uniform source shows + pub(super) clear: bool, + + /// The ⟲ shows: `Some(changed)`, faint and inert while unchanged + pub(super) reset: Option, + + /// A click on the row opens the source list + pub(super) pickable: bool, +} diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 7fa38fe1..e128d7fa 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -268,7 +268,14 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { .texture_sets .iter() .zip(&session.caches) - .map(|(set, cache)| TraceSet { material: set.material, composite: cache.composite.clone(), height_strength: set.atlas_height_strength() }) + .map(|(set, cache)| TraceSet { + material: set.material, + composite: cache.composite.clone(), + height_strength: set.atlas_height_strength(), + height_y_factor: set.atlas_height_y_factor(), + height_in_normal: set.height_in_normal(), + height_to_normal: set.height_to_normal, + }) .collect(); let env_image = display.environment_resource().and_then(|n| session.images.get(n)); @@ -327,7 +334,13 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { /// 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(); + let sets: Vec<_> = session + .doc + .project + .texture_sets + .iter() + .map(|set| (set.material, set.atlas_height_strength(), set.atlas_height_y_factor(), set.height_in_normal(), set.height_to_normal)) + .collect(); let display = &session.doc.project.display; let env_image = display.environment_resource().and_then(|name| session.images.get(name)).map(Arc::as_ptr); diff --git a/crates/ui-egui/src/resource_picker.rs b/crates/ui-egui/src/resource_picker.rs index 8c970158..85e34e5e 100644 --- a/crates/ui-egui/src/resource_picker.rs +++ b/crates/ui-egui/src/resource_picker.rs @@ -395,7 +395,7 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)), TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind), TilePicture::Generator(kind) => thumbs.generator(ui.ctx(), *kind), - TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, + TilePicture::Shape(..) | TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None, }; match (&item.picture, texture) { @@ -419,6 +419,10 @@ fn tile_ui(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz tokens.text_dim.gamma_multiply(LOADING_GLYPH_OPACITY), ); } + (TilePicture::Shape(alpha, hardness), None) => { + painter.rect_filled(picture, rounding, Color32::BLACK); + crate::thumbs::paint_alpha(painter, picture, *alpha, *hardness); + } (TilePicture::Swatch(color), None) => { painter.rect_filled(picture, rounding, *color); } diff --git a/crates/ui-egui/src/shader_settings.rs b/crates/ui-egui/src/shader_settings.rs index 1e7cd39e..8a7746e5 100644 --- a/crates/ui-egui/src/shader_settings.rs +++ b/crates/ui-egui/src/shader_settings.rs @@ -42,8 +42,8 @@ pub const SHADER_TYPES: [&str; 17] = [ /// The shader choice's search starts as the reference's: shaders only pub const SHADER_QUERY: &str = "u:shader"; -/// The reference's default instance name -const INSTANCE_NAME: &str = "Main shader"; +/// The reference's default instance name: the project's one shader, which every set uses +pub(crate) const INSTANCE_NAME: &str = "Main shader"; /// Wide enough for the longer shader model name const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 830a10ff..a79c1c44 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -270,24 +270,36 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { let folder = app.ui.shelf_path.clone(); let picked_tab = app.ui.shelf_tab; - let mut matching: Vec = all_entries.into_iter().filter(|entry| entry.matches(&filter)).collect(); - if app.ui.shelf_favorites_only { - matching.retain(|entry| crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some()); - } + let mut matching: Vec<_> = { + // A duplicated preference keeps the first rank it had on disk + let mut ranks = std::collections::HashMap::with_capacity(app.ui.shelf_favorites.len()); + for (rank, favorite) in app.ui.shelf_favorites.iter().enumerate() { + ranks.entry((favorite.kind.as_str(), favorite.id.as_str())).or_insert(rank); + } + + all_entries + .into_iter() + .filter(|entry| entry.matches(&filter)) + .filter_map(|entry| { + let rank = if ranks.is_empty() { None } else { ranks.get(&entry.identity()).copied() }; + (!app.ui.shelf_favorites_only || rank.is_some()).then_some((entry, rank)) + }) + .collect() + }; let path_pane_open = app.ui.shelf_panes.filter_by_path; let mut applicable = if path_pane_open { - crate::shelf_folders::paths(matching.iter().filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) + crate::shelf_folders::paths(matching.iter().map(|(entry, _)| entry).filter(|entry| crate::shelf_tabs::shows(picked_tab, entry.tab()))) } else { Vec::new() }; // All libraries includes every result without constructing an asset path if !folder.is_empty() { - matching.retain(|entry| entry.in_folder(&folder)); + matching.retain(|(entry, _)| entry.in_folder(&folder)); } - let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|entry| entry.tab() == *tab).count()).collect(); + let mut counts: Vec = TABS.iter().map(|(tab, _, _)| matching.iter().filter(|(entry, _)| entry.tab() == *tab).count()).collect(); // Saved smart materials and masks count toward their tabs even without tiles; they can't be favorites yet let favorites_only = app.ui.shelf_favorites_only; @@ -314,10 +326,10 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { && crate::shelf_tabs::shows(tab, Tab::Brushes) && folder.len() <= 2 && folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part); - let mut entries: Vec = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect(); + let mut entries: Vec<_> = matching.into_iter().filter(|(entry, _)| crate::shelf_tabs::shows(tab, entry.tab())).collect(); + // Favorites first, the most recently added first, then by name - let favorites = &app.ui.shelf_favorites; - entries.sort_by_cached_key(|entry| (crate::shelf_favorite::rank(favorites, entry).unwrap_or(usize::MAX), entry.label().to_lowercase())); + entries.sort_by_cached_key(|(entry, rank)| (rank.unwrap_or(usize::MAX), entry.label().to_lowercase())); // The toolbar has its own strip at the panel's bottom, so nothing above it can push it out let area = ui.available_rect_before_wrap(); @@ -342,7 +354,7 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } /// The tiles of `entries` in a scroll area `height` high, then user brushes, saved smart materials and saved smart masks when selected -fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: f32, saved: [bool; 2], show_user_brushes: bool, filter: &str) { +fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[(ShelfEntry, Option)], height: f32, saved: [bool; 2], show_user_brushes: bool, filter: &str) { let ctx = ui.ctx().clone(); let view = app.ui.shelf_view; let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE))); @@ -354,9 +366,9 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: .show(ui, |ui| { ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { tiles(ui, |ui| { - for entry in entries { + for (entry, rank) in entries { let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str())); - entry_tile(app, ui, &ctx, entry, view, is_selected); + entry_tile(app, ui, &ctx, entry, view, is_selected, rank.is_some()); } }); if show_user_brushes { @@ -515,7 +527,7 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str, masks: bool) { fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str, _: bool) {} /// The tile of `entry`, outlined when `selected`: a click applies it, a right-click opens its menu -fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) { +fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool, favorite: bool) { // An image removed this frame has nothing to show if let ShelfEntry::Image(name) = entry && !app.session.images.contains_key(name) @@ -523,15 +535,13 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry return; } - // A picture the user picked replaces the thumbnail, unless its file is gone; it is read only once its tile shows - let thumbnail = entry.thumbnail(app, ctx); let custom_file = crate::shelf_custom_preview::file_for(&app.ui.shelf_custom_previews, entry); let asset = entry.asset(); let session = &app.session; let response = tile_in_view( ui, &mut app.thumbs, - |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or(thumbnail), + |ui, thumbs| custom_file.and_then(|file| thumbs.custom_preview(ui.ctx(), file)).or_else(|| entry.thumbnail(thumbs, session, ui.ctx())), |thumbs| match entry { ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)), _ => entry.preview(session), @@ -550,7 +560,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry if entry.includes_randomness() { randomness_badge(ui.painter(), view.thumbnail_rect(response.rect)); } - if crate::shelf_favorite::rank(&app.ui.shelf_favorites, entry).is_some() { + if favorite { crate::shelf_favorite::star(ui.painter(), view.thumbnail_rect(response.rect), Tokens::get(ctx).warning); ctx.accesskit_node_builder(response.id, |node| node.set_description(tr("Favorite"))); } diff --git a/crates/ui-egui/src/shelf_custom_preview.rs b/crates/ui-egui/src/shelf_custom_preview.rs index 6fbe2ca1..c25ec3d1 100644 --- a/crates/ui-egui/src/shelf_custom_preview.rs +++ b/crates/ui-egui/src/shelf_custom_preview.rs @@ -43,10 +43,20 @@ pub(crate) fn remove(previews: &mut Vec, entry: &ShelfEntry) /// The largest centred square of `image`, scaled to [`CUSTOM_PREVIEW_PX`] (smaller images keep their size) pub(crate) fn square(image: &image::DynamicImage) -> image::RgbaImage { + use image::{DynamicImage, GenericImageView, imageops}; + let side = image.width().min(image.height()); - let cropped = image.crop_imm((image.width() - side) / 2, (image.height() - side) / 2, side, side); + let left = (image.width() - side) / 2; + let top = (image.height() - side) / 2; let size = side.min(CUSTOM_PREVIEW_PX); - cropped.resize_exact(size, size, image::imageops::FilterType::Triangle).to_rgba8() + let filter = imageops::FilterType::Triangle; + + // Sample common thumbnail formats directly from the decoded pixels + match image { + DynamicImage::ImageRgba8(pixels) => imageops::resize(&*pixels.view(left, top, side, side), size, size, filter), + DynamicImage::ImageRgb8(pixels) => DynamicImage::ImageRgb8(imageops::resize(&*pixels.view(left, top, side, side), size, size, filter)).into_rgba8(), + other => other.crop_imm(left, top, side, side).resize_exact(size, size, filter).into_rgba8(), + } } #[cfg(test)] diff --git a/crates/ui-egui/src/shelf_drag_ghost.rs b/crates/ui-egui/src/shelf_drag_ghost.rs index 2c11a2a1..7ffd7e43 100644 --- a/crates/ui-egui/src/shelf_drag_ghost.rs +++ b/crates/ui-egui/src/shelf_drag_ghost.rs @@ -87,9 +87,11 @@ fn dragged(ctx: &Context) -> Option<(Option, String)> { if let Some(drag) = egui::DragAndDrop::payload::(ctx) { return Some((drag.thumb.as_ref().map(egui::TextureHandle::id), drag.label.clone())); } + if !egui::DragAndDrop::has_payload_of_type::(ctx) { return None; } + ctx.data(|data| data.get_temp::(Id::unique(LAYER))).map(|label| (None, label)) } diff --git a/crates/ui-egui/src/shelf_entry.rs b/crates/ui-egui/src/shelf_entry.rs index 32669e7f..9c3f6f6c 100644 --- a/crates/ui-egui/src/shelf_entry.rs +++ b/crates/ui-egui/src/shelf_entry.rs @@ -16,6 +16,7 @@ use crate::TextureCraftApp; use crate::i18n::{n_, tr}; use crate::shelf::{Asset, Tab, apply}; use crate::shelf_preview::ShelfPreview; +use crate::thumbs::Thumbs; /// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines const SEED_PROBES: usize = 4; @@ -171,23 +172,23 @@ impl ShelfEntry { } /// The thumbnail, or None while it renders - pub(crate) fn thumbnail(&self, app: &mut TextureCraftApp, ctx: &egui::Context) -> Option { + pub(crate) fn thumbnail(&self, thumbs: &mut Thumbs, session: &Session, ctx: &egui::Context) -> Option { match self { - ShelfEntry::Material(material) => app.thumbs.material(ctx, material.id), - ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id), - ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id), - ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset), - ShelfEntry::SavedBrush { path: Some(path), .. } => app.thumbs.saved_brush(ctx, path, &app.session.images), + ShelfEntry::Material(material) => thumbs.material(ctx, material.id), + ShelfEntry::SmartMask(mask) => thumbs.smart_mask(ctx, mask.id), + ShelfEntry::Filter(filter) => thumbs.filter(ctx, filter.id), + ShelfEntry::Brush(preset) => thumbs.brush_preset(ctx, preset), + ShelfEntry::SavedBrush { path: Some(path), .. } => thumbs.saved_brush(ctx, path, &session.images), ShelfEntry::SavedBrush { path: None, name, index } => { - let brush = &app.session.brush_presets.list.get(*index)?.brush; - app.thumbs.session_brush(ctx, name, brush, &app.session.images) + let brush = &session.brush_presets.list.get(*index)?.brush; + thumbs.session_brush(ctx, name, brush, &session.images) } - ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha), - ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind), - ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name), + ShelfEntry::Alpha(alpha) => thumbs.alpha(ctx, alpha), + ShelfEntry::Procedural(kind) => thumbs.procedural(ctx, *kind), + ShelfEntry::Environment(name) => thumbs.environment(ctx, name), ShelfEntry::Image(name) => { - let image = app.session.images.get(name).cloned()?; - Some(app.thumbs.image(ctx, name, &image)) + let image = session.images.get(name)?; + Some(thumbs.image(ctx, name, image)) } } } diff --git a/crates/ui-egui/src/shelf_menu.rs b/crates/ui-egui/src/shelf_menu.rs index e098ef5f..07d8847b 100644 --- a/crates/ui-egui/src/shelf_menu.rs +++ b/crates/ui-egui/src/shelf_menu.rs @@ -222,6 +222,7 @@ fn custom_preview_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32, entry && row(ui, width, tr("Remove custom preview"), true, tokens).clicked() { crate::shelf_custom_preview::remove(&mut app.ui.shelf_custom_previews, entry); + app.thumbs.retain_custom_previews(&app.ui.shelf_custom_previews); ui.close(); } } @@ -243,6 +244,7 @@ fn pick_custom_preview(app: &mut TextureCraftApp, entry: &ShelfEntry) { app.thumbs.forget_custom_preview(&file); crate::shelf_custom_preview::set(&mut app.ui.shelf_custom_previews, kind, id, file); + app.thumbs.retain_custom_previews(&app.ui.shelf_custom_previews); }); } diff --git a/crates/ui-egui/src/shelf_updates.rs b/crates/ui-egui/src/shelf_updates.rs index 5a53fd27..a010bcd2 100644 --- a/crates/ui-egui/src/shelf_updates.rs +++ b/crates/ui-egui/src/shelf_updates.rs @@ -58,6 +58,15 @@ fn last_run_id() -> Id { /// Runs the automatic updates once their minutes have passed since the last run, and wakes the app for the next one pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { + let failures_id = Id::unique("shelf_updates_reported_failures"); + ctx.data_mut(|data| { + let owner = data.get_temp_mut_or(failures_id, app.session.project_id); + if *owner != app.session.project_id { + *owner = app.session.project_id; + data.remove::>(failures_id); + } + }); + let updates = app.ui.shelf_updates; if !updates.assets && !updates.resources { ctx.data_mut(|data| data.remove::(last_run_id())); @@ -83,7 +92,7 @@ pub(crate) fn tick(app: &mut TextureCraftApp, ctx: &Context) { refresh_assets(app); } if updates.resources { - update_resources(app, ctx); + update_resources(app, ctx, failures_id); } ctx.request_repaint_after(std::time::Duration::from_secs_f64(every)); } @@ -101,19 +110,17 @@ pub(crate) fn refresh_assets(app: &mut TextureCraftApp) { } /// Reads the project's changed image files again; a file that is gone or can't be read says why once, until it reads again -fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { +fn update_resources(app: &mut TextureCraftApp, ctx: &Context, failures_id: Id) { let Some(status) = app.run("resource.status", json!({})) else { return }; - let rows = status["resources"].as_array().cloned().unwrap_or_default(); - let mut failures: Vec<(String, String)> = - rows.iter().filter(|row| row["status"] == "missing").map(|row| (text(&row["name"]), text(&row["error"]))).collect(); + let rows = status["resources"].as_array().into_iter().flatten(); + let mut failures: Vec<(String, String)> = rows.filter(|row| row["status"] == "missing").map(|row| (text(&row["name"]), text(&row["error"]))).collect(); if status["outdated"].as_u64().is_some_and(|outdated| outdated > 0) && let Some(result) = app.run("resource.update", json!({})) { failures.extend(result["failed"].as_array().into_iter().flatten().map(|failure| (text(&failure["name"]), text(&failure["error"])))); } - let reported_id = reported_failures_id(app.session.project_id); - let mut reported: Vec = ctx.data(|data| data.get_temp(reported_id)).unwrap_or_default(); + let mut reported: Vec = ctx.data_mut(|data| data.remove_temp(failures_id)).unwrap_or_default(); reported.retain(|name| failures.iter().any(|(failed, _)| failed == name)); for (name, error) in failures { if !reported.contains(&name) { @@ -121,7 +128,9 @@ fn update_resources(app: &mut TextureCraftApp, ctx: &Context) { reported.push(name); } } - ctx.data_mut(|data| data.insert_temp(reported_id, reported)); + if !reported.is_empty() { + ctx.data_mut(|data| data.insert_temp(failures_id, reported)); + } } /// Reads the files of `names` (every changed image when None) again through the Resources Updater, which says what happened @@ -141,11 +150,6 @@ fn text(value: &serde_json::Value) -> String { value.as_str().unwrap_or_default().to_owned() } -/// The files of project `project_id` whose failure to read was already shown (ctx temp data) -fn reported_failures_id(project_id: u64) -> Id { - Id::unique(("shelf_updates_reported_failures", project_id)) -} - /// The refresh button with its popup of update settings, opening upward from the toolbar `panel` with its left edge on the panel's pub(crate) fn button(app: &mut TextureCraftApp, ui: &mut Ui, size: f32, panel: egui::Rect) { let label = tr("Refresh"); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 7429a617..b9bd4672 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -85,14 +85,6 @@ pub enum ViewLayout { Only2D, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] -pub enum PropsTab { - #[default] - Brush, - Alpha, - Material, -} - #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct Windows { pub export: bool, @@ -666,7 +658,6 @@ pub struct UiState { /// The share of the Assets panel's width the filter panes take #[serde(default = "default_shelf_panes_share", deserialize_with = "deserialize_shelf_panes_share")] pub shelf_panes_share: f32, - pub props_tab: PropsTab, #[serde(default)] pub text: TextUi, /// Layer being renamed and the edit buffer. @@ -892,7 +883,6 @@ impl Default for UiState { shelf_updates: crate::shelf_updates::ShelfUpdates::default(), shelf_panes_split: default_shelf_panes_split(), shelf_panes_share: default_shelf_panes_share(), - props_tab: PropsTab::Brush, text: TextUi::default(), rename: None, new_project: NewProject::default(), diff --git a/crates/ui-egui/src/state/project_config.rs b/crates/ui-egui/src/state/project_config.rs index 174b0987..0d848f6e 100644 --- a/crates/ui-egui/src/state/project_config.rs +++ b/crates/ui-egui/src/state/project_config.rs @@ -7,6 +7,8 @@ pub struct ProjectConfig { pub reimport: bool, /// Whether painted strokes follow the surface of a newly imported mesh pub preserve: bool, + /// The name as typed, or None to leave the current name unvalidated and unchanged + pub draft_name: Option, /// The selected normal map format when it differs from the project's pub normal_format: Option, /// Color management as chosen in the window; nothing is applied (the project stays Legacy) diff --git a/crates/ui-egui/src/stencil_choice.rs b/crates/ui-egui/src/stencil_choice.rs new file mode 100644 index 00000000..1414f08e --- /dev/null +++ b/crates/ui-egui/src/stencil_choice.rs @@ -0,0 +1,8 @@ +//! What the Stencil slot's picker offers + +/// One tile of the Stencil slot's picker: an image resource, or importing one +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum StencilChoice { + Image(String), + Import, +} diff --git a/crates/ui-egui/src/stencil_sheet.rs b/crates/ui-egui/src/stencil_sheet.rs new file mode 100644 index 00000000..2946de01 --- /dev/null +++ b/crates/ui-egui/src/stencil_sheet.rs @@ -0,0 +1,260 @@ +//! The Stencil section of a brush tool's Properties: the stencil's slot with its picker, its Tiling mode, and its placement beside a picture of where it sits in the view + +use std::ops::RangeInclusive; + +use egui::{Color32, CornerRadius, Painter, Pos2, Rect, Stroke, StrokeKind, TextureId, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::{Value, json}; +use texturecraft_engine::session::StencilState; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::stencil_choice::StencilChoice; +use crate::theme::Tokens; + +/// Scale = the image's height as a fraction of the view's +const SCALE_RANGE: RangeInclusive = 0.05..=4.0; + +/// How far the Position sliders move the stencil's center from the middle of the view (NDC; -1..1 is the view) +const POSITION_RANGE: RangeInclusive = -2.0..=2.0; + +/// The Rotation dial's range in degrees +const ROTATION_RANGE: RangeInclusive = 0.0..=360.0; + +/// The view's outline in the placement picture +const VIEW_OUTLINE_WIDTH: f32 = 1.0; + +/// Air between the placement picture's edge and the view drawn in it +const VIEW_INSET: f32 = 6.0; + +/// A Tiling mode picture's cell: its share of the picture and the air between two cells +const TILE_CELL_FRACTION: f32 = 0.42; +const TILE_CELL_GAP: f32 = 2.0; + +/// The Stencil section under its caption, whose reset puts the stencil back in the middle of the view +pub(crate) fn stencil_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let moved = app.session.tool.stencil.as_ref().is_some_and(|stencil| placement(stencil) != placement(&StencilState::new(&stencil.image))); + if sheet.section_reset(tr("Stencil"), moved) + && let Some(stencil) = &app.session.tool.stencil + { + let start = StencilState::new(&stencil.image); + app.run("tool.stencil", json!({"center": start.center, "scale": start.scale, "rotation": start.rotation})); + } + + stencil_slot(app, sheet); + let Some(stencil) = app.session.tool.stencil.clone() else { return }; + + let tile_name = |tile: bool| if tile { tr("H and V Tiling") } else { tr("No Tiling") }.to_owned(); + let text = Tokens::get(sheet.ui.ctx()).text; + let tile_picture = |painter: &Painter, rect: Rect, tile: bool| paint_tiling(painter, rect, tile, text); + let (picked, _) = sheet.dropdown(tr("Tiling mode"), stencil.tile, &[false, true], tile_name, Some(&tile_picture)); + if let Some(tile) = picked { + app.run("tool.stencil", json!({ "tile": tile })); + } + + placement_rows(app, sheet, &stencil); + + let mut opacity = stencil.opacity; + if sheet.slider(tr("Overlay opacity"), &mut opacity, 0.0..=1.0, 2).is_some() { + app.run("tool.stencil", json!({ "opacity": opacity })); + } +} + +/// What the section's reset puts back: where the stencil sits, its size and its turn +fn placement(stencil: &StencilState) -> ([f32; 2], f32, f32) { + (stencil.center, stencil.scale, stencil.rotation) +} + +/// The slot showing the stencil's image; a click opens the picker of images, × takes the stencil away +fn stencil_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) { + let ctx = sheet.ui.ctx().clone(); + let current = app.session.tool.stencil.as_ref().map(|stencil| StencilChoice::Image(stencil.image.clone())); + let texture = match ¤t { + Some(StencilChoice::Image(name)) => app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image)), + _ => None, + }; + let (name, source) = match ¤t { + Some(StencilChoice::Image(name)) => (name.clone(), tr("Imported image")), + _ => (tr("None").to_owned(), tr("Pick an image to paint through")), + }; + let tokens = Tokens::get(&ctx); + let thumbnail = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + if let Some(texture) = &texture { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + }; + let slot = sheet.slot(&thumbnail, &name, source, None, current.is_some(), false); + let slot_pick = + slot.pick.clone().on_hover_text(tr("S + left-drag rotates (with Shift in 15° steps), S + right-drag scales, S + middle-drag moves the stencil")); + + let popup = sheet.ui.make_persistent_id("brush_stencil_source"); + if slot_pick.clicked() { + resource_picker::toggle(&ctx, popup); + } + let tabs = || { + let textures = ResourcePickerItem::textures(&app.session, StencilChoice::Import, |name| StencilChoice::Image(name.to_owned())); + vec![PickerTab { icon: ic::FRAME_CORNERS, name: tr("Stencils"), groups: vec![PickerGroup { header: None, items: textures }] }] + }; + match resource_picker::show(&slot_pick, popup, &mut app.thumbs, current.as_ref(), true, tabs) { + Some(StencilChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"), + Some(choice) if Some(&choice) != current.as_ref() => { + if let StencilChoice::Image(name) = choice { + app.run("tool.stencil", json!({ "image": name })); + } + } + _ => {} + } + if slot.clear { + app.run("tool.stencil", json!({"clear": true})); + } + + // An image from the Assets panel dropped on the slot becomes the stencil + if let Some(name) = crate::dock::image_drop(sheet.ui, &slot_pick) { + app.run("tool.stencil", json!({ "image": name })); + } + sheet.close_card(); +} + +/// Scale, Rotation and Position X / Y beside a picture of the view with the stencil placed in it +fn placement_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, stencil: &StencilState) { + let ctx = sheet.ui.ctx().clone(); + let tokens = Tokens::get(&ctx); + let image = app.session.images.get(&stencil.image).cloned(); + let texture = image.as_ref().map(|image| app.thumbs.stencil(&ctx, &stencil.image, image)); + let view_aspect = app.session.viewport.x.max(1.0) / app.session.viewport.y.max(1.0); + let image_aspect = image.as_ref().map_or(1.0, |image| image.width as f32 / image.height.max(1) as f32); + let picture = |painter: &Painter, rect: Rect| { + painter.rect_filled(rect, CornerRadius::ZERO, tokens.field); + let view = fit(rect.shrink(VIEW_INSET), view_aspect); + painter.rect_filled(view, CornerRadius::ZERO, tokens.panel); + if let Some(texture) = &texture { + paint_stencil(&painter.with_clip_rect(view), view, texture.id(), stencil, image_aspect, Color32::WHITE, stencil.tile); + } + painter.rect_stroke(view, CornerRadius::ZERO, Stroke::new(VIEW_OUTLINE_WIDTH, tokens.text_dim), StrokeKind::Inside); + }; + + let (mut scale, mut rotation, [mut x, mut y]) = (stencil.scale, stencil.rotation, stencil.center); + let edits = sheet.picture_sliders( + &picture, + &mut [ + StackSlider { label: tr("Scale"), value: &mut scale, range: SCALE_RANGE, typed: SCALE_RANGE, decimals: 2, suffix: "", dial: false }, + StackSlider { label: tr("Rotation"), value: &mut rotation, range: ROTATION_RANGE, typed: ROTATION_RANGE, decimals: 0, suffix: "°", dial: true }, + StackSlider { label: tr("Position X"), value: &mut x, range: POSITION_RANGE, typed: POSITION_RANGE, decimals: 2, suffix: "", dial: false }, + StackSlider { label: tr("Position Y"), value: &mut y, range: POSITION_RANGE, typed: POSITION_RANGE, decimals: 2, suffix: "", dial: false }, + ], + ); + let [scale_edit, rotation_edit, x_edit, y_edit] = edits.map(|edit| edit.is_some()); + let mut params = serde_json::Map::new(); + if scale_edit { + params.insert("scale".into(), json!(scale)); + } + if rotation_edit { + params.insert("rotation".into(), json!(rotation)); + } + if x_edit || y_edit { + params.insert("center".into(), json!([x, y])); + } + if !params.is_empty() { + app.run("tool.stencil", Value::Object(params)); + } +} + +/// The largest rect of `aspect` (width / height) centred in `outer` +fn fit(outer: Rect, aspect: f32) -> Rect { + let width = outer.width().min(outer.height() * aspect); + Rect::from_center_size(outer.center(), vec2(width, width / aspect.max(f32::EPSILON))) +} + +/// Paints the stencil's image where it sits in the view `rect`, `tint`ed: one copy, or every copy that reaches the view when `tiled`; returns the middle copy's corners (top left, top right, bottom right, bottom left) +pub(crate) fn paint_stencil( + painter: &Painter, + rect: Rect, + texture: TextureId, + stencil: &StencilState, + image_aspect: f32, + tint: Color32, + tiled: bool, +) -> [Pos2; 4] { + let aspect = rect.width() / rect.height().max(1.0); + let (center, half_size, rotation) = stencil.placement(image_aspect, aspect); + let to_screen = |x: f32, y: f32| pos2(rect.left() + (x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - y * 0.5) * rect.height()); + let (sine, cosine) = rotation.sin_cos(); + + let square = [(-1.0, 1.0), (1.0, 1.0), (1.0, -1.0), (-1.0, -1.0)]; + let corners = square.map(|(x, y)| { + let (x, y) = (x * half_size[0], y * half_size[1]); + to_screen(center[0] + x * cosine - y * sine, center[1] + x * sine + y * cosine) + }); + + let mut mesh = egui::Mesh::with_texture(texture); + for ((x, y), corner) in square.into_iter().zip(corners) { + let (position, local_x, local_y) = if tiled { + // Map view corners back into stencil space so the sampler repeats at any scale + let (dx, dy) = (x - center[0], y - center[1]); + (to_screen(x, y), (dx * cosine + dy * sine) / half_size[0].max(f32::EPSILON), (dy * cosine - dx * sine) / half_size[1].max(f32::EPSILON)) + } else { + (corner, x, y) + }; + let uv = pos2(0.5 + local_x * 0.5, 0.5 - local_y * 0.5); + mesh.vertices.push(egui::epaint::Vertex { pos: position, uv, color: tint }); + } + + mesh.indices.extend([0, 1, 2, 0, 2, 3]); + painter.add(egui::Shape::mesh(mesh)); + corners +} + +/// A Tiling mode's picture: one square for No Tiling, four for H and V Tiling +fn paint_tiling(painter: &Painter, rect: Rect, tile: bool, color: Color32) { + let cell = rect.width() * TILE_CELL_FRACTION; + if !tile { + painter.rect_filled(Rect::from_center_size(rect.center(), vec2(cell, cell)), CornerRadius::ZERO, color); + return; + } + + let half_step = (cell + TILE_CELL_GAP) / 2.0; + for (direction_x, direction_y) in [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] { + let center = rect.center() + vec2(direction_x * half_step, direction_y * half_step); + painter.rect_filled(Rect::from_center_size(center, vec2(cell, cell)), CornerRadius::ZERO, color); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_tiny_offset_tiled_stencil_repeats_across_the_placement_picture() { + let ctx = egui::Context::default(); + let view = Rect::from_min_size(pos2(0.0, 0.0), vec2(200.0, 200.0)); + let image = std::sync::Arc::new(texturecraft_engine::compose::ImageRes::new(2, 8, vec![[1.0; 4]; 16], false)); + let stencil = StencilState { center: [2.0, 2.0], scale: 0.05, rotation: 90.0, tile: true, ..StencilState::new("offset") }; + let texture = crate::thumbs::Thumbs::default().stencil(&ctx, "offset", &image); + + let mut frame = ctx.run_ui(egui::RawInput::default(), |ui| { + paint_stencil(ui.painter(), view, texture.id(), &stencil, 0.25, Color32::WHITE, true); + }); + let options = frame.textures_delta.set[&texture.id()][0].options; + frame.textures_delta.clear(); + let mesh = frame + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Mesh(mesh) if mesh.texture_id == texture.id() => Some(mesh), + _ => None, + }) + .expect("the stencil picture"); + println!("Tile geometry: {} vertices, {} indices", mesh.vertices.len(), mesh.indices.len()); + + assert!(mesh.calc_bounds().contains_rect(view), "the rotated tiles reach the entire view"); + if mesh.vertices.iter().any(|vertex| !(0.0..=1.0).contains(&vertex.uv.x) || !(0.0..=1.0).contains(&vertex.uv.y)) { + assert_eq!(options.wrap_mode, egui::TextureWrapMode::Repeat, "the image repeats outside its first tile"); + } + } +} diff --git a/crates/ui-egui/src/tabbed_page.rs b/crates/ui-egui/src/tabbed_page.rs new file mode 100644 index 00000000..815af5eb --- /dev/null +++ b/crates/ui-egui/src/tabbed_page.rs @@ -0,0 +1,8 @@ +//! Which page under jump tabs the Properties panel shows + +/// A fill's sections (`mask` for a mask fill effect) or the paint tool's +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum TabbedPage { + Fill { mask: bool }, + Tool, +} diff --git a/crates/ui-egui/src/texture_set_list.rs b/crates/ui-egui/src/texture_set_list.rs new file mode 100644 index 00000000..3e394fcd --- /dev/null +++ b/crates/ui-egui/src/texture_set_list.rs @@ -0,0 +1,787 @@ +//! The Texture Set list: a toolbar, one row per set with its dropdowns, edits in place, a menu and a UV tile set's tiles + +use egui::{Align2, CornerRadius, FontId, Popup, Rect, Response, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::project::{MAX_RESOLUTION, MIN_RESOLUTION}; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::layer_toolbar::{AddItem, ItemIcon, MENU_PADDING, MenuIcon, Pick, menu_button, menu_frame, menu_row, menu_width}; +use crate::property_sheet::option_row; +use crate::shader_settings::INSTANCE_NAME; +use crate::theme::{Tokens, semibold}; +use crate::widgets::elided; + +mod description_mode; +mod list_state; +mod row_action; +mod row_edit; +mod set_row; +mod tile_action; + +use description_mode::DescriptionMode; +pub(crate) use list_state::ListState; +use row_action::RowAction; +use row_edit::RowEdit; +use set_row::SetRow; +use tile_action::TileAction; + +/// The layer toolbar's height and its menu buttons, so both panels' toolbars line up +const BAR_HEIGHT: f32 = 40.0; +const BAR_PADDING: f32 = 8.0; +const MENU_BUTTON: egui::Vec2 = vec2(32.0, 26.0); +const SOLO_SIZE: f32 = 24.0; +const SOLO_GAP: f32 = 6.0; + +/// Row geometry: a set row, the description line under it and a UV tile row +const ROW_HEIGHT: f32 = 28.0; +const DESCRIPTION_HEIGHT: f32 = 14.0; +const TILE_ROW_HEIGHT: f32 = 24.0; +const ROW_GAP: f32 = 2.0; +const ROW_INSET: f32 = 6.0; +const ROW_ROUNDING: u8 = 4; +const GLYPH_SIZE: f32 = 20.0; +const GLYPH_FONT: f32 = 14.0; +const NAME_GAP: f32 = 8.0; +const FOLD_WIDTH: f32 = 14.0; +const TILE_INDENT: f32 = 34.0; +const TILE_BRANCH: f32 = 12.0; + +const NAME_SIZE: f32 = 12.0; +const DESCRIPTION_SIZE: f32 = 11.0; +const CARET_SIZE: f32 = 11.0; + +/// A row dropdown: its text, the caret after it and the air around both +const DROPDOWN_HEIGHT: f32 = 22.0; +const DROPDOWN_TEXT_X: f32 = 6.0; +const DROPDOWN_CARET_GAP: f32 = 4.0; +const DROPDOWN_RIGHT: f32 = 6.0; +const DROPDOWN_GAP: f32 = 4.0; +const SIZE_LIST_WIDTH: f32 = 72.0; + +/// Narrow panels drop the shader dropdown, then the size, before cutting the name +const SHADER_MIN_ROW_WIDTH: f32 = 240.0; +const SIZE_MIN_ROW_WIDTH: f32 = 160.0; + +/// From an edit field's left edge to its text: the field starts this far left of the drawn text +const EDIT_TEXT_X: f32 = 4.0; +/// The name field's air above and below inside the row +const EDIT_FIELD_INSET: f32 = 3.0; +/// The description line starts this far up into the set row and stops this far above the row's end +const DESCRIPTION_OVERLAP: f32 = 4.0; +const DESCRIPTION_BOTTOM: f32 = 1.0; +/// The description field's air above and below its text +const DESCRIPTION_FIELD_AIR: f32 = 1.0; +/// How far an empty description's placeholder fades from the dim text +const PLACEHOLDER_FADE: f32 = 0.7; +/// Keyboard focus ring: inset from the row's edge +const FOCUS_INSET: f32 = 2.0; +/// Space between a dropdown and its list +const MENU_GAP: f32 = 1.0; + +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + // The empty state lists nothing + if !app.session.project_open { + return; + } + + let tokens = Tokens::get(ui.ctx()); + let mut state = ListState::load(ui.ctx(), (app.session.project_id, app.session.mesh_id)); + + let rows: Vec = (0..app.session.doc.project.texture_sets.len()) + .filter_map(|index| { + let set = app.session.doc.project.texture_sets.get(index)?; + Some(SetRow { + name: set.name.clone(), + description: set.description.clone(), + renamed: app.session.original_set_name(index).is_some_and(|original| original != set.name), + width: set.resolution, + height: set.height(), + visible: set.visible, + tiles: set.uv_tiles.iter().map(|tile| (*tile, set.tile_resolution(*tile))).collect(), + }) + }) + .collect(); + + // A picked UV tile only stays picked while its set is the active one + let active = app.session.ts(); + if state.tile.is_some_and(|(set, tile)| set != active || !rows.get(set).is_some_and(|row| row.tiles.iter().any(|(udim, _)| *udim == tile))) { + state.tile = None; + } + + toolbar(app, ui, &mut state, &rows, active, &tokens); + egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { + ui.spacing_mut().item_spacing = vec2(0.0, ROW_GAP); + for (index, row) in rows.iter().enumerate() { + let action = set_row(app, ui, &mut state, index, row, index == active, &tokens); + if !row.tiles.is_empty() && !state.folded.contains(&index) { + for (udim, resolution) in &row.tiles { + let selected = state.tile == Some((index, *udim)); + match tile_row(ui, index, *udim, *resolution, row.width, selected, &tokens) { + Some(TileAction::Select) => { + app.run("textureSet.select", json!({"ts": index})); + state.tile = Some((index, *udim)); + } + Some(TileAction::Resize(size)) => { + app.run("textureSet.tile.resolution", json!({"ts": index, "tile": udim, "resolution": size})); + } + None => {} + } + } + } + match action { + Some(RowAction::Select) => { + app.run("textureSet.select", json!({"ts": index})); + state.tile = None; + } + Some(RowAction::ToggleVisible) => { + app.run("textureSet.visible", json!({"ts": index})); + } + Some(RowAction::Resize(width)) => { + app.start_resize(index, width); + } + Some(RowAction::Edit(edit)) => { + let text = if edit == RowEdit::Name { row.name.clone() } else { row.description.clone() }; + state.edit = Some((index, edit, text, true)); + } + Some(RowAction::ResetName) => { + app.run("textureSet.rename", json!({"ts": index, "reset": true})); + } + Some(RowAction::ToggleFold) => { + if state.folded.contains(&index) { + state.folded.remove(&index); + } else { + state.folded.insert(index); + } + } + None => {} + } + } + }); + state.hovered = ui.ui_contains_pointer().then(|| ui.ctx().cumulative_pass_nr()); + state.store(ui.ctx()); +} + +/// Whether the pointer was over the list in the last pass, so F2 and the menu keys are the list's and not their bindings +pub(crate) fn pointer_over(ctx: &egui::Context) -> bool { + // A list no longer drawn (another tab, no project) has none + ListState::stored(ctx).and_then(|state| state.hovered).is_some_and(|pass| pass + 1 == ctx.cumulative_pass_nr()) +} + +/// Hands the selected row F2 (`rename`) or Shift+F10 or the Menu key (`menu`), read before the shortcuts ran +pub(crate) fn take_keys(ctx: &egui::Context, rename: bool, menu: bool) { + if let Some(mut state) = ListState::stored(ctx).filter(|_| rename || menu) { + state.rename_key |= rename; + state.menu_key |= menu; + state.store(ctx); + } +} + +/// Visibility menu and solo at the left, the descriptions menu at the right +fn toolbar(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, rows: &[SetRow], active: usize, tokens: &Tokens) { + let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), BAR_HEIGHT), Sense::hover()); + let visibility = Rect::from_min_size(pos2(bar.left() + BAR_PADDING, bar.center().y - MENU_BUTTON.y * 0.5), MENU_BUTTON); + let items = || { + [(ic::EYE, "Show All", "showAll"), (ic::EYE_SLASH, "Hide All", "hideAll"), (ic::SWAP, "Invert Show/Hide", "invert")] + .into_iter() + .map(|(glyph, short, mode)| AddItem { + icon: ItemIcon::Glyph(glyph), + short, + long: short, + command: "textureSet.visibility", + params: json!({ "mode": mode }), + enabled: true, + }) + .collect() + }; + if let Some(Pick::Run { command, params }) = + menu_button(ui, visibility, tr("Show or hide texture sets"), MenuIcon::Glyph(ic::EYE), tr("Visibility"), items, tokens) + { + app.run(command, params); + } + + let solo_rect = Rect::from_min_size(pos2(visibility.right() + SOLO_GAP, bar.center().y - SOLO_SIZE * 0.5), vec2(SOLO_SIZE, SOLO_SIZE)); + let solo = rows.len() > 1 && rows.iter().enumerate().all(|(index, row)| row.visible == (index == active)); + if glyph_button(ui, "ts_solo", solo_rect, ic::NUMBER_CIRCLE_ONE, tr("Show only the selected texture set"), solo, tokens).clicked() { + app.run("textureSet.visibility", json!({ "mode": "solo" })); + } + + // The descriptions choice is the list's own look, so it stays in the UI + let menu = Rect::from_min_size(pos2(bar.right() - BAR_PADDING - MENU_BUTTON.x, bar.center().y - MENU_BUTTON.y * 0.5), MENU_BUTTON); + let modes = [ + (DescriptionMode::HideEmpty, "Hide Empty Descriptions"), + (DescriptionMode::ShowAll, "Show All Descriptions"), + (DescriptionMode::HideAll, "Hide All Descriptions"), + ]; + let current = state.descriptions; + let items = || { + modes + .iter() + .enumerate() + .map(|(index, (mode, short))| AddItem { + icon: ItemIcon::Glyph(if *mode == current { ic::CHECK } else { "" }), + short, + long: short, + command: "", + params: json!(index), + enabled: true, + }) + .collect() + }; + if let Some(Pick::Run { params, .. }) = menu_button(ui, menu, tr("Texture set list settings"), MenuIcon::Glyph(ic::LIST), tr("Descriptions"), items, tokens) + && let Some((mode, _)) = params.as_u64().and_then(|index| modes.get(usize::try_from(index).ok()?)) + { + state.descriptions = *mode; + } +} + +/// One texture set: eye, fold caret for UV tiles, name (or its field), size and shader dropdowns, description line +fn set_row(app: &mut TextureCraftApp, ui: &mut Ui, state: &mut ListState, index: usize, row: &SetRow, selected: bool, tokens: &Tokens) -> Option { + let editing_description = matches!(state.edit, Some((set, RowEdit::Description, ..)) if set == index); + let description_line = editing_description || state.descriptions.shows(&row.description); + let height = if description_line { ROW_HEIGHT + DESCRIPTION_HEIGHT } else { ROW_HEIGHT }; + let (full, response) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &row.name)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(selected)); + let rect = Rect::from_min_size(full.min, vec2(full.width(), ROW_HEIGHT)); + + let painter = ui.painter(); + if selected { + painter.rect(full, CornerRadius::same(ROW_ROUNDING), tokens.row_selected, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(full, CornerRadius::same(ROW_ROUNDING), tokens.row_hover); + } + if response.has_focus() { + painter.rect_stroke(full.shrink(FOCUS_INSET), CornerRadius::same(ROW_ROUNDING), Stroke::new(1.0, tokens.text_strong), StrokeKind::Inside); + } + + let mut action = None; + let eye = Rect::from_center_size(pos2(rect.left() + ROW_INSET + GLYPH_SIZE * 0.5, rect.center().y), vec2(GLYPH_SIZE, GLYPH_SIZE)); + let eye_label = if row.visible { tr("Hide texture set") } else { tr("Show texture set") }; + let eye_response = glyph_button(ui, ("ts_eye", index), eye, if row.visible { ic::EYE } else { ic::EYE_SLASH }, eye_label, false, tokens); + if eye_response.clicked() { + action = Some(RowAction::ToggleVisible); + } + if ui.is_enabled() && (response.contains_pointer() || eye_response.contains_pointer()) { + app.next_hovered_texture_set = Some((app.session.project_id, index)); + } + + let mut name_x = eye.right() + NAME_GAP; + if !row.tiles.is_empty() { + let folded = state.folded.contains(&index); + let fold = Rect::from_min_size(pos2(name_x - NAME_GAP * 0.5, rect.top()), vec2(FOLD_WIDTH, ROW_HEIGHT)); + let label = if folded { tr("Show UV tiles") } else { tr("Hide UV tiles") }; + if glyph_button(ui, ("ts_fold", index), fold, if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, label, false, tokens).clicked() { + action = Some(RowAction::ToggleFold); + } + name_x = fold.right() + NAME_GAP * 0.5; + } + + // Dropdowns from the right edge: shader, then size + let mut right = rect.right() - ROW_INSET; + let name_color = if !row.visible { + tokens.text_dim + } else if selected { + tokens.text_strong + } else { + tokens.text + }; + if rect.width() >= SHADER_MIN_ROW_WIDTH { + let shader = tr(INSTANCE_NAME); + let name = trf("Shader of {name}", &[("name", &row.name)]); + let dropdown = row_dropdown(ui, ("ts_shader", index), pos2(right, rect.center().y), (shader, &name), true, tokens, |ui| { + let _ = option_row(ui, shader, true); + }); + right = dropdown.left() - DROPDOWN_GAP; + } + if rect.width() >= SIZE_MIN_ROW_WIDTH { + let text = if row.width == row.height { row.width.to_string() } else { format!("{}x{}", row.width, row.height) }; + let mut picked = None; + let name = trf("Size of {name}", &[("name", &row.name)]); + let dropdown = row_dropdown(ui, ("ts_size", index), pos2(right, rect.center().y), (&text, &name), true, tokens, |ui| { + picked = size_list(ui, row.width); + }); + if let Some(size) = picked { + action = Some(RowAction::Resize(size)); + } + right = dropdown.left() - DROPDOWN_GAP; + } + + let editing_name = matches!(state.edit, Some((set, RowEdit::Name, ..)) if set == index); + if editing_name { + let field = Rect::from_min_max(pos2(name_x - EDIT_TEXT_X, rect.top() + EDIT_FIELD_INSET), pos2(right, rect.bottom() - EDIT_FIELD_INSET)); + if let Some(name) = edit_field(ui, state, field, NAME_SIZE) + && name.trim() != row.name + { + app.run("textureSet.rename", json!({"ts": index, "name": name})); + } + } else { + let font = if selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + let mut job = egui::text::LayoutJob::simple_singleline(row.name.clone(), font, name_color); + job.wrap = egui::text::TextWrapping::truncate_at_width((right - name_x).max(0.0)); + let galley = ui.painter().layout_job(job); + ui.painter().galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, name_color); + } + + if description_line { + let line = Rect::from_min_max(pos2(name_x, rect.bottom() - DESCRIPTION_OVERLAP), pos2(full.right() - ROW_INSET, full.bottom() - DESCRIPTION_BOTTOM)); + if editing_description { + if let Some(description) = edit_field(ui, state, line.expand2(vec2(EDIT_TEXT_X, DESCRIPTION_FIELD_AIR)), DESCRIPTION_SIZE) + && description.trim() != row.description + { + app.run("textureSet.settings", json!({"ts": index, "description": description.trim()})); + } + } else { + let (text, color) = if row.description.trim().is_empty() { + (tr("No description").to_owned(), tokens.text_dim.gamma_multiply(PLACEHOLDER_FADE)) + } else { + (row.description.clone(), tokens.text_dim) + }; + let galley = elided(ui.painter(), text, DESCRIPTION_SIZE, color, line.width()); + ui.painter().galley(pos2(line.left(), line.center().y - galley.size().y * 0.5), galley, color); + } + } + + // F2 renames the focused row, or the selected one with the pointer over the list, as a double click does + let rename_key = (selected && std::mem::take(&mut state.rename_key)) + || (response.has_focus() && ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, egui::Key::F2))); + if response.double_clicked() || rename_key { + action = Some(RowAction::Edit(RowEdit::Name)); + } else if action.is_none() && (response.clicked() || response.secondary_clicked()) { + action = Some(RowAction::Select); + } + let menu_key = selected && std::mem::take(&mut state.menu_key); + context_menu(ui, &response, row, menu_key, tokens).or(action) +} + +/// The row's right-click menu in the toolbar menus' look, also from Shift+F10 or the Menu key (`menu_key` over the list) +fn context_menu(ui: &Ui, response: &Response, row: &SetRow, menu_key: bool, tokens: &Tokens) -> Option { + let visibility = if row.visible { (ic::EYE_SLASH, "Hide Texture Set") } else { (ic::EYE, "Show Texture Set") }; + let entries = [ + (visibility.0, visibility.1, true, RowAction::ToggleVisible), + (ic::PENCIL_SIMPLE, "Edit Name", true, RowAction::Edit(RowEdit::Name)), + (ic::ARROW_COUNTER_CLOCKWISE, "Reset Name to Original", row.renamed, RowAction::ResetName), + (ic::NOTE_PENCIL, "Edit Description", true, RowAction::Edit(RowEdit::Description)), + ]; + let items = entries.map(|(glyph, short, enabled, _)| AddItem { + icon: ItemIcon::Glyph(glyph), + short, + long: short, + command: "", + params: serde_json::Value::Null, + enabled, + }); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_has_popup(egui::accesskit::HasPopup::Menu)); + let mut popup = Popup::context_menu(response).frame(menu_frame(tokens)); + let return_focus = popup.is_open() && ui.input(|input| input.key_pressed(egui::Key::Escape)); + + // A menu opened from the keyboard has no pointer to open at: it hangs under the row while it stays open + let from_keyboard = response.id.with("ts_menu_from_keyboard"); + let pressed = + |input: &mut egui::InputState| input.consume_key(egui::Modifiers::SHIFT, egui::Key::F10) || input.consume_key(egui::Modifiers::NONE, egui::Key::Menu); + if menu_key || (response.has_focus() && ui.input_mut(pressed)) { + ui.data_mut(|data| data.insert_temp(from_keyboard, true)); + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); + } else if !popup.is_open() { + ui.data_mut(|data| data.remove::(from_keyboard)); + } + if ui.data(|data| data.get_temp::(from_keyboard)).unwrap_or(false) { + popup = popup.anchor(response); + } + + let mut picked = None; + popup.show(|ui| { + let width = menu_width(ui, &items); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); + ui.add_space(MENU_PADDING); + for (item, (.., action)) in items.iter().zip(entries) { + if menu_row(ui, width, item, tokens).clicked() { + picked = Some(action); + ui.close(); + } + } + ui.add_space(MENU_PADDING); + }); + if return_focus { + response.request_focus(); + } + picked +} + +/// A UV tile under its set: a branch from the set's fold caret, its UDIM and its own size dropdown +fn tile_row(ui: &mut Ui, set: usize, udim: u32, resolution: u32, set_width: u32, selected: bool, tokens: &Tokens) -> Option { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), TILE_ROW_HEIGHT), Sense::click()); + let label = trf("UV tile {udim}", &[("udim", &udim)]); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &label)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(selected)); + let face = rect.with_min_x(rect.left() + TILE_INDENT - ROW_INSET); + let painter = ui.painter(); + if selected { + painter.rect(face, CornerRadius::same(ROW_ROUNDING), tokens.row_selected, Stroke::new(1.0, tokens.accent), StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(face, CornerRadius::same(ROW_ROUNDING), tokens.row_hover); + } + if response.has_focus() { + painter.rect_stroke(face.shrink(FOCUS_INSET), CornerRadius::same(ROW_ROUNDING), Stroke::new(1.0, tokens.text_strong), StrokeKind::Inside); + } + let branch_x = rect.left() + ROW_INSET + GLYPH_SIZE + NAME_GAP * 0.5 + FOLD_WIDTH * 0.5; + painter.vline(branch_x, rect.top() - ROW_GAP..=rect.center().y, Stroke::new(1.0, tokens.separator)); + painter.hline(branch_x..=branch_x + TILE_BRANCH, rect.center().y, Stroke::new(1.0, tokens.separator)); + let color = if selected { tokens.text_strong } else { tokens.text }; + let font = if selected { semibold(NAME_SIZE) } else { FontId::proportional(NAME_SIZE) }; + painter.text(pos2(rect.left() + TILE_INDENT, rect.center().y), Align2::LEFT_CENTER, &label, font, color); + + // An overridden tile shows its size in full text colour, one that follows the set dims it + let mut picked = None; + let text = resolution.to_string(); + let name = trf("Size of UV tile {udim}", &[("udim", &udim)]); + let size_right = rect.right() - ROW_INSET - shader_column_width(ui, rect.width()); + let dim = resolution == set_width; + row_dropdown(ui, ("ts_tile_size", set, udim), pos2(size_right, rect.center().y), (&text, &name), dim, tokens, |ui| { + picked = size_list(ui, resolution); + }); + if let Some(size) = picked { + return Some(TileAction::Resize(size)); + } + + (response.clicked() || response.secondary_clicked()).then_some(TileAction::Select) +} + +/// The shader dropdown's width on set rows, so tile sizes line up under set sizes +fn shader_column_width(ui: &Ui, row_width: f32) -> f32 { + if row_width < SHADER_MIN_ROW_WIDTH { + return 0.0; + } + + dropdown_width(ui, tr(INSTANCE_NAME)) + DROPDOWN_GAP +} + +fn dropdown_width(ui: &Ui, text: &str) -> f32 { + let text_width = ui.fonts_mut(|fonts| fonts.layout_no_wrap(text.to_owned(), FontId::proportional(NAME_SIZE), egui::Color32::WHITE).size().x); + DROPDOWN_TEXT_X + text_width + DROPDOWN_CARET_GAP + CARET_SIZE + DROPDOWN_RIGHT +} + +/// A dropdown drawn as its text (`labels`: shown text, then what it sets) and a small caret, its right end middle at `anchor`: a button face only while hovered or open +fn row_dropdown( + ui: &mut Ui, + id: impl egui::AsIdSalt, + anchor: egui::Pos2, + labels: (&str, &str), + dim: bool, + tokens: &Tokens, + list: impl FnOnce(&mut Ui), +) -> Rect { + let (text, name) = labels; + let width = dropdown_width(ui, text); + let rect = Rect::from_min_size(pos2(anchor.x - width, anchor.y - DROPDOWN_HEIGHT * 0.5), vec2(width, DROPDOWN_HEIGHT)); + let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(name); + let accessible = format!("{text}, {name}"); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), &accessible)); + let popup = Popup::menu(&response).frame(menu_frame(tokens)).width(SIZE_LIST_WIDTH.max(width)).gap(MENU_GAP).align(egui::RectAlign::BOTTOM_END); + let open = popup.is_open(); + let painter = ui.painter(); + if open || response.hovered() { + painter.rect(rect, CornerRadius::same(ROW_ROUNDING), tokens.button, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + let color = if dim && !response.hovered() && !open { tokens.text_dim } else { tokens.text }; + painter.text(pos2(rect.left() + DROPDOWN_TEXT_X, rect.center().y), Align2::LEFT_CENTER, text, FontId::proportional(NAME_SIZE), color); + painter.text( + pos2(rect.right() - DROPDOWN_RIGHT - CARET_SIZE * 0.5, rect.center().y), + Align2::CENTER_CENTER, + ic::CARET_DOWN, + FontId::proportional(CARET_SIZE), + tokens.text_dim, + ); + popup.show(|ui| { + ui.set_min_width(SIZE_LIST_WIDTH.max(width)); + ui.add_space(MENU_PADDING); + list(ui); + ui.add_space(MENU_PADDING); + }); + rect +} + +/// The sizes a set or tile can take, the current one ticked; the one picked +fn size_list(ui: &mut Ui, current: u32) -> Option { + let mut picked = None; + let mut size = MIN_RESOLUTION; + while size <= MAX_RESOLUTION { + if option_row(ui, &size.to_string(), size == current).clicked() && size != current { + picked = Some(size); + } + size *= 2; + } + picked +} + +/// The field of the row's text being edited: Enter (or clicking away) gives the text, Esc drops it +fn edit_field(ui: &mut Ui, state: &mut ListState, rect: Rect, size: f32) -> Option { + let (_, _, text, needs_focus) = state.edit.as_mut()?; + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); + + // The text sits where the drawn name or description sat, centred in the field + let font = FontId::proportional(size); + let text_height = ui.fonts_mut(|fonts| fonts.row_height(&font)); + let margin = vec2(EDIT_TEXT_X, ((rect.height() - text_height) * 0.5).max(0.0)); + let response = child.add_sized(rect.size(), egui::TextEdit::singleline(text).font(font).margin(margin)); + if std::mem::take(needs_focus) { + response.request_focus(); + } + if !response.lost_focus() { + return None; + } + + let edit = state.edit.take()?; + + // Raw Escape: with the field's focus gone, the window's cancel takes it from egui's input + let escaped = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + (!escaped).then_some(edit.2) +} + +/// A glyph button of the list: dim glyph, bright and framed when hovered or lit +fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, label: &str, lit: bool, tokens: &Tokens) -> Response { + let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(label); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), lit, label)); + if lit || response.hovered() { + ui.painter().rect(rect, CornerRadius::same(ROW_ROUNDING), tokens.button, Stroke::new(1.0, tokens.button_border), StrokeKind::Inside); + } + let color = if lit || response.hovered() { tokens.text_strong } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_FONT), color); + response +} + +#[cfg(test)] +mod tests { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + + use super::*; + + fn harness(mesh: &str) -> Harness<'static, TextureCraftApp> { + let mesh_ref = format!("builtin:{mesh}"); + let geometry = texturecraft_engine::geom::primitives::builtin(mesh).unwrap(); + let session = texturecraft_engine::Session::new_project("Texture set list", geometry, &mesh_ref, None, 128).unwrap(); + let mut harness = Harness::builder() + // Tall enough that every row clears the panel under the list + .with_size(vec2(1600.0, 2400.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + harness + } + + /// Presses and lets go on `label`'s node through the real pointer path, as a person's click lands on a control drawn over its row + fn click(harness: &mut Harness<'static, TextureCraftApp>, role: egui::Role, label: &str, button: egui::PointerButton) { + let rect = harness.get_by_role_and_label(role, label).rect(); + + // A row's middle is under its size dropdown in a narrow panel: aim at its name + let at = if role == egui::Role::ListItem { egui::pos2(rect.left() + rect.width() * 0.25, rect.center().y) } else { rect.center() }; + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button, pressed: false, modifiers }); + harness.run_steps(2); + } + + #[test] + fn the_row_size_dropdown_resizes_its_set() { + let mut harness = harness("material_ball"); + let name = harness.state().session.doc.project.texture_sets[1].name.clone(); + + click(&mut harness, egui::Role::ComboBox, &format!("128, Size of {name}"), egui::PointerButton::Primary); + click(&mut harness, egui::Role::ListBoxOption, "512", egui::PointerButton::Primary); + + // Wait for the worker and let the next frame apply its actual result + if let Some(resize) = harness.state_mut().resize.as_mut() { + let result = resize.rx.recv_timeout(std::time::Duration::from_secs(30)).expect("resize worker did not send a result"); + let (sender, receiver) = std::sync::mpsc::channel(); + assert!(sender.send(result).is_ok(), "resize completion could not be forwarded"); + resize.rx = receiver; + } + + harness.run_steps(2); + + assert!(harness.state().resize.is_none(), "the app consumed the resize result"); + let sets = &harness.state().session.doc.project.texture_sets; + assert!(sets[1].resolution > 128 && sets[1].height() == sets[1].resolution, "the set grew and stayed square"); + assert_eq!(sets[0].resolution, 128, "the other set kept its size"); + } + + #[test] + fn a_width_change_cannot_distort_a_set_at_the_height_limit() { + let mut harness = harness("material_ball"); + let app = harness.state_mut(); + + for (width, height, picked_width) in [(256, 128, MIN_RESOLUTION), (128, 256, MAX_RESOLUTION)] { + texturecraft_engine::execute(&mut app.session, "textureSet.resolution", &json!({"resolution": width, "height": height})).unwrap(); + + app.start_resize(0, picked_width); + + assert!(app.resize.is_none(), "an unrepresentable height must not start a resize worker"); + assert_eq!(app.session.doc.project.texture_sets[0].size(), (width, height)); + } + } + + #[test] + fn the_right_click_menu_renames_in_place_and_resets_to_the_material_name() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + + click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Secondary); + click(&mut harness, egui::Role::Button, "Edit Name", egui::PointerButton::Primary); + harness.run_steps(3); + + // The field took focus, so typed text goes to it + harness.event(egui::Event::Text("x".into())); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + let renamed = harness.state().session.doc.project.texture_sets[1].name.clone(); + assert!(renamed != original && renamed.contains('x'), "{renamed}"); + + click(&mut harness, egui::Role::ListItem, &renamed, egui::PointerButton::Secondary); + click(&mut harness, egui::Role::Button, "Reset Name to Original", egui::PointerButton::Primary); + harness.run_steps(3); + assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original); + } + + #[test] + fn a_focused_row_renames_with_f2_and_opens_its_menu_from_the_keyboard() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + + harness.get_by_role_and_label(egui::Role::ListItem, &original).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::F2); + harness.run_steps(3); + harness.event(egui::Event::Text("y".into())); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + let renamed = harness.state().session.doc.project.texture_sets[1].name.clone(); + assert!(renamed != original && renamed.contains('y'), "{renamed}"); + + harness.get_by_role_and_label(egui::Role::ListItem, &renamed).focus(); + harness.run_steps(2); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_none()); + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + harness.run_steps(3); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu"); + } + + #[test] + fn escape_drops_a_rename_under_way() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Secondary); + click(&mut harness, egui::Role::Button, "Edit Name", egui::PointerButton::Primary); + harness.run_steps(3); + harness.event(egui::Event::Text("q".into())); + harness.run_steps(1); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original); + } + + #[test] + fn over_the_list_f2_renames_the_selected_set_and_shift_f10_opens_its_menu() { + // A clicked row has no keyboard focus, so these keys would otherwise reach the 3D view and Render mode + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + let layout = harness.state().ui.layout; + click(&mut harness, egui::Role::ListItem, &original, egui::PointerButton::Primary); + harness.key_press(egui::Key::F2); + harness.run_steps(3); + harness.event(egui::Event::Text("w".into())); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + let renamed = harness.state().session.doc.project.texture_sets[1].name.clone(); + assert!(renamed != original && renamed.contains('w'), "{renamed}"); + assert!(harness.state().ui.layout == layout, "the viewers layout stayed"); + + let mode = harness.state().ui.mode; + harness.key_press_modifiers(egui::Modifiers::SHIFT, egui::Key::F10); + harness.run_steps(3); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Edit Description").is_some(), "Shift+F10 opens the row's menu"); + assert!(harness.state().ui.mode == mode, "the mode stayed"); + } + + #[test] + fn a_modal_opening_over_the_hovered_list_blocks_its_row_keys() { + let mut harness = harness("material_ball"); + let name = harness.state().session.doc.project.texture_sets[1].name.clone(); + click(&mut harness, egui::Role::ListItem, &name, egui::PointerButton::Primary); + harness.state_mut().ui.keymap.insert("ui.layout.3d".into(), "F7".into()); + + // Open the modal after the list records its hover for the next pass + let modal = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("test_modal")); + let open = Arc::new(AtomicBool::new(false)); + let open_in_pass = Arc::clone(&open); + harness.ctx.on_end_pass( + "open test modal", + Arc::new(move |ui| { + if open_in_pass.swap(false, Ordering::Relaxed) { + ui.ctx().memory_mut(|memory| memory.set_modal_layer(modal)); + } + }), + ); + + for (key, modifiers) in [(egui::Key::F2, egui::Modifiers::NONE), (egui::Key::F10, egui::Modifiers::SHIFT), (egui::Key::Menu, egui::Modifiers::NONE)] { + harness.run_steps(2); + open.store(true, Ordering::Relaxed); + harness.step(); + assert_eq!(harness.ctx.memory(|memory| memory.top_modal_layer()), Some(modal)); + assert!(pointer_over(&harness.ctx), "the list still reports hover from the opening pass"); + + harness.event(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }); + harness.step(); + + assert!(ListState::stored(&harness.ctx).unwrap().edit.is_none(), "{key:?} did not start a rename behind the modal"); + assert!(!Popup::is_any_open(&harness.ctx), "{key:?} did not open the row menu behind the modal"); + } + } + + #[test] + fn a_rename_under_way_is_dropped_when_another_project_replaces_this_one() { + let mut harness = harness("material_ball"); + let original = harness.state().session.doc.project.texture_sets[1].name.clone(); + harness.get_by_role_and_label(egui::Role::ListItem, &original).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::F2); + harness.run_steps(3); + harness.event(egui::Event::Text("z".into())); + harness.run_steps(1); + + // Another project with the same texture sets takes this one's place mid-edit + let geometry = texturecraft_engine::geom::primitives::builtin("material_ball").unwrap(); + harness.state_mut().session = texturecraft_engine::Session::new_project("Other", geometry, "builtin:material_ball", None, 128).unwrap(); + harness.run_steps(3); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.texture_sets[1].name, original, "the new project's set keeps its name"); + } + + #[test] + fn a_uv_tile_row_sizes_its_own_tile() { + let mut harness = harness("udim_plane"); + let tiles = harness.state().session.doc.project.texture_sets[0].uv_tiles.clone(); + assert!(harness.query_by_role_and_label(egui::Role::ListItem, &format!("UV tile {}", tiles[1])).is_some()); + + click(&mut harness, egui::Role::ComboBox, &format!("128, Size of UV tile {}", tiles[1]), egui::PointerButton::Primary); + click(&mut harness, egui::Role::ListBoxOption, "256", egui::PointerButton::Primary); + harness.run_steps(3); + + let set = &harness.state().session.doc.project.texture_sets[0]; + assert!(set.tile_resolution(tiles[1]) > set.tile_resolution(tiles[0]), "only the picked tile grew"); + } +} diff --git a/crates/ui-egui/src/texture_set_list/description_mode.rs b/crates/ui-egui/src/texture_set_list/description_mode.rs new file mode 100644 index 00000000..ff042a2d --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/description_mode.rs @@ -0,0 +1,19 @@ +/// Which rows show their description line under the name (the list menu's choice) +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub(crate) enum DescriptionMode { + #[default] + HideEmpty, + ShowAll, + HideAll, +} + +impl DescriptionMode { + /// Whether a row with `description` shows the line + pub(crate) fn shows(self, description: &str) -> bool { + match self { + Self::HideEmpty => !description.trim().is_empty(), + Self::ShowAll => true, + Self::HideAll => false, + } + } +} diff --git a/crates/ui-egui/src/texture_set_list/list_state.rs b/crates/ui-egui/src/texture_set_list/list_state.rs new file mode 100644 index 00000000..d3776c43 --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/list_state.rs @@ -0,0 +1,47 @@ +use std::collections::BTreeSet; + +use super::{DescriptionMode, RowEdit}; + +/// The list's UI state: the row being edited, which descriptions show, folded UV tile sets and the selected tile +#[derive(Clone, Default)] +pub(crate) struct ListState { + /// Project and mesh ids the rows' set indices belong to + owner: (u64, u64), + /// Set, what it edits, the text so far, and whether the field still needs focus + pub(crate) edit: Option<(usize, RowEdit, String, bool)>, + pub(crate) descriptions: DescriptionMode, + /// UV tile sets whose tile rows are folded away + pub(crate) folded: BTreeSet, + /// Set and UDIM of the selected UV tile row + pub(crate) tile: Option<(usize, u32)>, + /// The last pass that drew the list with the pointer over it + pub(crate) hovered: Option, + /// F2 or the menu key came while the pointer was over the list: the selected row takes it in this pass + pub(crate) rename_key: bool, + pub(crate) menu_key: bool, +} + +impl ListState { + fn id() -> egui::Id { + egui::Id::unique("texture_set_list_state") + } + + /// Restore row state for `owner`. The description preference and last hover pass survive a change of project or mesh. + pub(crate) fn load(ctx: &egui::Context, owner: (u64, u64)) -> Self { + let state: Self = ctx.data(|data| data.get_temp::(Self::id())).unwrap_or_default(); + if state.owner == owner { + return state; + } + + ListState { owner, descriptions: state.descriptions, hovered: state.hovered, ..ListState::default() } + } + + /// The stored state, whatever project it belongs to + pub(crate) fn stored(ctx: &egui::Context) -> Option { + ctx.data(|data| data.get_temp::(Self::id())) + } + + pub(crate) fn store(self, ctx: &egui::Context) { + ctx.data_mut(|data| data.insert_temp(Self::id(), self)); + } +} diff --git a/crates/ui-egui/src/texture_set_list/row_action.rs b/crates/ui-egui/src/texture_set_list/row_action.rs new file mode 100644 index 00000000..a8340f3b --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/row_action.rs @@ -0,0 +1,12 @@ +use super::RowEdit; + +/// What a set row asks for once it has drawn +#[derive(Clone, Copy)] +pub(super) enum RowAction { + Select, + ToggleVisible, + Resize(u32), + Edit(RowEdit), + ResetName, + ToggleFold, +} diff --git a/crates/ui-egui/src/texture_set_list/row_edit.rs b/crates/ui-egui/src/texture_set_list/row_edit.rs new file mode 100644 index 00000000..c595220b --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/row_edit.rs @@ -0,0 +1,6 @@ +/// The text a row is editing in place +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum RowEdit { + Name, + Description, +} diff --git a/crates/ui-egui/src/texture_set_list/set_row.rs b/crates/ui-egui/src/texture_set_list/set_row.rs new file mode 100644 index 00000000..c0a22dd8 --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/set_row.rs @@ -0,0 +1,12 @@ +/// What one texture set row shows, read before drawing so commands can run while the rows draw +pub(crate) struct SetRow { + pub(crate) name: String, + pub(crate) description: String, + /// Whether the row can restore its original mesh material name + pub(crate) renamed: bool, + pub(crate) width: u32, + pub(crate) height: u32, + pub(crate) visible: bool, + /// UDIM and resolution of each UV tile, in UDIM order + pub(crate) tiles: Vec<(u32, u32)>, +} diff --git a/crates/ui-egui/src/texture_set_list/tile_action.rs b/crates/ui-egui/src/texture_set_list/tile_action.rs new file mode 100644 index 00000000..f638fef4 --- /dev/null +++ b/crates/ui-egui/src/texture_set_list/tile_action.rs @@ -0,0 +1,5 @@ +/// What a UV tile row asks for +pub(super) enum TileAction { + Select, + Resize(u32), +} diff --git a/crates/ui-egui/src/texture_set_settings.rs b/crates/ui-egui/src/texture_set_settings.rs new file mode 100644 index 00000000..8abd249a --- /dev/null +++ b/crates/ui-egui/src/texture_set_settings.rs @@ -0,0 +1,546 @@ +//! The Texture Set Settings panel: general properties, the set's channels and their mixing, and its mesh maps + +use egui::{Align2, CornerRadius, FontId, Popup, Rect, Sense, Stroke, StrokeKind, Ui, pos2, vec2}; +use egui_phosphor::regular as ic; +use serde_json::json; +use texturecraft_engine::core::{ + AoMixing, BakedMap, Channel, ChannelFormat, HeightToNormalMethod, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, TextureSet, UvPaddingMode, +}; + +use crate::TextureCraftApp; +use crate::i18n::{baked_map_label, tr, trf}; +use crate::layer_toolbar::menu_frame; +use crate::picker_group::PickerGroup; +use crate::picker_tab::PickerTab; +use crate::property_sheet::{PropertySheet, option_row}; +use crate::resource_picker; +use crate::resource_picker_item::ResourcePickerItem; +use crate::shader_settings::INSTANCE_NAME; +use crate::theme::{Tokens, semibold}; + +/// A channel row's height, and its name and format text sizes +const CHANNEL_ROW_HEIGHT: f32 = 26.0; +const CHANNEL_TEXT_SIZE: f32 = 12.0; + +/// A channel row's gear and × buttons, and the air between them and the format text +const GLYPH_BUTTON: f32 = 20.0; +const GLYPH_SIZE: f32 = 13.0; +const GLYPH_GAP: f32 = 3.0; +const FORMAT_GAP: f32 = 6.0; +const GLYPH_ROUNDING: u8 = 3; + +/// The channel format list's width and its padding +const FORMAT_LIST_WIDTH: f32 = 120.0; +const MENU_PADDING: f32 = 3.0; +/// Space between a channel's gear and its format list +const MENU_GAP: f32 = 1.0; + +/// Height to normal strength's slider range +const HEIGHT_STRENGTH_RANGE: std::ops::RangeInclusive = 0.0..=10.0; + +/// The empty slot's outline width (and inset), and the slot's corner rounding +const EMPTY_MAP_OUTLINE: f32 = 1.0; +const MAP_ROUNDING: u8 = 2; + +pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + crate::channel_manager::ChannelManager::show(app, &ui.ctx().clone()); + let set_index = app.session.ts(); + let Some(set) = app.session.doc.project.texture_sets.get(set_index).cloned() else { return }; + let list = crate::texture_set_list::ListState::load(ui.ctx(), (app.session.project_id, app.session.mesh_id)); + let tile = list.tile.filter(|(picked_set, udim)| *picked_set == set_index && set.uv_tiles.contains(udim)).map(|(_, udim)| udim); + egui::ScrollArea::vertical().id_salt("tss").show(ui, |ui| { + PropertySheet::show(ui, ("texture_set_settings", set_index), |sheet| { + general(app, sheet, set_index, &set, tile); + channels(app, sheet, set_index, &set); + mesh_maps(app, sheet, set_index, &set); + }); + }); +} + +/// Name, description, size (of the UV tile picked in the list, else of the set), UV tiles and shader +fn general(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet, tile: Option) { + sheet.section(tr("General Properties"), false); + sheet.attribute(tr("Name"), &set.name); + + // Typing merges into one undo step until the field loses focus; typing after it comes back starts another + let mut description = set.description.clone(); + let changed = sheet.text_field_above(tr("Description"), &mut description); + let typing_id = sheet.ui.scope_id().with(("tss_description_typing", ts)); + let focused = sheet.ui.memory(|memory| memory.focused()); + let typing = sheet.ui.data(|data| data.get_temp::>(typing_id)).flatten(); + if typing.is_some() && typing != focused { + sheet.ui.data_mut(|data| data.remove::>(typing_id)); + } + if changed { + let merge = typing.is_some() && typing == focused; + sheet.ui.data_mut(|data| data.insert_temp(typing_id, focused)); + app.run("textureSet.settings", json!({"ts": ts, "description": description, "merge": merge})); + } + + let sizes = resolutions(); + let size_name = |size: u32| size.to_string(); + if let Some(udim) = tile { + let label = trf("Size of UV tile {udim}", &[("udim", &udim)]); + if let Some(size) = sheet.dropdown_above(&label, set.tile_resolution(udim), &sizes, size_name) { + app.run("textureSet.tile.resolution", json!({"ts": ts, "tile": udim, "resolution": size})); + } + } else { + let lock_id = sheet.ui.scope_id().with(("tss_size_lock", ts)); + let mut locked = sheet.ui.data(|data| data.get_temp::(lock_id)).unwrap_or(set.resolution == set.height()); + let picked = sheet.dropdown_pair_above(tr("Size"), [set.resolution, set.height()], &sizes, size_name, &mut locked, tr("Lock Size")); + sheet.ui.data_mut(|data| data.insert_temp(lock_id, locked)); + let resize = match picked { + Some((0, width)) if locked => Some((width, width)), + Some((0, width)) => Some((width, set.height())), + Some((_, height)) => Some((set.resolution, height)), + None => None, + }; + if let Some((width, height)) = resize { + app.start_resize_to(ts, width, height); + } + } + + let mut tiled = !set.uv_tiles.is_empty(); + if sheet.check(tr("UV tiles (UDIM)"), &mut tiled) { + app.run("textureSet.uvTiles", json!({"ts": ts, "enabled": tiled})); + } + + // The project has one shader: the list holds it + sheet.dropdown(tr("Shader Instance"), 0, &[0], |_| tr(INSTANCE_NAME).to_owned(), None); +} + +/// Add or remove channels, a row per channel (name, format and its list, ×), then how they mix +fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet) { + sheet.section(tr("Channels"), false); + let manage = sheet.button(ic::LIST_PLUS, tr("Add or remove channels")); + if manage.clicked() { + crate::channel_manager::ChannelManager::open(app, &manage, ts); + } + for (channel, format) in set.formats() { + let (picked, remove) = channel_row(sheet, channel, format); + if let Some(picked) = picked { + app.run("textureSet.channel.format", json!({"ts": ts, "channel": channel.id(), "format": picked.label()})); + } + if remove { + app.run("textureSet.channel.remove", json!({"ts": ts, "channel": channel.id()})); + } + } + + let mixing = NormalMixing::ALL; + let mixing_name = |mixing| tr(if mixing == NormalMixing::Combine { "Combine" } else { "Replace" }).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Normal mixing"), set.normal_mixing, &mixing, mixing_name, None) { + app.run("textureSet.settings", json!({"ts": ts, "normalMixing": picked.id()})); + } + let methods = HeightToNormalMethod::ALL; + let method_name = |method| tr(if method == HeightToNormalMethod::Sharp { "Sharp" } else { "Smooth (Sobel)" }).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("Height to normal method"), set.height_to_normal, &methods, method_name, None) { + app.run("textureSet.settings", json!({"ts": ts, "heightToNormal": picked.id()})); + } + let mut strength = set.height_strength; + if let Some(merge) = sheet.slider(tr("Height to normal strength"), &mut strength, HEIGHT_STRENGTH_RANGE, 2) { + app.run("textureSet.settings", json!({"ts": ts, "heightStrength": strength, "merge": merge})); + } + + // Occlusion mixes a baked or set ambient occlusion map in: greyed until the set has one + let has_occlusion = app.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&BakedMap::AmbientOcclusion)); + let occlusion = AoMixing::ALL; + let occlusion_name = |mixing| tr(if mixing == AoMixing::Multiply { "Multiply" } else { "None" }).to_owned(); + let picked = sheet.greyed(has_occlusion, Some(tr("Needs an Ambient occlusion mesh map")), |sheet| { + sheet.dropdown(tr("Ambient occlusion mixing"), set.ao_mixing, &occlusion, occlusion_name, None).0 + }); + if let Some(picked) = picked { + app.run("textureSet.settings", json!({"ts": ts, "aoMixing": picked.id()})); + } + + let paddings = UvPaddingMode::ALL; + let padding_name = |mode| tr(if mode == UvPaddingMode::Space3d { "Across Seams (3D)" } else { "From Island Edges (2D)" }).to_owned(); + if let (Some(picked), _) = sheet.dropdown(tr("UV padding"), set.uv_padding, &paddings, padding_name, None) { + app.run("textureSet.settings", json!({"ts": ts, "uvPadding": picked.id()})); + } + + // For the whole project, shown here beside the other normal settings + let formats = [NormalFormat::OpenGl, NormalFormat::DirectX]; + let format_name = |format| if format == NormalFormat::DirectX { "DirectX" } else { "OpenGL" }.to_owned(); + let current = app.session.doc.project.normal_format; + if let (Some(picked), _) = sheet.dropdown(tr("Normal map format"), current, &formats, format_name, None) { + let id = if picked == NormalFormat::DirectX { "directX" } else { "openGl" }; + app.run("textureSet.settings", json!({"ts": ts, "normalFormat": id})); + } +} + +/// A channel: its name, its format with the gear that lists the formats, and × (Base color stays); returns the format picked and whether × was clicked +fn channel_row(sheet: &mut PropertySheet<'_>, channel: Channel, format: ChannelFormat) -> (Option, bool) { + sheet.embed(|ui| { + if ui.available_width() < 2.0 * GLYPH_BUTTON + GLYPH_GAP { + return (None, false); + } + + let tokens = Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), CHANNEL_ROW_HEIGHT), Sense::hover()); + let name = tr(channel.label()); + let mut picked = None; + let mut removed = false; + + let remove = Rect::from_center_size(pos2(rect.right() - GLYPH_BUTTON * 0.5, rect.center().y), vec2(GLYPH_BUTTON, GLYPH_BUTTON)); + if channel != Channel::BaseColor + && glyph_button(ui, ("tss_remove", channel.id()), remove, ic::X, &trf("Remove {channel}", &[("channel", &name)]), &tokens).clicked() + { + removed = true; + } + + let gear = remove.translate(vec2(-GLYPH_BUTTON - GLYPH_GAP, 0.0)); + let gear_label = trf("{channel} format", &[("channel", &name)]); + let gear_response = glyph_button(ui, ("tss_format", channel.id()), gear, ic::GEAR_SIX, &gear_label, &tokens); + Popup::menu(&gear_response).frame(menu_frame(&tokens)).width(FORMAT_LIST_WIDTH).gap(MENU_GAP).align(egui::RectAlign::BOTTOM_END).show(|ui| { + ui.set_min_width(FORMAT_LIST_WIDTH); + ui.add_space(MENU_PADDING); + for option in ChannelFormat::ALL { + if option_row(ui, option.label(), option == format).clicked() && option != format { + picked = Some(option); + } + } + ui.add_space(MENU_PADDING); + }); + + let painter = ui.painter().clone(); + let format_at = pos2(gear.left() - FORMAT_GAP, rect.center().y); + let format_rect = painter.text(format_at, Align2::RIGHT_CENTER, format.label(), FontId::proportional(CHANNEL_TEXT_SIZE), tokens.text_dim); + let name_rect = painter.text(pos2(rect.left(), rect.center().y), Align2::LEFT_CENTER, name, semibold(CHANNEL_TEXT_SIZE), tokens.text); + painter.hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, tokens.separator)); + + // The drawn name and format read as labels + for (salt, text_rect, text) in [("tss_channel_name", name_rect, name), ("tss_channel_format", format_rect, format.label())] { + let label = ui.interact(text_rect, ui.scope_id().with((salt, channel.id())), Sense::hover()); + label.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, text)); + } + + (picked, removed) + }) +} + +/// The Bake Mesh Maps button (the bake mode's own icon), then a slot per map: a click lists the images, × clears it +fn mesh_maps(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize, set: &TextureSet) { + sheet.section(tr("Mesh Maps"), false); + if sheet.button(ic::ATOM, tr("Bake Mesh Maps")).clicked() { + crate::menus::invoke(app, &sheet.ui.ctx().clone(), "ui.mode.bake"); + } + let empty_outline = Tokens::get(sheet.ui.ctx()).field_border; + for map in BakedMap::ALL { + let present = app.session.doc.baked.get(&ts).is_some_and(|baked| baked.maps.contains_key(&map)); + let color = crate::dock::mesh_map_color(map); + let thumbnail = move |painter: &egui::Painter, rect: Rect| { + if present { + painter.rect_filled(rect, CornerRadius::same(MAP_ROUNDING), color); + } else { + painter.rect_stroke( + rect.shrink(EMPTY_MAP_OUTLINE), + CornerRadius::same(MAP_ROUNDING), + Stroke::new(EMPTY_MAP_OUTLINE, empty_outline), + StrokeKind::Inside, + ); + } + }; + let label = tr(baked_map_label(map)); + let source = if present { format!("{}_{}", set.name, map.id()) } else { trf("Select {map} map", &[("map", &label.to_lowercase())]) }; + let slot = sheet.slot(&thumbnail, label, &source, None, present, false); + sheet.close_card(); + if slot.clear { + app.run("textureSet.meshMap.clear", json!({"ts": ts, "map": map.id()})); + } + let popup = slot.pick.id.with("mesh_map_picker"); + if slot.pick.clicked() { + resource_picker::toggle(&slot.pick.ctx, popup); + } + let tabs = || { + vec![PickerTab { + icon: ic::SQUARES_FOUR, + name: tr("Resources"), + groups: vec![PickerGroup { + header: Some(tr("Textures")), + items: ResourcePickerItem::textures(&app.session, None, |name| Some(name.to_owned())), + }], + }] + }; + let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, None, false, tabs); + + // A shelf image dropped on the slot becomes this map too + let dropped = crate::dock::image_drop(sheet.ui, &slot.pick).map(Some); + + // The picker's Import... tile is None + match picked.or(dropped) { + Some(None) => crate::menus::invoke(app, &sheet.ui.ctx().clone(), "resource.import"), + Some(Some(name)) => { + app.run("textureSet.meshMap.set", json!({"ts": ts, "map": map.id(), "image": name})); + } + None => {} + } + } +} + +/// Every size a set or tile can take +fn resolutions() -> Vec { + std::iter::successors(Some(MIN_RESOLUTION), |size| size.checked_mul(2)).take_while(|size| *size <= MAX_RESOLUTION).collect() +} + +/// A small square glyph button with its face on hover +fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, label: &str, tokens: &Tokens) -> egui::Response { + let response = ui.interact(rect, ui.scope_id().with(id), Sense::click()).on_hover_text(label); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ui.is_enabled(), label)); + if response.hovered() { + ui.painter().rect_filled(rect, CornerRadius::same(GLYPH_ROUNDING), tokens.row_hover); + } + let color = if response.hovered() { tokens.text } else { tokens.text_dim }; + ui.painter().text(rect.center(), Align2::CENTER_CENTER, glyph, FontId::proportional(GLYPH_SIZE), color); + response +} + +#[cfg(test)] +mod tests { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT as _, Queryable as _}; + + use super::*; + + fn harness(mesh: &str) -> Harness<'static, TextureCraftApp> { + let mesh_ref = format!("builtin:{mesh}"); + let geometry = texturecraft_engine::geom::primitives::builtin(mesh).unwrap(); + let session = texturecraft_engine::Session::new_project("Texture set settings", geometry, &mesh_ref, None, 128).unwrap(); + let mut harness = Harness::builder() + // Tall enough that the list's rows and the settings' channels show without scrolling + .with_size(vec2(1600.0, 2400.0)) + .with_context_setup(crate::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let ctx = harness.ctx.clone(); + crate::menus::invoke(harness.state_mut(), &ctx, "ui.view.textureSetSettings"); + harness.run_steps(4); + harness + } + + /// Presses and lets go at `at` through the real pointer path, as a person's click lands on a control drawn over a row + fn click_at(harness: &mut Harness<'static, TextureCraftApp>, at: egui::Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.event(egui::Event::PointerMoved(at)); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(1); + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + } + + fn click(harness: &mut Harness<'static, TextureCraftApp>, role: egui::Role, label: &str) { + let rect = harness.get_by_role_and_label(role, label).rect(); + + // A row's middle is under its size dropdown in a narrow panel: aim at its name + let at = if role == egui::Role::ListItem { egui::pos2(rect.left() + rect.width() * 0.25, rect.center().y) } else { rect.center() }; + click_at(harness, at); + } + + /// Steps until the resize worker has handed its result back + fn finish_resize(harness: &mut Harness<'static, TextureCraftApp>) { + for _ in 0..200 { + harness.run_steps(1); + if harness.state().resize.is_none() { + break; + } + + std::thread::sleep(std::time::Duration::from_millis(10)); + } + harness.run_steps(2); + } + + #[test] + fn typing_in_the_description_again_after_leaving_it_is_its_own_undo_step() { + let mut harness = harness("material_ball"); + let description = |harness: &Harness<'static, TextureCraftApp>| harness.state().session.doc.project.texture_sets[0].description.clone(); + let type_into_description = |harness: &mut Harness<'static, TextureCraftApp>, text: &str| { + click(harness, egui::Role::TextInput, "Description"); + for character in text.chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } + let ctx = harness.ctx.clone(); + ctx.memory_mut(|memory| { + if let Some(focused) = memory.focused() { + memory.surrender_focus(focused); + } + }); + harness.run_steps(2); + }; + + type_into_description(&mut harness, "ab"); + let first = description(&harness); + type_into_description(&mut harness, "c"); + assert!(description(&harness).len() > first.len(), "the second typing landed: {:?}", description(&harness)); + + harness.state_mut().session.undo().unwrap(); + assert_eq!(description(&harness), first, "undo takes back the second typing alone"); + } + + #[test] + fn a_uv_tile_picked_in_the_list_is_what_size_edits() { + let mut harness = harness("udim_plane"); + let tiles = harness.state().session.doc.project.texture_sets[0].uv_tiles.clone(); + assert!(harness.query_by_role_and_label(egui::Role::ComboBox, &format!("Size of UV tile {}", tiles[1])).is_none()); + + click(&mut harness, egui::Role::ListItem, &format!("UV tile {}", tiles[1])); + click(&mut harness, egui::Role::ComboBox, &format!("Size of UV tile {}", tiles[1])); + click(&mut harness, egui::Role::ListBoxOption, "256"); + harness.run_steps(3); + + let set = &harness.state().session.doc.project.texture_sets[0]; + assert!(set.tile_resolution(tiles[1]) > set.tile_resolution(tiles[0]), "only the picked tile grew"); + } + + #[test] + fn unlocked_size_sets_the_height_alone() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::CheckBox, "Lock Size"); + let height = + harness.get_all_by_role_and_label(egui::Role::ComboBox, "Size").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().rect().center(); + click_at(&mut harness, height); + click(&mut harness, egui::Role::ListBoxOption, "256"); + finish_resize(&mut harness); + + let set = &harness.state().session.doc.project.texture_sets[0]; + assert!(set.height() > set.resolution, "{}x{}", set.resolution, set.height()); + } + + #[test] + fn a_channel_gear_lists_the_formats_and_stores_the_one_picked() { + let mut harness = harness("material_ball"); + let format = |harness: &Harness<'static, TextureCraftApp>| { + let formats = harness.state().session.doc.project.texture_sets[0].formats(); + formats.into_iter().find(|(channel, _)| *channel == Channel::BaseColor).map(|(_, format)| format) + }; + let before = format(&harness); + + click(&mut harness, egui::Role::Button, "Base color format"); + click(&mut harness, egui::Role::ListBoxOption, "RGB32F"); + harness.run_steps(3); + + assert!(format(&harness) != before, "{:?}", format(&harness)); + } + + #[test] + fn the_channel_window_marks_unread_material_channels_but_not_user_channels() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + + // The dialog lays itself out over a few frames before its checks are in the tree + harness.run_steps(4); + let marked = |label: &str| harness.get_by_role_and_label(egui::Role::CheckBox, label).accesskit_node().description().is_some(); + + assert!(marked("Base weight"), "a channel the shader ignores is marked"); + assert!(!marked("User0"), "a user channel is not"); + } + + #[test] + fn a_narrow_window_can_apply_its_channel_selection() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(390.0, 600.0)); + harness.run_steps(5); + let viewport = harness.ctx.content_rect(); + let apply = harness.get_by_role_and_label(egui::Role::Button, "Apply").rect(); + + assert!(viewport.contains_rect(apply), "Apply must fit on screen"); + click(&mut harness, egui::Role::CheckBox, "Base weight"); + click(&mut harness, egui::Role::Button, "Apply"); + + assert!(harness.state().session.doc.project.texture_sets[0].has_channel(Channel::BaseWeight)); + } + + #[test] + fn a_narrow_channel_window_keeps_its_legend_inside_the_footer() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(300.0, 600.0)); + harness.run_steps(5); + + let legend: Vec<_> = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "Not used by the shader" => Some((clipped.clip_rect, text.visual_bounding_rect())), + _ => None, + }) + .collect(); + assert!(!legend.is_empty(), "the footer paints its legend"); + for (clip, painted) in legend { + assert!(clip.contains_rect(painted), "the legend at {painted:?} is cut off by {clip:?}"); + } + } + + #[test] + fn a_very_narrow_channel_window_wraps_its_checkbox_label() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(165.0, 300.0)); + harness.run_steps(5); + + let label = "Apply to all Texture Sets"; + let (text, clip) = harness + .output() + .shapes + .iter() + .find_map(|shape| match &shape.shape { + egui::Shape::Text(text) if text.galley.text() == label => Some((text.visual_bounding_rect(), shape.clip_rect)), + _ => None, + }) + .expect("the footer paints its checkbox label"); + + assert!(clip.contains_rect(text), "the checkbox text must fit on screen: {text:?}"); + + let checkbox = harness.get_by_role_and_label(egui::Role::CheckBox, label).rect(); + let legend = harness.get_by_role_and_label(egui::Role::Label, "Not used by the shader").rect(); + let apply = harness.get_by_role_and_label(egui::Role::Button, "Apply").rect(); + assert!(checkbox.bottom() < legend.top() && legend.bottom() < apply.top(), "the three footer rows must stay separate"); + } + + #[test] + fn a_short_channel_window_keeps_apply_on_screen() { + let mut harness = harness("material_ball"); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.set_size(vec2(300.0, 175.0)); + harness.run_steps(5); + + let screen = harness.ctx.content_rect(); + let apply: Vec<_> = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == "Apply" => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert!(!apply.is_empty(), "the footer paints Apply"); + for painted in apply { + assert!(screen.contains_rect(painted), "Apply at {painted:?} falls outside the window {screen:?}"); + } + } + + #[test] + fn escape_closes_the_channel_window_with_nothing_focused_and_drops_its_ticks() { + let mut harness = harness("material_ball"); + let had = harness.state().session.doc.project.texture_sets[0].has_channel(Channel::User0); + click(&mut harness, egui::Role::Button, "Add or remove channels"); + harness.run_steps(4); + click(&mut harness, egui::Role::CheckBox, "User0"); + + // As after a click on the dialog's empty space: no control keeps the keyboard + let ctx = harness.ctx.clone(); + ctx.memory_mut(|memory| { + if let Some(focused) = memory.focused() { + memory.surrender_focus(focused); + } + }); + harness.run_steps(2); + + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + assert!(harness.query_by_role_and_label(egui::Role::CheckBox, "User0").is_none(), "the window closed"); + assert_eq!(harness.state().session.doc.project.texture_sets[0].has_channel(Channel::User0), had, "nothing was applied"); + } +} diff --git a/crates/ui-egui/src/theme.rs b/crates/ui-egui/src/theme.rs index 30af4f1e..3ed5451e 100644 --- a/crates/ui-egui/src/theme.rs +++ b/crates/ui-egui/src/theme.rs @@ -301,20 +301,20 @@ pub(crate) const HARD_SHADOW: Color32 = Color32::from_rgb(12, 14, 18); /// adds CJK). pub fn font_definitions() -> egui::FontDefinitions { use std::sync::Arc; - let mut fonts = egui::FontDefinitions::default(); - let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.bytes.is_empty()); + let mut fonts = crate::fonts::egui_default_definitions(); + let face = |style: &str| crate::fonts::CRAFT_FONTS.iter().find(|f| f.family == "Inter" && f.style == style && !f.is_empty()); // Inter is drawn a little under its size, as in VectorCraft: its letters are wide. - let inter = |bytes: &'static [u8]| Arc::new(egui::FontData::from_static(bytes).tweak(egui::FontTweak { scale: 0.92, ..Default::default() })); + let inter = |face: &crate::fonts::CraftFont| Arc::new(face.font_data().tweak(egui::FontTweak { scale: 0.92, ..Default::default() })); let mut semibold = None; if let (Some(regular), Some(bold)) = (face("Regular"), face("SemiBold")) { - fonts.font_data.insert("inter".into(), inter(regular.bytes)); - fonts.font_data.insert("inter-semibold".into(), inter(bold.bytes)); + fonts.font_data.insert("inter".into(), inter(regular)); + fonts.font_data.insert("inter-semibold".into(), inter(bold)); if let Some(list) = fonts.families.get_mut(&FontFamily::Proportional) { list.insert(0, "inter".into()); } semibold = Some("inter-semibold"); } - egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); + crate::fonts::add_icon_font(&mut fonts); // The semibold family: the regular family with its first face swapped for the weight. let mut list = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default(); if let (Some(w), Some(first)) = (semibold, list.first_mut()) { diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 66925033..b0814b39 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -36,6 +36,8 @@ const GENERATOR_SET_KEY_PREFIX: &str = "generator-set:"; const SAVED_FILE_KEY_PREFIX: &str = "saved-"; /// Largest stencil preview dimension in pixels const STENCIL_MAX_SIZE_PX: f32 = 1024.0; +/// The texture name prefix of a stencil preview +const STENCIL_KEY_PREFIX: &str = "stencil:"; /// Big hover previews kept at most (the least recently shown go first) const BIG_PREVIEWS_KEPT: usize = 32; @@ -53,6 +55,8 @@ pub struct Thumbs { saved_files_epoch: u64, images: HashMap, TextureHandle)>, images_revision: Option, + /// The large preview of the selected stencil, shared by Properties and the viewport + stencil: Option<(Weak, TextureHandle)>, preview_session: Option<(u64, u64)>, /// Weak identities for images read by configured generator previews generator_images: HashMap>, @@ -79,13 +83,15 @@ pub struct Thumbs { impl Thumbs { /// A larger cached texture of an image resource for the stencil overlay (up to 1024 px) pub fn stencil(&mut self, ctx: &egui::Context, name: &str, image: &Arc) -> TextureHandle { - let key = format!("stencil:{name}"); - if let Some((cached_image, texture)) = self.images.get(&key) - && cached_image.ptr_eq(&Arc::downgrade(image)) + if let Some((cached_image, texture)) = &self.stencil + && std::ptr::eq(cached_image.as_ptr(), Arc::as_ptr(image)) { return texture.clone(); } + // Release the previous overlay before allocating its replacement + self.stencil = None; + let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0); let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1)); let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT); @@ -100,8 +106,8 @@ impl Thumbs { } } - let texture = ctx.load_texture(key.clone(), color_image, TextureOptions::LINEAR); - self.images.insert(key, (Arc::downgrade(image), texture.clone())); + let texture = ctx.load_texture(format!("{STENCIL_KEY_PREFIX}{name}"), color_image, TextureOptions::LINEAR_REPEAT); + self.stencil = Some((Arc::downgrade(image), texture.clone())); texture } @@ -149,14 +155,19 @@ impl Thumbs { } self.images_revision = Some(revision); - self.images.retain(|key, (cached_image, _)| { - let name = key.strip_prefix("stencil:").unwrap_or(key); - images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image))) - }); + self.images.retain(|name, (cached_image, _)| images.get(name).is_some_and(|image| std::ptr::eq(cached_image.as_ptr(), Arc::as_ptr(image)))); } /// Keep project previews only while they refer to current resources or bake maps. pub(crate) fn sync_project_previews(&mut self, session: &Session) -> bool { + // Clearing the stencil does not advance the session revision + if let Some((shown, _)) = &self.stencil { + let current = session.tool.stencil.as_ref().and_then(|stencil| session.images.get(&stencil.image)); + if !current.is_some_and(|image| std::ptr::eq(shown.as_ptr(), Arc::as_ptr(image))) { + self.stencil = None; + } + } + let current = (session.project_id, session.revision); let previous = self.preview_session.replace(current); if previous == Some(current) { @@ -319,6 +330,12 @@ impl Thumbs { self.custom_previews.clear(); } + /// Release custom textures after their last tile stops using the file + pub(crate) fn retain_custom_previews(&mut self, previews: &[crate::shelf_custom_preview::ShelfCustomPreview]) { + let in_use: std::collections::HashSet<_> = previews.iter().map(|preview| preview.file.as_path()).collect(); + self.custom_previews.retain(|file, _| in_use.contains(file.as_path())); + } + /// Load the picture at `file` again next time: the user picked it anew, maybe after changing it #[cfg(not(target_arch = "wasm32"))] pub(crate) fn forget_custom_preview(&mut self, file: &Path) { @@ -501,41 +518,60 @@ impl Thumbs { } } -/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews). -pub fn paint_sphere(p: &Painter, c: Pos2, r: f32, base: [f32; 3]) { - let mut mesh = egui::Mesh::default(); - let rings = 10; - let segs = 28; +/// Metallic and roughness of a sphere drawn without a material's own values +pub(crate) const SPHERE_DEFAULT_METALLIC: f32 = 0.0; +pub(crate) const SPHERE_DEFAULT_ROUGHNESS: f32 = 0.5; + +/// Rings and segments per ring of a drawn sphere's mesh +const SPHERE_RINGS: usize = 10; +const SPHERE_SEGMENTS: usize = 28; + +/// Exposure applied to a drawn sphere's shading before tone mapping +const SPHERE_EXPOSURE: f32 = 1.4; + +/// A small shaded sphere drawn with a vertex-colored mesh (layer thumbnails, previews) +pub fn paint_sphere(painter: &Painter, center: Pos2, radius: f32, base: [f32; 3]) { + paint_material_sphere(painter, center, radius, base, SPHERE_DEFAULT_METALLIC, SPHERE_DEFAULT_ROUGHNESS); +} + +/// [`paint_sphere`] with the material's `metallic` and `roughness` (0..1) +pub fn paint_material_sphere(painter: &Painter, center: Pos2, radius: f32, base: [f32; 3], metallic: f32, roughness: f32) { let color = |dx: f32, dy: f32| { - let d2 = (dx * dx + dy * dy).min(1.0); - let n = [dx, dy, (1.0 - d2).sqrt()]; - let s = shade(n, base, 0.0, 0.5).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0) as u8); - Color32::from_rgb(s[0], s[1], s[2]) + let distance_squared = (dx * dx + dy * dy).min(1.0); + let normal = [dx, dy, (1.0 - distance_squared).sqrt()]; + let srgb = shade(normal, base, metallic, roughness).map(|linear| (linear_to_srgb(aces(linear * SPHERE_EXPOSURE)) * 255.0) as u8); + Color32::from_rgb(srgb[0], srgb[1], srgb[2]) }; - mesh.colored_vertex(c, color(0.0, 0.0)); - for i in 1..=rings { - let rr = i as f32 / rings as f32; - for j in 0..segs { - let a = j as f32 / segs as f32 * std::f32::consts::TAU; - let (dx, dy) = (a.cos() * rr, a.sin() * rr); - mesh.colored_vertex(Pos2::new(c.x + dx * r, c.y - dy * r), color(dx, dy)); + + // A center vertex, then each ring's vertices outwards + let mut mesh = egui::Mesh::default(); + mesh.colored_vertex(center, color(0.0, 0.0)); + for ring in 1..=SPHERE_RINGS { + let ring_radius = ring as f32 / SPHERE_RINGS as f32; + for segment in 0..SPHERE_SEGMENTS { + let angle = segment as f32 / SPHERE_SEGMENTS as f32 * std::f32::consts::TAU; + let (dx, dy) = (angle.cos() * ring_radius, angle.sin() * ring_radius); + mesh.colored_vertex(Pos2::new(center.x + dx * radius, center.y - dy * radius), color(dx, dy)); } } - for j in 0..segs { - let (a, b) = (1 + j, 1 + (j + 1) % segs); - mesh.add_triangle(0, a as u32, b as u32); + + // A fan from the center to the first ring, then quads between neighbouring rings + for segment in 0..SPHERE_SEGMENTS { + let (first, next) = (1 + segment, 1 + (segment + 1) % SPHERE_SEGMENTS); + mesh.add_triangle(0, first as u32, next as u32); } - for i in 1..rings { - let r0 = 1 + (i - 1) * segs; - let r1 = 1 + i * segs; - for j in 0..segs { - let (a, b) = (r0 + j, r0 + (j + 1) % segs); - let (c2, d) = (r1 + j, r1 + (j + 1) % segs); - mesh.add_triangle(a as u32, c2 as u32, d as u32); - mesh.add_triangle(a as u32, d as u32, b as u32); + for ring in 1..SPHERE_RINGS { + let inner_start = 1 + (ring - 1) * SPHERE_SEGMENTS; + let outer_start = 1 + ring * SPHERE_SEGMENTS; + for segment in 0..SPHERE_SEGMENTS { + let next_segment = (segment + 1) % SPHERE_SEGMENTS; + let (inner, inner_next) = (inner_start + segment, inner_start + next_segment); + let (outer, outer_next) = (outer_start + segment, outer_start + next_segment); + mesh.add_triangle(inner as u32, outer as u32, outer_next as u32); + mesh.add_triangle(inner as u32, outer_next as u32, inner_next as u32); } } - p.add(egui::Shape::mesh(mesh)); + painter.add(egui::Shape::mesh(mesh)); } /// Brush alpha preview drawn as small cells (cheap, no texture). diff --git a/crates/ui-egui/src/tile_picture.rs b/crates/ui-egui/src/tile_picture.rs index d031e666..3a0f955e 100644 --- a/crates/ui-egui/src/tile_picture.rs +++ b/crates/ui-egui/src/tile_picture.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::Color32; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::{GeneratorKind, ProceduralKind}; +use texturecraft_engine::paint::BrushAlpha; use texturecraft_engine::paint::alphas::LibraryAlpha; /// A tile's picture source. Previews are requested only when its tile is drawn. @@ -12,6 +13,8 @@ pub(crate) enum TilePicture { Material(&'static str), Filter(&'static str), Alpha(&'static LibraryAlpha), + /// A built-in brush shape at a hardness, drawn as the shape tiles of the old alpha grid were + Shape(BrushAlpha, f32), Image(String, Arc), Procedural(ProceduralKind), /// A mask generator at its defaults on the smart masks' orb, a die in its corner when a seed changes its result diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 59f56357..72cbf52d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -283,7 +283,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) const SIZE_PERCENT_RANGE: std::ops::RangeInclusive = 0.05..=100.0; /// Spacing's track, in percent of the brush's diameter - const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=200.0; + const SPACING_PERCENT_RANGE: std::ops::RangeInclusive = 1.0..=1000.0; /// Lazy mouse Distance's track, in pixels const LAZY_DISTANCE_RANGE_PX: std::ops::RangeInclusive = 1.0..=200.0; diff --git a/crates/ui-egui/src/view_mode_picker.rs b/crates/ui-egui/src/view_mode_picker.rs index 332f136b..1bc5d7b1 100644 --- a/crates/ui-egui/src/view_mode_picker.rs +++ b/crates/ui-egui/src/view_mode_picker.rs @@ -70,13 +70,12 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid ViewMode::Image => app.session.view_image.clone().unwrap_or_else(|| tr(OTHER).to_owned()), _ => tr(&app.session.view.label()).to_owned(), }; - let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default(); let popup_id = child.make_persistent_id((id_salt, "other")); // The picker stays greyed without project maps let combo = child .add_enabled_ui(project_open, |child| { - egui::ComboBox::from_id_salt(id_salt).width(width).height(LIST_HEIGHT).selected_text(label).show_ui(child, |ui| { + egui::ComboBox::from_id_salt(id_salt).width(width).height(LIST_HEIGHT).selected_text(label.as_str()).show_ui(child, |ui| { // Bake mode keeps its own list: the material, then the mesh maps, without titles if !baking { section(ui, "Lighting"); @@ -112,11 +111,18 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid } section(ui, "Single channel"); + let channels = app.session.doc.project.texture_sets.get(app.session.ts()).into_iter().flat_map(|set| set.viewport_channels()); + let mut picked_channel = None; for channel in channels { if ui.selectable_label(app.session.view == ViewMode::Channel(channel), tr(channel_label(channel))).clicked() { - app.run("viewport.view", json!({"mode": channel.id()})); + picked_channel = Some(channel); } } + + if let Some(channel) = picked_channel { + app.run("viewport.view", json!({"mode": channel.id()})); + } + if ui.selectable_label(app.session.view == ViewMode::NormalHeightMesh, tr(texturecraft_engine::NORMAL_HEIGHT_MESH_LABEL)).clicked() { app.run("viewport.view", json!({"mode": "normalHeightMesh"})); } @@ -135,6 +141,11 @@ pub(crate) fn show(app: &mut TextureCraftApp, child: &mut Ui, id_salt: &str, wid }) .inner; + // The box shows only the mode's name: it is named for what it picks + combo.response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(label.clone()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, project_open, tr("View mode")) + }); image_picker(app, &combo.response, popup_id); } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4c1fe3c7..ef9c0d73 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -23,7 +23,7 @@ use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; -/// Hold this key with the Projection tool to rotate, scale or move the stencil with the mouse +/// Hold this key with a brush tool to rotate, scale or move the stencil with the mouse pub const STENCIL_KEY: egui::Key = egui::Key::S; /// Hold this key with the Clone tool and click to set the source pub const CLONE_SOURCE_KEY: egui::Key = egui::Key::V; @@ -305,7 +305,7 @@ const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0; const BAKE_PAINT_CURSOR_STROKE: f32 = 1.0; const BAKE_PAINT_CURSOR_ALPHA: u8 = 200; -/// The projection stencil's dashed outline: width, white alpha, dash and gap, in points +/// The stencil's dashed outline: width, white alpha, dash and gap, in points const STENCIL_OUTLINE_STROKE: f32 = 1.0; const STENCIL_OUTLINE_ALPHA: u8 = 120; const STENCIL_OUTLINE_DASH: f32 = 5.0; @@ -381,17 +381,25 @@ fn shade(app: &TextureCraftApp) -> Shade { ViewMode::NormalHeightMesh => (VIEW_MODE_NORMAL_HEIGHT_MESH, 0), }; let set_index = app.session.ts(); - let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let active_set = app.session.doc.project.texture_sets.get(set_index); + let height_strength = active_set.map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let height_y_factor = active_set.map_or(1.0, |texture_set| texture_set.atlas_height_y_factor()); + let height_in_normal = active_set.is_none_or(|texture_set| texture_set.height_in_normal()); + let height_to_normal = active_set.map_or_else(Default::default, |texture_set| texture_set.height_to_normal); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, + height_y_factor, + height_in_normal, + height_to_normal, view_mode, channel, wireframe: wireframe_shown(&app.ui, polygon_fill_tool), wireframe_3d: wireframe_shown(&app.ui, polygon_fill_tool), background: app.ui.prefs.background, + // Polygon fill's own wireframe keeps its look when the user's opacity hides the switch's wireframe wireframe_opacity: if app.ui.mesh_wireframe { app.ui.wireframe_opacity / 100.0 } else { POLYGON_FILL_WIREFRAME_OPACITY }, ..Shade::from_project(&app.session.doc.project) @@ -572,7 +580,7 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { let names: Vec = app.session.doc.project.cameras.iter().map(|camera| camera.name.clone()).collect(); let shown = current.and_then(|index| names.get(index)).map_or(tr(DEFAULT_CAMERA), String::as_str); if project_open { - egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { + let picker = egui::ComboBox::from_id_salt(format!("{id}_cam")).width(VIEW_PICKER_WIDTH).selected_text(shown).show_ui(&mut child, |ui| { if ui.selectable_label(current.is_none(), tr(DEFAULT_CAMERA)).clicked() { app.run("camera.select", json!({})); } @@ -586,6 +594,13 @@ fn view_header(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, id: &str) { app.run("camera.add", json!({})); } }); + + // The box shows only the camera's name: it is named for what it picks + let enabled = child.is_enabled(); + picker.response.widget_info(|| egui::WidgetInfo { + current_text_value: Some(shown.to_owned()), + ..egui::WidgetInfo::labeled(egui::Role::ComboBox, enabled, tr("View camera")) + }); } // The 2D view of a UV tile project: a checkable button left of the view mode, with no tooltip, that shows or hides the tile numbers and the hover label @@ -779,13 +794,13 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let holding = crate::move_on_model::holding(app, ui.ctx()); let navigating = !adjusting && !holding && (alt || ui.input(|input| input.pointer.middle_down() || input.pointer.secondary_down())); - // Navigation; S + drag moves the projection stencil instead, below + // Navigation; S + drag moves the stencil instead, below let delta = ui.input(|input| input.pointer.delta()); let s_held = app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(STENCIL_KEY)) && !crate::framework::widget_has_keyboard(ui.ctx()); - // Only an equipped Projection tool that can act moves its stencil: it isn't drawn otherwise - let stencil_moves = tool_acts(app) && app.session.tool.tool == Tool::Projection; + // Only an equipped brush tool that can act moves the stencil: it isn't drawn otherwise + let stencil_moves = tool_acts(app) && stencil_applies(app); let stencil_drag = s_held && stencil_moves && app.session.tool.stencil.is_some(); if stencil_drag || adjusting || holding { // The stencil, the brush or the held Move on model button changes instead of the camera @@ -918,8 +933,9 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Depth of field focus pick: a click focuses there instead of painting - let focus_pick = focus_picking(ui.ctx()) || point_pick.is_some(); - if focus_picking(ui.ctx()) { + let picking_focus_distance = focus_picking(ui.ctx()); + let focus_pick = picking_focus_distance || point_pick.is_some(); + if picking_focus_distance { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt && response.clicked_by(PointerButton::Primary) @@ -1011,7 +1027,6 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let gizmo_handle = gizmo_free && !app.session.stroke_active() && began_on_handle; - // Painting let painting = tool_acts(app) && !popup && !alt @@ -1182,35 +1197,24 @@ fn bake_visualization(app: &TextureCraftApp) -> Option bool { + app.session.tool.tool.uses_stencil() && !app.session.quick_mask.editing +} + /// Whether the active tool can act on the selection now: a greyed tool ignores clicks, keys and drags in the views fn tool_acts(app: &TextureCraftApp) -> bool { app.ui.mode == crate::state::Mode::Painting && app.session.tool_usable(app.session.tool.tool) diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 6078a4c7..b9074d89 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -258,24 +258,26 @@ const HISTORY_MARK_INSET_RIGHT: f32 = 3.0; /// The History panel body (a dock tab): one row per step, the current one outlined pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); - let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); - let done_count = done.len() as i64; - let total_rows = 1 + done.len() + undone.len(); + let done = app.session.iter_history_labels(); + let undone = app.session.iter_redo_labels(); + let done_count = done.len(); + let total_rows = 1 + done_count + undone.len(); - // New steps or a new container (with its own scroll) bring the current one into view; a tool change keeps the user's scroll - let shown = Some((ui.make_persistent_id("history"), app.session.steps_added(), done.len(), undone.len())); - // A list made shorter keeps the current step on screen if it was there; one the user scrolled away from it stays put + // Follow document steps and moved panels while leaving tool changes alone + let history_key = Some((ui.make_persistent_id("history"), app.session.steps_added(), done_count, undone.len())); + + // Preserve visibility during a resize if the user was already viewing the current step let height = ui.available_height(); - let shrunk = app.ui.history_view.is_some_and(|(height_before, was_in_view)| was_in_view && height < height_before); - let follow = app.ui.history_shown != shown || shrunk; - app.ui.history_shown = shown; + let shrunk = app.ui.history_view.is_some_and(|(previous_height, was_in_view)| was_in_view && height < previous_height); + let follow = app.ui.history_shown != history_key || shrunk; + app.ui.history_shown = history_key; // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - // Not animated: a scroll request then shows in the offset returned this frame, which a resize by dragging relies on - let area = egui::ScrollArea::vertical().id_salt("history").auto_shrink([false, false]).animated(false); - let current_row_top = done.len() as f32 * HISTORY_ROW_HEIGHT; + // Update the returned offset immediately so each frame of a dragged resize sees the previous reveal + let area = egui::ScrollArea::vertical().id_salt("history").auto_shrink([false, false]).animated(false).vertical_scroll_bar_label(tr("History scrollbar")); + let current_row_top = done_count as f32 * HISTORY_ROW_HEIGHT; let list = crate::log_panel::panel_rows(ui, area, HISTORY_ROW_HEIGHT, total_rows, |ui, range| { if follow { let top = ui.max_rect().top() + current_row_top - range.start as f32 * HISTORY_ROW_HEIGHT; @@ -283,12 +285,11 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { ui.scroll_to_rect_animation(current, None, egui::style::ScrollAnimation::none()); } - // Only the shown rows are translated - for row in range { - let Some((name, color)) = history_row_name(&done, &undone, row, &tokens) else { continue }; + let labels = std::iter::once(None).chain(done.map(|label| Some((label, false)))).chain(undone.map(|label| Some((label, true)))); + for (row, label) in labels.enumerate().skip(range.start).take(range.len()) { + let (name, color) = history_row_name(label, &tokens); + let steps = done_count as i64 - row as i64; - // Each row is the state after that many steps - let steps = done_count - row as i64; if history_row(ui, &tokens, &name, color, steps == 0).on_hover_text(tr("Return to this step")).clicked() { // Point history is consumed before the document rows shown here jump = if steps >= 0 { @@ -311,15 +312,12 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The name and colour of History row `row`: the opened project, then the done steps, then the undone ones -fn history_row_name(done: &[String], undone: &[String], row: usize, tokens: &Tokens) -> Option<(String, egui::Color32)> { - let Some(step) = row.checked_sub(1) else { return Some((tr("Project opened").to_owned(), tokens.text_dim)) }; - if let Some(label) = done.get(step) { - return Some((tr_history(label), tokens.text)); - } +/// The name and colour of a History row, with no step label for the opened project +fn history_row_name(step: Option<(&str, bool)>, tokens: &Tokens) -> (String, egui::Color32) { + let Some((label, undone)) = step else { return (tr("Project opened").to_owned(), tokens.text_dim) }; - let label = undone.get(step - done.len())?; - Some((trf("{action} (undone)", &[("action", &tr_history(label))]), tokens.text_dim)) + let translated = tr_history(label); + if undone { (trf("{action} (undone)", &[("action", &translated)]), tokens.text_dim) } else { (translated, tokens.text) } } /// One History row across the panel: a band under the pointer, the current step outlined @@ -339,7 +337,7 @@ fn history_row(ui: &mut Ui, tokens: &Tokens, name: &str, color: egui::Color32, c painter.rect_filled(rect, 0.0, tokens.row); } - // A name too long for the row ends in an ellipsis, as far from the outline's right side as it starts from its left + // Inset both text edges equally from the current-step outline let room = rect.width() - HISTORY_NAME_LEFT - HISTORY_MARK_INSET_RIGHT - (HISTORY_NAME_LEFT - HISTORY_MARK_INSET_LEFT); let mut job = egui::text::LayoutJob::simple_singleline(name.to_owned(), egui::FontId::proportional(HISTORY_NAME_SIZE), color); job.wrap = egui::text::TextWrapping::truncate_at_width(room.max(0.0)); diff --git a/crates/ui-egui/tests/autosave_recovery.rs b/crates/ui-egui/tests/autosave_recovery.rs new file mode 100644 index 00000000..2798df8f --- /dev/null +++ b/crates/ui-egui/tests/autosave_recovery.rs @@ -0,0 +1,143 @@ +//! Work recovered from an autosave copy survives the next autosave of the project the copy came from. This is a test +//! binary of its own because it points the process's data folder at a temporary one + +#![cfg(not(target_arch = "wasm32"))] + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use egui_kittest::Harness; +use serde_json::{Value, json}; +use texturecraft_engine::core::PROJECT_EXT; +use texturecraft_engine::formats::RamReservation; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::{TextureCraftApp, control}; + +/// App time each frame advances by, so a few frames pass any autosave interval +const FRAME_SECONDS: f32 = 600.0; + +/// Deadline for the background archive write +const WRITE_TIMEOUT: Duration = Duration::from_secs(60); + +/// Allow the worker to make progress between test frames. +const POLL_INTERVAL: Duration = Duration::from_millis(20); + +fn load_project(path: &Path) -> Option { + texturecraft_engine::file_cmds::open_path(path.to_str().unwrap()).ok() +} + +fn layers(session: &Session) -> usize { + session.doc.project.layers.len() +} + +fn start(session: Session) -> Harness<'static, TextureCraftApp> { + Harness::builder() + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)) +} + +fn add_layers(app: &mut TextureCraftApp, count: usize) { + for _ in 0..count { + execute(&mut app.session, "layer.add.paint", &json!({})).unwrap(); + } +} + +/// Wait for an autosave containing the requested number of layers. +fn autosave(harness: &mut Harness<'_, TextureCraftApp>, folder: &Path, layer_count: usize) -> PathBuf { + let started = Instant::now(); + loop { + if let Some(reservation) = RamReservation::try_for_save() { + // Wait for any previous archive write before advancing another frame + let found = std::fs::read_dir(folder).into_iter().flatten().filter_map(Result::ok).map(|entry| entry.path()).find(|path| { + path.extension().is_some_and(|extension| extension == PROJECT_EXT) && load_project(path).is_some_and(|session| layers(&session) == layer_count) + }); + drop(reservation); + if let Some(copy) = found { + return copy; + } + + harness.step(); + } + + assert!(started.elapsed() < WRITE_TIMEOUT, "autosave wrote no copy of {layer_count} layers"); + std::thread::sleep(POLL_INTERVAL); + } +} + +#[test] +fn recovered_work_survives_the_originals_next_autosave() { + let data = tempfile::tempdir().unwrap(); + texturecraft_ui_egui::set_data_root(data.path().to_path_buf()); + let folder = data.path().join("autosave"); + let original_path = data.path().join("hero.tcraft"); + let original_params = json!({ "path": original_path.to_str().unwrap() }); + + let mut session = Session::new_project("hero", primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + execute(&mut session, "file.saveAs", &original_params).unwrap(); + let saved_layer_count = layers(&session); + + let mut harness = start(session); + add_layers(harness.state_mut(), 1); + let original_copy = autosave(&mut harness, &folder, saved_layer_count + 1); + let copy_params = json!({ "path": original_copy.to_str().unwrap() }); + + let opened = harness.state_mut().run("file.open", copy_params.clone()).unwrap(); + assert_eq!(harness.state().session.path, None); + assert_eq!(opened.get("path"), Some(&Value::Null)); + assert_eq!(opened["modified"], true); + assert!(harness.state_mut().run("file.save", json!({})).is_none(), "saving the recovered project requires a destination"); + + add_layers(harness.state_mut(), 3); + let recovered_layer_count = layers(&harness.state().session); + let recovered_copy = autosave(&mut harness, &folder, recovered_layer_count); + assert_ne!(recovered_copy, original_copy); + + let kept_path = data.path().join("kept.tcraft"); + harness.state_mut().run("file.saveAs", json!({ "path": kept_path })).unwrap(); + assert_eq!(harness.state().session.path.as_deref(), kept_path.to_str()); + + let opened = harness.state_mut().run("file.open", original_params.clone()).unwrap(); + assert_eq!(opened["path"], original_params["path"]); + assert_eq!(opened["modified"], false); + add_layers(harness.state_mut(), 2); + assert_eq!(autosave(&mut harness, &folder, saved_layer_count + 2), original_copy, "the original keeps its copy"); + assert_eq!(layers(&load_project(&recovered_copy).unwrap()), recovered_layer_count); + assert_eq!(layers(&load_project(&kept_path).unwrap()), recovered_layer_count); + + // The control reply reports the same recovery state as session inspection + let ctx = harness.ctx.clone(); + let reply = control::handle(harness.state_mut(), &ctx, "command.run", &json!({ "id": "file.open", "params": copy_params })); + let inspected = control::handle(harness.state_mut(), &ctx, "session.inspect", &json!({})); + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(harness.state().session.path, None); + assert_eq!(reply["result"]["path"], inspected["result"]["path"]); + assert_eq!(reply["result"]["modified"], inspected["result"]["modified"]); + + // A case-insensitive volume resolves this spelling to the same archive + let alias = original_copy.with_file_name(original_copy.file_name().unwrap().to_str().unwrap().replace("-copy-", "-CoPy-")).with_extension("TCRAFT"); + let case_sensitive = !alias.exists(); + if case_sensitive { + // Exercise the same identity check with two names for one file + std::fs::hard_link(&original_copy, &alias).unwrap(); + } + + let opened = harness.state_mut().run("file.open", json!({ "path": alias })).unwrap(); + assert_eq!(opened.get("path"), Some(&Value::Null)); + assert_eq!(opened["modified"], true); + + if case_sensitive { + std::fs::remove_file(&alias).unwrap(); + std::fs::copy(&original_copy, &alias).unwrap(); + + let opened = harness.state_mut().run("file.open", json!({ "path": alias })).unwrap(); + assert_eq!(opened["path"], alias.to_str().unwrap()); + assert_eq!(opened["modified"], false); + } + + // The launcher gives the app a session that has already loaded the archive + let startup = start(load_project(&original_copy).unwrap()); + assert_eq!(startup.state().session.path, None); + assert!(startup.state().session.modified); +} diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 9d99354b..14a949c7 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -72,11 +72,32 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { #[test] fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() { + use std::sync::{Arc, atomic::Ordering, mpsc}; + use texturecraft_engine::bake::Progress; + use texturecraft_ui_egui::RunningBake; + let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + let progress = Arc::new(Progress::new()); - // One frame starts the worker; a finished map shows only from the next one - harness.state_mut().start_bake(vec![0]); + // Keep both worker channels open and empty so cancellation precedes the first map + let (_map_sender, maps) = mpsc::channel(); + let (_result_sender, receiver) = mpsc::channel(); + let app = harness.state_mut(); + app.start_bake(vec![0]); + let job = app.bake.as_mut().unwrap(); + let set_index = job.queue.remove(0); + job.current = Some(RunningBake { + set_index, + progress: Arc::clone(&progress), + receiver, + maps, + maps_done: Default::default(), + maps_total: MAPS.len(), + finished: Default::default(), + sources: Default::default(), + painted_stroke: 0, + }); harness.run_steps(1); assert!(harness.state().session.bake_preview_active()); @@ -87,6 +108,7 @@ fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_al harness.state_mut().cancel_bake(); harness.run_steps(2); + assert!(progress.cancel.load(Ordering::Relaxed), "cancellation reaches the running worker"); assert_eq!(harness.state().session.view, ViewMode::UvChecker); assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none()); assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before); diff --git a/crates/ui-egui/tests/i18n_build.rs b/crates/ui-egui/tests/i18n_build.rs index d2d690de..b8f61a03 100644 --- a/crates/ui-egui/tests/i18n_build.rs +++ b/crates/ui-egui/tests/i18n_build.rs @@ -1,6 +1,7 @@ //! Optional catalog embedding must work without network or application dependencies. #[path = "../i18n_build.rs"] -#[allow(dead_code)] // The production build entry point is not invoked by these pure-input tests. +// The tests call catalog collection directly +#[allow(dead_code)] mod i18n_build; /// The catalogs' Rust includes alone, which is what these tests assert on; the build itself asks @@ -36,6 +37,7 @@ fn no_input_is_english_but_required_input_errors() { #[test] fn invalid_and_relative_checkouts_are_rejected() { let fixture = Fixture::new(); + assert!(generate(Some(&fixture.0.join("missing")), false).is_err()); assert!(generate(Some(std::path::Path::new("relative")), false).is_err()); } @@ -44,6 +46,7 @@ fn invalid_and_relative_checkouts_are_rejected() { fn shared_only_locale_is_not_offered_and_required_needs_app_catalog() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); + assert!(!generate(Some(&fixture.0), false).unwrap().contains("include_str!")); assert!(generate(Some(&fixture.0), true).is_err()); } @@ -53,11 +56,15 @@ fn app_catalog_is_embedded_with_optional_shared_catalog() { let fixture = Fixture::new(); let app = fixture.0.join("locales/es/texturecraft.tsv"); std::fs::write(&app, "\tLayers\tCapas\n").unwrap(); + let source = generate(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); assert!(source.contains("(\"es\", \"\",")); + let common = fixture.0.join("locales/es/common.tsv"); std::fs::write(&common, "\tSave\tGuardar\n").unwrap(); + assert!(generate(Some(&fixture.0), true).unwrap().contains("common.tsv")); } @@ -65,20 +72,36 @@ fn app_catalog_is_embedded_with_optional_shared_catalog() { fn unreadable_catalog_fails_before_generating_rust_source() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), [0xff, 0xfe]).unwrap(); + assert!(generate(Some(&fixture.0), true).is_err()); } #[test] -fn generated_paths_compile_and_embed_the_catalog_contents() { +fn generated_catalogs_are_readable_through_the_runtime_accessor() { let fixture = Fixture::new(); - std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); - let generated = generate(Some(&fixture.0), true).unwrap(); + let app = "\tLayers\tCapas\n"; + std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), app).unwrap(); + + let populated = generate(Some(&fixture.0), true).unwrap(); + let empty = generate(None, false).unwrap(); let program = format!( - "extern crate self as craft_i18n;\npub type Embedded = [(&'static str, &'static str, &'static str)];\n{generated}\nfn main() {{ assert_eq!(CRAFT_I18N[0].2, \"\\tLayers\\tCapas\\n\"); }}" + r#" +extern crate self as craft_i18n; +pub type Embedded = [(&'static str, &'static str, &'static str)]; + +mod populated {{ {populated} }} +mod empty {{ {empty} }} + +fn main() {{ + assert_eq!(populated::craft_i18n_catalogs(), &[("es", "", {app:?})]); + assert!(empty::craft_i18n_catalogs().is_empty()); +}} +"# ); let source = fixture.0.join("check.rs"); let binary = fixture.0.join(format!("check{}", std::env::consts::EXE_SUFFIX)); std::fs::write(&source, program).unwrap(); + assert!(std::process::Command::new("rustc").arg(&source).arg("-o").arg(&binary).status().unwrap().success()); assert!(std::process::Command::new(binary).status().unwrap().success()); } @@ -98,6 +121,7 @@ fn malformed_utf8_catalogs_and_invalid_rows_fail_during_generation() { let fixture = Fixture::new(); std::fs::write(fixture.0.join("locales/es/texturecraft.tsv"), "\tLayers\tCapas\n").unwrap(); std::fs::write(fixture.0.join("locales/es").join(file), invalid).unwrap(); + for required in [false, true] { assert!(generate(Some(&fixture.0), required).is_err(), "accepted {file}: {invalid:?}"); } @@ -112,11 +136,13 @@ fn the_catalog_characters_are_the_ones_the_web_font_keeps() { std::fs::write(fixture.0.join("locales/es/common.tsv"), "\tSave\tGuardar\n").unwrap(); std::fs::create_dir_all(fixture.0.join("locales/ja")).unwrap(); std::fs::write(fixture.0.join("locales/ja/texturecraft.tsv"), "\tLayers\t\u{30ec}\u{30a4}\u{30e4}\u{30fc}\n").unwrap(); - // A shared-only locale contributes no characters: its catalog is not embedded. + + // Shared-only locales have no embedded catalog std::fs::create_dir_all(fixture.0.join("locales/de")).unwrap(); std::fs::write(fixture.0.join("locales/de/common.tsv"), "\tSave\tSpeichern \u{fc}\n").unwrap(); let (source, characters) = i18n_build::collect(Some(&fixture.0), true).unwrap(); + assert!(source.contains("texturecraft.tsv")); for used in ['L', 'a', 'y', 'e', 'r', 's', 'C', 'p', 'G', 'u', 'd', '\u{30ec}', '\u{30a4}', '\u{30e4}', '\u{30fc}'] { assert!(characters.contains(&used), "missing {used:?}"); @@ -127,7 +153,7 @@ fn the_catalog_characters_are_the_ones_the_web_font_keeps() { sorted.dedup(); assert_eq!(sorted, characters, "sorted and distinct"); - // Nothing to cut with no checkout: the web build then keeps the faces whole. + // With no catalog checkout the web build keeps the full font assert_eq!(i18n_build::collect(None, false).unwrap().1, Vec::::new()); assert!(i18n_build::collect(None, true).is_err()); } diff --git a/crates/ui-egui/tests/it/alpha_parameters.rs b/crates/ui-egui/tests/it/alpha_parameters.rs index acbd588f..394a135d 100644 --- a/crates/ui-egui/tests/it/alpha_parameters.rs +++ b/crates/ui-egui/tests/it/alpha_parameters.rs @@ -4,7 +4,6 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{AlphaParams, BrushAlpha, BrushSettings}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); const STARTUP_FRAMES: usize = 4; @@ -23,13 +22,19 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().session.tool.brush = brush; - harness.state_mut().ui.props_tab = PropsTab::Alpha; harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(egui::Role::Tab, "Alpha").click(); + harness.run_steps(SETTLE_FRAMES); harness } +/// The reset on the Parameters band's row fn restore_defaults<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'tree> { - harness.get_by_role_and_label(egui::Role::Button, "Parameters: Reset to defaults") + let band = harness.get_by_role_and_label(egui::Role::Button, "Parameters").rect(); + harness + .query_all_by_role_and_label(egui::Role::Button, "Restore defaults") + .find(|node| node.rect().y_range().intersects(band.y_range())) + .unwrap_or_else(|| panic!("no reset on the Parameters band")) } fn invert_checkbox<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> Option> { @@ -86,10 +91,11 @@ fn the_invert_checkbox_sets_the_brush_parameter() { #[test] fn hardness_left_the_brush_tab_and_its_reset() { - let mut harness = app_with_brush(BrushSettings::default()); - harness.state_mut().ui.props_tab = PropsTab::Brush; - harness.run_steps(SETTLE_FRAMES); + let harness = app_with_brush(BrushSettings::default()); - assert!(harness.query_by_label("Hardness").is_none(), "Hardness is in the Alpha tab now"); - assert!(harness.query_by_label("Flow").is_some()); + // One page: the Brush section comes first, Hardness only in the Alpha section under it + let hardness: Vec<_> = harness.query_all_by_role_and_label(egui::Role::Slider, "Hardness").map(|node| node.rect().top()).collect(); + let flow = harness.get_by_role_and_label(egui::Role::Slider, "Flow").rect().top(); + assert_eq!(hardness.len(), 1, "Hardness is in the Alpha section alone"); + assert!(hardness[0] > flow, "the Alpha section follows the Brush section's Flow"); } diff --git a/crates/ui-egui/tests/it/alpha_slot.rs b/crates/ui-egui/tests/it/alpha_slot.rs new file mode 100644 index 00000000..0093e077 --- /dev/null +++ b/crates/ui-egui/tests/it/alpha_slot.rs @@ -0,0 +1,107 @@ +//! The Alpha section's slot: its picker sets the brush alpha, × goes back to the Round shape, and Roundness shows only for the Round shape + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_widget}; + +/// Window the Alpha section tests run in +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames after a click in the slot, more than the crate's SETTLE_FRAMES to leave the alpha picker's popup time to open or close +const SLOT_CLICK_FRAMES: usize = 6; + +/// Frames for the jump tab's animated scroll to settle +const SCROLL_FRAMES: usize = 60; + +/// The app showing the Alpha section of Properties, with `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Alpha").click(); + harness.run_steps(SCROLL_FRAMES); + harness +} + +fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) { + click_widget(harness, role, label); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +/// The × of the slot showing `slot`: the Clear button on its row +fn click_clear(harness: &mut Harness<'_, TextureCraftApp>, slot: &str) { + let row = harness.get_by_role_and_label(Role::ComboBox, slot).rect(); + let clear = harness + .query_all_by_role_and_label(Role::Button, "Clear") + .find(|node| node.rect().y_range().intersects(row.y_range())) + .unwrap_or_else(|| panic!("no Clear on the {slot} slot")) + .rect(); + super::click_at(harness, clear.center()); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +/// Clicks the built-in shape `label`: the Shapes come first, above a library alpha of the same name +fn click_shape(harness: &mut Harness<'_, TextureCraftApp>, label: &str) { + let tile = harness + .query_all_by_role_and_label(Role::ListBoxOption, label) + .map(|node| node.rect()) + .min_by(|a, b| a.top().total_cmp(&b.top())) + .unwrap_or_else(|| panic!("no {label} tile")); + super::click_at(harness, tile.center()); + harness.run_steps(SLOT_CLICK_FRAMES); +} + +#[test] +fn the_slot_picks_a_shape_and_its_clear_goes_back_to_round() { + let mut harness = app_with_brush(BrushSettings::default()); + let row = harness.get_by_role_and_label(Role::ComboBox, "Round").rect(); + assert!( + !harness.query_all_by_role_and_label(Role::Button, "Clear").any(|node| node.rect().y_range().intersects(row.y_range())), + "the Round shape has nothing to clear back to" + ); + + click(&mut harness, Role::ComboBox, "Round"); + click_shape(&mut harness, "Star"); + assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Star); + assert!(harness.query_by_role_and_label(Role::ComboBox, "Star").is_some(), "the slot shows the picked shape"); + + click_clear(&mut harness, "Star"); + assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Round); +} + +#[test] +fn the_picker_offers_the_library_alphas() { + // Any library alpha + let alpha = &alphas::library()[0]; + let mut harness = app_with_brush(BrushSettings::default()); + + click(&mut harness, Role::ComboBox, "Round"); + harness.event(egui::Event::Text(alpha.label.clone())); + harness.run_steps(SLOT_CLICK_FRAMES); + click(&mut harness, Role::ListBoxOption, &alpha.label); + + let brush = &harness.state().session.tool.brush; + assert_eq!(brush.alpha_library.as_deref(), Some(alpha.id.as_str())); + assert!(harness.query_by_role_and_label(Role::ComboBox, &alpha.label).is_some(), "the slot shows the library alpha"); +} + +#[test] +fn roundness_shows_only_for_the_round_shape() { + let roundness = |harness: &Harness<'_, TextureCraftApp>| harness.query_all_by_role_and_label(Role::Slider, "Roundness").count(); + + let round = app_with_brush(BrushSettings::default()); + assert_eq!(roundness(&round), 1, "the Round shape has a roundness"); + + let star = app_with_brush(BrushSettings { alpha: BrushAlpha::Star, ..BrushSettings::default() }); + assert_eq!(roundness(&star), 0, "other alphas have none"); + assert_eq!(star.query_all_by_role_and_label(Role::Slider, "Hardness").count(), 1, "the rest of the Parameters stay"); +} diff --git a/crates/ui-egui/tests/it/brush_section_reset.rs b/crates/ui-egui/tests/it/brush_section_reset.rs index 16270401..19dd4b0c 100644 --- a/crates/ui-egui/tests/it/brush_section_reset.rs +++ b/crates/ui-egui/tests/it/brush_section_reset.rs @@ -1,11 +1,11 @@ -//! Each brush section header has a reset icon that puts only that section's settings back to their defaults +//! Each band of the Brush section has a reset that puts back only that band's settings, grouped as the reference groups them use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{Alignment, BrushAlpha, BrushSettings, Particles, Symmetry}; use texturecraft_ui_egui::TextureCraftApp; -/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +/// The default window; Properties shows only the top of the brush there, so lower bands are scrolled to const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); /// Frames for the first layout and fonts to settle @@ -17,25 +17,22 @@ const SETTLE_FRAMES: usize = 3; /// Puts one section's fields of the first brush back to the second's values type SectionReset = fn(&mut BrushSettings, &BrushSettings); -/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset -const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ - ("Size", "Minimum size (%)", true, |brush, defaults| { - (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) +/// Each band's title, a label shown only while it is open, whether it starts open, and its reset +const SECTIONS: [(&str, &str, bool, SectionReset); 6] = [ + ("Size", "Minimum Size (%)", true, |brush, defaults| { + (brush.size, brush.size_pressure, brush.min_size, brush.spacing) = (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing) }), - ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { - (brush.flow, brush.opacity, brush.spacing) = (defaults.flow, defaults.opacity, defaults.spacing) - }), - ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), - ("Jitters", "Size jitter", false, |brush, defaults| { + ("Opacity", "Stroke opacity", true, |brush, defaults| (brush.flow, brush.opacity) = (defaults.flow, defaults.opacity)), + ("Orientation", "Follow Path", true, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitter", "Size Jitter", true, |brush, defaults| { (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) }), - ("Alignment and culling", "Backface culling", false, |brush, defaults| { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = - (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + ("Projection", "Backface culling", true, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.screen_space, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.screen_space, defaults.depth) }), ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), - ("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 @@ -43,6 +40,7 @@ fn changed_brush() -> BrushSettings { BrushSettings { size: 0.1, min_size: 0.5, + size_pressure: false, screen_space: true, flow: 0.5, opacity: 0.6, @@ -82,24 +80,40 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { harness } -/// The reset icon on the header row titled `title` -fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { - let label = format!("{title}: Reset to defaults"); +/// The band titled `title` in Properties: the rightmost, as the top bar has a Size too +fn band<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { harness .query_all_by_role(egui::Role::Button) - .find(|node| node.accesskit_node().label().as_deref() == Some(label.as_str())) - .unwrap_or_else(|| panic!("no reset icon on the {title} header")) + .filter(|node| node.accesskit_node().label().as_deref() == Some(title)) + .max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())) + .unwrap_or_else(|| panic!("no {title} band")) } -/// Scrolls the header titled `title` into view and clicks its reset icon +/// The reset on the band titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + let band = band(harness, title).rect(); + harness + .query_all_by_role(egui::Role::Button) + .find(|node| node.accesskit_node().label().as_deref() == Some("Restore defaults") && node.rect().y_range().intersects(band.y_range())) + .unwrap_or_else(|| panic!("no reset on the {title} band")) +} + +/// Scrolls the band titled `title` into view and clicks its reset fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { - reset_icon(harness, title).scroll_to_me(); + band(harness, title).scroll_to_me(); harness.run_steps(SETTLE_FRAMES); reset_icon(harness, title).click(); harness.run_steps(SETTLE_FRAMES); } +#[test] +fn the_lazy_mouse_is_set_only_in_the_top_bar() { + let harness = app_with_brush(BrushSettings::default()); + + assert_eq!(harness.query_all_by_label("Lazy mouse").count(), 1, "the top bar's button, no band in Properties"); +} + #[test] fn each_reset_puts_back_only_its_own_section() { let defaults = BrushSettings::default(); @@ -118,13 +132,12 @@ fn each_reset_puts_back_only_its_own_section() { } } -/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +/// Scrolls the band titled `title` into view and clicks it, folding or unfolding it fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { - reset_icon(harness, title).scroll_to_me(); + band(harness, title).scroll_to_me(); harness.run_steps(SETTLE_FRAMES); - let icon = reset_icon(harness, title).rect(); - harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + band(harness, title).click(); harness.run_steps(SETTLE_FRAMES); } @@ -157,7 +170,7 @@ fn at_the_defaults_the_reset_icons_are_inert() { click_reset(&mut harness, title); - assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + assert_eq!(harness.query_by_label(body_label).is_some(), !starts_open, "an inert reset folds the {title} band like the rest of it"); assert_eq!(harness.state().session.tool.brush, BrushSettings::default(), "the {title} reset is inert"); } } @@ -168,6 +181,7 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { let mut harness = app_with_brush(changed_brush()); reset_icon(&harness, "Size").focus(); harness.run_steps(SETTLE_FRAMES); + assert!(reset_icon(&harness, "Size").is_focused()); harness.key_press(key); @@ -175,7 +189,8 @@ fn enter_and_space_on_the_focused_reset_icon_reset_only_its_section() { let defaults = BrushSettings::default(); let mut expected = changed_brush(); - (expected.size, expected.min_size, expected.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space); + (expected.size, expected.size_pressure, expected.min_size, expected.spacing) = + (defaults.size, defaults.size_pressure, defaults.min_size, defaults.spacing); assert_eq!(harness.state().session.tool.brush, expected, "resetting Size with {key:?}"); } } diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index d2edee62..4997545b 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -143,16 +143,16 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { let rows = plan(&mut h).len(); h.get_all_by_label_contains("Enable override for ").nth(4).unwrap().click(); h.run_steps(4); - let m = maps(&h); - let (_, first) = m.iter().next().unwrap(); + let map_overrides = maps(&h); + let (_, first) = map_overrides.iter().next().unwrap(); - assert!(first.file_type.is_some(), "{m:?}"); + assert!(first.file_type.is_some(), "{map_overrides:?}"); assert!(h.query_by_label("*").is_some(), "the set is marked"); click(&mut h, "Output maps menu"); click(&mut h, "Override every item"); - assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows); + assert_eq!(maps(&h).values().filter(|map_overrides| map_overrides.file_type.is_some()).count(), rows); click(&mut h, "Output maps menu"); click(&mut h, "Clear all overrides"); @@ -165,12 +165,12 @@ fn export_writes_a_map_with_its_own_file_type() { let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; let dir = TempDir::new("export-map-overrides"); let template = h.state().ui.export.preset.clone(); - let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); - let e = &mut h.state_mut().ui.export; - e.dir = dir.display().to_string(); - e.sets.insert(0, o); - e.skip = (1..32).collect(); + let mut overrides = SetExport { maps_template: template, ..SetExport::default() }; + overrides.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None }); + let export = &mut h.state_mut().ui.export; + export.dir = dir.display().to_string(); + export.sets.insert(0, overrides); + export.skip = (1..32).collect(); h.run_steps(3); click(&mut h, "Export"); @@ -193,9 +193,9 @@ fn a_map_the_template_no_longer_has_is_ignored() { let mut h = harness(); let before = selected(&h); let template = h.state().ui.export.preset.clone(); - let mut o = SetExport { maps_template: template, ..SetExport::default() }; - o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); - h.state_mut().ui.export.sets.insert(0, o); + let mut overrides = SetExport { maps_template: template, ..SetExport::default() }; + overrides.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); + h.state_mut().ui.export.sets.insert(0, overrides); h.run_steps(3); assert_eq!(selected(&h), before, "the export still plans every file"); @@ -285,11 +285,13 @@ fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { let mut h = harness(); let rows: Vec = plan(&mut h).iter().take(2).map(|file| file["map"].as_u64().unwrap() as usize).collect(); let template = h.state().ui.export.preset.clone(); - let mut o = SetExport { maps_template: template, ..SetExport::default() }; + let mut overrides = SetExport { maps_template: template, ..SetExport::default() }; for map in &rows { - o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); + overrides + .maps + .insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None }); } - h.state_mut().ui.export.sets.insert(0, o); + h.state_mut().ui.export.sets.insert(0, overrides); h.run_steps(4); let greyed: Vec<_> = diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 3579ece6..0deb8df8 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -73,6 +73,25 @@ fn a_texture_set_page_shows_what_it_inherits() { assert!(h.query_by_label("*").is_none(), "no override yet"); } +#[test] +fn rectangular_export_sizes_follow_the_plan_in_settings_and_the_file_list() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + session.doc.project.texture_sets[0].set_size(256, 128); + let mut h = harness_with_session(session); + + assert!(h.query_by_label("256x128 (Texture Set size)").is_some()); + toggle(&mut h, 2); + let size = h.get_all_by_role(egui::Role::ComboBox).find(|node| node.value().as_deref() == Some("256x128 (Texture Set size)")).unwrap(); + size.click(); + h.run_steps(4); + click(&mut h, "128x64"); + + h.state_mut().ui.export.tab = 2; + h.run_steps(4); + + assert!(h.query_all_by_label("128x64").next().is_some()); +} + #[test] fn an_override_turns_the_row_into_a_list_and_marks_the_set() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index ec4bf518..7ed2a5a6 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -50,6 +50,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { click(&mut h, "Export"); assert_eq!(h.state().ui.export.tab, 2, "Export switches to LIST OF EXPORTS"); h.run_steps(1); + assert!(h.query_by_label("Cancel Export").is_some()); assert_eq!(h.get_by_role(egui::Role::ProgressIndicator).accesskit_node().live(), egui::accesskit::Live::Polite); assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons"); @@ -63,6 +64,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() { h.run_steps(1); } h.run_steps(2); + assert!(h.state().ui.windows.export, "the window stays open"); assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none()); let lines = console(&h); @@ -176,6 +178,7 @@ fn long_filenames_leave_the_export_details_reachable_by_scrolling() { assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus(); h.run_steps(3); + assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused()); for _ in 0..12 { @@ -232,6 +235,21 @@ fn the_settings_at_export_are_kept_while_it_runs() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn changing_only_the_height_stops_a_frozen_export_before_writing() { + let (mut h, directory) = harness("height-change"); + click(&mut h, "Export"); + let next_set = h.state().ui.export.job.as_ref().unwrap().pending[0].0; + let set = &mut h.state_mut().session.doc.project.texture_sets[next_set]; + set.set_size(set.resolution, 128); + + finish(&mut h); + + assert_eq!(exports(&h), 0); + assert!(console(&h).iter().any(|line| line.contains("planned files") && line.contains("changed"))); + assert!(!directory.exists()); +} + #[test] fn texture_sets_writing_the_same_file_name_do_not_start_an_export() { let (mut h, dir) = harness("clash"); @@ -379,3 +397,30 @@ fn a_texture_set_that_leaves_the_export_leaves_its_count() { assert_eq!(job.total - job.pending.len(), exports(&h), "the bar counts the writes done"); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_folded_set_stays_folded_while_a_selection_is_exported() { + let (mut harness, _) = harness("folded-selection"); + let directory = super::temp_dir::TempDir::new("folded-export-selection"); + harness.state_mut().ui.export.dir = directory.display().to_string(); + harness.state_mut().ui.export.skip = vec![0]; + harness.state_mut().ui.export.tab = 2; + harness.run_steps(3); + let set = harness.state().session.doc.project.texture_sets[1].name.clone(); + let preset = harness.state().ui.export.preset.clone(); + let plan = texturecraft_engine::execute(&mut harness.state_mut().session, "export.plan", &json!({"preset": preset, "ts": 1})).unwrap(); + let file = plan[0]["file"].as_str().unwrap(); + assert!(harness.query_by_label(file).is_some()); + + harness.get_by_role_and_label(egui::Role::DisclosureTriangle, &set).click(); + harness.run_steps(2); + + assert!(harness.query_by_label(file).is_none()); + + click(&mut harness, "Export"); + harness.run_steps(1); + + assert!(harness.query_by_label("Cancel Export").is_some(), "the selection is being written"); + assert!(harness.query_by_label(file).is_none(), "starting the export keeps the selected set folded"); + assert_eq!(harness.get_by_role_and_label(egui::Role::DisclosureTriangle, &set).accesskit_node().data().is_expanded(), Some(false)); +} diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index d3309e43..bc2b230a 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -198,8 +198,9 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { assert!(h.query_by_label("Dilation (pixels)").is_some()); - // A click on the slider sets the width and leaves the menu open - h.get_by_role(egui::Role::Slider).click(); + // A click on the slider sets the width and leaves the menu open; Properties has sliders too, so take the one under the menu's label + let label = h.get_by_label("Dilation (pixels)").rect().left_bottom(); + h.query_all_by_role(egui::Role::Slider).min_by(|a, b| a.rect().left_top().distance(label).total_cmp(&b.rect().left_top().distance(label))).unwrap().click(); h.run_steps(4); assert_ne!(h.state().ui.export.dilation, 16); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index ade144d7..018616ec 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -28,15 +28,15 @@ fn press(harness: &mut Harness<'_, TextureCraftApp>, key: Key) { harness.run_steps(3); } -/// The History rows shown as the current step: name and top edge -fn current_rows(harness: &Harness<'_, TextureCraftApp>) -> Vec<(String, f32)> { +/// The labels and bounds of the rows marked as current +fn current_rows(harness: &Harness<'_, TextureCraftApp>) -> Vec<(String, Rect)> { let session = &harness.state().session; let undone = session.redo_labels().into_iter().map(|label| format!("{label} (undone)")); let names: Vec = session.history_labels().into_iter().chain(undone).chain(["Project opened".to_owned()]).collect(); harness .get_all_by_role(egui::accesskit::Role::Button) .filter(|node| node.accesskit_node().toggled() == Some(Toggled::True)) - .filter_map(|node| Some((node.accesskit_node().label()?, node.rect().top()))) + .filter_map(|node| Some((node.accesskit_node().label()?, node.rect()))) .filter(|(name, _)| names.contains(name)) .collect() } @@ -231,7 +231,7 @@ fn only_the_current_step_is_marked_selected() { press(&mut harness, Key::Z); let after = current_rows(&harness); assert_eq!(after.len(), 1); - assert!(after[0].1 < before[0].1, "the outline moves up a row"); + assert!(after[0].1.top() < before[0].1.top(), "the outline moves up a row"); harness.get_by_label("Rename layer (undone)").click(); harness.run_steps(3); @@ -250,18 +250,17 @@ fn long_session(steps: usize) -> Session { session } -/// Whether the current step's row named `name` is on screen +/// Whether the entire current row is within the History list's viewport fn current_shown(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { - let screen = harness.ctx.content_rect(); - current_rows(harness).iter().any(|(row, top)| row == name && screen.y_range().contains(*top)) + let track = harness.get_by_role_and_label(egui::accesskit::Role::ScrollBar, "History scrollbar").rect(); + + current_rows(harness).iter().any(|(label, row)| label == name && track.top() <= row.top() && row.bottom() <= track.bottom()) } /// Scroll the History list back to its first rows with the mouse wheel fn scroll_to_top(harness: &mut Harness<'_, TextureCraftApp>) { - // Exactly one row is the current step; its top finds the row under the wheel - let (_, top) = current_rows(harness)[0]; - let over = harness.get_all_by_label("Rename layer").find(|node| node.rect().top() == top).unwrap().rect().center(); - harness.hover_at(over); + let (_, row) = current_rows(harness)[0]; + harness.hover_at(row.center()); harness.event(Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, 100_000.0), @@ -393,8 +392,8 @@ fn an_undocked_history_shows_the_newest_step() { #[test] fn the_keyboard_reaches_rows_scrolled_out_of_view() { let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); - let (_, top) = current_rows(&harness)[0]; - harness.get_all_by_label("Rename layer").find(|node| node.rect().top() == top).unwrap().focus(); + let (_, row) = current_rows(&harness)[0]; + harness.get_all_by_label("Rename layer").find(|node| node.rect() == row).unwrap().focus(); harness.run_steps(2); let first_row_focused = |harness: &Harness<'_, TextureCraftApp>| { diff --git a/crates/ui-egui/tests/it/library_theme.rs b/crates/ui-egui/tests/it/library_theme.rs new file mode 100644 index 00000000..3afe5219 --- /dev/null +++ b/crates/ui-egui/tests/it/library_theme.rs @@ -0,0 +1,38 @@ +//! craft-ui's parts (the dock's frames and tab strips) draw in TextureCraft's colours, not the suite's default grey + +use craft_ui::style::StyleCx; +use egui::Color32; +use egui_kittest::Harness; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::theme::{Brightness, Tokens}; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, TEXTURE_RESOLUTION}; + +/// A window wide enough for the dock's groups, strips and splitters +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1200.0, 800.0); + +fn srgba(color: craft_theme::Rgba) -> Color32 { + let [r, g, b, a] = color.0; + Color32::from_rgba_unmultiplied(r, g, b, a) +} + +#[test] +fn the_dock_strips_and_panel_bodies_take_the_app_theme_colours() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW_SIZE) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + for brightness in [Brightness::Dark, Brightness::MediumDark, Brightness::MediumLight, Brightness::Light] { + harness.state_mut().ui.prefs.brightness = brightness; + harness.run_steps(SETTLE_FRAMES); + let tokens = Tokens::get(&harness.ctx); + let (strip, body, frame) = StyleCx::with_root(&harness.ctx, |cx| { + let color = &cx.tokens.color; + (color.surface.background, color.surface.panel, color.line.border) + }); + assert_eq!(srgba(strip), tokens.chrome, "{brightness:?}: the tab strips lie on the window chrome"); + assert_eq!(srgba(body), tokens.panel, "{brightness:?}: the shown tab and the panel body are the panel card"); + assert_eq!(srgba(frame), tokens.separator, "{brightness:?}: the group frames are the cards' hairline"); + } +} diff --git a/crates/ui-egui/tests/it/log_panel_680.rs b/crates/ui-egui/tests/it/log_panel_680.rs index 3fa9764d..27c94c13 100644 --- a/crates/ui-egui/tests/it/log_panel_680.rs +++ b/crates/ui-egui/tests/it/log_panel_680.rs @@ -166,13 +166,11 @@ fn the_log_tabs_split_the_panel_width() { fn the_log_scroll_bar_stands_clear_of_the_list_frame() { let harness = app(); let (general, assets) = (harness.get_by_label("GENERAL").rect(), harness.get_by_label("ASSETS").rect()); - let bars = - harness.get_all_by_role(egui::accesskit::Role::ScrollBar).filter(|bar| bar.rect().left() > general.left() && bar.rect().right() <= assets.right()); - let bar = bars.max_by(|a, b| a.rect().height().total_cmp(&b.rect().height())).expect("the list's scroll bar").rect(); + let bar = harness.get_by_role_and_label(egui::accesskit::Role::ScrollBar, "Log vertical scrollbar").rect(); // The frame ends where the tab strip ends; its 1 point line and 1 point padding come before its inside let frame_inside = assets.right() - 2.0; - assert!(bar.right() < frame_inside, "{bar:?} {assets:?}"); + assert!(general.left() < bar.left() && bar.right() < frame_inside, "{bar:?} {assets:?}"); } /// How many rows each painted text containing `part` has @@ -204,13 +202,37 @@ fn a_long_line_stays_one_row() { assert_eq!(painted_rows(&harness, "long long"), vec![1]); } -/// A message with a line break is painted on its row, not over the lines around it #[test] -fn a_message_with_a_line_break_is_painted_on_one_row() { +fn a_multiline_message_scrolls_on_one_row_and_copies_verbatim() { let mut harness = app(); - log_behind_a_newer_line(&mut harness, "broken\nmessage"); + let message = format!("broken\r\n{}end", "long ".repeat(100)); + log_behind_a_newer_line(&mut harness, &message); + let label = format!("[Exporter] {message}"); + let painted_left = |harness: &Harness<'_, TextureCraftApp>| { + harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text().starts_with("[Exporter] broken") => Some(text.pos.x), + _ => None, + }) + }; assert_eq!(painted_rows(&harness, "broken"), vec![1]); + let before = painted_left(&harness).unwrap(); + let track = harness.get_by_role_and_label(egui::Role::ScrollBar, "Log horizontal scrollbar").rect(); + harness.hover_at(egui::pos2(track.right() - 1.0, track.center().y)); + harness.step(); + let at = egui::pos2(track.right() - 1.0, track.center().y); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.step(); + } + harness.run_steps(3); + + assert!(painted_left(&harness).unwrap() < before); + key_click(&mut harness, &label, Modifiers::NONE); + harness.event(Event::Copy); + harness.step(); + + assert!(harness.output().platform_output.commands.contains(&OutputCommand::CopyText(label))); } #[test] diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 1c805d02..1b0167ac 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available. mod alpha_parameters; +mod alpha_slot; mod anchor_point; mod auto_rebake; mod bake_job_mesh; @@ -62,6 +63,7 @@ mod layer_rename; mod layer_toolbar; mod layers_panel; mod levels_editor; +mod library_theme; mod log_panel_680; mod mask_export; mod mask_fill_rows; @@ -72,6 +74,8 @@ mod nav_buttons; mod new_project_baked_maps; mod new_project_window; mod output_templates; +mod paint_hint_lines; +mod paint_tool_tabs; mod panel_header; mod path_in_view; mod path_list; @@ -103,6 +107,7 @@ mod shift_lines_3d; mod shortcut_keys; mod shortcut_list; mod side_panels; +mod size_pressure; mod skew_paint; mod smudge_channels; mod snapped_lines; @@ -112,6 +117,7 @@ mod temp_dir; mod template_invert; mod templates_681; mod tool_availability; +mod tool_material; mod tool_settings_saved; mod toolbar; mod user_smart_mask; diff --git a/crates/ui-egui/tests/it/mask_paint_grayscale.rs b/crates/ui-egui/tests/it/mask_paint_grayscale.rs index 059beb4f..b619ea48 100644 --- a/crates/ui-egui/tests/it/mask_paint_grayscale.rs +++ b/crates/ui-egui/tests/it/mask_paint_grayscale.rs @@ -7,7 +7,6 @@ use serde_json::json; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; @@ -32,8 +31,9 @@ fn folder_mask_harness() -> (Harness<'static, TextureCraftApp>, String) { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.props_tab = PropsTab::Material; harness.run_steps(STARTUP_FRAMES); + harness.get_by_role_and_label(Role::Tab, "Grayscale").click(); + harness.run_steps(SETTLE_FRAMES); (harness, image) } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index edb10bfe..268d9480 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -213,10 +213,10 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { two.maps.truncate(2); h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap(); let own = "Unreal Engine (Packed)".to_string(); - let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; - o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); + let mut overrides = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() }; + overrides.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); let ts = h.state().session.ts(); - h.state_mut().ui.export.sets.insert(ts, o); + h.state_mut().ui.export.sets.insert(ts, overrides); h.state_mut().ui.export.preset = "Two".into(); h.run_steps(4); @@ -235,13 +235,13 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { let library = TemplateLibrary::new("follow"); let mut h = harness(&library); - let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; - o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); + let mut overrides = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() }; + overrides.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None }); // The override is there when the window opens h.state_mut().ui.windows.export = false; h.run_steps(2); - h.state_mut().ui.export.sets.insert(0, o); + h.state_mut().ui.export.sets.insert(0, overrides); let ui = &mut h.state_mut().ui; ui.windows.export = true; ui.export.tab = 1; @@ -256,10 +256,10 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { h.run_steps(4); assert_eq!(h.state().ui.export.preset, "Yours"); - let o = h.state().ui.export.sets[&0].clone(); + let overrides = h.state().ui.export.sets[&0].clone(); - assert_eq!((o.preset.as_deref(), o.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks"); - assert_eq!(o.maps.len(), 1); + assert_eq!((overrides.preset.as_deref(), overrides.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks"); + assert_eq!(overrides.maps.len(), 1); right_click(&mut h, "Yours"); click(&mut h, "Remove"); @@ -271,7 +271,7 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() { // Cancel goes back to the settings the window opened with, minus the removed template click(&mut h, "Cancel"); - assert!(h.state().ui.export.sets.values().all(|o| o.preset.as_deref() != Some("Yours") && o.preset.as_deref() != Some("Mine"))); + assert!(h.state().ui.export.sets.values().all(|overrides| overrides.preset.as_deref() != Some("Yours") && overrides.preset.as_deref() != Some("Mine"))); } #[test] @@ -460,21 +460,35 @@ fn the_map_lists_stand_in_three_panes_with_their_groups_and_names() { let h = harness(&library); let input = h.get_by_label("Input maps").rect(); + // A built-in template is called "Mesh maps" too: the pane's title comes after the Presets list let mesh = h.get_all_by_label("Mesh maps").last().unwrap().rect(); let converted = h.get_by_label("Converted maps").rect(); assert!(mesh.left() > input.right(), "Mesh maps stand in a column right of Input maps"); assert!(converted.top() > mesh.bottom() && (converted.left() - mesh.left()).abs() < 2.0, "Converted maps stand below Mesh maps"); - for group in ["Transmission", "Subsurface", "Sheen", "Thin film", "Other"] { + for group in ["Transmission", "Subsurface", "Sheen", "Thin film", "Other", "User"] { assert!(h.query_all_by_label(group).next().is_some(), "group {group}"); } - for name in ["Specular level", "Sheen weight", "Coat normal", "Emissive", "World Space Normal", "Bent Normals", "Normal DirectX", "F0 from specular level"] - { + for name in [ + "Specular level", + "Sheen weight", + "Coat normal", + "Emissive", + "World Space Normal", + "Bent Normals", + "Normal DirectX", + "F0 from specular level", + "Base weight", + "Coat tangent", + "Thin-film weight", + "Subsurface radius scale", + "User31", + ] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(!entry.accesskit_node().is_disabled(), "{name} can be dragged"); } - for name in ["Base weight", "Coat tangent", "Thin film weight", "Subsurface radius"] { + for name in ["Coat IOR", "Thin film thickness"] { let entry = h.query_all_by_label(name).next().unwrap_or_else(|| panic!("{name}")); assert!(entry.accesskit_node().is_disabled(), "{name} is listed greyed"); } @@ -786,5 +800,6 @@ fn feedback_template_preview_counts_overrides_only_for_its_own_maps() { assert!(h.query_by_label(&format!("{} output maps will be exported", initial - 1)).is_some()); h.state_mut().ui.export.sets.get_mut(&ts).unwrap().preset = Some("Separate maps".into()); h.run_steps(4); + assert!(h.query_by_label(&format!("{initial} output maps will be exported")).is_some()); } diff --git a/crates/ui-egui/tests/it/paint_hint_lines.rs b/crates/ui-egui/tests/it/paint_hint_lines.rs new file mode 100644 index 00000000..c4759186 --- /dev/null +++ b/crates/ui-egui/tests/it/paint_hint_lines.rs @@ -0,0 +1,53 @@ +//! A brush tool's Properties explain themselves in tooltips: no line of instructions under the controls + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +fn with_tool(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The words of every label in the app +fn labels(harness: &Harness<'_, TextureCraftApp>) -> Vec { + harness.query_all_by_role(Role::Label).filter_map(|node| node.accesskit_node().value().map(|value| value.to_string())).collect() +} + +#[test] +fn the_brush_section_has_no_shortcut_lines() { + let harness = with_tool("paint"); + assert!(harness.query_by_role_and_label(Role::Slider, "Size").is_some(), "the Brush section is on screen"); + let labels = labels(&harness); + let shortcut = labels.iter().find(|label| label.contains("drag")); + assert!(shortcut.is_none(), "the view shortcuts are in the keymap, not under the brush: {shortcut:?}"); +} + +#[test] +fn the_smudge_section_has_no_explanation_lines() { + let labels = labels(&with_tool("smudge")); + assert!(labels.iter().any(|label| label == "Channels dragged"), "the Smudge section is on screen"); + let sentence = labels.iter().find(|label| label.ends_with('.')); + assert!(sentence.is_none(), "what Smudge does is in its tooltips: {sentence:?}"); +} + +#[test] +fn the_clone_section_shows_its_source_state_without_instructions() { + let labels = labels(&with_tool("clone")); + assert!(labels.iter().any(|label| label == "Source: none"), "no source set yet reads as state"); + let sentence = labels.iter().find(|label| label.ends_with('.')); + assert!(sentence.is_none(), "how to set the source is in the tooltip: {sentence:?}"); +} diff --git a/crates/ui-egui/tests/it/paint_tool_tabs.rs b/crates/ui-egui/tests/it/paint_tool_tabs.rs new file mode 100644 index 00000000..ca7ee50c --- /dev/null +++ b/crates/ui-egui/tests/it/paint_tool_tabs.rs @@ -0,0 +1,174 @@ +//! A paint tool's Properties: one page of sections under jump tabs, Brush · Alpha · (Stencil) · Material, below a brush preview that stays put + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Short enough that the tool's sections scroll +const WINDOW: egui::Vec2 = egui::vec2(1400.0, 800.0); + +/// A second at 60 frames: a jump scrolls with egui's scroll animation +const SCROLL_FRAMES: usize = 60; + +fn paint_harness(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// egui reports a tab's selection as its toggled state +fn tab_selected(harness: &Harness<'_, TextureCraftApp>, tab: &str) -> bool { + harness.get_by_role_and_label(Role::Tab, tab).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) +} + +#[test] +fn the_tabs_jump_within_one_page_of_the_tools_sections() { + let mut harness = paint_harness("paint"); + for tab in ["Brush", "Alpha", "Stencil", "Material"] { + assert!(harness.query_by_role_and_label(Role::Tab, tab).is_some(), "the {tab} tab"); + } + assert!(tab_selected(&harness, "Brush"), "the page opens on its first section"); + let flow_before = harness.get_by_label("Flow").rect().top(); + + harness.get_by_role_and_label(Role::Tab, "Material").click(); + harness.run_steps(SCROLL_FRAMES); + + assert!(tab_selected(&harness, "Material"), "the clicked section is the one in view"); + assert!(!tab_selected(&harness, "Brush")); + assert!(harness.get_by_label("Flow").rect().top() < flow_before, "the Brush rows scrolled up out of the way, still on the page"); +} + +#[test] +fn every_brush_tool_has_a_stencil_tab_and_polygon_fill_none() { + for tool in ["paint", "eraser", "projection", "smudge", "clone"] { + let harness = paint_harness(tool); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some(), "{tool}"); + } + + let harness = paint_harness("polygonFill"); + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "polygon fill paints no strokes"); +} + +#[test] +fn the_brush_preview_stays_under_the_tabs_while_the_sections_scroll() { + let mut harness = paint_harness("paint"); + let preview_before = harness.get_by_label("Brush preview").rect(); + let flow_before = harness.get_by_label("Flow").rect().top(); + + harness.get_by_role_and_label(Role::Tab, "Material").click(); + harness.run_steps(SCROLL_FRAMES); + + assert!(harness.get_by_label("Flow").rect().top() < flow_before, "the sections scrolled"); + assert_eq!(harness.get_by_label("Brush preview").rect(), preview_before, "the preview stayed where it was"); + assert!(preview_before.top() >= harness.get_by_role_and_label(Role::Tab, "Material").rect().bottom(), "under the tabs"); +} + +#[test] +fn the_brush_preview_keeps_its_picture_until_the_paint_colour_changes() { + let mut harness = paint_harness("paint"); + let pictures = |harness: &Harness<'_, TextureCraftApp>| -> Vec { + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name == "brush_stroke_preview").map(|(id, _)| *id).collect() + }; + let first = pictures(&harness); + + harness.run_steps(SCROLL_FRAMES); + + assert_eq!(pictures(&harness), first, "an unchanged brush reuses its picture"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.run_steps(SCROLL_FRAMES); + let recoloured = pictures(&harness); + assert_eq!(recoloured.len(), 1, "the old picture is released"); + assert_ne!(recoloured, first, "a new colour draws a new picture"); +} + +#[test] +fn the_brush_preview_ignores_values_of_disabled_channels() { + let mut harness = paint_harness("paint"); + let preview_meshes = |harness: &Harness<'_, TextureCraftApp>| { + let preview = harness.get_by_role_and_label(Role::Image, "Brush preview").rect(); + let mut meshes = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) if preview.contains_rect(mesh.calc_bounds()) => Some(mesh), + _ => None, + }); + let stroke = meshes.find(|mesh| mesh.calc_bounds().right() <= preview.center().x).unwrap(); + let sphere = meshes.find(|mesh| mesh.calc_bounds().left() >= preview.center().x).unwrap(); + (stroke.texture_id, sphere.vertices.iter().map(|vertex| vertex.color).collect::>()) + }; + + for (channel, material) in [ + ("baseColor", json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})), + ("metallic", json!({"channel": "metallic", "value": 1.0})), + ("roughness", json!({"channel": "roughness", "value": 0.0})), + ] { + execute(&mut harness.state_mut().session, "tool.material", &material).unwrap(); + harness.run_steps(1); + let enabled = preview_meshes(&harness); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": channel, "enabled": false})).unwrap(); + harness.run_steps(1); + let disabled = preview_meshes(&harness); + + assert!(disabled.1 != enabled.1, "disabling {channel} changes the sphere shading"); + if channel == "baseColor" { + assert_ne!(disabled.0, enabled.0, "disabling base color redraws the tinted stroke"); + } + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": channel, "enabled": true})).unwrap(); + harness.run_steps(1); + + assert!(preview_meshes(&harness).1 == enabled.1, "re-enabling {channel} restores its stored value in the sphere"); + } +} + +#[test] +fn the_brush_preview_uses_neutral_coverage_while_editing_the_quick_mask() { + let mut harness = paint_harness("paint"); + let stroke_texture = |harness: &Harness<'_, TextureCraftApp>| { + let preview = harness.get_by_role_and_label(Role::Image, "Brush preview").rect(); + harness + .output() + .shapes + .iter() + .find_map(|clipped| match &clipped.shape { + egui::Shape::Mesh(mesh) if preview.contains_rect(mesh.calc_bounds()) && mesh.calc_bounds().right() <= preview.center().x => { + Some(mesh.texture_id) + } + _ => None, + }) + .unwrap() + }; + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap(); + harness.step(); + let blue = stroke_texture(&harness); + + execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + harness.step(); + + let coverage = stroke_texture(&harness); + assert_ne!(coverage, blue, "editing the quick mask redraws the blue stroke as coverage"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 1.0, 1.0]})).unwrap(); + harness.step(); + + assert_eq!(stroke_texture(&harness), coverage, "material changes do not tint the quick mask stroke"); + + execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.step(); + + assert_eq!(stroke_texture(&harness), coverage, "the quick mask preview uses the same neutral stroke as white paint"); +} diff --git a/crates/ui-egui/tests/it/popup_press_close.rs b/crates/ui-egui/tests/it/popup_press_close.rs index 72605f64..42393fa3 100644 --- a/crates/ui-egui/tests/it/popup_press_close.rs +++ b/crates/ui-egui/tests/it/popup_press_close.rs @@ -1,4 +1,4 @@ -//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the tool's colour, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart +//! A press outside a popup closes it when it turns into a drag (a paint stroke on the model), as a click does: the brush presets, the layer menus and the symmetry settings, in the default layout and in a rearranged one restored after a restart use eframe::App as _; use egui::accesskit::Role; @@ -18,9 +18,6 @@ const DRAG_MOVES: usize = 6; /// A short stroke on the model const STROKE: Vec2 = vec2(-60.0, 40.0); -/// From the tool's Base color label to inside its swatch -const LABEL_TO_SWATCH: f32 = 60.0; - /// The app started on `storage` (its saved arrangement, if any) with the paint tool's Properties showing fn app(storage: &MemoryStorage) -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); @@ -91,23 +88,17 @@ fn stroke_on_model(harness: &mut Harness<'_, TextureCraftApp>, modifiers: Modifi drag(harness, view.center(), STROKE, modifiers); } -/// Opens the paint tool's Base color swatch from its Properties' Material tab -fn open_tool_color(harness: &mut Harness<'_, TextureCraftApp>) { - let header = harness.get_by_role_and_label(egui::Role::Tab, "Properties - Paint").rect(); - let in_properties = |rect: egui::Rect| header.x_range().contains(rect.center().x) && rect.top() > header.top(); - let material = harness.get_all_by_label("Material").find(|node| in_properties(node.rect())).unwrap(); - material.click(); - harness.run_steps(SETTLE_FRAMES); - - let label = harness.get_all_by_value("Base color").find(|node| in_properties(node.rect())).unwrap().rect(); - click(harness, label.right_center() + vec2(LABEL_TO_SWATCH, 0.0)); - assert!(egui::Popup::is_any_open(&harness.ctx), "the swatch opens its colour popup"); +/// Opens the brush presets from the ≡ on the paint tool's Brush caption +fn open_brush_presets(harness: &mut Harness<'_, TextureCraftApp>) { + let menu = harness.get_by_role_and_label(Role::Button, "Brush presets").rect(); + click(harness, menu.center()); + assert!(egui::Popup::is_any_open(&harness.ctx), "the ≡ opens the brush presets"); } #[test] -fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_restored_rearranged_layout() { +fn a_stroke_on_the_model_closes_the_brush_presets_in_the_default_and_a_restored_rearranged_layout() { let check_stroke = |mut harness: Harness<'_, TextureCraftApp>, layout: &str| { - open_tool_color(&mut harness); + open_brush_presets(&mut harness); let history = harness.state().session.history_labels().len(); stroke_on_model(&mut harness, Modifiers::NONE); @@ -121,9 +112,9 @@ fn a_stroke_on_the_model_closes_the_tool_colour_popup_in_the_default_and_a_resto } #[test] -fn an_alt_orbit_keeps_the_tool_colour_popup_open() { +fn an_alt_orbit_keeps_the_brush_presets_open() { let mut harness = app(&MemoryStorage::default()); - open_tool_color(&mut harness); + open_brush_presets(&mut harness); stroke_on_model(&mut harness, Modifiers::ALT); @@ -147,7 +138,7 @@ fn a_stroke_on_the_model_closes_the_add_effect_menu() { fn outside_drag_dismissal_handles_motion_batched_with_release() { for (modifiers, stays_open) in [(Modifiers::ALT, true), (Modifiers::NONE, false)] { let mut harness = app(&MemoryStorage::default()); - open_tool_color(&mut harness); + open_brush_presets(&mut harness); let origin = harness.state().viewport_rect.center(); harness.event(Event::ModifiersChanged(modifiers)); harness.hover_at(origin); diff --git a/crates/ui-egui/tests/it/project_config.rs b/crates/ui-egui/tests/it/project_config.rs index a44c4640..f6a85502 100644 --- a/crates/ui-egui/tests/it/project_config.rs +++ b/crates/ui-egui/tests/it/project_config.rs @@ -526,7 +526,8 @@ fn the_normal_map_format_changes_on_ok_and_shows_in_the_texture_set_panel() { h.state_mut().ui.dock.focus(texturecraft_ui_egui::docking::Panel::TextureSetSettings); h.run_steps(3); - assert!(h.query_all_by_value("DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format"); + // The panel's dropdown shows the project's format (the project window is closed by now) + assert!(h.query_all_by_role_and_label(Role::ComboBox, "DirectX").next().is_some(), "the Texture Set Settings panel shows the project's format"); // One undo step puts it back h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); @@ -570,7 +571,9 @@ fn uv_tiles_are_shown_read_only() { hover_uv_tile_box(&mut h); assert!(h.query_by_label_contains("No UV tiles").is_none()); - assert!(h.query_by_label_contains("1001").is_some(), "the tile list of a UDIM project"); + + // The hint's own text, not the Texture Sets list's tile rows + assert!(h.query_all_by_label_contains("1001").any(|node| node.accesskit_node().role() == Role::Label), "the tile list of a UDIM project"); } /// Hover the disabled Use UV Tile workflow box, whose hint lists the project's UV tiles. @@ -765,3 +768,99 @@ fn project_config_snapshots() { h.run_steps(6); h.render().unwrap().save(output_dir.join("project-config-ocio.png")).unwrap(); } + +fn type_project_name(h: &mut Harness<'_, TextureCraftApp>, name: &str) { + in_window(h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + in_window(h, Role::TextInput, "Project name").type_text(name); + h.run_steps(2); +} + +#[test] +fn a_typed_project_name_applies_only_with_ok() { + let dir = temp_dir("project-name"); + let mut h = app_on_a_quad(&dir); + let before = h.state().session.doc.project.name.clone(); + + for button in ["Cancel", "OK"] { + open_window(&mut h); + type_project_name(&mut h, "Knight"); + click_in_window(&mut h, Role::Button, button); + + let expected = if button == "OK" { "Knight" } else { before.as_str() }; + assert_eq!(h.state().session.doc.project.name, expected, "after {button}"); + assert!(!window_is_open(&h), "{button} closes the window"); + } +} + +#[test] +fn an_invalid_project_name_leaves_other_configuration_changes_pending() { + use texturecraft_engine::core::NormalFormat; + + let dir = temp_dir("invalid-project-name"); + let mut h = app_on_a_quad(&dir); + let triangle = dir.join("tri.obj"); + std::fs::write(&triangle, TRIANGLE).unwrap(); + + open_window(&mut h); + select(&mut h, &triangle); + click_in_window(&mut h, Role::ComboBox, FORMAT_HINT); + click_in_window(&mut h, Role::Button, "DirectX"); + type_project_name(&mut h, " "); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, "quad"); + assert_eq!(h.state().session.mesh.triangle_count(), 2); + assert_eq!(project_normal_format(&h), NormalFormat::OpenGl); + let message = h.get_by_label("Project name must be 1 to 128 characters after trimming, without control characters."); + assert_eq!(message.accesskit_node().live(), egui::accesskit::Live::Polite); + + type_project_name(&mut h, "Knight"); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, "Knight"); + assert_eq!(h.state().session.mesh.triangle_count(), 1); + assert_eq!(project_normal_format(&h), NormalFormat::DirectX); +} + +#[test] +fn the_project_name_limit_applies_after_trimming_in_the_dialog() { + use texturecraft_engine::project_cmds::MAX_PROJECT_NAME_CHARS; + + let dir = temp_dir("project-name-limit"); + let mut h = app_on_a_quad(&dir); + let name = format!("{}Z", "x".repeat(MAX_PROJECT_NAME_CHARS - 1)); + + open_window(&mut h); + type_project_name(&mut h, &format!(" {name} ")); + click_in_window(&mut h, Role::Button, "OK"); + + assert!(!window_is_open(&h)); + assert_eq!(h.state().session.doc.project.name, name); +} + +#[test] +fn a_reopened_name_field_cannot_undo_to_a_discarded_draft() { + let dir = temp_dir("project-name-history"); + let mut h = app_on_a_quad(&dir); + let original = h.state().session.doc.project.name.clone(); + + open_window(&mut h); + type_project_name(&mut h, "Discard this name"); + + // Drive enough virtual frames for the text edit to record an undo point + h.run_steps(90); + click_in_window(&mut h, Role::Button, "Cancel"); + + open_window(&mut h); + in_window(&h, Role::TextInput, "Project name").focus(); + h.run_steps(2); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Z); + h.run_steps(2); + + let field = in_window(&h, Role::TextInput, "Project name"); + assert_eq!(field.accesskit_node().value().as_deref(), Some(original.as_str())); +} diff --git a/crates/ui-egui/tests/it/properties_lists.rs b/crates/ui-egui/tests/it/properties_lists.rs index 3486b719..cb2501c2 100644 --- a/crates/ui-egui/tests/it/properties_lists.rs +++ b/crates/ui-egui/tests/it/properties_lists.rs @@ -22,6 +22,9 @@ const GESTURE: Vec2 = vec2(-60.0, 40.0); /// Where in the view the gestures start, as a share of its width from its left edge const GESTURE_SHARE: f32 = 0.3; +/// Frames for a scroll to a list to finish its animation +const SCROLL_FRAMES: usize = 30; + /// Escapes between lists, so one that stays open can't leave its popup over the next const ESCAPES_TO_CLEAR: usize = 2; @@ -242,6 +245,17 @@ fn every_list_opens_leaves_the_view_its_camera_and_closes_on_escape_a_click_and_ continue; }; + // A list low in a long panel sits below its visible part until scrolled to + let same_before = lists(&harness).iter().take(index).filter(|(_, other)| *other == shown).count(); + if let Some(node) = harness.query_all_by_role(Role::ComboBox).find(|node| node.rect() == button) { + node.scroll_to_me(); + } + harness.run_steps(SCROLL_FRAMES); + let Some((button, _)) = lists(&harness).into_iter().filter(|(_, other)| *other == shown).nth(same_before) else { + problems.push(format!("{screen}: {shown} is gone after scrolling to it")); + continue; + }; + problems.extend(check_list(&mut harness, button, &format!("{screen}: {shown}"))); for _ in 0..ESCAPES_TO_CLEAR { harness.key_press(egui::Key::Escape); diff --git a/crates/ui-egui/tests/it/properties_popup.rs b/crates/ui-egui/tests/it/properties_popup.rs index 19de942d..0453378a 100644 --- a/crates/ui-egui/tests/it/properties_popup.rs +++ b/crates/ui-egui/tests/it/properties_popup.rs @@ -9,7 +9,7 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; -use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; +use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION}; /// A common laptop window const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); @@ -35,6 +35,9 @@ const SCROLL_FRAMES: usize = 25; /// How far left of the popup a click lands on the model const MODEL_LEFT_OF_POPUP: f32 = 60.0; +/// How far in from the popup's right edge a slider drag ends, still over the slider's band +const DROP_LEFT_OF_POPUP_EDGE: f32 = 30.0; + fn harness() -> Harness<'static, TextureCraftApp> { harness_sized(WINDOW_SIZE) } @@ -156,21 +159,23 @@ fn dragging_its_size_slider_changes_the_brush() { click(&mut harness, PointerButton::Secondary, center); let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); - // The Size section's header sits above its slider of the same name - let slider_label = harness - .query_all_by_label("Size") + // The Size band holds a slider of the same name, its track right of the label + let slider = harness + .query_all_by_role(egui::Role::Slider) + .filter(|node| node.accesskit_node().label().as_deref() == Some("Size")) .map(|node| node.rect()) - .filter(|rect| popup.contains_rect(*rect)) - .max_by(|first, second| first.top().total_cmp(&second.top())) + .find(|rect| popup.contains_rect(*rect)) .unwrap(); - let track_y = slider_label.bottom() + 10.0; + let track_y = slider.center().y; let size = harness.state().session.tool.brush.size; - harness.drag_at(egui::pos2(slider_label.left() + 20.0, track_y)); - harness.run_steps(2); - harness.hover_at(egui::pos2(popup.right() - 30.0, track_y)); - harness.run_steps(2); - harness.drop_at(egui::pos2(popup.right() - 30.0, track_y)); - harness.run_steps(3); + let drop = egui::pos2(popup.right() - DROP_LEFT_OF_POPUP_EDGE, track_y); + harness.drag_at(egui::pos2(slider.left() + SLIDER_END_INSET, track_y)); + harness.run_steps(DRAG_STEP_FRAMES); + harness.hover_at(drop); + harness.run_steps(DRAG_STEP_FRAMES); + harness.drop_at(drop); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().session.tool.brush.size > size, "{size} -> {}", harness.state().session.tool.brush.size); assert!(is_open(&harness), "editing it keeps it open"); } @@ -194,7 +199,28 @@ fn it_shows_what_the_properties_panel_shows() { let popup = harness.ctx.memory(|memory| memory.area_rect(properties_popup::area_id())).unwrap(); let in_popup = |label: &str| harness.query_all_by_label(label).any(|node| popup.contains_rect(node.rect())); assert!(in_popup("UV projection"), "a selected fill shows its fill settings"); - assert!(!in_popup("Minimum size (%)"), "not the brush's"); + assert!(!in_popup("Minimum Size (%)"), "not the brush's"); +} + +#[test] +fn its_brush_pictures_and_the_docked_panels_keep_their_own_textures() { + let mut harness = harness(); + let center = view_center(&harness); + click(&mut harness, PointerButton::Secondary, center); + + assert!(is_open(&harness)); + + let previews = |harness: &Harness<'_, TextureCraftApp>| { + let mut ids: Vec<_> = + harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name == "brush_stroke_preview").map(|(id, _)| *id).collect(); + ids.sort_unstable_by_key(|id| format!("{id:?}")); + ids + }; + let before = previews(&harness); + harness.run_steps(SETTLE_FRAMES); + + assert_eq!(before.len(), 2, "one stroke preview for the docked panel and one for the popup"); + assert_eq!(previews(&harness), before, "neither is drawn again while the brush stays the same"); } /// Whether the jump tab `name` inside `area` is the lit one diff --git a/crates/ui-egui/tests/it/shelf_drag_ghost.rs b/crates/ui-egui/tests/it/shelf_drag_ghost.rs index eb5525ba..56f72830 100644 --- a/crates/ui-egui/tests/it/shelf_drag_ghost.rs +++ b/crates/ui-egui/tests/it/shelf_drag_ghost.rs @@ -64,6 +64,7 @@ fn the_badge_says_whether_the_place_under_the_pointer_takes_the_asset_without_co harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); } @@ -96,5 +97,6 @@ fn a_layer_dragged_in_the_layer_stack_gets_the_same_ghost_and_badge() { harness.event(Event::PointerButton { pos: background, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); + assert!(shown(&harness.ctx).is_none(), "the ghost goes when the drag ends"); } diff --git a/crates/ui-egui/tests/it/shelf_hover_preview.rs b/crates/ui-egui/tests/it/shelf_hover_preview.rs index c2809684..dcb99d5e 100644 --- a/crates/ui-egui/tests/it/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/it/shelf_hover_preview.rs @@ -39,14 +39,14 @@ fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static (harness, unique) } -/// Largest drawn texture in pixels, excluding fonts and images below `min_width` points -fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_width: f32) -> Option<[usize; 2]> { +/// Largest drawn texture in pixels, excluding fonts and images below `min_side` points on either side (a wide strip is not a big preview) +fn largest_drawn_texture(h: &Harness<'_, TextureCraftApp>, min_side: f32) -> Option<[usize; 2]> { let textures = h.ctx.tex_manager(); let textures = textures.read(); h.output() .shapes .iter() - .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().width() >= min_width) + .filter(|clipped| clipped.shape.texture_id() != egui::TextureId::default() && clipped.shape.visual_bounding_rect().size().min_elem() >= min_side) .filter_map(|clipped| textures.meta(clipped.shape.texture_id()).map(|meta| meta.size)) .max() } diff --git a/crates/ui-egui/tests/it/shelf_menu.rs b/crates/ui-egui/tests/it/shelf_menu.rs index 261b72ac..dbc70547 100644 --- a/crates/ui-egui/tests/it/shelf_menu.rs +++ b/crates/ui-egui/tests/it/shelf_menu.rs @@ -51,6 +51,7 @@ fn a_built_in_tile_menu_says_what_the_asset_is_and_where_it_lives() { harness.get_by_label("Close").click(); harness.run_steps(3); + assert!(harness.query_by_label("Usages material").is_none(), "Close closes the menu"); } @@ -88,8 +89,11 @@ fn type_name(harness: &mut Harness<'_, TextureCraftApp>, text: &str) { #[test] fn a_saved_brush_menu_renames_replaces_and_deletes_it() { - // A name that sorts before every built-in brush, so its tile is in view + let dir = super::temp_dir::TempDir::new("shelf-rename-brush"); let mut harness = shelf(BRUSHES_TYPE); + harness.state_mut().session.brush_presets.dir = Some(dir.to_path_buf()); + + // Keep the saved brush in view at the beginning of the sorted grid texturecraft_engine::execute(&mut harness.state_mut().session, "brush.preset.store", &json!({"name": "Aa ink"})).unwrap(); harness.run_steps(3); @@ -97,23 +101,27 @@ fn a_saved_brush_menu_renames_replaces_and_deletes_it() { type_name(&mut harness, "Never applied"); harness.key_press(Key::Escape); harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa ink"], "Escape keeps the name"); right_click(&mut harness, "Aa ink"); type_name(&mut harness, "Aa pen"); harness.key_press(Key::Enter); harness.run_steps(3); + assert_eq!(preset_names(&harness), ["Aa pen"], "Enter renames the brush"); texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({"size": 77})).unwrap(); right_click(&mut harness, "Aa pen"); harness.get_by_label("Replace with the current brush").click(); harness.run_steps(3); + assert_eq!(harness.state().session.brush_presets.list[0].brush, harness.state().session.tool.brush, "the preset holds the current brush"); right_click(&mut harness, "Aa pen"); harness.get_by_label("Delete").click(); harness.run_steps(3); + assert!(preset_names(&harness).is_empty(), "Delete removes the brush"); } @@ -188,14 +196,17 @@ fn shift_f10_opens_the_menu_of_the_focused_tile_on_its_first_row_and_escape_retu harness.get_all_by_label(&name).next().unwrap().focus(); harness.run_steps(2); + assert!(harness.get_all_by_label(&name).next().unwrap().is_focused(), "the tile takes the focus"); harness.key_press_modifiers(Modifiers::SHIFT, Key::F10); harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_some(), "Shift+F10 opens the menu"); assert!(harness.get_by_label("Delete").is_focused(), "the first row that can be picked takes the focus (Reload can't: no file)"); harness.key_press(Key::Escape); harness.run_steps(3); + assert!(harness.query_by_label("Usages texture").is_none(), "Escape closes it"); assert!(harness.get_all_by_label(&name).next().unwrap().accesskit_node().is_focused(), "the focus is back on the tile"); } @@ -266,3 +277,76 @@ fn set_custom_preview_shows_a_picked_picture_until_removed() { right_click(&mut harness, material.label); assert!(harness.query_by_label("Remove custom preview").is_none(), "only a tile with a custom preview offers to remove it"); } + +#[test] +fn custom_preview_textures_live_until_their_last_tile_releases_them() { + let mut materials: Vec<_> = MATERIALS.iter().filter(|material| !material.smart).collect(); + materials.sort_by_key(|material| material.label.to_lowercase()); + let (first, second) = (materials[0].label, materials[1].label); + let mut harness = shelf(MATERIALS_TYPE); + let directory = super::temp_dir::TempDir::new("shared-shelf-preview"); + let shared = directory.join("shared.png"); + let replacement = directory.join("replacement.png"); + let last = directory.join("last.png"); + for path in [&shared, &replacement, &last] { + image::RgbaImage::from_pixel(164, 164, image::Rgba([40, 160, 90, 255])).save(path).unwrap(); + } + let mut answers = vec![shared.clone(), shared, replacement, last].into_iter(); + harness.state_mut().file_dialogs.set_override(Some(Box::new(move |_| Answer::Paths(vec![answers.next().unwrap()])))); + + let allocated = |harness: &Harness<'_, TextureCraftApp>| { + harness + .ctx + .tex_manager() + .read() + .allocated() + .filter(|(_, texture)| texture.name.starts_with("custom_preview_")) + .fold((0, 0), |(count, bytes), (_, texture)| (count + 1, bytes + texture.size[0] * texture.size[1] * texture.bytes_per_pixel)) + }; + + pick_from_menu(&mut harness, first, "Set custom preview..."); + pick_from_menu(&mut harness, second, "Set custom preview..."); + let shared = allocated(&harness); + pick_from_menu(&mut harness, first, "Set custom preview..."); + let separate = allocated(&harness); + pick_from_menu(&mut harness, second, "Remove custom preview"); + let remaining = allocated(&harness); + pick_from_menu(&mut harness, first, "Set custom preview..."); + let replaced_last = allocated(&harness); + pick_from_menu(&mut harness, first, "Remove custom preview"); + let cleared = allocated(&harness); + + println!( + "Custom preview (textures, bytes): shared {shared:?}, replaced {separate:?}, removed {remaining:?}, replaced last {replaced_last:?}, cleared {cleared:?}" + ); + assert_eq!(shared.0, 1); + assert!(shared.1 > 0); + assert_eq!(separate, (2, 2 * shared.1)); + assert_eq!(remaining, shared); + assert_eq!(replaced_last, shared); + assert_eq!(cleared, (0, 0)); +} + +#[test] +fn the_shelf_uploads_only_the_project_thumbnails_in_view() { + const RESOURCE_COUNT: usize = 100; + let mut harness = shelf(TEXTURES_TYPE); + harness.state_mut().ui.shelf_filter = "visible-tile".into(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(64, 64, image::Rgba([80, 140, 40, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + for index in 0..RESOURCE_COUNT { + harness.state_mut().session.import_resource_bytes(&format!("visible-tile-{index:03}.png"), png.clone()).unwrap(); + } + + harness.run_steps(3); + + let allocated = harness + .ctx + .tex_manager() + .read() + .allocated() + .filter(|(_, texture)| texture.name.starts_with("res_visible-tile-")) + .fold((0, 0), |(count, bytes), (_, texture)| (count + 1, bytes + texture.size[0] * texture.size[1] * texture.bytes_per_pixel)); + println!("Shelf of {RESOURCE_COUNT} textures: {} uploads retained, {} bytes", allocated.0, allocated.1); + assert!(allocated.0 > 0 && allocated.0 < RESOURCE_COUNT); +} diff --git a/crates/ui-egui/tests/it/shelf_panel.rs b/crates/ui-egui/tests/it/shelf_panel.rs index 5c3c9275..45b8a657 100644 --- a/crates/ui-egui/tests/it/shelf_panel.rs +++ b/crates/ui-egui/tests/it/shelf_panel.rs @@ -237,6 +237,7 @@ fn a_long_saved_search_list_can_select_the_last_query() { }) .collect(); harness.run_steps(3); + assert!(harness.query_by_label("search 500").is_none(), "offscreen searches do not build rows"); harness.get_by_label("search 0").hover(); diff --git a/crates/ui-egui/tests/it/shelf_second.rs b/crates/ui-egui/tests/it/shelf_second.rs index ef3413db..aac41b23 100644 --- a/crates/ui-egui/tests/it/shelf_second.rs +++ b/crates/ui-egui/tests/it/shelf_second.rs @@ -33,6 +33,7 @@ fn the_folder_button_opens_a_second_assets_panel_that_searches_on_its_own() { harness.get_by_label("New Assets panel").click(); harness.run_steps(3); + assert!(harness.state().ui.dock.is_visible(Panel::AssetsSecond), "the folder button shows a second Assets panel"); search_shown_panel(&mut harness, "brick"); diff --git a/crates/ui-egui/tests/it/shelf_updates.rs b/crates/ui-egui/tests/it/shelf_updates.rs index 717a6d4a..7e6ab880 100644 --- a/crates/ui-egui/tests/it/shelf_updates.rs +++ b/crates/ui-egui/tests/it/shelf_updates.rs @@ -113,13 +113,14 @@ fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { harness.run_steps(2); let mut reported = Vec::new(); - for project in ["first", "second"] { - if project == "second" { + let mut retained = Vec::new(); + for project in ["first", "second", "third"] { + if project != "first" { harness.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap(); } let folder = std::env::temp_dir().join(format!("texturecraft-failed-read-{project}-{}", std::process::id())); std::fs::create_dir_all(&folder).unwrap(); - let path = folder.join("photo.png"); + let path = folder.join("missing-update-photo.png"); std::fs::write(&path, grey_png(0.2)).unwrap(); let name = harness.state_mut().run("resource.import", json!({"path": path.to_str().unwrap()})).unwrap()["name"].as_str().unwrap().to_string(); std::fs::remove_dir_all(&folder).unwrap(); @@ -127,8 +128,17 @@ fn a_file_that_fails_to_read_is_reported_again_in_the_next_project() { pass_a_minute(&mut harness); + let allocations = harness.ctx.data(|data| { + data.iter_temp_by_type::>().filter(|names| names.contains(&name)).fold((0, 0), |(count, bytes), names| { + (count + 1, bytes + names.capacity() * size_of::() + names.iter().map(String::capacity).sum::()) + }) + }); + retained.push(allocations); reported.push(harness.state().toasts.iter().any(|toast| toast.error && toast.text.starts_with(&format!("{name}:")))); } - assert_eq!(reported, [true, true], "each project says once that its file can't be read"); + println!("Cached missing-file reports (lists, bytes) for successive projects: {retained:?}"); + assert_eq!(retained[0].0, 1, "the active project remembers the report"); + assert_eq!(retained, [retained[0]; 3], "each replacement releases the previous project's failure list"); + assert_eq!(reported, [true; 3], "each project says once that its file can't be read"); } diff --git a/crates/ui-egui/tests/it/size_pressure.rs b/crates/ui-egui/tests/it/size_pressure.rs new file mode 100644 index 00000000..9d6013c3 --- /dev/null +++ b/crates/ui-egui/tests/it/size_pressure.rs @@ -0,0 +1,47 @@ +//! The pen button on the paint tool's Size row turns pen pressure on Size on and off; Minimum Size only applies while it is on + +use egui::accesskit::{Role, Toggled}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::{BAKE_RESOLUTION, SETTLE_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + +/// Tall enough that the Size band shows without scrolling +const WINDOW: egui::Vec2 = egui::vec2(1600.0, 960.0); + +fn paint_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder() + .with_size(WINDOW) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +fn pen_toggled(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness.get_by_role_and_label(Role::CheckBox, "Size pen pressure").accesskit_node().toggled() +} + +/// Whether every Minimum Size slider node is greyed +fn minimum_size_greyed(harness: &Harness<'_, TextureCraftApp>) -> bool { + let sliders: Vec<_> = harness.get_all_by_label("Minimum Size (%)").filter(|node| node.accesskit_node().role() == Role::Slider).collect(); + assert!(!sliders.is_empty(), "Minimum Size has a slider"); + sliders.iter().all(|node| node.accesskit_node().is_disabled()) +} + +#[test] +fn the_pen_button_turns_size_pressure_off_and_greys_minimum_size() { + let mut harness = paint_harness(); + assert_eq!(pen_toggled(&harness), Some(Toggled::True), "a new brush follows the pen"); + assert!(!minimum_size_greyed(&harness)); + + harness.get_by_role_and_label(Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().session.tool.brush.size_pressure, "the click reached the brush"); + assert_eq!(pen_toggled(&harness), Some(Toggled::False)); + assert!(minimum_size_greyed(&harness), "Minimum Size does nothing without pen pressure"); +} diff --git a/crates/ui-egui/tests/it/smudge_channels.rs b/crates/ui-egui/tests/it/smudge_channels.rs index 024377d6..414ea372 100644 --- a/crates/ui-egui/tests/it/smudge_channels.rs +++ b/crates/ui-egui/tests/it/smudge_channels.rs @@ -8,7 +8,9 @@ use texturecraft_engine::core::Channel; use texturecraft_engine::geom::primitives; use texturecraft_engine::{Session, Tool, execute}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::state::PropsTab; + +/// Frames egui's scroll animation takes to bring a row into view +const SCROLL_FRAMES: usize = 30; fn harness() -> Harness<'static, TextureCraftApp> { let session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); @@ -26,11 +28,13 @@ fn run(harness: &mut Harness<'_, TextureCraftApp>, command: &str, params: Value) harness.run_steps(4); } -/// The channel chips drawn in the open Properties panel +/// The Smudge panel's chip for `channel` (the Material section's pill below it is a checkbox) +fn smudge_chip<'a>(harness: &'a Harness<'_, TextureCraftApp>, channel: Channel) -> egui_kittest::Node<'a> { + harness.get_by_role_and_label(Role::Button, channel.short()) +} + fn chip_is_on(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> bool { - let chips: Vec<_> = harness.get_all_by_role_and_label(Role::Button, channel.short()).collect(); - assert_eq!(chips.len(), 1, "one {} chip is drawn", channel.short()); - chips[0].accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) + smudge_chip(harness, channel).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) } /// Channels whose chip is on, in the order of `Channel::ALL` @@ -67,13 +71,15 @@ fn smudge_panel_shows_the_channels_the_material_has_on() { fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() { let mut harness = harness(); - harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + smudge_chip(&harness, Channel::Metallic).click(); harness.run_steps(4); + assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic)); assert!(!chip_is_on(&harness, Channel::Metallic)); - harness.get_by_role_and_label(Role::Button, Channel::Metallic.short()).click(); + smudge_chip(&harness, Channel::Metallic).click(); harness.run_steps(4); + assert!(harness.state().session.tool.enabled.contains(&Channel::Metallic)); assert!(chip_is_on(&harness, Channel::Metallic)); } @@ -81,19 +87,23 @@ fn clicking_a_channel_in_the_smudge_panel_turns_it_off_and_on_for_the_material() #[test] fn material_tab_and_smudge_panel_stay_in_sync() { let mut harness = harness(); - harness.state_mut().ui.props_tab = PropsTab::Material; - harness.run_steps(4); - // Both the Smudge panel and the Material tab draw a chip per channel - let chips = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).count(); - assert_eq!(chips, 2, "Smudge panel and Material tab"); - - let first = harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()).next().unwrap(); - first.click(); + // The Smudge panel draws a chip per channel, the Material section a pill + harness.get_by_role_and_label(Role::CheckBox, "Height").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + harness.get_by_role_and_label(Role::CheckBox, "Height").click(); harness.run_steps(4); assert!(!harness.state().session.tool.enabled.contains(&Channel::Height)); - for chip in harness.get_all_by_role_and_label(Role::Button, Channel::Height.short()) { - assert_ne!(chip.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "both chips show height off"); - } + assert!(!chip_is_on(&harness, Channel::Height), "the Smudge panel's chip shows height off"); + let pill = harness.get_by_role_and_label(Role::CheckBox, "Height"); + assert_ne!(pill.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "so does the Material section's pill"); + + smudge_chip(&harness, Channel::Height).scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + smudge_chip(&harness, Channel::Height).click(); + harness.run_steps(4); + + let pill = harness.get_by_role_and_label(Role::CheckBox, "Height"); + assert_eq!(pill.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True), "the chip turns the pill back on") } diff --git a/crates/ui-egui/tests/it/stencil.rs b/crates/ui-egui/tests/it/stencil.rs index fc72b047..74543239 100644 --- a/crates/ui-egui/tests/it/stencil.rs +++ b/crates/ui-egui/tests/it/stencil.rs @@ -1,5 +1,4 @@ -//! The Projection tool's stencil: an Assets image dropped on its slot, position fields and a reset in the tool panel, -//! S + Shift + left-drag to turn it in snapped steps, and the 2D view saying that projection paints in the 3D view +//! The brush tools' stencil: an Assets image dropped on its slot, position fields, Tiling mode and the section reset in the tool panel, S + Shift + left-drag to turn it in snapped steps, the 2D view saying that projection paints in the 3D view, and no stencil while the quick mask is painted use egui::accesskit::Role; use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2}; @@ -11,30 +10,50 @@ use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; use texturecraft_ui_egui::state::ViewLayout; +use crate::{BAKE_RESOLUTION, REDRAW_FRAMES, STARTUP_FRAMES, TEXTURE_RESOLUTION}; + /// The sample project with the Projection tool equipped, and an imported image's resource name fn projection_app() -> (Harness<'static, TextureCraftApp>, String) { - let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + tool_app(Tool::Projection) +} + +/// Window the stencil tests run in +const WINDOW_SIZE: egui::Vec2 = vec2(1600.0, 960.0); + +/// Side of the plain white image imported for the stencil +const IMAGE_SIZE: u32 = 4; + +/// The sample project with `tool` equipped and its Stencil section in view, and an imported image's resource name +fn tool_app(tool: Tool) -> (Harness<'static, TextureCraftApp>, String) { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); let mut png = Vec::new(); - image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let white = image::RgbaImage::from_pixel(IMAGE_SIZE, IMAGE_SIZE, image::Rgba([255, 255, 255, 255])); + white.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = session.import_resource_bytes("logo.png", png).unwrap(); - session.tool.tool = Tool::Projection; + session.tool.tool = tool; + let mut harness = Harness::builder() - .with_size(egui::vec2(1600.0, 960.0)) + .with_size(WINDOW_SIZE) .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.run_steps(4); + harness.run_steps(STARTUP_FRAMES); + + harness.get_by_role_and_label(Role::Tab, "Stencil").click(); + harness.run_steps(REDRAW_FRAMES); (harness, name) } -/// The number field beside a uniquely labelled slider +/// The number field a click on a slider's value opens, on the slider's line fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { - let row = harness.get_by_label(label).rect().center().y; + let row = harness.get_by_role_and_label(Role::Slider, label).rect().center().y; harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } -/// Type a complete value in the number field beside a uniquely labelled slider +/// Type a complete value in the number field of a uniquely labelled slider fn set_number(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + harness.get_by_label(&format!("{label} value")).click(); + harness.run_steps(2); let length = number_field(harness, label).value().unwrap().len(); number_field(harness, label).focus(); harness.run_steps(2); @@ -87,7 +106,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { let (mut harness, name) = projection_app(); assert!(harness.state().session.tool.stencil.is_none()); - let slot = harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("None")).unwrap().rect().center(); + let slot = harness.get_by_role_and_label(Role::ComboBox, "None").rect().center(); egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Texture(name.clone()), label: "Dragged".into(), thumb: None }); harness.hover_at(slot); harness.run_steps(2); @@ -98,7 +117,7 @@ fn an_assets_image_dropped_on_the_stencil_slot_becomes_the_stencil() { } #[test] -fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { +fn the_position_fields_move_the_stencil_and_the_section_reset_puts_it_back() { let (mut harness, name) = projection_app(); texturecraft_engine::execute( &mut harness.state_mut().session, @@ -112,20 +131,35 @@ fn the_position_fields_move_the_stencil_and_reset_puts_it_back() { set_number(&mut harness, "Position X", "-0.75"); let moved = harness.state().session.tool.stencil.clone().unwrap(); assert_eq!(moved.center, [-0.75, -0.25], "only X changed"); - harness.get_by_label("Position Y"); + harness.get_by_role_and_label(Role::Slider, "Position Y"); - harness.get_by_label("Reset stencil").scroll_to_me(); + harness.get_by_label("Stencil: Reset to defaults").scroll_to_me(); harness.run_steps(3); - harness.get_by_label("Reset stencil").click(); + harness.get_by_label("Stencil: Reset to defaults").click(); harness.run_steps(3); let reset = harness.state().session.tool.stencil.clone().unwrap(); assert_eq!((reset.center, reset.scale, reset.rotation), ([0.0, 0.0], 0.8, 0.0)); assert_eq!((reset.image.as_str(), reset.opacity, reset.tile), (name.as_str(), 0.3, true), "image, opacity and tiling stay"); } +#[test] +fn the_tiling_mode_list_tiles_the_stencil() { + let (mut harness, name) = tool_app(Tool::Paint); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + harness.run_steps(3); + + harness.get_by_role_and_label(Role::ComboBox, "No Tiling").click(); + harness.run_steps(3); + harness.get_by_label("H and V Tiling").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.stencil.as_ref().is_some_and(|stencil| stencil.tile)); +} + +/// The Paint tool's stencil turns like the Projection tool's #[test] fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { - let (mut harness, name) = projection_app(); + let (mut harness, name) = tool_app(Tool::Paint); texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); harness.run_steps(2); let from = harness.state().viewport_rect.center(); @@ -148,6 +182,26 @@ fn s_shift_left_drag_turns_the_stencil_in_snapped_steps_without_painting() { assert_eq!(history(&harness), steps); } +#[test] +fn the_stencil_hides_and_stays_put_while_the_quick_mask_is_painted() { + let (mut harness, name) = tool_app(Tool::Paint); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": name})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask", &json!({"enabled": true})).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": true})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + let from = harness.state().viewport_rect.center(); + let before = harness.state().session.tool.stencil.clone().unwrap(); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_none(), "quick mask strokes skip the stencil, so it has no tab"); + drag_holding(&mut harness, &[Key::S], Modifiers::SHIFT, from, vec2(100.0, -40.0)); + assert_eq!(harness.state().session.tool.stencil.clone().unwrap().rotation, before.rotation, "S + drag leaves it alone"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "viewport.quickMask.edit", &json!({"editing": false})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + + assert!(harness.query_by_role_and_label(Role::Tab, "Stencil").is_some(), "back when the quick mask is done"); +} + #[test] fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { let (mut harness, name) = projection_app(); @@ -175,3 +229,39 @@ fn the_2d_view_says_projection_paints_in_3d_and_paints_nothing() { drag_holding(&mut harness, &[], Modifiers::NONE, from, vec2(60.0, 0.0)); assert!(history(&harness) > steps, "the paint tool paints there"); } + +#[test] +fn picking_another_stencil_releases_the_last_ones_overlay_texture() { + const OVERLAY_SIDE_PX: u32 = 1024; + let (mut harness, _) = tool_app(Tool::Paint); + let stencil_textures = |harness: &Harness<'_, TextureCraftApp>| { + harness + .ctx + .tex_manager() + .read() + .allocated() + .filter(|(_, texture)| texture.name.starts_with("stencil:")) + .fold((0, 0), |(count, bytes), (_, texture)| (count + 1, bytes + texture.size[0] * texture.size[1] * texture.bytes_per_pixel)) + }; + + // Switch among three full-size overlays + for gray in [64, 128, 192] { + let mut png = Vec::new(); + let image = image::RgbaImage::from_pixel(OVERLAY_SIDE_PX, OVERLAY_SIDE_PX, image::Rgba([gray, gray, gray, 255])); + image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes(&format!("stencil_{gray}.png"), png).unwrap(); + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({ "image": name })).unwrap(); + harness.run_steps(REDRAW_FRAMES); + } + + let (count, bytes) = stencil_textures(&harness); + eprintln!("selected stencil retains {count} texture(s) and {bytes} texture bytes"); + assert_eq!(count, 1, "only the current stencil keeps its big texture"); + + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.stencil", &json!({"clear": true})).unwrap(); + harness.run_steps(REDRAW_FRAMES); + + let (count, bytes) = stencil_textures(&harness); + eprintln!("cleared stencil retains {count} texture(s) and {bytes} texture bytes"); + assert_eq!(count, 0, "clearing the stencil releases its overlay"); +} diff --git a/crates/ui-egui/tests/it/tool_material.rs b/crates/ui-egui/tests/it/tool_material.rs new file mode 100644 index 00000000..691edec0 --- /dev/null +++ b/crates/ui-egui/tests/it/tool_material.rs @@ -0,0 +1,100 @@ +//! A brush tool's Material section: the fill layer's channel pills, then a card per channel that is on with the value the brush paints + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; + +use crate::filter_support::drag; +use crate::{BAKE_RESOLUTION, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_at, click_widget}; + +/// A second at 60 frames: the Material tab's jump scrolls with egui's scroll animation +const SCROLL_FRAMES: usize = 60; + +/// `tool`'s Properties scrolled to its Material section +fn material_section(tool: &str) -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": tool})).unwrap(); + let mut harness = Harness::builder() + .with_size(PROPERTIES_WINDOW) + .with_step_dt(FRAME_SECONDS) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + click_widget(&mut harness, Role::Tab, "Material"); + harness.run_steps(SCROLL_FRAMES); + harness +} + +fn tool_value(harness: &Harness<'_, TextureCraftApp>, channel: Channel) -> [f32; 3] { + harness.state().session.tool.values.get(&channel).copied().unwrap_or(channel.default_value()) +} + +/// The top row of the card named `card` ("Metallic: Uniform"), if it shows +fn card_row(harness: &Harness<'_, TextureCraftApp>, card: &str) -> Option { + let named = |node: &egui_kittest::Node<'_>| node.accesskit_node().value().is_some_and(|value| value.starts_with(&format!("{card}: "))); + harness.query_all_by_role(Role::Label).find(named).map(|node| node.rect()) +} + +/// Clicks the widget with `role` and `label` on the top row of the card named `card` +fn click_in_card(harness: &mut Harness<'_, TextureCraftApp>, card: &str, role: Role, label: &str) { + let row = card_row(harness, card).unwrap(); + let at = harness.get_all_by_role_and_label(role, label).map(|node| node.rect().center()).find(|at| row.contains(*at)).unwrap(); + click_at(harness, at); +} + +#[test] +fn each_channel_that_is_on_gets_a_card_whose_reset_returns_the_channels_default() { + let mut harness = material_section("paint"); + assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_some(), "Base color is a colour bar"); + for gray in ["Metallic", "Roughness", "Height"] { + assert!(harness.query_by_role_and_label(Role::Slider, gray).is_some(), "{gray} is a gray ramp"); + } + assert!(card_row(&harness, "Normal").is_some(), "Normal has a card"); + assert!(harness.query_by_role_and_label(Role::Slider, "Normal").is_none(), "the normal paints flat: no value to set"); + + execute(&mut harness.state_mut().session, "tool.material", &json!({"channel": "metallic", "value": 0.8})).unwrap(); + harness.run_steps(SETTLE_FRAMES); + click_in_card(&mut harness, "Metallic", Role::Button, "Restore defaults"); + + assert_eq!(tool_value(&harness, Channel::Metallic), Channel::Metallic.default_value(), "⟲ goes back to the channel's default"); + + click_widget(&mut harness, Role::CheckBox, "Metal"); + + assert!(!harness.state().session.tool.enabled.contains(&Channel::Metallic), "off in the strip, the brush stops painting Metallic"); + assert!(card_row(&harness, "Metallic").is_none(), "a channel that is off has no card"); +} + +#[test] +fn a_click_on_a_ramp_sets_the_value_the_brush_paints() { + let mut harness = material_section("paint"); + let before = tool_value(&harness, Channel::Roughness); + harness.get_by_role_and_label(Role::Slider, "Roughness").scroll_to_me(); + harness.run_steps(SCROLL_FRAMES); + let track = harness.get_by_role_and_label(Role::Slider, "Roughness").rect(); + + drag(&mut harness, track.center(), egui::pos2(track.right() - SLIDER_END_INSET, track.center().y)); + + assert!(tool_value(&harness, Channel::Roughness)[0] > before[0], "dragged toward the ramp's white end the brush paints rougher"); +} + +#[test] +fn the_eraser_picks_its_channels_without_value_cards() { + let harness = material_section("eraser"); + assert!(harness.query_by_role_and_label(Role::CheckBox, "Color").is_some(), "the channel strip"); + assert!(harness.query_by_role_and_label(Role::Button, "Base color").is_none(), "the eraser paints no colour"); + assert!(harness.query_by_role_and_label(Role::Slider, "Roughness").is_none()); +} + +#[test] +fn a_channel_cards_name_is_not_read_as_unavailable() { + let harness = material_section("paint"); + let named = |node: &egui_kittest::Node<'_>| node.accesskit_node().value().is_some_and(|value| value.starts_with("Metallic: ")); + let card = harness.query_all_by_role(Role::Label).find(named).unwrap(); + + assert!(!card.accesskit_node().is_disabled(), "the card's reset and value row answer, so its name must not read as unavailable"); +} diff --git a/crates/ui-egui/tests/it/toolbar.rs b/crates/ui-egui/tests/it/toolbar.rs index c9271888..9c1b1adf 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -6,6 +6,8 @@ use texturecraft_engine::{Session, Tool}; use texturecraft_ui_egui::state::{Mode, ViewLayout}; use texturecraft_ui_egui::{TextureCraftApp, theme, toolbar}; +use crate::DRAG_STEP_FRAMES; + fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> { let session = Session::new_project("Toolbar", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); let context = eframe::CreationContext::_new_kittest(egui::Context::default()); @@ -24,12 +26,17 @@ fn toolbar_harness(width: f32, tool: Tool) -> Harness<'static, TextureCraftApp> } fn size_label(harness: &Harness<'_, TextureCraftApp>) -> (egui::Pos2, egui::Rect) { + bar_label(harness, "Size") +} + +/// Where the top bar paints the slider label `label`, and that text's clip +fn bar_label(harness: &Harness<'_, TextureCraftApp>, label: &str) -> (egui::Pos2, egui::Rect) { harness .output() .shapes .iter() .find_map(|shape| match &shape.shape { - egui::Shape::Text(text) if text.galley.text() == "Size" => Some((text.pos, shape.clip_rect)), + egui::Shape::Text(text) if text.galley.text() == label => Some((text.pos, shape.clip_rect)), _ => None, }) .unwrap() @@ -88,6 +95,34 @@ fn arrows_and_wheel_scroll_without_changing_the_brush() { assert_eq!(harness.state().session.tool.brush, brush); } +#[test] +fn the_spacing_slider_reaches_as_far_as_the_properties_one() { + // Wide enough that the bar shows Spacing without scrolling + const BAR_WIDTH: f32 = 1600.0; + // From the label's top left onto its text, which drags the value + const LABEL_GRAB_OFFSET: egui::Vec2 = egui::vec2(4.0, 8.0); + // Far enough right to pass the slider's end + const DRAG_PAST_END: f32 = 400.0; + // The top bar's old Spacing limit: 200 % of the diameter + const OLD_SPACING_LIMIT: f32 = 2.0; + + let mut harness = toolbar_harness(BAR_WIDTH, Tool::Paint); + let (label, _) = bar_label(&harness, "Spacing"); + let from = label + LABEL_GRAB_OFFSET; + let past_the_end = from + egui::vec2(DRAG_PAST_END, 0.0); + + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + harness.hover_at(past_the_end); + harness.run_steps(DRAG_STEP_FRAMES); + harness.event(egui::Event::PointerButton { pos: past_the_end, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); + harness.run_steps(DRAG_STEP_FRAMES); + + // Properties' Spacing goes to 1000 % of the diameter + assert!(harness.state().session.tool.brush.spacing > OLD_SPACING_LIMIT, "past the 200 % the top bar used to stop at"); +} + #[test] fn shorter_tools_and_wider_windows_remove_the_arrows() { let mut harness = toolbar_harness(700.0, Tool::Path); diff --git a/crates/ui-egui/tests/it/user_smart_mask.rs b/crates/ui-egui/tests/it/user_smart_mask.rs index 7547e74c..83f15b96 100644 --- a/crates/ui-egui/tests/it/user_smart_mask.rs +++ b/crates/ui-egui/tests/it/user_smart_mask.rs @@ -65,8 +65,8 @@ fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected let source = add_layer(&mut saved, "Source", true); let dir = std::env::temp_dir().join(format!("tc-ui-smart-mask-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let file = dir.join("Stencil.tcmask"); - std::fs::write(&file, saved.smart_mask_bytes(source, "Stencil").unwrap()).unwrap(); + let file = dir.join("Zebra Saved.tcmask"); + std::fs::write(&file, saved.smart_mask_bytes(source, "Zebra Saved").unwrap()).unwrap(); let mut harness = harness(|_| {}); let target = harness.state().session.selected_layer().unwrap(); @@ -75,11 +75,12 @@ fn a_saved_smart_mask_is_listed_with_the_smart_masks_and_applies_to_the_selected harness.state_mut().ui.shelf_path = vec!["user".into()]; harness.state_mut().ui.shelf_tab = SMART_MATERIALS_TYPE; harness.run_steps(3); - assert!(harness.query_by_label_contains("Stencil").is_none(), "it is not a smart material"); + + assert!(harness.query_by_label_contains("Zebra Saved").is_none(), "it is not a smart material"); harness.state_mut().ui.shelf_tab = SMART_MASKS_TYPE; harness.run_steps(3); - harness.get_by_label_contains("Stencil").click(); + harness.get_by_label_contains("Zebra Saved").click(); harness.run_steps(3); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs index 27700d8b..b35b8fcc 100644 --- a/crates/ui-egui/tests/list_panels.rs +++ b/crates/ui-egui/tests/list_panels.rs @@ -36,11 +36,12 @@ fn dock_in_left_column(harness: &mut Harness<'_, TextureCraftApp>, panel: &str) harness.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); } -/// The height of the list's vertical scroll bar (the taller one, as the Log also scrolls sideways), which runs the visible height of the list -fn list_height(harness: &Harness<'_, TextureCraftApp>) -> f32 { - let bars = harness.get_all_by_role(Role::ScrollBar).filter(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X); - let bar = bars.max_by(|a, b| a.rect().height().total_cmp(&b.rect().height())).expect("a scroll bar in the left column"); - bar.rect().height() +/// The named vertical track measures the visible list height +fn list_height(harness: &Harness<'_, TextureCraftApp>, scrollbar: &str) -> f32 { + let track = harness.get_by_role_and_label(Role::ScrollBar, scrollbar).rect(); + assert!(track.right() < LEFT_COLUMN_MAX_X, "the track must be in the left column"); + + track.height() } #[test] @@ -59,7 +60,7 @@ fn the_history_list_fills_a_tall_panel() { harness.run_steps(STARTUP_FRAMES); assert!(harness.state().ui.dock.is_visible(Panel::History)); - let height = list_height(&harness); + let height = list_height(&harness, "History scrollbar"); assert!(height > OLD_HISTORY_HEIGHT, "the history list is {height} points tall"); } @@ -77,6 +78,6 @@ fn the_log_list_fills_a_tall_panel() { harness.run_steps(STARTUP_FRAMES); assert!(harness.state().ui.dock.is_visible(Panel::Log)); - let height = list_height(&harness); + let height = list_height(&harness, "Log vertical scrollbar"); assert!(height > OLD_LOG_HEIGHT, "the log list is {height} points tall"); } diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index ae1e7c83..32285025 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -801,6 +801,7 @@ fn assets_pass_two_snapshots() { .with_pixels_per_point(1.0) // The system draws the pointer, not the app .with_render_cursor(false) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) .wgpu() .build_eframe(|context| TextureCraftApp::new(context, session)); let app = harness.state_mut(); @@ -822,6 +823,7 @@ fn assets_pass_two_snapshots() { if MATERIALS.iter().filter(|material| material.smart).all(|material| thumbnails.material(&context, material.id).is_some()) { break; } + assert!(started.elapsed() < std::time::Duration::from_secs(120), "smart material thumbnails did not arrive"); std::thread::sleep(std::time::Duration::from_millis(20)); } @@ -864,6 +866,7 @@ fn assets_pass_two_snapshots() { // 05: the drag ghost over the layer stack (takes a material) and over Properties (doesn't) let viewport_right = harness.state().viewport_rect.max.x; let layer = harness.get_all_by_role(Role::ListItem).find(|row| row.rect().min.x > viewport_right).expect("a layer row").rect().center(); + // Properties fills the right column under the layer stack, in the window's lower part let properties = egui::pos2(layer.x, harness.ctx.content_rect().height() * PROPERTIES_HEIGHT_SHARE); let tile = harness.get_all_by_label("Gold Dirty").next().unwrap().rect().center(); @@ -1219,12 +1222,7 @@ fn panel_header_snapshots() { save(&mut harness, &output_dir, &format!("panel-header-{name}")); } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - let close = harness - .get_all_by_label("Close Panel") - .map(|node| node.rect()) - .filter(|rect| rect.min.x > 1200.0) - .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) - .expect("the Properties header's close button"); + let close = harness.get_by_role_and_label(egui::Role::Button, "Close Properties - Fill").rect(); harness.hover_at(close.center()); save(&mut harness, &output_dir, "panel-header-close-hovered"); } @@ -1298,12 +1296,7 @@ fn default_layout_snapshots() { save(&mut harness, &output_dir, &format!("default-layout-{name}")); } harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; - let properties_close = harness - .get_all_by_label("Close Panel") - .map(|node| node.rect()) - .filter(|rect| rect.min.x > 1200.0) - .max_by(|a, b| a.min.y.total_cmp(&b.min.y)) - .expect("the Properties header's close button"); + let properties_close = harness.get_by_role_and_label(egui::Role::Button, "Close Properties - Fill").rect(); harness.hover_at(egui::pos2(properties_close.center().x - 120.0, properties_close.min.y - 6.0)); save(&mut harness, &output_dir, "default-layout-split-hovered"); } @@ -2404,7 +2397,8 @@ fn folder_mask_snapshots() { .with_context_setup(texturecraft_ui_egui::framework::install_headless) .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); - harness.state_mut().ui.props_tab = texturecraft_ui_egui::state::PropsTab::Material; + harness.run_steps(6); + harness.get_by_role_and_label(egui::Role::Tab, "Grayscale").click(); harness.run_steps(6); save(&mut harness, &output_dir, "foldermask-white"); if std::env::var_os("TC_UI_THEMES").is_some() { @@ -3446,6 +3440,188 @@ fn sheet_scroll_end_snapshots() { save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } +/// The paint tool's Properties: the Brush tab with every section open and scrolled down, its presets, pen button and Alignment list mid-use, the Alpha tab with its picker open, the Material tab with a pill hovered, a stencil on the Projection tool, a mask's Grayscale tab, the right-click popup, and the Clone and Eraser tools' tabs; `TC_UI_THEMES` set adds the dark and light themes +#[test] +#[ignore] +fn paint_tool_properties_snapshots() { + use egui::{Event, Modifiers, PointerButton}; + use serde_json::json; + use texturecraft_engine::core::Channel; + use texturecraft_engine::execute; + use texturecraft_engine::paint::{BrushAlpha, BrushSettings}; + + 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(); + let stripes = image::RgbaImage::from_fn(64, 64, |x, _| { + let value = if (x / 8) % 2 == 0 { 230 } else { 40 }; + image::Rgba([value, value, value, 255]) + }); + let mut bytes = Vec::new(); + stripes.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap(); + let image = session.import_resource_bytes("stripes.png", bytes).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "paint"})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_pixels_per_point(2.0) + .wgpu() + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.set_render_cursor(false); + harness.run_steps(6); + save(&mut harness, &output_dir, "paint-brush"); + + // The top preview follows the brush and the paint: one picture per brush + let default_brush = harness.state().session.tool.brush.clone(); + let default_values = harness.state().session.tool.values.clone(); + let brushes = [ + ("dotted-red", BrushSettings { size: 0.06, hardness: 1.0, spacing: 1.6, ..default_brush.clone() }, [0.8, 0.05, 0.04], 0.0, 0.5), + ("soft-blue-metal", BrushSettings { size: 0.12, hardness: 0.0, flow: 0.35, ..default_brush.clone() }, [0.1, 0.3, 0.9], 1.0, 0.2), + ( + "star-jitter-green", + BrushSettings { + size: 0.08, + alpha: BrushAlpha::Star, + spacing: 0.9, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.3, + jitter_position: 0.6, + ..default_brush.clone() + }, + [0.1, 0.6, 0.15], + 0.0, + 0.8, + ), + ]; + for (name, brush, base_color, metallic, roughness) in brushes { + let tool = &mut harness.state_mut().session.tool; + tool.brush = brush; + tool.values.insert(Channel::BaseColor, base_color); + tool.values.insert(Channel::Metallic, [metallic; 3]); + tool.values.insert(Channel::Roughness, [roughness; 3]); + save(&mut harness, &output_dir, &format!("paint-preview-{name}")); + } + let tool = &mut harness.state_mut().session.tool; + tool.brush = default_brush; + tool.values = default_values; + + // The top bar has labels of the same names: Properties is the rightmost + let in_properties = |harness: &Harness<'_, TextureCraftApp>, label: &str| { + harness.get_all_by_label(label).map(|node| node.rect().center()).max_by(|a, b| a.x.total_cmp(&b.x)).unwrap() + }; + + harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(3); + let at = in_properties(&harness, "Particles"); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + + let themes = std::env::var_os("TC_UI_THEMES").is_some(); + let shoot = |harness: &mut Harness<'_, TextureCraftApp>, name: &str| { + save(harness, &output_dir, name); + if themes { + for (brightness, theme) in [(Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(harness, &output_dir, &format!("{name}-{theme}")); + } + harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; + } + }; + let hover = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + let at = harness.get_by_role_and_label(role, label).rect().center(); + harness.hover_at(at); + harness.run_steps(40); + }; + let open = |harness: &mut Harness<'_, TextureCraftApp>, role: egui::Role, label: &str| { + harness.get_by_role_and_label(role, label).scroll_to_me(); + harness.run_steps(6); + harness.get_by_role_and_label(role, label).click(); + harness.run_steps(6); + }; + let close = |harness: &mut Harness<'_, TextureCraftApp>| { + harness.key_press(egui::Key::Escape); + harness.run_steps(4); + }; + harness.get_by_label_contains("Brush presets").scroll_to_me(); + harness.run_steps(3); + shoot(&mut harness, "paint-brush-open"); + open(&mut harness, egui::Role::Button, "Brush presets"); + shoot(&mut harness, "paint-presets-open"); + close(&mut harness); + hover(&mut harness, egui::Role::CheckBox, "Size pen pressure"); + shoot(&mut harness, "paint-size-pen-hover"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(6); + shoot(&mut harness, "paint-size-pen-off"); + harness.get_by_role_and_label(egui::Role::CheckBox, "Size pen pressure").click(); + harness.run_steps(4); + open(&mut harness, egui::Role::ComboBox, "Tangent | Wrap"); + shoot(&mut harness, "paint-alignment-open"); + close(&mut harness); + harness.get_all_by_label("Particles").max_by(|a, b| a.rect().left().total_cmp(&b.rect().left())).unwrap().scroll_to_me(); + harness.run_steps(6); + shoot(&mut harness, "paint-brush-scrolled"); + + let tab = |harness: &mut Harness<'_, TextureCraftApp>, tab: &str, name: &str| { + harness.run_steps(2); + harness.get_by_role_and_label(egui::Role::Tab, tab).click(); + harness.run_steps(6); + shoot(harness, name); + }; + tab(&mut harness, "Brush", "paint-brush-top"); + tab(&mut harness, "Alpha", "paint-alpha"); + open(&mut harness, egui::Role::ComboBox, "Round"); + let star = + harness.query_all_by_role_and_label(egui::Role::ListBoxOption, "Star").map(|node| node.rect()).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap(); + harness.hover_at(star.center()); + harness.run_steps(6); + shoot(&mut harness, "paint-alpha-picker"); + close(&mut harness); + tab(&mut harness, "Material", "paint-material"); + hover(&mut harness, egui::Role::CheckBox, "Height"); + shoot(&mut harness, "paint-material-pill-hover"); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "eraser"})).unwrap(); + tab(&mut harness, "Material", "eraser-material"); + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "clone"})).unwrap(); + tab(&mut harness, "Brush", "clone-brush"); + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "projection"})).unwrap(); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"image": image})).unwrap(); + tab(&mut harness, "Stencil", "projection-stencil"); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"rotation": 15.0, "center": [0.1, -0.05]})).unwrap(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::ComboBox, "No Tiling").click(); + harness.run_steps(4); + shoot(&mut harness, "projection-stencil-tiling-open"); + harness.get_by_label("H and V Tiling").click(); + harness.run_steps(4); + save(&mut harness, &output_dir, "projection-stencil-tiled"); + execute(&mut harness.state_mut().session, "tool.stencil", &json!({"clear": true})).unwrap(); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "paint"})).unwrap(); + let layer = harness.state().session.selected_layer().map(|id| id.0); + execute(&mut harness.state_mut().session, "mask.add.black", &json!({"layer": layer})).unwrap(); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap(); + tab(&mut harness, "Grayscale", "mask-grayscale"); + execute(&mut harness.state_mut().session, "layer.select", &json!({"layer": layer, "target": "content"})).unwrap(); + + harness.get_by_role_and_label(egui::Role::Tab, "Brush").click(); + harness.run_steps(4); + let at = harness.state().viewport_rect.center() - egui::vec2(150.0, 250.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed, modifiers: Modifiers::NONE }); + harness.run_steps(2); + } + harness.run_steps(6); + shoot(&mut harness, "paint-popup"); +} + /// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light #[test] #[ignore] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 49070f1b..49df652a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -13,6 +13,12 @@ Everything TextureCraft does is an engine command with a stable id (`layer.add.f Programmatic calls never open dialogs: a command runs with its defaults. Only `ui.menu.invoke` behaves like a menu click. `session.inspect` shows every layer, mask, effect, fill source and painted tile count, so an agent can verify its work without a screenshot. + +`project.rename {name}` sets the internal project name used by `$project` in export +templates and returns `{name}` with the trimmed value. The name must contain 1–128 +characters after trimming and contain no control characters. Renaming is undoable. +Submitting the current name leaves history unchanged. The project file keeps its own name. + `effect.histogram {effect, channel?, bins?}` counts the values an effect reads (a levels effect's input), so an agent can pick its input range from the data. `effect.move {effect, index}` reorders an effect within its stack (0 = bottom) and `effect.duplicate {effect}` copies @@ -164,7 +170,13 @@ sampling at the source point. Changing `cloneAligned` forgets the offset of earl procedural Round alpha: 100 is a circle, 0 a square), `alphaContrast` (1..8, 1 leaves the values alone) and `alphaInvert` (swaps paint and no paint inside the stamp square). They apply to procedural, library and imported alphas alike and are returned by `tool.brush` with the other -values. The alpha's rotation is the brush `angle`. +values. The alpha's rotation is the brush `angle`. The Projection settings of the Brush section go +through `tool.brush` too and come back with it: `angleFade` (`[from, to]` in degrees, 0..90: with +`backfaceCulling` on, faces turned further than `from` from the view fade out until `to`), +`screenSpace` (Size Space Viewport: the size follows the view instead of the object) and +`stampDepth` (0.05..4). `sizePressure` (default `true`) lets pen pressure shrink the size towards +`minSize`. Setting `sizePressure` to `false` removes pen-pressure scaling. In 3D, `jitterSize` +still varies stamp size independently. Bake mode applies an edit in Common Settings or Mesh Map Settings to the texture sets sharing that group's settings: Common Settings, and each map's settings, are shared by any set of texture sets @@ -225,6 +237,27 @@ project file or an export (`file.exportTextures` and the CLI export the whole st back), and removing the soloed layer ends it. `session.inspect` reports it as `solo` (`{layer, ignoreMask}` or `null`). +### Texture sets + +`textureSet.resolution {ts: 0, resolution: 512, height: 256}` resizes the working +texture set to 512 texels across and 256 down. Each side must be a power of two +from 128 to 8192. Omitting `height` makes the set square. A set with individual +UV tile resolution overrides must stay square. Export size overrides set the +width and preserve the texture set's aspect ratio. + +`textureSet.settings {ts: 0, normalMixing: "replace", aoMixing: "none", +heightToNormal: "sharp", uvPadding: "3d"}` changes those four settings in one +undo step. `textureSet.inspect {ts: 0}` reports the size, settings and channels. +Across-seam padding is the default for new sets. Older sets without a padding +mode keep island-edge padding. + +`textureSet.channels {ts: 0, add: ["user0"]}` adds a stored, exportable channel. +Use `remove` to remove channels and `allSets: true` to apply the same edits to +every set. Inspect reports `shaded: false` for channels the viewport shader +does not use. `textureSet.channel.format {ts: 0, channel: "user0", format: "L8"}` +sets the composite format without lowering the precision of the painted layer +data. Float format selections currently store 16-bit precision. + ## Control channel (desktop app) ```sh @@ -807,7 +840,7 @@ operation returns a busy error and can be retried. | `material.link.saveSource` | `{layer?, path}`: the original linked source with its `.mcmat`, `.mcraft` or `.sbs` extension | For a 1024-pixel texture set, TextureCraft requests `materialcraft-cli export source.mcmat maps --profile maps --size 1024x1024` with repeated `--set` and `--input` arguments. It discovers the published image inputs through `info` when the texture set supplies mesh maps. The desktop worker decodes the returned maps before installing the fill at its original drop target. The executable is resolved from -`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH` +`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else in a `MaterialCraft` folder beside TextureCraft's own folder (the launcher's layout), else on `PATH` (the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`, `worldNormal`, `normal`, `height`, `id`, `bentNormal`, `opacity`, `colorMap`, `worldDirection`; @@ -848,7 +881,10 @@ steps or an object with an optional input and output (paths relative to the curr } ``` -The CLI is a console program and never opens a window; `render` needs a GPU or software adapter. +The CLI is a console program and never opens a window; `render` needs a GPU or software adapter, unless it path +traces (`--samples`). Like the desktop app, it takes the high-performance GPU; `WGPU_ADAPTER_NAME` +(part of the adapter's name or backend) or `WGPU_POWER_PREF` (`high`, `low` or `none`) picks another. +`WGPU_BACKEND` narrows the list first, so a name on a backend it leaves out matches nothing. `texturecraft-cli` follows [RFC-0018](https://github.com/storytold/craft-contrib/blob/main/rfcs/0018-cli-conventions.md) (command-line conventions); `texturecraft-cli --help` and ` --help` are the reference for every flag. diff --git a/docs/features.md b/docs/features.md index e66cc81e..8def0821 100644 --- a/docs/features.md +++ b/docs/features.md @@ -16,8 +16,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA **18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the stroke and keep the size. The Brush section's **Brush presets** popover (and the shelf) also keeps your own: save the current brush, click to use it, rename, replace or delete it. -- **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the - stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a +- **Tools:** paint, eraser, **projection** (paints an image's colors), a **stencil** every brush tool + paints through (its gray masks the stroke; hold S to move, turn and scale it; painting the quick mask, + or in the 2D UV view with any tool but projection, ignores the stencil), polygon fill (triangle, UV island or the whole mesh), **path** (Shift+click places a corner point for hard edges) and **lasso fill**, a **particle brush**, **smudge**, **clone** (V + click sets the source, marked in the 3D and 2D views; an Aligned option keeps or restarts the offset per stroke), material picker, Shift+click straight lines (Ctrl+Shift+click snaps them to 15 degree steps), and painting directly in the **2D UV view**. @@ -146,8 +147,14 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, other filters and height-to-normal slopes keep their size in UV space at any tile resolution) and one texture per tile on export (`$udim`). -- **Texture sets** from 128 to 8192 px per material, resampled when you change them, with 21 - channel types to add or remove. Show, hide or invert them all at once, or **focus** on the +- **Texture sets** from 128 to 8192 px per material, square or with a height of their own + (`textureSet.resolution {resolution, height}`), resampled when you change them, with 72 channel + types to add or remove: the 21 the shader reads, more material channels that are stored and + exported, and User0 to User31 (*Add or remove channels*, `textureSet.channels`). Each channel + has a storage format (`textureSet.channel.format`), and each set its normal mixing, ambient + occlusion mixing, height to normal method and UV padding, across seams (3D) or from island + edges (2D) (`textureSet.settings`). Rename a set in the list, or reset it to the mesh + material's name. Show, hide or invert them all at once, or **focus** on the active one. The project's **normal map format** (OpenGL or DirectX, in Texture Set Settings) says how a normal map image set as a mesh map is read, and is the default for export. - **Projects** are a single `.tcraft` file: the mesh (with its generated UV layout when *Rebuild mesh UVs* was chosen), every layer (sparse and lossless), baked maps @@ -308,7 +315,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA the default). Nightly shows its fixed profile path in the same row. - **Autosave**: each project keeps its own copy in the data folder's `autosave`, named `-copy-.tcraft` after its saved file (or, until it is saved, the project), so projects made from - one mesh never overwrite each other's copy. + one mesh never overwrite each other's copy. Opening a copy from the current desktop profile's + autosave folder starts an unsaved project. Save asks where to keep the recovered work. - A **Settings window** (Edit › Settings) with General, Shortcuts and Libraries pages; changes apply on OK and Cancel drops them. General holds the language (or the system's), the 3D view's rotation, zoom and wheel speeds with inverse directions, GPU or CPU bake rays, resource limits diff --git a/docs/nightly-signing-policy.example.json b/docs/nightly-signing-policy.example.json index 99924a91..1e4070e7 100644 --- a/docs/nightly-signing-policy.example.json +++ b/docs/nightly-signing-policy.example.json @@ -42,7 +42,15 @@ "unsigned_artifact_name": "nightly-unsigned-linux-x86_64", "trust": { "fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED" - } + }, + "package_formats": [ + "appimage", + "arch", + "deb", + "flatpak", + "oci", + "rpm" + ] }, "macos-aarch64": { "unsigned_artifact_name": "nightly-unsigned-macos-aarch64", diff --git a/docs/parity.md b/docs/parity.md index 46707737..bf1345ae 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -4,7 +4,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac **63 of 64 menu items live (98%).** -**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 40 no (window 33, os 5, engine-gap 2), 3 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`). +**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 21 yes, 39 no (window 33, os 5, engine-gap 1), 4 partial, 0 unknown.** An item is `headless: yes` when its id is an engine command, so `texturecraft-cli` and the MCP server reach it. A `ui.*` id is live in the desktop app only; its value is the hand mark in `HEADLESS` (`crates/ui-egui/src/parity.rs`). ## File @@ -32,7 +32,7 @@ Generated by `TC_UPDATE_PARITY=1 cargo test -p texturecraft-ui-egui parity`. Eac |---|---|---|---|---| | Undo | `edit.undo` | Ctrl+Z | live | yes | | Redo | `edit.redo` | Ctrl+Y | live | yes | -| Project Configuration | `ui.projectConfig` | | live | no, reach: engine-gap (project settings could be set by a command) | +| Project Configuration | `ui.projectConfig` | | live | partial, reach: window (the dialog is desktop-only; `project.rename` sets the project name) | | Reimport Mesh | `file.reimportMesh` | Ctrl+Shift+R | live | yes | | Settings | `ui.settings` | | live | no, reach: window (the desktop settings window) | diff --git a/packaging/macos/nightly.sh b/packaging/macos/nightly.sh index 4140e45a..47d03279 100755 --- a/packaging/macos/nightly.sh +++ b/packaging/macos/nightly.sh @@ -35,11 +35,12 @@ OUTPUT="$DIST/texturecraft-$VERSION-macos-aarch64-nightly.zip" nightly_compile_gui APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP" -mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs" cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" chmod 755 "$APP/Contents/MacOS/$MAC_NIGHTLY_EXECUTABLE" cp "$ROOT/assets/app-icon/$MAC_NIGHTLY_ICON.icns" "$APP/Contents/Resources/$MAC_NIGHTLY_ICON.icns" -nightly_copy_notices "$APP/Contents/Resources" +# Launcher admits notices under Resources/docs, not beside the icon. +nightly_copy_notices "$APP/Contents/Resources/docs" # The private mktemp cwd is the helper authority root: stage the template inside it. cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in" (cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \ diff --git a/packaging/macos/nightly_sign_tests.py b/packaging/macos/nightly_sign_tests.py index f0a2eddc..74f39763 100644 --- a/packaging/macos/nightly_sign_tests.py +++ b/packaging/macos/nightly_sign_tests.py @@ -6,8 +6,10 @@ crafted archive) as an argument, which is why packaging/macos/nightly_sign_tests app's ordinary Linux CI. """ import os +import shutil import stat import subprocess +import sys import tempfile import unittest import zipfile @@ -16,9 +18,18 @@ from pathlib import Path HERE = Path(__file__).resolve().parent LIB = HERE / "nightly-lib.sh" APP = "TextureCraft Nightly.app" +APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md") +OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT") IDENTITY = "A" * 40 TEAM = "DJ6XS33FX8" APP_CONFIG_ID = "ai.storyteller.texturecraft.nightly" +COMMIT = "0123456789abcdef0123456789abcdef01234567" +VERSION = "0.24.0-nightly.20261124.7.2.g" + COMMIT[:12] +ASSET = f"texturecraft-{VERSION}-macos-aarch64-nightly.zip" +SECRETS = ( + "APPLE_CERTIFICATE", "APPLE_CERTIFICATE_PASSWORD", "KEYCHAIN_PASSWORD", + "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "MACOS_SIGN_IDENTITY", "MACOS_KEYCHAIN", +) @@ -178,5 +189,198 @@ class ZipEntries(unittest.TestCase): self.assertFalse(self.checked([*good, entry]), entry[0]) +class PackageFixture: + """Stand-in POSIX harness for driving packaging/macos/nightly.sh and nightly-verify.sh.""" + + def __init__(self, case): + directory = tempfile.TemporaryDirectory() + case.addCleanup(directory.cleanup) + self.root = Path(directory.name).resolve() + self.bin = self.root / "bin" + self.dist = self.root / "dist" + self.temp = self.root / "tmp" + for path in (self.bin, self.dist, self.temp): + path.mkdir() + self._install_shims() + + def _write_shim(self, name, body): + path = self.bin / name + path.write_text(body) + path.chmod(0o755) + + def _install_shims(self): + python = sys.executable + self._write_shim( + "uname", + "#!/bin/sh\n" + "case \"$1\" in\n" + " -s) echo Darwin ;;\n" + " -m) echo arm64 ;;\n" + " *) /usr/bin/uname \"$@\" ;;\n" + "esac\n", + ) + self._write_shim("lipo", "#!/bin/sh\necho arm64\n") + self._write_shim( + "plutil", + f"#!{python}\n" + "import plistlib, sys\n" + "args = sys.argv[1:]\n" + "if args[:1] == ['-lint']:\n" + " with open(args[1], 'rb') as f:\n" + " plistlib.load(f)\n" + " sys.exit(0)\n" + "if args[:1] == ['-extract'] and len(args) == 6 and args[3:5] == ['-o', '-']:\n" + " key, fmt, plist_path = args[1], args[2], args[5]\n" + " with open(plist_path, 'rb') as f:\n" + " data = plistlib.load(f)\n" + " if key not in data:\n" + " sys.exit(1)\n" + " value = data[key]\n" + " if fmt == 'raw':\n" + " print(value)\n" + " else:\n" + " print(plistlib.dumps(value).decode('utf-8'))\n" + " sys.exit(0)\n" + "sys.exit(f'unsupported plutil args: {args}')\n", + ) + self._write_shim( + "ditto", + f"#!{python}\n" + "import os, stat, sys, zipfile\n" + "from pathlib import Path\n" + "args = sys.argv[1:]\n" + "src, dst = Path(args[-2]), Path(args[-1])\n" + "if '-c' in args:\n" + " base = src.parent if '--keepParent' in args else src\n" + " with zipfile.ZipFile(dst, 'w', compression=zipfile.ZIP_DEFLATED) as z:\n" + " items = [src] + sorted(src.rglob('*')) if '--keepParent' in args else sorted(src.rglob('*'))\n" + " for item in items:\n" + " rel = item.relative_to(base).as_posix()\n" + " if item.is_dir():\n" + " info = zipfile.ZipInfo(rel + '/')\n" + " info.external_attr = (stat.S_IFDIR | (item.stat().st_mode & 0o777)) << 16\n" + " z.writestr(info, b'')\n" + " else:\n" + " info = zipfile.ZipInfo(rel)\n" + " info.external_attr = (stat.S_IFREG | (item.stat().st_mode & 0o777)) << 16\n" + " z.writestr(info, item.read_bytes())\n" + "elif '-x' in args:\n" + " dst.mkdir(parents=True, exist_ok=True)\n" + " with zipfile.ZipFile(src) as z:\n" + " for info in z.infolist():\n" + " target = dst / info.filename\n" + " if info.is_dir():\n" + " target.mkdir(parents=True, exist_ok=True)\n" + " else:\n" + " target.parent.mkdir(parents=True, exist_ok=True)\n" + " target.write_bytes(z.read(info.filename))\n" + " mode = (info.external_attr >> 16) & 0o777\n" + " if mode:\n" + " os.chmod(target, mode)\n" + "else:\n" + " sys.exit(f'unsupported ditto args: {args}')\n", + ) + + def env(self, **changes): + env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "RUNNER_TEMP": str(self.temp)} + for key, value in changes.items(): + if value is None: + env.pop(key, None) + else: + env[key] = str(value) + return env + + def run(self, script, *args, **changes): + path = Path(script) if Path(script).is_absolute() else HERE / script + return subprocess.run( + ["bash", str(path), *(str(a) for a in args)], + env=self.env(**changes), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60, + ) + + def package(self, font_licences): + """Drive the real producer from a clean fixture checkout, without Cargo or Apple tools.""" + source = HERE.parents[1] + checkout = self.root / "source" + checkout.mkdir() + notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file()) + for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py", + "packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh", + "packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py", + "assets/app-icon/texturecraft-nightly.icns"): + target = checkout / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source / relative, target) + env = self.env(**dict.fromkeys(SECRETS)) + + def git(*args): + return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args], + cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout + + git("init", "-q") + git("add", "--", ".") + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture") + commit = git("rev-parse", "HEAD").strip() + version = VERSION[:-12] + commit[:12] + # Generated licence text exercises the copier without depending on a font checkout. + fonts = self.root / "craft-fonts" + for family, data in font_licences.items(): + licence = fonts / "fonts" / family / "OFL.txt" + licence.parent.mkdir(parents=True) + licence.write_bytes(data) + self._write_shim( + "cargo", + '#!/bin/sh\nset -eu\n' + 'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/texturecraft"\n' + 'mkdir -p "$(dirname "$gui")"\n' + "printf \"#!/bin/sh\\necho 'TextureCraft %s (nightly-v1)'\\n\" \"$TEXTURECRAFT_VERSION\" >\"$gui\"\n", + ) + result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS), + DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts), + TEXTURECRAFT_BUILD_CHANNEL="nightly-v1", TEXTURECRAFT_VERSION=version, + TEXTURECRAFT_BUILD_SHA=commit, TEXTURECRAFT_BUILD_DATE="2026-11-24") + assert result.returncode == 0, result.stdout + return self.dist / ASSET.replace(VERSION, version) + + +class Build(unittest.TestCase): + def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self): + f = PackageFixture(self) + fonts = { + "inter": b"generated font notice one", + "biz-ud-pgothic": b"generated font notice two", + "noto-sans-cjk-sc": b"generated font notice three", + } + archive = f.package(fonts) + source = HERE.parents[1] + resources = f"{APP}/Contents/Resources" + icon = "texturecraft-nightly.icns" + notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES} + notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()}) + notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()}) + # Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon. + expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()} + expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes() + contents = f"{APP}/Contents" + gui = f"{contents}/MacOS/TextureCraft" + with zipfile.ZipFile(archive) as zipped: + entries = zipped.infolist() + names = {entry.filename for entry in entries} + self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case") + self.assertEqual({entry.filename for entry in entries if not entry.is_dir()}, + set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"}) + self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= { + f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"}) + for path, data in expected_files.items(): + with self.subTest(path=path): + self.assertEqual(zipped.read(path), data) + mode = zipped.getinfo(path).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode)) + self.assertFalse(mode & 0o111) + mode = zipped.getinfo(gui).external_attr >> 16 + self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR) + result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS)) + self.assertEqual(result.returncode, 0, result.stdout) + + if __name__ == "__main__": unittest.main() diff --git a/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index c55e54c1..55c08d86 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -13,6 +13,12 @@ APP_NAME = "texturecraft" PRODUCER_WORKFLOW_NAME = "TextureCraft unsigned nightly" NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64") +# The pinned shared registry enables Windows, Linux and macOS for TextureCraft. +SIGNER_SECRETS = { + "AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT", + "AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE", + "APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD", +} NIGHTLY_TRUST = { "windows-x86_64": ("publisher_subject", "CN=Learning Machines Inc, O=Learning Machines Inc, L=Atlanta, S=Georgia, C=US"), @@ -45,6 +51,49 @@ def assert_nightly_serialization(source): raise ValueError("nightly serialization must use its stable group and no cancellation") +def caller_entries(lines, indent): + """Split the callers' plain YAML block entries; refuse other forms at checked levels.""" + entries = {} + children = None + for line in lines: + if children is not None and line.startswith(" " * (indent + 1)): + children.append(line) + continue + row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line) + if row is None or row[1] in entries: + raise ValueError("malformed or duplicate caller mapping entry") + children = [] + entries[row[1]] = row[2], children + return entries + + +def assert_caller_secrets(source, job_name, names): + """Check the actual caller's root, job and secret blocks without a YAML dependency.""" + lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")] + root = caller_entries(lines, 0) + job_marker, job_lines = root.pop("jobs", (None, [])) + jobs = caller_entries(job_lines, 2) + if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None: + raise ValueError("the caller must have one plain job block") + job = caller_entries(jobs[job_name][1], 4) + if "environment" in job or "environment" in root or "secrets" in root: + raise ValueError("only the native callee may bind the environment") + if names: + if "secrets" not in job: + raise ValueError("signer requires an explicit target-specific secret map") + mode, secret_lines = job.pop("secrets") + expected = {name: ("${{ secrets." + name + " }}", []) for name in names} + if mode is not None or caller_entries(secret_lines, 6) != expected: + raise ValueError("signer must forward exactly the reviewed same-name secret references") + elif "secrets" in job: + raise ValueError("unsigned caller must not pass secrets") + for value, children in (*root.values(), *job.values()): + outside_map = "\n".join([value or "", *children]) + # Scan all remaining text: quoted braces can appear before a secret reference. + if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map): + raise ValueError("secret bindings belong only in the signer map") + + def literal_off(condition): """True only for a guard that a reviewed test update can still see is switched off.""" expression = " ".join(condition.split()) @@ -125,7 +174,7 @@ def reviewed_manual_actors(caller_source, policy): def caller_pin(name): - return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0] + return re.findall(r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text())[0] class TrustedSourcePreparation(unittest.TestCase): @@ -204,8 +253,49 @@ class TrustedSourcePreparation(unittest.TestCase): with self.subTest(workflow=name): self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache") self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:") - self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):") - self.assertNotIn("secrets.", executable) + + def test_signer_forwards_exactly_the_reviewed_secret_names(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + assert_caller_secrets(signer, "release", SIGNER_SECRETS) + + def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self): + signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text() + header = " secrets:\n" + linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n" + self.assertIn(linux, signer) + mutations = { + "missing name": signer.replace(linux, ""), + "extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n", + "renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")), + "duplicate name": signer.replace(linux, linux + linux), + "duplicate map": signer + header + linux, + "quoted duplicate map": signer + ' "secrets": inherit\n', + "inherit": signer.split(header)[0] + " secrets: inherit\n", + "yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"), + "yaml merge": signer + " <<: *other\n", + "environment": signer + " environment: release\n", + "secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"), + } + for change, source in mutations.items(): + with self.subTest(change=change), self.assertRaises(ValueError): + assert_caller_secrets(source, "release", SIGNER_SECRETS) + + def test_unsigned_caller_has_no_secrets(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + assert_caller_secrets(producer, "unsigned", set()) + for suffix in (" secrets: {}\n", " secrets: inherit\n", + " secrets:\n EXTRA: ${{ secrets.EXTRA }}\n", + " extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"): + with self.subTest(suffix=suffix), self.assertRaises(ValueError): + assert_caller_secrets(producer + suffix, "unsigned", set()) + + def test_unsigned_caller_refuses_secret_after_format_brace(self): + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + # This inert fixture is never dispatched; the brace is part of the format string. + env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n" + source = producer.replace("jobs:\n", env + "jobs:\n", 1) + with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"): + assert_caller_secrets(source, "unsigned", set()) class NightlyTrustAnchors(unittest.TestCase): @@ -242,7 +332,7 @@ class NightlyTrustAnchors(unittest.TestCase): self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match") pins.update(uses) self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit") - self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder") + self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main") class NightlyEnabledCallers(unittest.TestCase): @@ -648,7 +738,7 @@ def trust_closure_problems(workflows): if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"): if name == "nightly-sign.yml": signer_calls += 1 - if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref): + if name != "nightly-sign.yml" or ref != "main": problems.append(name + " calls nightly-release.yml@" + ref) if workflow.lower() in ("release.yml", "release.yaml"): stable_callers.add(name) @@ -698,7 +788,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase): "a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"}, "uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"}, "another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"}, - "a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])}, + "a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")}, "a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"}, "a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")}, } diff --git a/packaging/web/package.sh b/packaging/web/package.sh index 7b5a4915..8e453f49 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -36,6 +36,18 @@ for wasm in "$SITE"/*.wasm; do echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)" if [[ "$size" -gt "$MAX_WASM_BYTES" ]]; then echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2 + # Where the bytes go: the optimized file has no function names, so the crate breakdown reads + # cargo's own output (before wasm-bindgen and wasm-opt), which keeps them. Best effort only. + report="$HERE/wasm_size_report.py" + if command -v python3 >/dev/null && [[ -f "$report" ]]; then + echo "--- sections of $(basename "$wasm") ---" >&2 + python3 "$report" "$wasm" >&2 || true + raw="$CARGO_TARGET_DIR/wasm32-unknown-unknown/wasm-release/texturecraft-web.wasm" + if [[ -f "$raw" ]]; then + echo "--- largest crates and functions in cargo's output (before wasm-opt) ---" >&2 + python3 "$report" "$raw" >&2 || true + fi + fi exit 1 fi done diff --git a/packaging/web/wasm_size_report.py b/packaging/web/wasm_size_report.py new file mode 100644 index 00000000..f26acddc --- /dev/null +++ b/packaging/web/wasm_size_report.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""Print where a wasm module's bytes go: sections, data, and code by crate.""" +import os, re, sys +from collections import defaultdict + +def leb(b, i): + r = s = 0 + while True: + x = b[i]; i += 1 + r |= (x & 0x7f) << s; s += 7 + if x < 0x80: return r, i + +def crate_of(name): + if name.startswith("_ZN"): + m = re.match(r"_ZN(\d+)", name) + if m: + n = int(m.group(1)); s = name[3 + len(m.group(1)):3 + len(m.group(1)) + n] + if s.startswith("_$LT$"): + inner = re.match(r"_\$LT\$(?:\$RF\$|mut\$u20\$)*([A-Za-z_][A-Za-z0-9_]*)", s) + return (inner.group(1) if inner else s) + " (impl)" + return s + if name.startswith("_R"): + m = re.search(r"C(?:s[0-9A-Za-z]*_)?(\d+)_?([A-Za-z_][A-Za-z0-9_]*)", name) + if m: return m.group(2)[:int(m.group(1))] + return "" if "::" in name else "" + +def main(arg, top=25): + repo = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) + target_env = os.environ.get("CARGO_TARGET_DIR") + target = os.path.realpath(target_env) if target_env else None + path = os.path.realpath(arg) + root = target if target and path.startswith(target + os.sep) else repo + if not path.startswith(root + os.sep): + print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr) + return + if not path.endswith(".wasm") or not os.path.isfile(path): + print(f"wasm_size_report: skipped {arg!r}: not a .wasm file under the repository or CARGO_TARGET_DIR", file=sys.stderr) + return + with open(path, "rb") as f: + b = f.read() + assert b[:4] == b"\0asm" + i = 8; secs = []; names = {}; code_sizes = []; nimports = 0; data_total = 0 + while i < len(b): + sid = b[i]; i += 1 + size, i = leb(b, i); body = b[i:i + size] + label = {0:"custom",1:"type",2:"import",3:"function",4:"table",5:"memory",6:"global",7:"export",8:"start",9:"element",10:"code",11:"data",12:"datacount"}.get(sid, str(sid)) + if sid == 0: + nl, j = leb(body, 0); cname = body[j:j+nl].decode(); label = "custom:" + cname + if cname == "name": + j += nl + while j < len(body): + sub = body[j]; j += 1; sl, j = leb(body, j); end = j + sl + if sub == 1: + cnt, k = leb(body, j) + for _ in range(cnt): + idx, k = leb(body, k); ln, k = leb(body, k); names[idx] = body[k:k+ln].decode("utf-8", "replace"); k += ln + j = end + elif sid == 2: + cnt, j = leb(body, 0) + for _ in range(cnt): + l, j = leb(body, j); j += l; l, j = leb(body, j); j += l + kind = body[j]; j += 1 + if kind == 0: nimports += 1; _, j = leb(body, j) + elif kind == 1: j += 1; fl, j = leb(body, j); _, j = leb(body, j); j = leb(body, j)[1] if fl & 1 else j + elif kind == 2: fl, j = leb(body, j); _, j = leb(body, j); j = leb(body, j)[1] if fl & 1 else j + elif kind == 3: j += 2 + elif sid == 10: + cnt, j = leb(body, 0) + for _ in range(cnt): + fs, j2 = leb(body, j); code_sizes.append(fs + (j2 - j)); j = j2 + fs + elif sid == 11: + data_total = size + secs.append((label, size)); i += size + total = len(b) + print(f"{path}: {total} bytes") + for label, size in sorted(secs, key=lambda s: -s[1])[:8]: + print(f" {label:<24}{size:>12} bytes {100*size/total:5.1f}%") + by_crate = defaultdict(int); funcs = [] + for k, sz in enumerate(code_sizes): + n = names.get(nimports + k, f"func[{nimports+k}]") + by_crate[crate_of(n)] += sz; funcs.append((sz, n)) + if not names: + print(" (no name section: pass the wasm cargo wrote, before wasm-opt, to attribute code to crates)") + return + print(f" largest crates by code size (of {sum(code_sizes)} code bytes):") + for c, sz in sorted(by_crate.items(), key=lambda x: -x[1])[:top]: + print(f" {sz:>10} {c}") + print(" largest functions:") + for sz, n in sorted(funcs, reverse=True)[:10]: + print(f" {sz:>10} {n[:140]}") + +if __name__ == "__main__": + main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 25) diff --git a/sonar-project.properties b/sonar-project.properties index 21de440a..5ac46f82 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -1 +1,2 @@ sonar.coverage.exclusions=packaging/** +sonar.exclusions=packaging/web/wasm_size_report.py