diff --git a/.github/nightly-signing-policy.json b/.github/nightly-signing-policy.json index 51ac774f..58445c26 100644 --- a/.github/nightly-signing-policy.json +++ b/.github/nightly-signing-policy.json @@ -88,7 +88,9 @@ } }, "max_artifact_bytes": 2147483648, - "automatic_signer_actors": [], + "automatic_signer_actors": [ + "github-actions[bot]" + ], "platforms": { "windows-x86_64": { "unsigned_artifact_name": "nightly-unsigned-windows-x86_64", @@ -100,7 +102,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/ci.yml b/.github/workflows/ci.yml index 40294e0b..1145b532 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,6 @@ jobs: os: '["ubuntu-24.04","windows-latest"]' # xtask ci runs cargo test (including doctests), not cargo nextest. tools: "" - windows-command: pwsh -NoProfile -File .github/workflows/windows-vulkan-gate.ps1 packages: >- libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev - libgtk-3-dev mesa-vulkan-drivers + libgtk-3-dev diff --git a/.github/workflows/nightly-dispatch.yml b/.github/workflows/nightly-dispatch.yml index bd40f765..2445bdd2 100644 --- a/.github/workflows/nightly-dispatch.yml +++ b/.github/workflows/nightly-dispatch.yml @@ -11,9 +11,9 @@ permissions: {} jobs: dispatch: - # SOURCE PREPARATION: literal off until immutable shared tooling and policy qualification. + # Exact context guard only; admission belongs to the protected signer branch. if: >- - false && github.repository == 'storytold/texturecraft' && + github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_run' runs-on: ubuntu-latest timeout-minutes: 5 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index c05c2e31..173ba6cc 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,8 +1,9 @@ name: TextureCraft unsigned nightly -# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet. -# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it). +# Automated daily schedule at 06:00 UTC plus supervised manual runs by reviewed manual actors. on: + schedule: + - cron: '0 6 * * *' workflow_dispatch: permissions: diff --git a/.github/workflows/windows-vulkan-gate.ps1 b/.github/workflows/windows-vulkan-gate.ps1 deleted file mode 100644 index 92bcedf1..00000000 --- a/.github/workflows/windows-vulkan-gate.ps1 +++ /dev/null @@ -1,62 +0,0 @@ -$ErrorActionPreference = 'Stop' - -# Hosted Windows runners have no physical GPU. Use an isolated Vulkan ICD so -# the renderer tests run without relying on the D3D12 software driver. -$runtime = Join-Path ([System.IO.Path]::GetTempPath()) 'texturecraft-ci-vulkan' -New-Item -ItemType Directory -Path $runtime -Force | Out-Null - -function Get-VerifiedArchive($uri, $name, $sha256) { - $archive = Join-Path $runtime $name - Invoke-WebRequest -Uri $uri -OutFile $archive -TimeoutSec 120 - if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $sha256) { - throw "Unexpected SHA-256 for $name" - } - return $archive -} - -$mesa = Get-VerifiedArchive ` - 'https://github.com/pal1000/mesa-dist-win/releases/download/26.3.0/mesa3d-26.3.0-release-msvc.7z' ` - 'mesa.7z' 'C505FCC77E8F63A09D7DDAC086591D2F542C0698D37FC9E3094685A34D0D9991' -$loader = Get-VerifiedArchive ` - 'https://sdk.lunarg.com/sdk/download/1.4.363.0/windows/VulkanRT-X64-1.4.363.0-Components.zip' ` - 'vulkan.zip' 'A25A927AA8B9F0371048F1861CF88AC3B9BC9B1FB332C42D897C8AB32695769A' - -# The shared action starts this script from Git Bash, whose tar treats C: as a remote host. -$system = [System.Environment]::SystemDirectory -$tar = Join-Path $system 'tar.exe' -& $tar -xf $mesa -C $runtime x64/lvp_icd.x86_64.json x64/vulkan_lvp.dll -if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } -$loaderRoot = 'VulkanRT-X64-1.4.363.0-Components/x64' -& $tar -xf $loader -C $runtime "$loaderRoot/vulkan-1.dll" "$loaderRoot/vulkaninfo.exe" -if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - -$loaderBin = Join-Path $runtime $loaderRoot -$env:PATH = "$loaderBin;$env:PATH" -$env:VK_DRIVER_FILES = Join-Path $runtime 'x64/lvp_icd.x86_64.json' -if ($env:RUNNER_ENVIRONMENT -eq 'github-hosted') { - # The loader can ignore environment-based driver discovery for elevated processes. - $drivers = 'HKLM:\SOFTWARE\Khronos\Vulkan\Drivers' - New-Item -Path $drivers -Force | Out-Null - New-ItemProperty -LiteralPath $drivers -Name $env:VK_DRIVER_FILES -PropertyType DWord -Value 0 -Force | Out-Null - $systemLoader = Join-Path $system 'vulkan-1.dll' - if (!(Test-Path -LiteralPath $systemLoader)) { - Copy-Item -LiteralPath (Join-Path $loaderBin 'vulkan-1.dll') -Destination $systemLoader - } -} -$env:WGPU_BACKEND = 'vulkan' -$env:TC_CI_LAVAPIPE = '1' -# Keep software devices from contending for all runner cores at once. -$env:RUST_TEST_THREADS = '2' -$env:LP_NUM_THREADS = '2' -# LLVM's optimisation passes cost more than the tests' shaders then run -$env:GALLIVM_PERF = 'nopt' - -Write-Host 'Windows CI using Mesa Lavapipe 26.3.0 with Vulkan loader 1.4.363.0' -$summary = & (Join-Path $loaderBin 'vulkaninfo.exe') --summary -if ($LASTEXITCODE -ne 0 -or !($summary -match 'deviceName\s*=\s*llvmpipe')) { - $summary | Write-Host - throw 'Vulkan preflight did not find the Lavapipe adapter' -} -$summary | Select-String 'deviceType|deviceName|driverInfo' | ForEach-Object { Write-Host $_.Line } -cargo xtask ci -exit $LASTEXITCODE diff --git a/Cargo.lock b/Cargo.lock index e242b5b0..66fb8545 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1324,6 +1324,14 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-nightly" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" +dependencies = [ + "winsafe", +] + [[package]] name = "craft-pdf" version = "0.1.0" @@ -5949,6 +5957,7 @@ dependencies = [ "craft-host", "craft-image-codecs", "craft-menu", + "craft-nightly", "craft-update", "eframe", "egui", @@ -6119,6 +6128,7 @@ dependencies = [ "harfrust 0.12.0", "rayon", "serde", + "serde_json", "skrifa 0.44.0", "texturecraft-compose", "texturecraft-core", diff --git a/Cargo.toml b/Cargo.toml index bb398c92..2a15ba96 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -89,6 +89,8 @@ craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a craft-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } # The theme mode the app hands the runtime (crates/ui-egui/src/framework.rs). craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" } +# Nightly profile isolation, launch protocol, and security fence (apps/texturecraft). +craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24" } # egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them. [patch.crates-io] diff --git a/apps/texturecraft-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/Cargo.toml b/apps/texturecraft/Cargo.toml index 58e30a92..6b4a5965 100644 --- a/apps/texturecraft/Cargo.toml +++ b/apps/texturecraft/Cargo.toml @@ -25,6 +25,8 @@ log = { workspace = true } rfd = { workspace = true } # Pass the selected window backend to the title bar and UI runtime craft-host = { workspace = true } +# Nightly profile isolation, launch protocol, and security fence. +craft-nightly = { workspace = true } # Reads the saved System title bar setting before the window opens (eframe's settings format). ron = "0.12" diff --git a/apps/texturecraft/src/build_flavor.rs b/apps/texturecraft/src/build_flavor.rs index 294f1e19..9330b7d8 100644 --- a/apps/texturecraft/src/build_flavor.rs +++ b/apps/texturecraft/src/build_flavor.rs @@ -1,14 +1,9 @@ //! The build-time channel, which is distinct from a launch selector: no runtime environment can //! promote a stable build into the Nightly one. -use crate::launch_profile::Profile; use std::ffi::OsString; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum BuildFlavor { - Stable, - NightlyV1, -} +pub use craft_nightly::BuildFlavor; /// `TEXTURECRAFT_BUILD_CHANNEL=nightly-v1` at compile time (`build.rs`). pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable }; @@ -17,15 +12,6 @@ pub const COMPILED: BuildFlavor = if cfg!(texturecraft_nightly_v1) { BuildFlavor /// workspace version (`build.rs` bakes it so both flavors read it the same way). pub const BUILT_VERSION: &str = env!("TEXTURECRAFT_VERSION"); -/// A nightly build starts only with its profile, and a stable build only without one. -pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> { - match (flavor, profile.is_nightly()) { - (BuildFlavor::NightlyV1, false) => Err("Open TextureCraft Nightly from ArtCraft Launcher".into()), - (BuildFlavor::Stable, true) => Err("This is a stable TextureCraft build; nightly-v1 requires the nightly build".into()), - _ => Ok(()), - } -} - /// A refused nightly start explains itself in a native dialog: a release Windows build has no /// console, and a Dock launch on macOS has none either. pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool { @@ -58,22 +44,6 @@ mod tests { assert!(!needs_native_error(BuildFlavor::Stable, false)); } - #[test] - fn nightly_build_without_a_profile_is_refused_before_startup() { - let started = std::cell::Cell::new(false); - let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true)); - assert!(result.unwrap_err().contains("ArtCraft Launcher")); - assert!(!started.get()); - } - - #[test] - fn stable_and_nightly_flavors_accept_only_their_own_profile() { - let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root")); - assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok()); - assert!(require_profile(BuildFlavor::Stable, &nightly).is_err()); - assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok()); - } - #[test] fn the_nightly_version_line_is_exact_and_says_its_channel() { let nightly = version(BuildFlavor::NightlyV1); diff --git a/apps/texturecraft/src/gpu.rs b/apps/texturecraft/src/gpu.rs index 07cf6a4c..0bb474c3 100644 --- a/apps/texturecraft/src/gpu.rs +++ b/apps/texturecraft/src/gpu.rs @@ -84,19 +84,17 @@ pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, .iter() .enumerate() .min_by_key(|(orig_idx, c)| { - // Surface support is required; unsupported adapters rank last. + // The selected adapter must be able to present to the window let surface_penalty = !c.surface_supported; - // Explicit named filter (e.g. --gpu nvidia, WGPU_ADAPTER_NAME=3080). let name_penalty = match named_filter { Some(filter) => !c.matches_filter(filter), None => false, }; - // Hardware GPUs before software/CPU rasterizers. let software_penalty = c.is_software(); - // Native backends before OpenGL (except when preserving system order). + // Preserve system backend order when no power preference is set let backend_rank = match (power, c.backend) { (PowerPreference::None, _) => 0, (_, Backend::Dx12) if cfg!(windows) => 1, @@ -105,7 +103,6 @@ pub fn pick_adapter_index(candidates: &[Candidate], named_filter: Option<&str>, _ => 3, }; - // Power preference ranking. let power_rank = match power { PowerPreference::HighPerformance => match c.device_type { DeviceType::DiscreteGpu => 0, @@ -148,9 +145,8 @@ pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power let device_descriptor = create.device_descriptor.clone(); create.device_descriptor = Arc::new(move |adapter| { let mut descriptor = device_descriptor(adapter); - // The compositor sizes its bands and working buffers against the device's limits, so - // request everything the adapter reports, as `texturecraft_render::device_limits` - // does for headless devices. Negotiating a limit allocates nothing. + + // Request adapter limits so compositor bands fit the same budget as headless renders descriptor.required_limits = adapter.limits(); descriptor }); diff --git a/apps/texturecraft/src/launch_profile.rs b/apps/texturecraft/src/launch_profile.rs index 84f5061f..b75287fd 100644 --- a/apps/texturecraft/src/launch_profile.rs +++ b/apps/texturecraft/src/launch_profile.rs @@ -1,126 +1,30 @@ -//! The Launcher's nightly-v1 bootstrap, selected before logging, updates, fonts or saved state. -//! Stable launches keep their arguments and directory policy unchanged, and no environment is -//! mutated: the profile is a value this process reads, not a variable it exports. +//! The Launcher's nightly-v1 bootstrap and direct-launch self-isolation, backed by `craft-nightly`. +//! +//! Selected before logging, updates, fonts or saved state. Stable launches keep their arguments and +//! directory policy unchanged, and no environment is mutated: the profile is a value this process +//! reads, not a variable it exports. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; -use std::sync::OnceLock; -pub const VERSION: &str = "nightly-v1"; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Profile { - Stable, - NightlyV1(PathBuf), -} - -impl Profile { - pub fn is_nightly(&self) -> bool { - matches!(self, Self::NightlyV1(_)) - } - - pub fn root(&self) -> Option<&Path> { - match self { - Self::Stable => None, - Self::NightlyV1(root) => Some(root), - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub struct Launch { - pub profile: Profile, - pub args: Vec, -} - -static PROFILE: OnceLock = OnceLock::new(); +pub use craft_nightly::{BuildFlavor, Launch, Profile, ProfileError, StartupOptions}; pub fn current() -> &'static Profile { - PROFILE.get().unwrap_or(&Profile::Stable) + craft_nightly::current().unwrap_or(&Profile::Stable) } -pub fn install(profile: Profile) -> Result<(), String> { - PROFILE.set(profile).map_err(|_| "the launch profile was already selected".into()) -} - -/// Recognize only the agreed literal selector/root pair before `--`. Everything after it is a -/// file, even when it looks like a profile flag. No filesystem or startup hook runs here. -pub fn parse(args: Vec) -> Result { - let mut selector = None; - let mut root = None; - let mut other = Vec::new(); - let mut files = Vec::new(); - let mut iter = args.iter(); - let mut delimiter = false; - while let Some(arg) = iter.next() { - if arg == "--" { - delimiter = true; - files.extend(iter.cloned()); - break; - } - if arg == "--launch-profile" || arg == "--profile-root" { - let slot = if arg == "--launch-profile" { &mut selector } else { &mut root }; - if slot.is_some() { - return Err("the profile selector and root must each occur exactly once".into()); - } - let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?; - if value.to_string_lossy().starts_with("--") { - return Err("the profile selector/root needs a value".into()); - } - *slot = Some(value.clone()); - } else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") { - return Err("the nightly protocol requires separate literal selector/root argument tokens".into()); - } else { - other.push(arg.clone()); - } - } - match (selector, root) { - (None, None) => Ok(Launch { profile: Profile::Stable, args }), - (Some(version), Some(root)) if version == VERSION => { - if !delimiter || !other.is_empty() { - return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into()); - } - let root = PathBuf::from(root); - if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) { - return Err("the nightly profile root must be absolute and contain no parent traversal".into()); - } - Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() }) - } - (Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()), - _ => Err("--launch-profile and --profile-root must be supplied together".into()), - } -} - -/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`), -/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never -/// validated or touched, and `-- --version` stays a file name. -pub fn version_query(args: &[OsString]) -> bool { - let Some((last, pair)) = args.split_last() else { return false }; - if last != "--version" && last != "-V" { - return false; - } - let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect(); - matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1) -} - -/// Validation finishes before the caller's first startup effect. Stable never calls the nightly -/// root validator, so its old directory resolution stays unchanged. -pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result) -> Result { - if let Profile::NightlyV1(root) = &launch.profile { - launch.profile = Profile::NightlyV1(validate(root)?); - } - Ok(launch) -} - -/// Resolve the selected private root before the caller's first startup effect. -pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option, exe: Option<&Path>) -> Result { - crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable) +/// Parse startup arguments for `flavor`, validate and prepare the isolated nightly profile root +/// (self-isolating into `craft_nightly::canonical_profile_root("texturecraft")` on direct nightly +/// launches, or using the explicit `--launch-profile nightly-v1 --profile-root ` pair), and +/// install the resolved [`Profile`] into the process-wide `OnceLock`. +pub fn prepare(flavor: BuildFlavor, args: Vec) -> Result { + let spec = crate::profile_root::spec(); + craft_nightly::prepare_launch(flavor, &spec, args, &StartupOptions::new()) } #[cfg(test)] mod tests { use super::*; - use std::cell::Cell; + use std::path::PathBuf; fn args(values: &[&str]) -> Vec { values.iter().map(OsString::from).collect() @@ -130,88 +34,101 @@ mod tests { if cfg!(windows) { r"C:\NightlyData\profiles\texturecraft" } else { "/nightly-data/profiles/texturecraft" } } - fn nightly() -> Vec { - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"]) - } - #[test] - fn stable_arguments_and_directory_policy_are_unchanged() { + fn stable_arguments_are_unchanged_and_nightly_flags_are_refused() { + let spec = crate::profile_root::spec(); for argv in [args(&[]), args(&["model.glb"]), args(&["--gpu", "nvidia"]), args(&["--", "--launch-profile", "model.glb"])] { - let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap(); - assert_eq!(launch, Launch { profile: Profile::Stable, args: argv }); + let launch = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::Stable); + assert_eq!(launch.passthrough_args, argv); } + + let nightly_flags = args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]); + let err = craft_nightly::parse_startup(BuildFlavor::Stable, &spec, nightly_flags, &StartupOptions::new()).unwrap_err(); + assert!(matches!(err, ProfileError::NightlyFlagsInStableBuild)); } #[test] - fn exact_version_and_root_are_parsed_without_reinterpreting_file_names() { - let mut argv = nightly(); - argv.extend(args(&["--profile-root", "model with spaces.glb"])); - let launch = parse(argv).unwrap(); + fn direct_nightly_launch_self_isolates_to_canonical_root_and_preserves_args() { + let spec = crate::profile_root::spec(); + let expected_root = craft_nightly::canonical_profile_root(crate::profile_root::APP_ID).expect("canonical profile root"); + let argv = args(&["model.glb", "--gpu", "nvidia"]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).unwrap(); + assert_eq!(launch.profile, Profile::NightlyV1(expected_root)); + assert!(launch.profile.is_nightly()); + assert_eq!(launch.passthrough_args, argv); + assert!(!launch.is_version_query()); + } + + #[test] + fn explicit_launcher_flags_override_canonical_root_and_preserve_files() { + let spec = crate::profile_root::spec(); + let argv = args(&[ + craft_nightly::LAUNCH_PROFILE_FLAG, + craft_nightly::NIGHTLY_V1_CONTRACT, + craft_nightly::PROFILE_ROOT_FLAG, + absolute(), + "--", + "--profile-root", + "model with spaces.glb", + ]); + + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv, &StartupOptions::new()).unwrap(); assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute()))); - assert_eq!(launch.args, args(&["--", "--profile-root", "model with spaces.glb"])); + assert_eq!(launch.passthrough_args, args(&["--profile-root", "model with spaces.glb"])); } #[test] - fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() { + fn invalid_profile_arguments_are_refused() { + let spec = crate::profile_root::spec(); for argv in [ - args(&["--launch-profile", VERSION]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT]), args(&["--profile-root", absolute()]), args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", "", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]), - args(&["--launch-profile", VERSION, "--profile-root=/nightly-data/profiles/texturecraft", "--"]), + args(&[ + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--launch-profile", + craft_nightly::NIGHTLY_V1_CONTRACT, + "--profile-root", + absolute(), + "--", + ]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]), + args(&["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]), + args(&["--gpu", "nvidia", "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]), ] { - assert!(parse(argv.clone()).is_err(), "{argv:?}"); + assert!(craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::new()).is_err(), "{argv:?}"); } } #[test] - fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() { - let pair = &["--launch-profile", VERSION, "--profile-root", absolute()]; - let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION]; + fn version_queries_are_recognized_plain_and_via_launcher() { + let spec = crate::profile_root::spec(); for flag in ["--version", "-V"] { - for form in [pair, reversed] { - let mut argv = args(form); - argv.push(flag.into()); - assert!(version_query(&argv), "{argv:?}"); + let plain = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&[flag]), &StartupOptions::new()).unwrap(); + assert!(plain.is_version_query(), "plain {flag}"); + + for header in [ + ["--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT, "--profile-root", absolute()], + ["--profile-root", absolute(), "--launch-profile", craft_nightly::NIGHTLY_V1_CONTRACT], + ] { + let mut query = args(&header); + query.push(flag.into()); + assert!( + craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, query, &StartupOptions::new()).unwrap().is_version_query(), + "launcher {flag}" + ); + let mut gpu = args(&header); + gpu.extend(args(&["--gpu", "nvidia", flag])); + let launch = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, gpu, &StartupOptions::new()).unwrap(); + assert!(!launch.is_version_query()); + assert_eq!(launch.passthrough_args, args(&["--gpu", "nvidia", flag])); } } - for argv in [ - args(&["--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--gpu", "nvidia", "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]), - args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]), - args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]), - args(&["--launch-profile", VERSION, "--version"]), - args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]), - ] { - assert!(!version_query(&argv), "{argv:?}"); - } - // Outside the query the strict protocol still refuses the version flag. - assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err()); - } - #[test] - fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() { - let reached = Cell::new(false); - let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true)); - assert!(result.is_err()); - assert!(!reached.get()); - } - - #[test] - fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() { - let checked = PathBuf::from(absolute()).join("checked"); - let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap(); - assert_eq!(launch.profile.root(), Some(checked.as_path())); - assert!(launch.profile.is_nightly()); + let file_named_version = craft_nightly::parse_startup(BuildFlavor::NightlyV1, &spec, args(&["--", "--version"]), &StartupOptions::new()).unwrap(); + assert!(!file_named_version.is_version_query()); } } diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index d3c736c2..95690ba3 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -291,33 +291,31 @@ fn report_launch_profile_error(error: &str) { } } -/// Select the immutable launch profile before any startup service or side effect, and answer the -/// Launcher's version queries before root validation, logging, IPC or a window. `None` means the -/// launch is already answered and the process returns. +/// Select the immutable launch profile before any startup service or side effect, and answer +/// version queries before root validation, logging, IPC or a window. `None` means the launch is +/// already answered and the process returns. fn prepare_launch() -> Option> { let argv: Vec = std::env::args_os().skip(1).collect(); - // Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root - // --version`: both are answered here, with nothing but standard output written. - if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) { + // Plain `--version` / `-V` is answered immediately with nothing but standard output written, + // even in a minimal environment without home/data variables. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && build_flavor::version_query(&argv) { + use std::io::Write as _; + let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); + return None; + } + let early = launch_profile::prepare(build_flavor::COMPILED, argv).unwrap_or_else(|error| { + report_launch_profile_error(&error.to_string()); + std::process::exit(2) + }); + // Launcher's `--launch-profile nightly-v1 --profile-root --version`: `craft-nightly` + // skips root validation and profile installation for version queries. + if build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1 && early.is_version_query() { use std::io::Write as _; let _ = writeln!(std::io::stdout(), "{}", build_flavor::version(build_flavor::COMPILED)); return None; } - let early = launch_profile::parse(argv) - .and_then(|launch| { - build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?; - initialize_nightly_process_identity().map_err(|error| error.to_string())?; - Ok(launch) - }) - .and_then(|launch| { - launch_profile::prepare(launch, |root| launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())) - }) - .unwrap_or_else(|error| { - report_launch_profile_error(&error); - std::process::exit(2) - }); let identity = if early.profile.is_nightly() { LaunchIdentity::NightlyV1 } else { LaunchIdentity::Stable }; - if let Err(error) = launch_profile::install(early.profile).and_then(|()| os_window::select_identity(identity)) { + if let Err(error) = initialize_nightly_process_identity().map_err(|error| error.to_string()).and_then(|()| os_window::select_identity(identity)) { report_launch_profile_error(&error); std::process::exit(2); } @@ -326,7 +324,7 @@ fn prepare_launch() -> Option> { texturecraft_ui_egui::set_data_root(root.clone()); texturecraft_ui_egui::os_window::set_display_version(build_flavor::BUILT_VERSION.to_owned()); } - Some(early.args) + Some(early.passthrough_args) } /// The launch arguments as text. A Nightly protocol argument is a path the app opens, so a value diff --git a/apps/texturecraft/src/profile_root.rs b/apps/texturecraft/src/profile_root.rs index db10fdae..b2c53f2b 100644 --- a/apps/texturecraft/src/profile_root.rs +++ b/apps/texturecraft/src/profile_root.rs @@ -1,567 +1,225 @@ -//! App-owned nightly profile fences; no stable fallback, migration or process environment changes. +//! App-owned nightly profile specification backed by `craft-nightly`. //! -//! A Nightly profile has to hold *all* of its user state: eframe's `app.ron`/`ui.json`, the error -//! log, session logs, autosave copies, smart materials, layouts, templates, brush and export -//! presets. Anything that resolves to a stable folder would read and prune Stable's files, so the -//! root is refused when it overlaps one of them, when an entry inside it is an alias that leaves it, -//! or when it is not writable. +//! A Nightly profile holds *all* of its user state: eframe's `app.ron`/`ui.json`, the error log, +//! session logs, autosave copies, smart materials, layouts, templates, brush and export presets. +//! `craft-nightly` enforces the security fence, symlink/hardlink checks, `0o700` hardening, and +//! writability probe using the TextureCraft-specific boundaries declared here. use std::ffi::OsString; -use std::path::{Component, Path, PathBuf}; +use std::path::PathBuf; -/// The folder names the launch checks use for this app in each platform's location. +use craft_nightly::AppProfileSpec; + +/// Canonical lowercase app identifier used for the default nightly profile path. +pub const APP_ID: &str = "texturecraft"; +/// Human-readable application name and stable folder name. const BRAND: &str = "TextureCraft"; -/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). -const STABLE_ID: &str = "ai.storyteller.texturecraft"; -/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). Inside that -/// sandbox `FLATPAK_ID` is always set, so this exact id is the one a Nightly native launch accepts. -const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// eframe lowercases its folder name on Linux (`file_storage.rs`), so Stable's real settings folder /// is `$XDG_DATA_HOME/texturecraft`, not the capitalised `TextureCraft` the app is called. const LINUX_STORAGE_BRAND: &str = "texturecraft"; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Platform { - Windows, - Linux, - Mac, -} - -impl Platform { - fn current() -> Result { - match std::env::consts::OS { - "windows" => Ok(Self::Windows), - "linux" => Ok(Self::Linux), - "macos" => Ok(Self::Mac), - _ => Err("nightly-v1 is not defined for this operating system".into()), - } - } - - fn ignores_case(self) -> bool { - self != Self::Linux - } -} - -fn absolute(path: PathBuf, label: &str) -> Result { - if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) { - return Err(format!("{label} must be absolute and contain no parent traversal")); - } - Ok(path) -} - -fn required_base(env: &impl Fn(&str) -> Option, key: &str) -> Result { - let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?; - absolute(PathBuf::from(value), key) -} - -fn xdg_base(env: &impl Fn(&str) -> Option, key: &str, fallback: &str) -> Result { - match env(key).filter(|v| !v.is_empty()) { - Some(value) => absolute(PathBuf::from(value), key), - None => Ok(required_base(env, "HOME")?.join(fallback)), - } -} - -/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible ancestor -/// is not a missing directory that may be replaced or followed later. -fn canonical_future(path: &Path) -> Result { - let mut parent = path; - let mut missing = Vec::new(); - loop { - match std::fs::symlink_metadata(parent) { - Ok(_) => break, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - missing.push(parent.file_name().ok_or("the profile root has no existing ancestor")?.to_os_string()); - parent = parent.parent().ok_or("the profile root has no existing ancestor")?; - } - Err(error) => return Err(format!("cannot inspect the profile boundary: {error}")), - } - } - let mut resolved = std::fs::canonicalize(parent).map_err(|e| format!("cannot resolve the profile boundary: {e}"))?; - for part in missing.into_iter().rev() { - resolved.push(part); - } - Ok(resolved) -} - -/// Whether one path is the other or contains it (in either direction), compared component by -/// component and folded the way the platform's filesystem folds names. `TextureCraft2` is not -/// inside `TextureCraft`. -fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool { - let parts = |p: &Path| { - p.components() - .map(|c| { - let value = c.as_os_str().to_string_lossy().into_owned(); - if platform.ignores_case() { value.to_lowercase() } else { value } - }) - .collect::>() - }; - let (a, b) = (parts(a), parts(b)); - a.starts_with(&b) || b.starts_with(&a) -} - -/// The running install: never let the profile live inside it (it would be replaced or removed by -/// the next update). -fn installation_boundary(platform: Platform, exe: &Path) -> Result { - let parent = exe.parent().ok_or("cannot establish the installation boundary")?; - if platform == Platform::Mac { - // A profile in Resources is still inside the versioned bundle, not beside MacOS. - if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) { - return Ok(bundle.to_path_buf()); - } - } - Ok(parent.to_path_buf()) -} - -/// The default data folder, `Documents/TextureCraft`, as the app's own resolver builds it -/// (`crate::data_folder("")`): `USERPROFILE` on Windows and `HOME` elsewhere, then `Documents`. -fn default_data_folder(platform: Platform, env: &impl Fn(&str) -> Option) -> Result { - let home = match platform { - Platform::Windows => required_base(env, "USERPROFILE")?, - _ => required_base(env, "HOME")?, - }; - Ok(home.join("Documents").join(BRAND)) -} - -fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option, exe: &Path) -> Result, String> { - let mut roots = match platform { - Platform::Windows => { - // eframe's settings folder (`%APPDATA%\TextureCraft`), its local counterpart, and the MSI's - // per-machine and any per-user install folders. A custom install folder is covered by the - // executable's own folder below. - let mut roots = ["APPDATA", "LOCALAPPDATA"].into_iter().map(|key| required_base(env, key).map(|p| p.join(BRAND))).collect::, _>>()?; - roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join(BRAND)); - for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { - if let Some(base) = env(key).filter(|v| !v.is_empty()) { - roots.push(absolute(PathBuf::from(base), key)?.join(BRAND)); - } - } - roots - } - Platform::Linux => { - // The four XDG roots carry eframe's settings, caches and state under the app's name. - let mut roots = - [("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")] - .into_iter() - .map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join(BRAND))) - .collect::, _>>()?; - // eframe's own folder for this app on Linux, which is what holds Stable's `app.ron`, - // `ui.json` and `errors.log`: it folds the name, so it is the lowercase one. - roots.push(xdg_base(env, "XDG_DATA_HOME", ".local/share")?.join(LINUX_STORAGE_BRAND)); - roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); - // The stable Flatpak keeps its own per-app data folder. - roots.push(required_base(env, "HOME")?.join(format!(".var/app/{STABLE_ID}"))); - roots - } - Platform::Mac => { - let home = required_base(env, "HOME")?; - let library = home.join("Library"); - vec![ - library.join("Application Support").join(BRAND), - library.join("Caches").join(BRAND), - library.join("Caches").join(STABLE_ID), - library.join("Preferences").join(BRAND), - library.join("Preferences").join(format!("{STABLE_ID}.plist")), - library.join("Saved Application State").join(format!("{STABLE_ID}.savedState")), - home.join("Applications").join(format!("{BRAND}.app")), - PathBuf::from("/Applications").join(format!("{BRAND}.app")), - ] - } - }; - // The user's own documents folder is Stable's default data folder on every platform; a profile - // there would share autosaves, smart materials and presets with it. - roots.push(default_data_folder(platform, env)?); - roots.push(installation_boundary(platform, exe)?); - roots.into_iter().map(|p| canonical_future(&p)).collect() -} - -/// An entry inside the profile must resolve inside it, so a link planted there cannot point -/// 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 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) -} +/// The bundle identifier of the stable package (macOS library folders, the Linux Flatpak). +const STABLE_ID: &str = "ai.storyteller.texturecraft"; +/// The package id of the Nightly Flatpak bundle (`packaging/linux/flatpak-bundle.sh`). +const NIGHTLY_ID: &str = "ai.storyteller.texturecraft.nightly"; /// 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"]; +const PROFILE_FOLDERS: &[&str] = &["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> { - let entries = match std::fs::read_dir(root) { - Ok(entries) => entries, - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), - Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")), - }; - for entry in entries { - let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?; - 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(()) +/// Build TextureCraft's `craft_nightly::AppProfileSpec` from the current process environment. +pub fn spec() -> AppProfileSpec { + spec_with_env(|key| std::env::var_os(key)) } -/// 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()); - } +/// Build TextureCraft's `craft_nightly::AppProfileSpec` using a custom environment lookup. +pub fn spec_with_env(env: impl Fn(&str) -> Option) -> AppProfileSpec { + AppProfileSpec { + app_id: APP_ID, + display_name: BRAND, + stable_dir_names: &[BRAND, LINUX_STORAGE_BRAND], + stable_package_id: STABLE_ID, + nightly_package_id: NIGHTLY_ID, + profile_root_env: None, + forbidden_env_vars: &[], + portable_markers: &[], + folder_only_entries: PROFILE_FOLDERS, + extra_forbidden_roots: extra_forbidden_roots(&env), } - #[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"); - let file = std::fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; - drop(file); - std::fs::remove_file(probe) +fn non_empty_abs_env(env: &impl Fn(&str) -> Option, key: &str) -> Option { + let value = env(key).filter(|v| !v.is_empty())?; + let path = PathBuf::from(value); + path.is_absolute().then_some(path) } -/// Refuse a stable folder, the running install or an alias, create a missing root with owner-only -/// access where the platform has it, and return the resolved root to use. -pub fn validate( - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - validate_for(Platform::current()?, root, env, exe, writable) -} +/// Platform-specific stable data and install roots beyond the OS config/data/cache dirs that +/// `craft-nightly` already fences from `stable_dir_names` and `stable_package_id`. +fn extra_forbidden_roots(env: &impl Fn(&str) -> Option) -> Vec { + let mut roots = Vec::new(); -fn validate_for( - platform: Platform, - root: &Path, - env: impl Fn(&str) -> Option, - exe: Option<&Path>, - writable: impl FnOnce(&Path) -> std::io::Result<()>, -) -> Result { - absolute(root.to_path_buf(), "the nightly profile root")?; - // A native package must not carry another app's Flatpak namespace, and the Nightly bundle must - // be able to start inside its own sandbox, where the runtime always sets `FLATPAK_ID`. Its - // `~/.var/app/` sandbox is separate from stable's, so only other ids are refused. - if platform != Platform::Windows - && let Some(id) = env("FLATPAK_ID").filter(|v| !v.is_empty()) - && id != NIGHTLY_ID + // The user's own Documents folder is Stable's default data folder on every platform; a profile + // there would share autosaves, smart materials and presets with it. + #[cfg(target_os = "windows")] + if let Some(home) = non_empty_abs_env(env, "USERPROFILE") { + roots.push(home.join("Documents").join(BRAND)); + } + #[cfg(not(target_os = "windows"))] + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join("Documents").join(BRAND)); + } + + #[cfg(target_os = "windows")] { - return Err("nightly-v1 only runs inside its own Flatpak; launch through the native Launcher or the Nightly bundle".into()); + if let Some(local) = non_empty_abs_env(env, "LOCALAPPDATA") { + roots.push(local.join("Programs").join("ArtCraft").join(BRAND)); + } + for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] { + if let Some(base) = non_empty_abs_env(env, key) { + roots.push(base.join(BRAND)); + } + } } - let chosen = canonical_future(root)?; - let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?; - let forbidden = forbidden_roots(platform, &env, &exe)?; - if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) { - return Err("the nightly root must not overlap stable data or an installation".into()); - } - // Existing aliases under the profile must not redirect any of its folders elsewhere. - entries_stay_inside(&chosen)?; - let mut create = std::fs::DirBuilder::new(); - create.recursive(true); - #[cfg(unix)] + + #[cfg(target_os = "linux")] { - use std::os::unix::fs::DirBuilderExt as _; - create.mode(0o700); + roots.extend(["/usr/bin/texturecraft", "/usr/local/bin/texturecraft", "/opt/texturecraft"].map(PathBuf::from)); + if let Some(home) = non_empty_abs_env(env, "HOME") { + roots.push(home.join(format!(".var/app/{STABLE_ID}"))); + } } - create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?; - let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?; - if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) { - return Err("the nightly profile changed while it was being validated".into()); + + #[cfg(target_os = "macos")] + { + if let Some(home) = non_empty_abs_env(env, "HOME") { + let library = home.join("Library"); + roots.push(library.join("Preferences").join(format!("{STABLE_ID}.plist"))); + roots.push(library.join("Saved Application State").join(format!("{STABLE_ID}.savedState"))); + roots.push(home.join("Applications").join(format!("{BRAND}.app"))); + } + roots.push(PathBuf::from("/Applications").join(format!("{BRAND}.app"))); } - entries_stay_inside(&confirmed)?; - writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?; - Ok(confirmed) + + roots } #[cfg(test)] mod tests { use super::*; + use craft_nightly::{ProfileError, validate_and_prepare_root}; use std::collections::BTreeMap; + use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; - struct Fixture { - root: PathBuf, - env: BTreeMap, - exe: PathBuf, + struct TempDir { + path: PathBuf, } - impl Fixture { - fn new() -> Self { + impl TempDir { + fn new(label: &str) -> Self { static NEXT: AtomicU64 = AtomicU64::new(0); - let root = loop { - let candidate = - std::env::temp_dir().join(format!("texturecraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let base = std::fs::canonicalize(std::env::temp_dir()).unwrap_or_else(|_| std::env::temp_dir()); + let path = loop { + let candidate = base.join(format!("texturecraft-profile-spec-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); match std::fs::create_dir(&candidate) { - Ok(()) => break std::fs::canonicalize(candidate).unwrap(), + Ok(()) => break candidate, Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => panic!("cannot create owned fixture: {error}"), } }; - let home = root.join("home"); - let exe = root.join("install/texturecraft"); - std::fs::create_dir_all(&home).unwrap(); - std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); - std::fs::write(&exe, b"fixture executable, never run").unwrap(); - let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))] - .into_iter() - .map(|(key, value)| (key.into(), value.into_os_string())) - .collect(); - Self { root, env, exe } + Self { path } } - fn get(&self, key: &str) -> Option { - self.env.get(key).cloned() - } - - fn check(&self, platform: Platform, root: &Path) -> Result { - validate_for(platform, root, |key| self.get(key), Some(&self.exe), ensure_writable) - } - - fn home(&self) -> PathBuf { - PathBuf::from(self.get("HOME").unwrap()) - } - - fn profile(&self, name: &str) -> PathBuf { - self.root.join("profiles").join(name) + fn path(&self) -> &Path { + &self.path } } - impl Drop for Fixture { + impl Drop for TempDir { fn drop(&mut self) { - // Only the directory this fixture created is owned for removal. - std::fs::remove_dir_all(&self.root).unwrap(); + let _ = std::fs::remove_dir_all(&self.path); } } #[test] - fn a_fresh_private_profile_is_created_and_returned_resolved() { - let fixture = Fixture::new(); - let profile = fixture.profile("nightly"); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - assert_eq!(fixture.check(platform, &profile).unwrap(), profile); - assert!(profile.is_dir()); - std::fs::remove_dir_all(&profile).ok(); + fn spec_declares_texturecraft_ids_folders_and_extra_forbidden_roots() { + let tmp = TempDir::new("spec"); + let home = tmp.path().join("home"); + let mut env = BTreeMap::new(); + env.insert("HOME", home.clone().into_os_string()); + env.insert("USERPROFILE", home.clone().into_os_string()); + env.insert("LOCALAPPDATA", tmp.path().join("local").into_os_string()); + env.insert("ProgramFiles", tmp.path().join("Program Files").into_os_string()); + + let spec = spec_with_env(|key| env.get(key).cloned()); + assert_eq!(spec.app_id, "texturecraft"); + assert_eq!(spec.display_name, "TextureCraft"); + assert_eq!(spec.stable_dir_names, &["TextureCraft", "texturecraft"]); + assert_eq!(spec.stable_package_id, "ai.storyteller.texturecraft"); + assert_eq!(spec.nightly_package_id, "ai.storyteller.texturecraft.nightly"); + assert_eq!(spec.profile_root_env, None); + assert!(spec.forbidden_env_vars.is_empty()); + assert!(spec.portable_markers.is_empty()); + assert_eq!(spec.folder_only_entries, PROFILE_FOLDERS); + assert!(spec.extra_forbidden_roots.contains(&home.join("Documents").join(BRAND))); + + #[cfg(target_os = "linux")] + { + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/usr/bin/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from("/opt/texturecraft"))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!(".var/app/{STABLE_ID}")))); + } + #[cfg(target_os = "macos")] + { + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Preferences/{STABLE_ID}.plist")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Library/Saved Application State/{STABLE_ID}.savedState")))); + assert!(spec.extra_forbidden_roots.contains(&home.join(format!("Applications/{BRAND}.app")))); + assert!(spec.extra_forbidden_roots.contains(&PathBuf::from(format!("/Applications/{BRAND}.app")))); + } + #[cfg(target_os = "windows")] + { + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("local/Programs/ArtCraft").join(BRAND))); + assert!(spec.extra_forbidden_roots.contains(&tmp.path().join("Program Files").join(BRAND))); } } #[test] - fn every_stable_data_folder_of_each_platform_is_refused_before_any_probe() { - let fixture = Fixture::new(); - let home = fixture.home(); - let candidates: Vec<(Platform, PathBuf)> = vec![ - (Platform::Windows, PathBuf::from(fixture.get("APPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join(BRAND)), - (Platform::Windows, PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft").join(BRAND)), - (Platform::Windows, home.join("Documents").join(BRAND)), - (Platform::Linux, home.join(".config").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(BRAND)), - (Platform::Linux, home.join(".local/share").join(LINUX_STORAGE_BRAND)), - (Platform::Linux, home.join(".cache").join(BRAND)), - (Platform::Linux, home.join(".local/state").join(BRAND)), - (Platform::Linux, home.join("Documents").join(BRAND)), - (Platform::Linux, PathBuf::from("/usr/bin/texturecraft")), - (Platform::Linux, PathBuf::from("/opt/texturecraft")), - (Platform::Linux, home.join(format!(".var/app/{STABLE_ID}"))), - (Platform::Mac, home.join("Library/Application Support").join(BRAND)), - (Platform::Mac, home.join("Library/Caches").join(BRAND)), - (Platform::Mac, home.join("Library/Preferences").join(format!("{STABLE_ID}.plist"))), - (Platform::Mac, home.join("Library/Saved Application State").join(format!("{STABLE_ID}.savedState"))), - (Platform::Mac, home.join("Documents").join(BRAND)), - (Platform::Mac, PathBuf::from(format!("/Applications/{BRAND}.app"))), - ]; - for (platform, stable) in candidates { - for candidate in [stable.clone(), stable.join("nested nightly")] { - let probed = std::cell::Cell::new(false); - let result = validate_for( - platform, - &candidate, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - probed.set(true); - Ok(()) - }, - ); - assert!(result.is_err(), "{platform:?} accepted {}", candidate.display()); - assert!(!probed.get(), "a refused root must not be probed: {}", candidate.display()); - } + fn nightly_profile_reopens_and_enforces_folder_only_entries() { + let tmp = TempDir::new("reopen"); + let private = tmp.path().join("nightly-profile"); + let spec = spec_with_env(|_| None); + + let canonical = validate_and_prepare_root(&private, &spec).expect("fresh private profile"); + assert_eq!(canonical, 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!(validate_and_prepare_root(&private, &spec).expect("reopen populated profile"), private); + for name in ["app.ron", "ui.json", "errors.log", "nightly-session.lock", "nightly-session.json"] { + assert_eq!(std::fs::read(private.join(name)).unwrap(), b"saved profile data", "{name} remains intact after reopen"); + } + + 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!(matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))), "{name} must stay a directory"); + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); } } #[test] - fn the_running_install_is_fenced_on_every_platform() { - let fixture = Fixture::new(); - for platform in [Platform::Windows, Platform::Linux, Platform::Mac] { - let inside = fixture.exe.parent().unwrap().join("profile"); - assert!(fixture.check(platform, &inside).is_err(), "{platform:?} let the profile inside the install"); - } - } + fn documents_data_folder_is_refused() { + let tmp = TempDir::new("documents"); + let home = tmp.path().join("home"); + let documents_stable = home.join("Documents").join(BRAND); + let spec = spec_with_env(|key| matches!(key, "HOME" | "USERPROFILE").then(|| home.clone().into_os_string())); - #[test] - fn lookalike_names_are_not_overlaps_but_case_folding_is() { - let fixture = Fixture::new(); - let documents = fixture.home().join("Documents"); - assert!(fixture.check(Platform::Linux, &documents.join("TextureCraft2")).is_ok(), "a neighbor with a suffix is a different folder"); - assert!(fixture.check(Platform::Linux, &documents.join("texturecraft")).is_ok(), "Linux folds names exactly"); - for platform in [Platform::Windows, Platform::Mac] { - assert!(fixture.check(platform, &documents.join("texturecraft")).is_err(), "{platform:?} must fold case"); - } - } - - #[test] - fn relative_parent_traversal_and_empty_roots_are_refused() { - let fixture = Fixture::new(); - for root in [PathBuf::from("relative/profile"), PathBuf::from("/nightly/../stable"), PathBuf::from("")] { - assert!(fixture.check(Platform::Linux, &root).is_err(), "{}", root.display()); - } - } - - #[test] - fn only_the_nightly_flatpak_may_start_with_its_own_id() { - let fixture = Fixture::new(); - let profile = fixture.profile("flatpak"); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - std::fs::remove_dir_all(&profile).ok(); - let check_with = |id: &str, candidate: &Path| { - let id = OsString::from(id); - validate_for( - Platform::Linux, - candidate, - |key| if key == "FLATPAK_ID" { Some(id.clone()) } else { fixture.get(key) }, - Some(&fixture.exe), - ensure_writable, - ) - }; - // Stable's id, its window id and an unrelated app's id are all refusals. - for id in [STABLE_ID, "ai.storyteller.texturecraft.nightly-v1", "org.example.other"] { - assert!(check_with(id, &profile).is_err(), "{id} was accepted"); - } - // The Nightly bundle's own id is the sandbox the Nightly package runs in: accepted, with the - // profile its wrapper names inside it (`${XDG_DATA_HOME}/TextureCraft-Nightly`). - let sandbox = fixture.home().join(format!(".var/app/{NIGHTLY_ID}")); - let sandboxed = sandbox.join(".local/share/TextureCraft-Nightly"); - assert_eq!(check_with(NIGHTLY_ID, &sandboxed).expect("the Nightly Flatpak may start"), sandboxed); - std::fs::remove_dir_all(&sandbox).ok(); - } - - #[test] - #[cfg(unix)] - fn an_entry_that_leaves_the_profile_is_refused() { - let fixture = Fixture::new(); - let profile = fixture.profile("aliased"); - let outside = fixture.root.join("somewhere else"); - std::fs::create_dir_all(&profile).unwrap(); - std::fs::create_dir_all(&outside).unwrap(); - std::os::unix::fs::symlink(&outside, profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err(), "a link out of the profile must be refused"); - // A dangling link is not a missing folder that may be created. - std::fs::remove_file(profile.join("autosave")).unwrap(); - std::os::unix::fs::symlink(profile.join("missing"), profile.join("logs")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_err()); - std::fs::remove_file(profile.join("logs")).unwrap(); - // A plain folder inside it is fine. - std::fs::create_dir(profile.join("autosave")).unwrap(); - assert!(fixture.check(Platform::Linux, &profile).is_ok()); - } - - #[test] - fn a_failed_write_probe_never_falls_back_to_stable() { - let fixture = Fixture::new(); - let profile = fixture.profile("read only"); - let reached = std::cell::Cell::new(false); - let result = validate_for( - Platform::Linux, - &profile, - |key| fixture.get(key), - Some(&fixture.exe), - |_| { - reached.set(true); - Err(std::io::Error::other("read-only filesystem")) - }, - ); - assert!(result.is_err()); - assert!(reached.get()); - assert!(result.unwrap_err().contains("not writable")); - // The app must not then use the stable folder: it simply refuses to start. - 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() { - let fixture = Fixture::new(); - let real = fixture.root.join("real profiles"); - std::fs::create_dir_all(&real).unwrap(); - let link = fixture.root.join("linked"); - std::os::unix::fs::symlink(&real, &link).unwrap(); - // A link to a private folder is fine, and the resolved root is what the app uses. - let resolved = fixture.check(Platform::Linux, &link.join("nightly")).unwrap(); - assert_eq!(resolved, real.join("nightly")); + assert!(matches!(validate_and_prepare_root(&documents_stable, &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); + assert!(matches!(validate_and_prepare_root(&documents_stable.join("nested"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. }))); } } diff --git a/crates/automation/build.rs b/crates/automation/build.rs deleted file mode 100644 index 565782f6..00000000 --- a/crates/automation/build.rs +++ /dev/null @@ -1,17 +0,0 @@ -//! Test executables of this crate on Windows (MSVC) reserve 8 MiB for each thread that does not -//! ask for a stack size of its own, as texturecraft-render's do: the tests render through -//! texturecraft-render on Mesa's lavapipe on the Windows CI gate, whose shader threads get the -//! executable's default of 1 MiB there and overflow it on the larger programs (Linux gives them -//! 8 MiB). This library crate links no other executable. - -/// Bytes each thread reserves for its stack when it asks for none. -const THREAD_STACK_RESERVE: u32 = 8 * 1024 * 1024; - -fn main() { - println!("cargo:rerun-if-changed=build.rs"); - let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(); - if target_os == "windows" && target_env == "msvc" { - println!("cargo:rustc-link-arg=/STACK:{THREAD_STACK_RESERVE}"); - } -} 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 313c5858..11d6b2c2 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); @@ -166,7 +168,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)); @@ -201,10 +210,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) @@ -216,13 +230,7 @@ mod tests { use super::*; use serde_json::json; use texturecraft_engine::execute; - - /// One GPU test at a time: the NVIDIA driver (620.70) can deadlock when one test's device is - /// destroyed while another test records commands on its own device. - fn gpu_lock() -> std::sync::MutexGuard<'static, ()> { - static GPU: std::sync::Mutex<()> = std::sync::Mutex::new(()); - GPU.lock().unwrap_or_else(std::sync::PoisonError::into_inner) - } + use texturecraft_render::headless::TestGpuTurn; /// A 64×32 Radiance `.hdr` (flat RGBE scanlines): a hot orange sky over a dim blue ground. fn sky_hdr() -> Vec { @@ -245,11 +253,12 @@ mod tests { let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap(); let name = s.import_resource_bytes("sky.hdr", sky_hdr()).unwrap(); assert!(s.images[&name].rgba[0][0] > 10.0, "the decoder keeps HDR values"); - let _gpu = gpu_lock(); + let _turn = TestGpuTurn::take(); let Ok(mut gpu) = Gpu::new() else { eprintln!("skipping: no GPU adapter"); return; }; + let cam = s.camera; let (_, _, base) = gpu.render(&mut s, ViewKind::Scene, [160, 120], cam).unwrap(); execute(&mut s, "display.set", &json!({"environment": format!("resource:{name}"), "specGloss": true, "parallax": true})).unwrap(); @@ -264,7 +273,7 @@ mod tests { let mut session = Session::new_project("Test", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); session.doc.project.display.taa = false; let name = session.import_resource_bytes("sky.hdr", sky_hdr()).unwrap(); - let _gpu = gpu_lock(); + let _turn = TestGpuTurn::take(); let Ok(mut gpu) = Gpu::new() else { eprintln!("skipping: no GPU adapter"); return; @@ -296,7 +305,7 @@ mod tests { execute(&mut session, "viewport.view", &json!({"mode": "image", "image": "red"})).unwrap(); let camera = session.camera; let uv = |ts| ViewKind::Uv { ts, zoom: 1.0, pan: [0.0, 0.0], rotation: 0.0 }; - let _gpu = gpu_lock(); + let _turn = TestGpuTurn::take(); let Ok(mut gpu) = Gpu::new() else { eprintln!("skipping: no GPU adapter"); return; @@ -320,11 +329,12 @@ mod tests { let mesh = texturecraft_engine::geom::primitives::material_ball(); let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap(); execute(&mut s, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23], "roughness": 0.3, "metallic": 0.4})).unwrap(); - let _gpu = gpu_lock(); + let _turn = TestGpuTurn::take(); let Ok(mut gpu) = Gpu::new() else { eprintln!("skipping: no GPU adapter"); return; }; + let (cam, settings, size) = (s.camera, TraceSettings { bounces: 4 }, [64, 48]); let g = match gpu.path_trace(&mut s, size, cam, 384, &settings) { Ok((_, _, px)) => px, @@ -334,7 +344,8 @@ mod tests { } }; let (_, _, c) = path_trace(&mut s, size, cam, 384, &settings); - // Mean luminance per 8×8 block (8-bit levels) agrees. + + // Block averages absorb the expected variation between individual traced samples let lum = |img: &[u8], x: usize, y: usize| { let p = &img[(y * 64 + x) * 4..(y * 64 + x) * 4 + 3]; 0.2126 * p[0] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[2] as f32 @@ -354,7 +365,7 @@ mod tests { // Atlas UV 0.75 is the middle of tile 1002 execute(&mut s, "tool.strokeUv", &json!({"points": [[0.75, 0.5]]})).unwrap(); - let _gpu = gpu_lock(); + let _turn = TestGpuTurn::take(); let Ok(mut gpu) = Gpu::new() else { eprintln!("skipping: no GPU adapter"); return; 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/bake/src/map/source.rs b/crates/bake/src/map/source.rs index c5cd5f3f..cc2ffbc0 100644 --- a/crates/bake/src/map/source.rs +++ b/crates/bake/src/map/source.rs @@ -123,6 +123,8 @@ impl<'a> Source<'a> { } } +/// The material's base colour at `uv` (bilinear, wrapping), sRGB RGBA times its factor; white +/// where there is no texture or the UV is not finite. fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { let sampled_color = if material.texels.is_empty() || !uv.is_finite() { Vec4::ONE @@ -134,11 +136,31 @@ fn base_color(material: &BaseColor, uv: Vec2) -> Vec4 { Vec4::new(srgb_to_linear(color(0)), srgb_to_linear(color(1)), srgb_to_linear(color(2)), color(3)) }; let (fx, fy) = (uv.x * width as f32 - 0.5, uv.y * height as f32 - 0.5); - let (x0, y0) = (fx.floor(), fy.floor()); - let (tx, ty) = (fx - x0, fy - y0); - let (x, y) = (x0 as i64, y0 as i64); - texel(x, y).lerp(texel(x + 1, y), tx).lerp(texel(x, y + 1).lerp(texel(x + 1, y + 1), tx), ty) + if fx.is_finite() && fy.is_finite() { + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let (x, y) = (x0 as i64, y0 as i64); + let (x1, y1) = (x.saturating_add(1), y.saturating_add(1)); + texel(x, y).lerp(texel(x1, y), tx).lerp(texel(x, y1).lerp(texel(x1, y1), tx), ty) + } else { + Vec4::ONE + } }; let color = sampled_color * material.factor; Vec4::new(linear_to_srgb(color.x), linear_to_srgb(color.y), linear_to_srgb(color.z), color.w) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Sampling at huge but finite UVs returns a finite colour instead of overflowing. + #[test] + fn base_color_sampling_survives_huge_finite_uvs() { + let material = BaseColor { factor: Vec4::ONE, width: 2, height: 2, texels: vec![[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255; 4]] }; + for uv in [Vec2::new(1.0e30, 0.5), Vec2::new(0.5, -1.0e30), Vec2::splat(f32::MAX), Vec2::splat(1.0e6)] { + let c = base_color(&material, uv); + assert!(c.is_finite(), "{uv}: {c}"); + } + } +} diff --git a/crates/compose/src/below.rs b/crates/compose/src/below.rs index 9f5abdcf..7926b39c 100644 --- a/crates/compose/src/below.rs +++ b/crates/compose/src/below.rs @@ -240,10 +240,11 @@ impl StackKey { continue; } - // Unchanged resampled instances do not constrain the grid of another target. + // Unchanged resampled instances do not constrain the grid of another target if (left_image.width(), left_image.height()) != size { return None; } + let target = if left_channel.is_some() { PaintTarget::Layer(*left_id) } else { PaintTarget::Mask(*left_id) }; for tile_y in 0..left_image.tiles_y() { for tile_x in 0..left_image.tiles_x() { 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 35089842..265f6315 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,26 +110,28 @@ 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 { - encode_tile(composite, baked, kind, tx, ty, 0) +/// Tile bytes (`TILE × TILE`, row-major) for `kind`, mixing baked occlusion by `ao_mixing` and using channel defaults for absent source tiles. +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32) -> Vec { + encode_tile(composite, baked, ao_mixing, kind, tx, ty, 0) } /// Pack only the samples the viewport uses at a reduced display resolution. -pub fn display_tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec { +pub fn display_tile_bytes(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec { if shift == 0 { - return tile_bytes(composite, baked, kind, tx, ty); + return tile_bytes(composite, baked, ao_mixing, kind, tx, ty); } - encode_tile(composite, baked, kind, tx, ty, shift.min(TILE.ilog2())) + + encode_tile(composite, baked, ao_mixing, kind, tx, ty, shift.min(TILE.ilog2())) } -// Specialize the full-resolution entry point so its hot loops retain contiguous indexing. +// Specialize the full-resolution entry point so its hot loops retain contiguous indexing #[inline(always)] -fn encode_tile(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec { +fn encode_tile(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, kind: DisplayKind, tx: u32, ty: u32, shift: u32) -> Vec { let bytes_per_texel = kind.bytes_per_texel(); let area = TILE_AREA >> (2 * shift); let mut out = vec![0u8; area * bytes_per_texel]; - // Downscaling uses the top-left sample at each stride, matching the viewport upload. + + // Downscaling uses the top-left sample at each stride, matching the viewport upload let source = |offset: usize| { let side = TILE as usize >> shift; let row = offset >> (TILE.ilog2() - shift); @@ -208,9 +210,12 @@ fn encode_tile(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: for offset in 0..area { let i = source(offset); 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[offset * 4..offset * 4 + 4]; @@ -290,7 +295,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:?}"); } } } @@ -301,7 +306,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]); @@ -315,7 +320,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)); @@ -324,20 +329,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"); } @@ -366,7 +379,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()) } @@ -401,11 +414,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); @@ -429,7 +442,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 fd0922c2..69178417 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -4,6 +4,7 @@ mod draw_placement; mod evaluation_inputs; +mod layers_at; pub(crate) mod thumbnail; use std::borrow::Cow; @@ -12,16 +13,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}; @@ -33,6 +34,7 @@ use crate::fill_copies::FillCopies; use crate::fill_copy::FillCopy; use crate::fill_depth::FillDepth; use crate::fill_place::FillPlace; +use crate::flatten_folder_error::FlattenFolderError; use crate::generator_maps::GeneratorMaps; use crate::held_fields::HeldFields; use crate::mask_gray::MaskGray; @@ -52,6 +54,7 @@ use crate::wear; use crate::wear_inputs::WearInputs; use draw_placement::DrawPlacement; use evaluation_inputs::EvaluationInputs; +pub use layers_at::layers_at; const NCH: usize = Channel::ALL.len(); @@ -67,6 +70,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 +88,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 +204,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 +477,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 +537,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 +570,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 @@ -586,28 +628,31 @@ pub fn painted_tile_margin(project: &Project, ts: usize, target: PaintTarget) -> let (PaintTarget::Layer(id) | PaintTarget::Mask(id)) = target; let owner = project.effect(id).map_or(id, |(owner, _)| owner); let mut max_reach = 0; + for layer in project.render_tree(&set.stack).iter().filter_map(|id| project.layers.get(id)) { - // Anchor reads, Compare masks and lighting by the layer's material (its other channels - // over the stack below) read the stack below at the same texel + // Anchors, Compare masks and material lighting can read the stack below let lit = layer.content_effects.iter().any(|effect| effect.visible && lights_material(&effect.kind)); if layer.reads_stack() || lit { return (!stack_reads_neighbours(project, ts)).then_some(0); } + if owner == layer.id { let effects = match target { PaintTarget::Layer(_) => layer.content_effects.as_slice(), PaintTarget::Mask(_) => layer.mask.as_ref().map_or(&[][..], |mask| mask.effects.as_slice()), }; - // A wrapping filter reads past the set's edges from the far side: an edit near one - // edge changes the opposite one, which no margin around the edit holds + + // A local halo cannot include the opposite edge read by a wrapping filter if neighbourhood_filters(effects, resolution, None).any(|(index, _, _)| wraps(effects, index)) { return None; } + max_reach = neighbourhood_filters(effects, resolution, None) .map(|(_, radius, op)| filter_reach(radius, op, width.max(height), width.max(height)).1) .fold(0u32, u32::saturating_add); } } + Some(max_reach.div_ceil(TILE)) } @@ -806,15 +851,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); @@ -955,21 +1000,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; @@ -1199,21 +1241,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 }; @@ -1227,30 +1262,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; } @@ -1265,7 +1305,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; @@ -1274,7 +1314,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; } @@ -1420,6 +1460,17 @@ fn below_plan<'a>( return Vec::new(); } + stack_plan_below(inp, draw, channels, (tile_x, tile_y), fields) +} + +/// Plan the whole stack up to a draw, whatever the draw reads +fn stack_plan_below<'a>( + inp: &EvaluationInputs<'a>, + draw: (LayerId, usize), + channels: &[Channel], + (tile_x, tile_y): (u32, u32), + fields: Option<&'a Fields>, +) -> Vec> { let Ok(set) = inp.project.texture_set(inp.ts) else { return Vec::new() }; let compare_effects = layer_mask(inp.project, draw.0).into_iter().flat_map(|mask| mask.effects.iter()); let planned = compared_channels(compare_effects, channels.to_vec()); @@ -1631,16 +1682,22 @@ 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); - filter_reach(radius, op, longest_side, inputs.tile_grid().map_or(longest_side, |_| inputs.tile_res())) + let block_reach = inputs.block_size().into_iter().max().unwrap_or(longest_side); + filter_reach(radius, op, longest_side, block_reach) } -/// [`filter_extent`] for a set whose longest side is `longest_side`, where a repeated sampled source can reach `tile_reach` texels -fn filter_reach(radius: f32, op: Op, longest_side: u32, tile_reach: u32) -> (u32, u32) { +/// [`filter_extent`] for a set whose longest side is `longest_side`, where a repeated sampled source can reach `block_reach` texels +fn filter_reach(radius: f32, op: Op, longest_side: u32, block_reach: u32) -> (u32, u32) { // 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(block_reach), + _ 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 { @@ -1655,7 +1712,7 @@ fn filter_reach(radius: f32, op: Op, longest_side: u32, tile_reach: u32) -> (u32 _ => None, }; let source_reach = - if tiled_source.is_some_and(|source| source.mode != WarpSourceMode::DefaultNoise && source.tiling_factor() != 1.0) { tile_reach } else { 0 }; + if tiled_source.is_some_and(|source| source.mode != WarpSourceMode::DefaultNoise && source.tiling_factor() != 1.0) { block_reach } else { 0 }; (radius_texels, (reach + moved).max(source_reach)) } @@ -1862,7 +1919,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 { @@ -1875,7 +1932,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), @@ -3054,6 +3111,7 @@ fn takes_symmetry(proj: &Projection, sampling: Sampling) -> bool { } /// Per-texel context. +#[derive(Clone)] struct Texel<'a, 'b> { inp: &'b Inputs<'a>, x: u32, @@ -3075,10 +3133,13 @@ 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 /// (`Off`), evaluated and recorded, or replayed from a recording. +#[derive(Clone)] enum Tape<'t> { Off, Record(Vec), @@ -3110,7 +3171,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. @@ -3253,6 +3329,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 { @@ -3346,9 +3440,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) }; @@ -3413,11 +3509,20 @@ impl<'a, 'b> Texel<'a, 'b> { #[inline(always)] fn fill_texel(&mut self, place: FillPlace, source: Option<&Source>, ch: Channel) -> ([f32; 3], f32) { let FillPlace { fill, projection, depth, covers_all } = place; + let sampling = fill.sampling; + let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, sampling, depth) }; + if let Some(Source::Image { name, normal_format }) = source + && sampling.alpha_coverage + && cover > 0.0 + { + let (value, alpha) = self.image_value::(name, *normal_format, projection, sampling, ch.kind()); + return (value, cover * alpha); + } + let value = match source { - Some(source) => self.source(source, projection, fill.sampling, ch.kind()), + Some(source) => self.source(source, projection, sampling, ch.kind()), None => ch.default_value(), }; - let cover = if covers_all { 1.0 } else { self.cover(fill.sources.values(), projection, fill.sampling, depth) }; (value, cover) } @@ -3449,7 +3554,8 @@ impl<'a, 'b> Texel<'a, 'b> { }; let (coords, cover) = self.projected(proj); - if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha { + // With per-channel alpha the caller applies image coverage + if projector.crop == ShapeCrop::ExtendsOutside || projector.ignore_image_alpha || sampling.alpha_coverage { return cover * self.tile_cover(proj, &coords, sampling); } @@ -3526,49 +3632,61 @@ impl<'a, 'b> Texel<'a, 'b> { mix3(*low, *high, amount) } } - Source::Image { name, normal_format } => { - let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; - - let (coords, _) = self.projected(projection); - let samples = self.image_uvs(projection, &coords); - let footprints = match sampling.filtering { - Filtering::BilinearHq => self.footprints(projection, &samples, image), - Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], - }; - - // Blend projected planes in the same space when any of them reads a linear mip - let is_srgb_color = kind == ChannelKind::Color && image.srgb; - let planes = samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0); - let blend_linear = is_srgb_color && planes.clone().any(|(_, footprint)| crate::store::uses_mips(footprint)); - let mut rgb = [0.0; 3]; - for ((uv, weight), footprint) in planes { - let sampled = if blend_linear { - image.sample_srgb_color(uv.x, uv.y, sampling, footprint) - } else { - image.sample_filtered(uv.x, uv.y, sampling, footprint) - }; - - for (total, value) in rgb.iter_mut().zip(sampled) { - *total += value * weight; - } - } - - match kind { - ChannelKind::Color if is_srgb_color && !blend_linear => rgb.map(texturecraft_texel::srgb_to_linear), - - // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips - ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], - ChannelKind::Color | ChannelKind::NormalMap => rgb, - - // A one-value channel or mask reads the image's gray, so a color image works as a mask - ChannelKind::Scalar => [lum(rgb); 3], - ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], - } - } + Source::Image { name, normal_format } => self.image_value::(name, *normal_format, projection, sampling, kind).0, Source::Anchor { anchor, channel, .. } => self.anchor_value(*anchor, *channel, kind), } } + /// Sample the image through the projection and interpret its color for the requested channel. + fn image_value( + &mut self, + name: &str, + normal_format: NormalFormat, + projection: &Projection, + sampling: Sampling, + kind: ChannelKind, + ) -> ([f32; 3], f32) { + let Some(image) = self.inp.images.get(name) else { return ([0.5; 3], 0.0) }; + + let (coords, _) = self.projected(projection); + let samples = self.image_uvs(projection, &coords); + let footprints = match sampling.filtering { + Filtering::BilinearHq => self.footprints(projection, &samples, image), + Filtering::BilinearSharp | Filtering::Nearest => [1.0; 3], + }; + + // Blend projected planes in the same space when any of them reads a linear mip + let is_srgb_color = kind == ChannelKind::Color && image.srgb; + let planes = samples.into_iter().zip(footprints).filter(|((_, weight), _)| *weight > 0.0); + let blend_linear = is_srgb_color && planes.clone().any(|(_, footprint)| crate::store::uses_mips(footprint)); + let mut rgb = [0.0; 3]; + let mut alpha = 0.0; + for ((uv, weight), footprint) in planes { + let sampled = + if blend_linear { image.sample_srgb_color(uv.x, uv.y, sampling, footprint) } else { image.sample_filtered(uv.x, uv.y, sampling, footprint) }; + + for (total, value) in rgb.iter_mut().zip(sampled) { + *total += value * weight; + } + if WITH_ALPHA { + alpha += sampled[3] * weight; + } + } + + let value = match kind { + ChannelKind::Color if is_srgb_color && !blend_linear => rgb.map(texturecraft_texel::srgb_to_linear), + + // Normal channels are OpenGL so a DirectX image's green flips + ChannelKind::NormalMap if normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], + ChannelKind::Color | ChannelKind::NormalMap => rgb, + + // Scalar and signed channels read the image's luminance + ChannelKind::Scalar => [lum(rgb); 3], + ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], + }; + (value, alpha.clamp(0.0, 1.0)) + } + /// The value anchor point `anchor` recorded for `channel`, read as `kind` (colors read as gray /// where a scalar is needed). An anchor not evaluated yet (above this layer, hidden) reads the /// channel default. @@ -3957,7 +4075,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; @@ -3975,10 +4093,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; @@ -3992,6 +4119,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; @@ -4331,65 +4459,69 @@ 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 { - // As the commit erases: every painted channel, or the listed ones when any are - if p.values.is_empty() || Channel::ALL.get(c.ch).is_some_and(|ch| p.values.contains_key(ch)) { - val = val.map(|v| v * (1.0 - sa)); - cov *= 1.0 - sa; + if stroke.erase { + // Match the commit, which erases every painted channel when none are listed + if stroke.values.is_empty() || Channel::ALL.get(chan_plan.ch).is_some_and(|channel| stroke.values.contains_key(channel)) { + value = value.map(|component| component * (1.0 - stroke_alpha)); + coverage *= 1.0 - stroke_alpha; } - } else if let Some(ch) = Channel::ALL.get(c.ch) - && let Some(pval) = p.values.get(ch) + } 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 @@ -4735,13 +4867,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); @@ -4830,7 +4964,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) { @@ -4847,20 +4981,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(); @@ -4908,6 +5048,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 @@ -4937,37 +5079,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); @@ -4975,24 +5122,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)); } } @@ -5550,6 +5698,149 @@ pub fn lit_by_environment(project: &Project, texture_set_index: usize) -> bool { project.texture_set(texture_set_index).is_ok_and(|set| uses_environment(project, &set.stack, 0)) } +/// The premultiplied value and coverage (last) of a Normal layer that shows `shown` over `under`, covering at least `coverage`, with straight values inside `range` (Multiply or Overlay hide each component by a different amount, so the coverage grows where a straight value would leave it); None where it shows the stack as it is +fn normal_over(under: &[f32; 3], shown: &[f32; 3], coverage: f32, comps: usize, (low, high): (f32, f32)) -> Option<[f32; 4]> { + let needed = under.iter().zip(shown).take(comps).fold(coverage, |needed, (under, shown)| { + let change = shown - under; + let room = if change > 0.0 { high - under } else { under - low }; + if change.abs() <= f32::EPSILON || room <= 0.0 { needed } else { needed.max(change.abs() / room) } + }); + let coverage = needed.min(1.0); + if coverage <= 0.0 { + return None; + } + + // Over `under`, the layer shows its premultiplied value plus what it leaves of the stack + let mut premultiplied = [0.0, 0.0, 0.0, coverage]; + for ((slot, under), shown) in premultiplied.iter_mut().zip(under).zip(shown).take(comps) { + *slot = shown - (1.0 - coverage) * under; + } + Some(premultiplied) +} + +/// One tile of a flattened folder's mask: (tile, mask value + coverage data) +pub type FlatMaskTile = ((u32, u32), Vec); + +/// How far past its channel's range a folder's result may sit as rounding noise +const RANGE_TOLERANCE: f32 = 1e-3; + +/// A flattened folder: its content tiles and its mask tiles +pub type FlattenedFolder = (Vec, Vec); + +/// Flatten folder `id`: what its visible layers lay down (premultiplied value and coverage tiles per enabled channel and per channel a mask compares, as [`flatten_layer`]) without its mask or opacity, and its mask and submesh limits as mask tiles (none when it has neither) +pub fn flatten_folder(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Result { + let set = inputs.project.texture_set(inputs.ts).map_err(|_| FlattenFolderError::NotAFolder)?; + if !inputs.project.content_layer(id).is_some_and(Layer::is_group) { + return Err(FlattenFolderError::NotAFolder); + } + + // Force visibility so hidden folders can be flattened + let mut forced_visible = inputs.project.clone(); + if let Some(layer) = forced_visible.layers.get_mut(&id) { + layer.visible = true; + } + let visible_inputs = Inputs { project: &forced_visible, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let projectors = ProjectorDepthCache::default(); + let mut visible_inputs = EvaluationInputs::new(&visible_inputs, &projectors); + prepare_generators(&mut visible_inputs, Some(id)); + let planned_channels = evaluation_channels(&visible_inputs, set.channel_list()); + let fields = evaluation_fields(&visible_inputs, &planned_channels, tiles); + + // None for a tile where the folder's result leaves the range its image can hold + let out: Option, Option)>> = tiles + .par_iter() + .map(|&(tx, ty)| { + let nodes = plan(&visible_inputs, &[id], &planned_channels, tx, ty, 0, Some(&fields)); + let Some(node) = nodes.first() else { return Some((Vec::new(), None)) }; + let Content::Group(children) = &node.content else { return Some((Vec::new(), None)) }; + + let below = stack_plan_below(&visible_inputs, (id, 0), &planned_channels, (tx, ty), Some(&fields)); + + // Initialize signed channels at encoded zero + let mut buffers: Vec<(Channel, Vec, bool)> = node + .chans + .iter() + .filter_map(|planned| Channel::ALL.get(planned.ch).map(|channel| (*channel, vec![0u16; TILE_AREA * (planned.comps + 1)], false))) + .collect(); + for (channel, buffer, _) in &mut buffers { + if channel.kind() == ChannelKind::Signed { + for pixel in buffer.as_chunks_mut::<2>().0 { + pixel[0] = to_u16_signed(0.0); + } + } + } + + let masked = node.mask.is_some() || node.parts.is_some(); + let mut mask = masked.then(|| vec![0u16; TILE_AREA * 2]); + + for (x, y, offset) in tile_texels(inputs.gbuf, tx, ty) { + // Evaluate the lower stack once for all three probes + let mut over_below = Texel::new(&visible_inputs, x, y, offset, 0.0); + over_below.anchors_below(&below, (id, 0)); + let stack_below = over_below.below.unwrap_or_else(|| Channel::ALL.map(Channel::default_value)); + + // Record mask anchors before evaluating children that read them + let folder_mask = over_below.node_mask(node); + + // Black and white probes estimate coverage against different backgrounds + let over = |mut stack: Acc| { + let mut texel = over_below.clone(); + texel.eval(children, &mut stack); + stack + }; + let (low, high, shown) = (over([[0.0; 3]; NCH]), over([[1.0; 3]; NCH]), over(stack_below)); + for (planned, (channel, buffer, laid_down)) in node.chans.iter().zip(buffers.iter_mut()) { + let (Some(low), Some(high), Some(shown), Some(under)) = + (low.get(planned.ch), high.get(planned.ch), shown.get(planned.ch), stack_below.get(planned.ch)) + else { + continue; + }; + let comps = planned.comps.min(3); + let hidden = low.iter().zip(high).take(comps).map(|(low, high)| 1.0 - (high - low)).sum::() / comps as f32; + let range = if channel.kind() == ChannelKind::Signed { (-1.0, 1.0) } else { (0.0, 1.0) }; + let premultiplied = normal_over(under, shown, hidden.clamp(0.0, 1.0), comps, range); + + // Clipping matters only where the folder mask exposes the result + let clipped = match premultiplied { + Some(values) => { + let coverage = values[3]; + let min = range.0 * coverage - RANGE_TOLERANCE; + let max = range.1 * coverage + RANGE_TOLERANCE; + values.iter().take(comps).any(|value| *value < min || *value > max) + } + None => shown.iter().zip(under).take(comps).any(|(shown, under)| (shown - under).abs() > RANGE_TOLERANCE), + }; + if clipped && folder_mask > 0.0 { + return None; + } + + let Some(premultiplied) = premultiplied else { continue }; + + *laid_down = true; + let Some(pixel) = buffer.get_mut(offset * (planned.comps + 1)..(offset + 1) * (planned.comps + 1)) else { continue }; + let coverage = premultiplied[3]; + for (slot, value) in pixel.iter_mut().zip(premultiplied.iter().take(planned.comps)) { + *slot = if channel.kind() == ChannelKind::Signed { to_u16_signed(*value) } else { to_u16(*value) }; + } + if let Some(slot) = pixel.get_mut(planned.comps) { + *slot = to_u16(coverage); + } + } + + if let Some(pixel) = mask.as_mut().and_then(|mask| mask.get_mut(offset * 2..offset * 2 + 2)) { + pixel.copy_from_slice(&[to_u16(folder_mask), u16::MAX]); + } + } + + let content = buffers.into_iter().filter(|(_, _, laid_down)| *laid_down).map(|(channel, buffer, _)| (channel, (tx, ty), buffer)).collect(); + Some((content, mask.map(|mask| ((tx, ty), mask)))) + }) + .collect(); + + let (content, masks): (Vec<_>, Vec<_>) = out.ok_or(FlattenFolderError::ValueOutOfRange)?.into_iter().unzip(); + Ok((content.into_iter().flatten().collect(), masks.into_iter().flatten().collect())) +} + #[cfg(test)] mod tests { use super::*; @@ -5600,6 +5891,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(); @@ -5638,6 +5940,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(); @@ -6634,12 +6982,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)); @@ -6879,6 +7276,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| { @@ -7692,6 +8116,42 @@ soft {soft:?}" assert!(raised.iter().zip(flattened).any(|(raised, flat)| (*raised - flat).abs() > 1e-4)); } + #[test] + fn a_cropped_framed_fill_applies_its_image_alpha_once_with_alpha_coverage() { + let mut f = fixture(); + let mut images = ImageStore::default(); + images.insert("half".to_owned(), Arc::new(ImageRes::new(1, 1, vec![[1.0, 1.0, 1.0, 0.5]], false))); + let id = fill_layer(&mut f.project, [0.0; 3], 0.5); + let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") }; + fill.sources.insert(Channel::BaseColor, Source::image("half")); + fill.projection = Projection::Planar { + scale: 1.0, + axis: 1, + offset: [0.0; 3], + uv: Default::default(), + projector: texturecraft_core::Projector { crop: texturecraft_core::ShapeCrop::Cropped, ..Default::default() }, + placed: Some(texturecraft_core::Decal { + center: [0.0; 3], + normal: [0.0, 1.0, 0.0], + up: [0.0, 0.0, -1.0], + size: [4.0, 4.0], + rotation: 0.0, + offset: [0.0; 2], + depth: 1.0, + symmetry: None, + flip: [false; 2], + }), + }; + let plain = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32); + let LayerKind::Fill(fill) = &mut f.project.layer_mut(id).unwrap().kind else { panic!("fill fixture") }; + fill.sampling.alpha_coverage = true; + + let covered = run_with_images(&f, None, &images).value(Channel::BaseColor, 32, 32); + + assert!(!close(plain, Channel::BaseColor.default_value()), "the fill lands on the plane"); + assert!(close(covered, plain), "alpha coverage {covered:?}, image alpha {plain:?}"); + } + #[test] fn micro_height_uses_the_live_stroke_and_restores_the_committed_anchor_after_cancel() { let (mut fixture, images) = micro_height_fixture(); diff --git a/crates/compose/src/eval/layers_at.rs b/crates/compose/src/eval/layers_at.rs new file mode 100644 index 00000000..4ed8c2cd --- /dev/null +++ b/crates/compose/src/eval/layers_at.rs @@ -0,0 +1,111 @@ +//! Which layers lay something down at one texel, for R + click on the model + +use super::{ + Acc, BlendMode, Channel, Content, EvaluationInputs, Inputs, LayerId, NCH, NO_TRI, Node, ProjectorDepthCache, TILE, Texel, evaluation_channels, + evaluation_fields, mix_group, plan, prepare_generators, +}; + +/// Below this weight a layer leaves the texel unchanged (one 16-bit step) +const SMALLEST_WEIGHT: f32 = 1.0 / 65535.0; + +/// The paint and fill layers (and instances) that lay something down at texel (x, y) of texture set `inputs.ts` in any of `shown` channels, top first, each with the shown channels it changes there. Hidden layers, layers masked out there (by their own mask or a folder's) and channels at zero opacity count as laying nothing down. Projection depth maps come from `projectors` when it serves `inputs.mesh` +pub fn layers_at(inputs: &Inputs, projectors: &ProjectorDepthCache, (x, y): (u32, u32), shown: &[Channel]) -> Vec<(LayerId, Vec)> { + let Ok(set) = inputs.project.texture_set(inputs.ts) else { return Vec::new() }; + + let gbuf = inputs.gbuf; + let covered = x < gbuf.width && y < gbuf.height && gbuf.tri.get((y * gbuf.width + x) as usize).is_some_and(|tri| *tri != NO_TRI); + if !covered { + return Vec::new(); + } + + // A cache built for another mesh would hand out its depth maps + let unbound = ProjectorDepthCache::default(); + let served = projectors.serves(inputs.mesh); + let mut inputs = EvaluationInputs::new(inputs, if served { projectors } else { &unbound }); + + // The viewport's anchor heights are kept for the next query + if served { + inputs = inputs.of_the_session_stack(); + } + prepare_generators(&mut inputs, None); + + let inputs = &inputs; + let channels = evaluation_channels(inputs, set.channel_list()); + + // Plan the neighborhood that filters and anchors can read + let (tile_x, tile_y) = (x / TILE, y / TILE); + let fields = evaluation_fields(inputs, &channels, &[(tile_x, tile_y)]); + let nodes = plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)); + let offset = ((y % TILE) * TILE + x % TILE) as usize; + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + + let mut stack = Channel::ALL.map(Channel::default_value); + let mut found = Vec::new(); + texel.layers_laying_down(&nodes, &mut stack, [1.0; NCH], shown, &mut found); + + // The stack runs bottom first + found.reverse(); + found +} + +impl Texel<'_, '_> { + /// Composite `nodes` (bottom first) over `stack`, pushing the leaf layers that lay something down in a `shown` channel, with those channels, each channel weighted by `weights` (the opacity and mask of the folders holding them) + fn layers_laying_down(&mut self, nodes: &[Node], stack: &mut Acc, weights: [f32; NCH], shown: &[Channel], found: &mut Vec<(LayerId, Vec)>) { + for node in nodes { + // A mask comparing with the layers below reads the stack under its own layer + self.below = Some(*stack); + let mask = self.node_mask(node); + if mask <= 0.0 { + // A masked-out layer still records its anchor points + self.eval(std::slice::from_ref(node), stack); + continue; + } + + let mut node_weights = [0.0; NCH]; + for chan in node.chans.iter().filter(|chan| shown.iter().any(|channel| channel.index() == chan.ch)) { + if let (Some(weight), Some(slot)) = (weights.get(chan.ch), node_weights.get_mut(chan.ch)) { + *slot = weight * chan.opacity * mask; + } + } + + match &node.content { + Content::Group(children) => { + let mut inner = *stack; + let first_child = found.len(); + self.layers_laying_down(children, &mut inner, node_weights, shown, found); + mix_group(stack, &inner, &node.chans, mask); + + // The folder instance is the selectable row for its source's children + if found.len() > first_child && self.inp.project.layers.get(&node.draw.0).and_then(|layer| layer.instance_source()).is_some() { + let contributed: Vec = + shown.iter().copied().filter(|channel| found[first_child..].iter().any(|(_, channels)| channels.contains(channel))).collect(); + found.truncate(first_child); + found.push((node.draw.0, contributed)); + } + } + content => { + let changed: Vec = shown + .iter() + .copied() + .filter(|channel| { + node.chans.iter().filter(|chan| chan.ch == channel.index()).any(|chan| { + let weight = node_weights.get(chan.ch).copied().unwrap_or(0.0); + + // Replace lays its value down at full weight wherever the layer has content + weight > SMALLEST_WEIGHT + && self + .content(content, chan) + .is_some_and(|(_, coverage)| chan.blend == BlendMode::Replace || weight * coverage > SMALLEST_WEIGHT) + }) + }) + .collect(); + if !changed.is_empty() { + found.push((node.draw.0, changed)); + } + + self.eval(std::slice::from_ref(node), stack); + } + } + } + } +} 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/flatten_folder_error.rs b/crates/compose/src/flatten_folder_error.rs new file mode 100644 index 00000000..40b0bac5 --- /dev/null +++ b/crates/compose/src/flatten_folder_error.rs @@ -0,0 +1,8 @@ +/// Why a folder can't be flattened +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FlattenFolderError { + NotAFolder, + + /// Its layers add up past what an image holds, which baking would clip + ValueOutOfRange, +} diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index d17a955d..28b8e6eb 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; @@ -26,6 +27,7 @@ pub mod fill_copies; pub mod fill_copy; mod fill_depth; mod fill_place; +mod flatten_folder_error; pub mod frame_placement; mod fur_lock; mod generator_maps; @@ -37,6 +39,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 +47,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 +56,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; @@ -73,12 +79,15 @@ pub use display::{DisplayKind, display_tile_bytes, kinds_for, tile_bytes}; pub use effect_histogram::EffectHistogram; pub use eval::{ BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, compare_histograms, composite_tiles, composite_tiles_cached, - composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_layer, mask_at, mask_image, mask_image_sized, mask_texels, mask_values, - pad_tiles, stack_reads_neighbours, + composite_tiles_with_projectors, covered_tiles, effect_histogram, flatten_folder, flatten_layer, layers_at, mask_at, mask_image, mask_image_sized, + mask_texels, mask_values, pad_tiles, stack_reads_neighbours, }; +pub use flatten_folder_error::FlattenFolderError; 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}; diff --git a/crates/compose/src/padding_maps.rs b/crates/compose/src/padding_maps.rs new file mode 100644 index 00000000..3c73bfa7 --- /dev/null +++ b/crates/compose/src/padding_maps.rs @@ -0,0 +1,196 @@ +//! 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 { + /// A padding map without seam continuation. + pub fn from_flat(flat: DilationMap) -> Self { + Self { flat, crossed: Vec::new(), row_starts: Vec::new(), crossed_into: BTreeMap::new() } + } + + /// Bytes in the dense map, sparse seam arrays, and tile-index entries. + pub fn bytes(&self) -> usize { + self.flat.src.capacity() * size_of::() + + self.crossed.capacity() * size_of::<(u32, u32)>() + + self.row_starts.capacity() * size_of::() + + (self.crossed_into.len() + self.crossed_into.values().map(BTreeSet::len).sum::()) * size_of::<(u32, u32)>() + } + + /// 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/projector_depth.rs b/crates/compose/src/projector_depth.rs index 22219b4d..213ff788 100644 --- a/crates/compose/src/projector_depth.rs +++ b/crates/compose/src/projector_depth.rs @@ -33,26 +33,9 @@ const MIN_CELL_SIZE: f32 = 1e-6; /// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps const EDGE_TOLERANCE: f32 = 1e-6; -/// A depth map's grid as the CPU reads it in [`ProjectorDepth::cover`], for the GPU compositor -#[derive(Clone, Copy, Debug)] -pub struct DepthGrid<'a> { - /// The view the grid lies across - pub view: ProjectorView, - /// The view point at the grid's lower corner - pub origin: Vec2, - /// One cell's size across and up in the view - pub cell: Vec2, - /// Cells across and up - pub grid_side: usize, - /// The mesh radius measured along the view's depth axis - pub nearness_unit: f32, - /// Per cell, row by row from the lower corner: the nearest surface's nearness at the cell centre and its slope across and up (nearness -inf where no surface is) - pub front: &'a [[f32; 3]], - /// `cover`'s bias, slope bias limit and fade width, in mesh radii - pub bias: f32, - pub max_slope_bias: f32, - pub fade: f32, -} +mod depth_grid; + +pub use depth_grid::DepthGrid; impl ProjectorDepth { /// The grid as `cover` reads it. diff --git a/crates/compose/src/projector_depth/depth_grid.rs b/crates/compose/src/projector_depth/depth_grid.rs new file mode 100644 index 00000000..8f8312dd --- /dev/null +++ b/crates/compose/src/projector_depth/depth_grid.rs @@ -0,0 +1,22 @@ +use super::{ProjectorView, Vec2}; + +/// A depth map's grid as the CPU reads it in [`super::ProjectorDepth::cover`], for the GPU compositor +#[derive(Clone, Copy, Debug)] +pub struct DepthGrid<'a> { + /// The view the grid lies across + pub view: ProjectorView, + /// The view point at the grid's lower corner + pub origin: Vec2, + /// One cell's size across and up in the view + pub cell: Vec2, + /// Cells across and up + pub grid_side: usize, + /// The mesh radius measured along the view's depth axis + pub nearness_unit: f32, + /// Per cell, row by row from the lower corner: the nearest surface's nearness at the cell centre and its slope across and up (nearness -inf where no surface is) + pub front: &'a [[f32; 3]], + /// `cover`'s bias, slope bias limit and fade width, in mesh radii + pub bias: f32, + pub max_slope_bias: f32, + pub fade: f32, +} diff --git a/crates/compose/src/projector_depth_cache.rs b/crates/compose/src/projector_depth_cache.rs index b8337d88..2cbb3b37 100644 --- a/crates/compose/src/projector_depth_cache.rs +++ b/crates/compose/src/projector_depth_cache.rs @@ -27,6 +27,11 @@ impl ProjectorDepthCache { } } + /// Whether its depth maps were built for `mesh` + pub(crate) fn serves(&self, mesh: &Mesh) -> bool { + std::ptr::eq(self.mesh.as_ptr(), mesh) + } + pub(crate) fn get(&self, mesh: &Mesh, key: FillDepthKey) -> Option> { // Rasterization is serial so tile workers can wait for a single build let mut maps = self.maps.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); diff --git a/crates/compose/src/seam_padding.rs b/crates/compose/src/seam_padding.rs new file mode 100644 index 00000000..40030121 --- /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.iter() { + 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..0f4de225 --- /dev/null +++ b/crates/compose/src/seam_padding_input.rs @@ -0,0 +1,47 @@ +use std::borrow::Cow; +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: Cow<'a, [UvSeam]>, + 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: Cow::Owned(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: Cow::Owned(seams), triangles, material: Some((mesh, material)), islands: OnceLock::new() }) + } + + /// Reuse already identified seams for a material's current UV layout. + pub fn with_material_seams(mesh: &'a Mesh, material: usize, triangles: &'a [u32], seams: &'a [UvSeam]) -> Self { + Self { seams: Cow::Borrowed(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/store.rs b/crates/compose/src/store.rs index 71f93b3b..0b9275a6 100644 --- a/crates/compose/src/store.rs +++ b/crates/compose/src/store.rs @@ -362,6 +362,7 @@ mod tests { fn the_public_mip_chains_are_the_levels_bilinear_hq_reads() { let image = ImageRes::new(8, 8, (0..64).map(|i| [i as f32 / 63.0, 0.25, 0.75, 1.0]).collect(), false); let sampling = Sampling { filtering: Filtering::BilinearHq, ..Sampling::SAVED_BEFORE }; + // Footprint 2: exactly the first halved level let level = &image.mip_chain()[0]; assert_eq!(image.sample_filtered(0.3, 0.6, sampling, 2.0), bilinear(&level.rgba, level.width, level.height, 0.3, 0.6, (true, true))); 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/compose/src/tile_pattern.rs b/crates/compose/src/tile_pattern.rs index b751ae7a..1c199e33 100644 --- a/crates/compose/src/tile_pattern.rs +++ b/crates/compose/src/tile_pattern.rs @@ -8,6 +8,12 @@ use texturecraft_geom::glam::Vec2; use crate::store::{ImageRes, ImageStore}; use crate::tile_random_stream::TileRandomStream; +mod tile_layout; +mod tile_placement; + +pub use tile_layout::TileLayout; +pub use tile_placement::TilePlacement; + /// The settings a Tile Generator pattern saved without its own reads pub(crate) static DEFAULT: LazyLock = LazyLock::new(TileGenerator::default); @@ -177,30 +183,6 @@ fn wrap(delta: f32, span: f32) -> f32 { delta - (delta / span).round() * span } -/// The part of a tile's evaluation that is constant across every image texel. -#[derive(Clone, Copy, Debug)] -pub struct TilePlacement { - pub center: Vec2, - pub size: Vec2, - pub radius: Vec2, - /// Sine and cosine of the clockwise screen-space rotation. - pub rotation: [f32; 2], - pub quarter_turns: u32, - pub mirrors: [bool; 2], - pub input: Option, - pub luminance: f32, -} - -/// Positions and search bounds shared by the CPU and GPU Tile Generator. -#[derive(Debug)] -pub struct TileLayout { - pub amount: [u32; 2], - pub reach: Vec2, - pub line_shifts: Vec, - /// Columns first, then rows, matching the generator's pattern order. - pub placements: Vec>, -} - pub fn prepare_tile_layout(tile: &TileGenerator, seed: u32) -> TileLayout { let amount = tile.amount.map(|count| count.clamp(1, *TileGenerator::AMOUNT.end())); let [columns, rows] = amount.map(|count| count as i32); @@ -283,11 +265,13 @@ fn tile_value(tile: &TileGenerator, seed: u32, cell: (i32, i32), counts: (i32, i if y.abs() > radius.y { continue; } + for copy_x in first.x as i32..=last.x as i32 { let x = delta.x + copy_x as f32; if x.abs() > radius.x { continue; } + let mut local = Vec2::new(cos * x + sin * y, -sin * x + cos * y) * 2.0 / size; for _ in 0..quarter_turns { local = Vec2::new(local.y, -local.x); diff --git a/crates/compose/src/tile_pattern/tile_layout.rs b/crates/compose/src/tile_pattern/tile_layout.rs new file mode 100644 index 00000000..8830efc7 --- /dev/null +++ b/crates/compose/src/tile_pattern/tile_layout.rs @@ -0,0 +1,13 @@ +use texturecraft_geom::glam::Vec2; + +use super::TilePlacement; + +/// Positions and search bounds shared by the CPU and GPU Tile Generator. +#[derive(Debug)] +pub struct TileLayout { + pub amount: [u32; 2], + pub reach: Vec2, + pub line_shifts: Vec, + /// Columns first, then rows, matching the generator's pattern order. + pub placements: Vec>, +} diff --git a/crates/compose/src/tile_pattern/tile_placement.rs b/crates/compose/src/tile_pattern/tile_placement.rs new file mode 100644 index 00000000..f4f424b1 --- /dev/null +++ b/crates/compose/src/tile_pattern/tile_placement.rs @@ -0,0 +1,15 @@ +use texturecraft_geom::glam::Vec2; + +/// The part of a tile's evaluation that is constant across every image texel. +#[derive(Clone, Copy, Debug)] +pub struct TilePlacement { + pub center: Vec2, + pub size: Vec2, + pub radius: Vec2, + /// Sine and cosine of the clockwise screen-space rotation. + pub rotation: [f32; 2], + pub quarter_turns: u32, + pub mirrors: [bool; 2], + pub input: Option, + pub luminance: f32, +} 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/layer.rs b/crates/core/src/layer.rs index f0265ed2..d4c493e0 100644 --- a/crates/core/src/layer.rs +++ b/crates/core/src/layer.rs @@ -2428,10 +2428,16 @@ pub struct Effect { impl Effect { pub fn new(id: LayerId, kind: EffectKind) -> Effect { + // Generators are named after their kind, as filters are + let name = match &kind { + EffectKind::Generator(generator) => generator.kind.label(), + _ => kind.name(), + }; + // Generators and fills that build a mask usually add on top of the background Effect { id, - name: kind.name().to_string(), + name: name.to_string(), visible: true, kind, blend: BlendMode::Normal, diff --git a/crates/core/src/layer/sampling.rs b/crates/core/src/layer/sampling.rs index 9fa568fb..4a1c4b6d 100644 --- a/crates/core/src/layer/sampling.rs +++ b/crates/core/src/layer/sampling.rs @@ -14,12 +14,15 @@ pub struct Sampling { pub scale: ScaleMode, #[serde(default, skip_serializing_if = "FillSymmetry::is_default")] pub symmetry: FillSymmetry, + /// Each channel's image alpha is how much of that channel shows (the images a folder is flattened into) + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub alpha_coverage: bool, } impl Sampling { /// What fills saved before the sampling choices existed did: plain bilinear pub const SAVED_BEFORE: Sampling = - Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF }; + Sampling { filtering: Filtering::BilinearSharp, wrap: UvWrap::Repeat, scale: ScaleMode::Tiling, symmetry: FillSymmetry::OFF, alpha_coverage: false }; /// Serde default for fills saved before the field existed pub fn saved_before() -> Sampling { 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/src/add_mask_cmds.rs b/crates/engine/src/add_mask_cmds.rs index be508092..5ad36c90 100644 --- a/crates/engine/src/add_mask_cmds.rs +++ b/crates/engine/src/add_mask_cmds.rs @@ -1,10 +1,10 @@ //! The layer toolbar's Add mask items that add a mask with an effect in it (a bitmap, a height combination) and Add effect's colour selection use serde_json::Value; -use texturecraft_core::{BlendMode, EffectKind, Sampling, Source}; +use texturecraft_core::{BlendMode, Channel, EffectKind, Sampling, Source}; use texturecraft_paint::alphas; -use crate::commands::{CommandSpec, bad, has_layer, strp}; +use crate::commands::{CommandSpec, bad, content_param, has_layer, strp}; use crate::mask_cmds::{color_selection, mask_target, new_compare, push_effect_as, push_own_mask_effect}; use crate::{Result, Session, cmd}; @@ -24,9 +24,9 @@ pub fn specs() -> Vec { "Add mask with height combination", ["Layers", "Mask"], None, - "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected", + "{layer?} → {effect} — a compare mask (this layer's height greater than the layers below it, hardness 0.9) in the layer's mask (a new one if it has none); selected. The layer's height channel, if it has one, blends Normal", has_layer, - |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |_| Ok(())) + |s, p| push_own_mask_effect(s, p, new_compare(), "Add mask with height combination", |s| height_blends_normal(s, p)) ), cmd!( "effect.add.colorSelection", @@ -40,6 +40,16 @@ pub fn specs() -> Vec { ] } +/// Where a height-combination mask shows the layer, the layer's height replaces the height below instead of mixing with it +fn height_blends_normal(s: &mut Session, p: &Value) -> Result<()> { + let id = content_param(s, "mask.add.heightCombination", p)?; + if let Some(blend) = s.doc.project.layers.get_mut(&id).and_then(|layer| layer.channels.get_mut(&Channel::Height)) { + blend.mode = BlendMode::Normal; + } + + Ok(()) +} + /// A mask fill reading an image resource or a library alpha, in one undo step with the alpha's resource fn add_bitmap(s: &mut Session, p: &Value) -> Result { const CMD: &str = "mask.add.bitmap"; diff --git a/crates/engine/src/brush_device.rs b/crates/engine/src/brush_device.rs index fcb3a182..be36d362 100644 --- a/crates/engine/src/brush_device.rs +++ b/crates/engine/src/brush_device.rs @@ -16,34 +16,13 @@ pub type BrushTiles = BTreeSet<(u32, u32)>; /// Stencil samples by document tile, in row-major linear RGBA. pub type ProjectedTiles = BTreeMap<(u32, u32), Vec<[f32; 4]>>; -pub struct BrushBackend { - pub device: Arc, - pub surface: Weak, -} +mod brush_backend; +mod brush_surface; +mod device_stroke_preview; -pub struct BrushSurface { - pub mesh: Arc, - pub bvh: Arc, - pub uv: Arc, - pub material: usize, - pub depth: Option>, - pub settings: BrushSettings, - pub stencil: Option, - pub limit: Option<(TileImage, bool)>, -} - -pub struct DeviceStrokePreview<'a> { - pub ts: usize, - pub target: PaintTarget, - pub values: &'a BTreeMap, - pub mask_value: f32, - /// The image resource whose gray a mask stroke paints per texel in place of `mask_value`. - pub mask_image: Option<&'a str>, - pub opacity: f32, - /// The Eraser: the stroke scales the target's paint and coverage down instead of painting. - pub erase: bool, - pub stroke: &'a dyn DeviceStroke, -} +pub use brush_backend::BrushBackend; +pub use brush_surface::BrushSurface; +pub use device_stroke_preview::DeviceStrokePreview; pub trait BrushDevice: Send + Sync { fn start(&self, surface: BrushSurface) -> std::result::Result, String>; diff --git a/crates/engine/src/brush_device/brush_backend.rs b/crates/engine/src/brush_device/brush_backend.rs new file mode 100644 index 00000000..360a212a --- /dev/null +++ b/crates/engine/src/brush_device/brush_backend.rs @@ -0,0 +1,6 @@ +use super::{Arc, BrushDevice, UvGBuffer, Weak}; + +pub struct BrushBackend { + pub device: Arc, + pub surface: Weak, +} diff --git a/crates/engine/src/brush_device/brush_surface.rs b/crates/engine/src/brush_device/brush_surface.rs new file mode 100644 index 00000000..49698ac4 --- /dev/null +++ b/crates/engine/src/brush_device/brush_surface.rs @@ -0,0 +1,12 @@ +use super::{Arc, BrushSettings, Bvh, EyeDepth, Mesh, Stencil, TileImage, UvGBuffer}; + +pub struct BrushSurface { + pub mesh: Arc, + pub bvh: Arc, + pub uv: Arc, + pub material: usize, + pub depth: Option>, + pub settings: BrushSettings, + pub stencil: Option, + pub limit: Option<(TileImage, bool)>, +} diff --git a/crates/engine/src/brush_device/device_stroke_preview.rs b/crates/engine/src/brush_device/device_stroke_preview.rs new file mode 100644 index 00000000..707ba159 --- /dev/null +++ b/crates/engine/src/brush_device/device_stroke_preview.rs @@ -0,0 +1,14 @@ +use super::{BTreeMap, Channel, DeviceStroke, PaintTarget}; + +pub struct DeviceStrokePreview<'a> { + pub ts: usize, + pub target: PaintTarget, + pub values: &'a BTreeMap, + pub mask_value: f32, + /// The image resource whose gray a mask stroke paints per texel in place of `mask_value`. + pub mask_image: Option<&'a str>, + pub opacity: f32, + /// The Eraser: the stroke scales the target's paint and coverage down instead of painting. + pub erase: bool, + pub stroke: &'a dyn DeviceStroke, +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 0b7b1630..e7bc8445 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -193,6 +193,46 @@ pub fn check_enabled(spec: &CommandSpec, s: &Session) -> std::result::Result<(), (spec.enabled)(s) } +/// [`check_enabled`] for a run with `params`, checking a command that takes `layer`, or `effect` first, as if the named layer (one drawing the effect) were selected +fn check_enabled_for(spec: &CommandSpec, s: &mut Session, params: &Value) -> std::result::Result<(), String> { + let refused = match check_enabled(spec, s) { + Ok(()) => return Ok(()), + Err(why) => why, + }; + let id_param = |key: &str| u64p(params, key).map(texturecraft_core::LayerId); + let ts = s.ts(); + let project = &s.doc.project; + let in_active_set = |id| project.locate(id).is_some_and(|(found, _, _)| found == ts); + let named_layer = id_param("layer").filter(|_| spec.params.contains("layer?")).filter(|id| in_active_set(*id)); + let named_effect = id_param("effect").filter(|_| spec.params.starts_with("{effect")); + + // An effect's layer may sit in another texture set, drawn here by an instance + let layer_drawing_effect = || { + let owner = project.effect(named_effect?)?.0; + if in_active_set(owner) { + return Some(owner); + } + + project.texture_set(ts).ok()?.stack.iter().copied().find(|id| project.render_tree(&[*id]).contains(&owner)) + }; + let Some(id) = named_layer.or_else(layer_drawing_effect) else { return Err(refused) }; + + let selected = s.selected.insert(ts, id); + let target = s.target; + if let Some(effect) = named_effect { + s.target = crate::StackTarget::Effect(effect); + } + + let enabled = check_enabled(spec, s); + + s.target = target; + match selected { + Some(old) => s.selected.insert(ts, old), + None => s.selected.remove(&ts), + }; + enabled +} + pub fn find(id: &str) -> Option<&'static CommandSpec> { command_specs().iter().find(|c| c.id == id) } @@ -201,7 +241,7 @@ pub fn find(id: &str) -> Option<&'static CommandSpec> { /// `merge: true` its edits continue the previous undo step of the same label (drags). pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result { let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; - check_enabled(spec, s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; + check_enabled_for(spec, s, params).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?; let outer = std::mem::replace(&mut s.merge_edits, boolp(params, "merge").unwrap_or(false)); let result = (spec.run)(s, params); s.merge_edits = outer; diff --git a/crates/engine/src/display_padding.rs b/crates/engine/src/display_padding.rs index d373790a..862af827 100644 --- a/crates/engine/src/display_padding.rs +++ b/crates/engine/src/display_padding.rs @@ -4,18 +4,21 @@ use std::collections::BTreeSet; use std::ops::Deref; use std::sync::{Arc, OnceLock}; -use texturecraft_compose::{Composite, pad_tiles}; -use texturecraft_geom::{NO_TRI, UvGBuffer}; +use texturecraft_compose::{Composite, PaddingMaps, SeamPaddingInput, pad_tiles}; +use texturecraft_core::{TextureSet, UvPaddingMode}; +use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; use texturecraft_texel::DilationMap; +use crate::display_seam_geometry::DisplaySeamGeometry; use crate::session::DISPLAY_PADDING; /// The viewport's padding map. Reading the dense map explicitly also works for uniform UVs. pub struct DisplayPadding { - dense: Arc>>, + dense: Arc>, size: (u32, u32), mixed: Option>, - block: u32, + block: (u32, u32), + seam_geometry: Option>, #[cfg(not(target_arch = "wasm32"))] worker_started: bool, /// All texels covered or all uncovered. Mixed coverage needs the ordinary dilation map. @@ -23,7 +26,7 @@ pub struct DisplayPadding { } impl DisplayPadding { - pub(crate) fn new(gbuf: &Arc, has_coverage: bool, block: u32) -> Self { + pub(crate) fn new(mesh: &Arc, set: &TextureSet, gbuf: &Arc, has_coverage: bool, block: (u32, u32)) -> Self { let size = (gbuf.width, gbuf.height); let uniform = if !has_coverage { Some(false) @@ -33,11 +36,15 @@ impl DisplayPadding { None }; let mixed = uniform.is_none().then(|| Arc::clone(gbuf)); + let seam_geometry = + if mixed.is_some() && set.uv_padding == UvPaddingMode::Space3d { DisplaySeamGeometry::new(mesh, set.material).map(Arc::new) } else { None }; + Self { dense: Arc::default(), size, mixed, block, + seam_geometry, #[cfg(not(target_arch = "wasm32"))] worker_started: false, uniform, @@ -45,28 +52,38 @@ impl DisplayPadding { } pub(crate) fn apply_to_tiles(&self, output: &mut Composite, tiles: &[(u32, u32)]) -> BTreeSet<(u32, u32)> { - if self.uniform.is_some() { BTreeSet::new() } else { pad_tiles(output, self, tiles) } + if self.uniform.is_some() { BTreeSet::new() } else { pad_tiles(output, self.maps(), tiles) } } /// The same nearest covered source as the dense map, without constructing it for one pick. - pub(crate) fn source_for_sample(&self, x: u32, y: u32) -> Option<(u32, u32)> { + pub(crate) fn source_for_sample(&self, across_seams: bool, x: u32, y: u32) -> Option<(u32, u32)> { if let Some(dense) = self.dense.get() { - return dense.source(x, y); + return dense.source(across_seams, x, y); } + let gbuf = self.mixed.as_ref()?; - let block = if self.block == 0 { u32::MAX } else { self.block }; - let bounds = |pos: u32, size: u32| { + if across_seams && self.seam_geometry.is_some() { + return self.maps().source(true, x, y); + } + + let bounds = |pos: u32, size: u32, block: u32| { + let block = if block == 0 { u32::MAX } else { block }; let start = pos / block * block; let last = start.saturating_add(block - 1).min(size - 1); pos.saturating_sub(DISPLAY_PADDING).max(start)..=pos.saturating_add(DISPLAY_PADDING).min(last) }; - let columns = bounds(x, self.size.0); - bounds(y, self.size.1) + let columns = bounds(x, self.size.0, self.block.0); + bounds(y, self.size.1, self.block.1) .flat_map(|sy| columns.clone().map(move |sx| (sx, sy))) .filter(|&(sx, sy)| gbuf.tri[(sy * gbuf.width + sx) as usize] != NO_TRI) .min_by_key(|&(sx, sy)| (sx.abs_diff(x).max(sy.abs_diff(y)), sy, sx)) } + /// Seam continuation needs the CPU when the atlas has uncovered texels. + pub fn needs_seam_padding(&self) -> bool { + self.seam_geometry.is_some() + } + /// Whether every texel has a surface sample and the display needs no padding. pub fn fully_covered(&self) -> bool { self.uniform == Some(true) @@ -85,45 +102,50 @@ impl DisplayPadding { /// Start the dense CPU fallback on a worker so the viewport can keep drawing. #[cfg(not(target_arch = "wasm32"))] - pub fn prepare_on_worker(&mut self) -> bool { - if self.is_ready() { - return true; + pub fn prepare_on_worker(&mut self) { + if self.worker_started || self.is_ready() { + return; } - let Some(gbuf) = self.mixed.as_ref() else { return true }; - if !self.worker_started { - let (gbuf, dense, block) = (gbuf.clone(), self.dense.clone(), self.block); - self.worker_started = std::thread::Builder::new() - .name("texturecraft-padding".into()) - .spawn(move || { - dense.get_or_init(|| mixed_sources(&gbuf, block)); - }) - .is_ok(); - } - // If creating a thread failed, let the caller prepare the map synchronously. - !self.worker_started + + let Some(gbuf) = self.mixed.as_ref() else { return }; + let (gbuf, dense, block) = (Arc::downgrade(gbuf), Arc::downgrade(&self.dense), self.block); + let seam_geometry = self.seam_geometry.as_ref().map(Arc::downgrade); + self.worker_started = true; + rayon::spawn(move || { + let (Some(dense), Some(gbuf)) = (dense.upgrade(), gbuf.upgrade()) else { return }; + let seam_geometry = seam_geometry.and_then(|geometry| geometry.upgrade()); + dense.get_or_init(|| mixed_sources(&gbuf, block, seam_geometry.as_deref())); + }); } pub(crate) fn bytes(&self) -> usize { - self.dense.get().map_or(0, |map| map.src.capacity() * size_of::()) + self.dense.get().map_or(0, PaddingMaps::bytes) } -} -impl Deref for DisplayPadding { - type Target = Arc; - - fn deref(&self) -> &Self::Target { + pub(crate) fn maps(&self) -> &PaddingMaps { self.dense.get_or_init(|| { - let (width, height) = self.size; if let Some(gbuf) = &self.mixed { - return mixed_sources(gbuf, self.block); + return mixed_sources(gbuf, self.block, self.seam_geometry.as_deref()); } - let n = width as usize * height as usize; - let src = if self.uniform == Some(true) { (0..n as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; n] }; - Arc::new(DilationMap { width, height, src }) + + let (width, height) = self.size; + let texel_count = width as usize * height as usize; + let src = if self.uniform == Some(true) { (0..texel_count as u32).collect() } else { vec![texturecraft_texel::dilate::NONE; texel_count] }; + PaddingMaps::from_flat(DilationMap { width, height, src }) }) } } -fn mixed_sources(gbuf: &UvGBuffer, block: u32) -> Arc { - Arc::new(DilationMap::in_blocks(&gbuf.coverage_mask(), gbuf.width, gbuf.height, Some(DISPLAY_PADDING), block)) +impl Deref for DisplayPadding { + type Target = DilationMap; + + fn deref(&self) -> &Self::Target { + &self.maps().flat + } +} + +fn mixed_sources(gbuf: &UvGBuffer, block: (u32, u32), seam_geometry: Option<&DisplaySeamGeometry>) -> PaddingMaps { + let seams = seam_geometry.map(|geometry| SeamPaddingInput::with_material_seams(&geometry.mesh, geometry.material, &gbuf.tri, &geometry.seams)); + let mode = if seams.is_some() { UvPaddingMode::Space3d } else { UvPaddingMode::Space2d }; + PaddingMaps::new(mode, &gbuf.coverage_mask(), (gbuf.width, gbuf.height), Some(DISPLAY_PADDING), block, seams.as_ref()) } diff --git a/crates/engine/src/display_seam_geometry.rs b/crates/engine/src/display_seam_geometry.rs new file mode 100644 index 00000000..c455d80f --- /dev/null +++ b/crates/engine/src/display_seam_geometry.rs @@ -0,0 +1,17 @@ +use std::sync::Arc; + +use texturecraft_geom::{Mesh, UvSeam}; + +/// Seam topology shared with the worker that prepares display padding. +pub(crate) struct DisplaySeamGeometry { + pub(crate) mesh: Arc, + pub(crate) material: usize, + pub(crate) seams: Vec, +} + +impl DisplaySeamGeometry { + pub(crate) fn new(mesh: &Arc, material: usize) -> Option { + let seams = UvSeam::of_material(mesh, material); + (!seams.is_empty()).then(|| Self { mesh: mesh.clone(), material, seams }) + } +} diff --git a/crates/engine/src/effect_step.rs b/crates/engine/src/effect_step.rs new file mode 100644 index 00000000..32aeb4cf --- /dev/null +++ b/crates/engine/src/effect_step.rs @@ -0,0 +1,8 @@ +//! Which way a step of `effect.moveUp` / `effect.moveDown` moves an effect + +/// Which way an effect moves one place: up is later in its stack (rows list the top first) +#[derive(Clone, Copy)] +pub(crate) enum EffectStep { + Up, + Down, +} diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 1a6c24b7..818f4cdb 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -104,7 +104,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 ), @@ -442,6 +442,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), )?; @@ -456,6 +457,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 { @@ -463,6 +465,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, @@ -470,6 +477,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) @@ -488,6 +496,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), ) @@ -627,7 +636,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; @@ -640,12 +649,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, @@ -657,7 +669,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/fill_reset_cmds.rs b/crates/engine/src/fill_reset_cmds.rs index b2e10670..0e12f002 100644 --- a/crates/engine/src/fill_reset_cmds.rs +++ b/crates/engine/src/fill_reset_cmds.rs @@ -19,9 +19,9 @@ pub fn specs() -> Vec { )] } -/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) +/// The sampling a reset Fill section has: a new fill's, with `current`'s symmetry (it belongs to the Symmetry section) and its alpha coverage (a flattened folder's shape) pub fn reset_sampling(current: Sampling) -> Sampling { - Sampling { symmetry: current.symmetry, ..Sampling::default() } + Sampling { symmetry: current.symmetry, alpha_coverage: current.alpha_coverage, ..Sampling::default() } } /// The defaults of `current`'s projection kind: a new fill's projection of that kind, with the frame a placed planar or a warp projects from kept diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 00faf66b..95737d88 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/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index f33e4167..2b5dec00 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -87,6 +87,24 @@ pub fn specs() -> Vec { always, select ), + cmd!( + "layer.layersAt", + "Layers under the cursor", + [], + None, + "{x, y, viewport?: [w,h]} a point on the mesh — {layers: [{layer, name, channels}]}: the layers laying something down there in the shown channels, top first, each with the channels it changes there (R + click lists them)", + always, + layers_at + ), + cmd!( + "layer.pickAt", + "Pick layer under the cursor", + [], + None, + "{x, y, viewport?: [w,h], layer?} a point on the mesh — selects the top layer laying something down there in the shown channels, or `layer`, refused when it lays nothing down there (R + click)", + always, + pick_at + ), cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename), cmd!( "layer.visible", @@ -282,6 +300,35 @@ fn new_folder(id: LayerId, name: String, channels: &[Channel]) -> Layer { folder } +fn pick_at(s: &mut Session, p: &Value) -> Result { + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.pickAt", "`x` and `y` are required")) }; + + let viewport = crate::tool_cmds::viewport_of(s, p); + + // An explicitly supplied layer must parse before falling back to the top layer + let wanted = match p.get("layer").filter(|layer| !layer.is_null()) { + Some(_) => Some(u64p(p, "layer").map(LayerId).ok_or_else(|| bad("layer.pickAt", "`layer` must be a layer id"))?), + None => None, + }; + let id = s.pick_layer(texturecraft_geom::glam::Vec2::new(x, y), viewport, wanted)?; + Ok(json!({ "layer": id.0 })) +} + +fn layers_at(s: &mut Session, p: &Value) -> Result { + let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("layer.layersAt", "`x` and `y` are required")) }; + + let viewport = crate::tool_cmds::viewport_of(s, p); + let (_, layers) = s.layers_under(texturecraft_geom::glam::Vec2::new(x, y), viewport)?; + let layers: Vec = layers + .iter() + .map(|(id, channels)| { + let name = s.doc.project.layers.get(id).map(|layer| layer.name.as_str()).unwrap_or_default(); + json!({ "layer": id.0, "name": name, "channels": channels.iter().map(|channel| channel.id()).collect::>() }) + }) + .collect(); + Ok(json!({ "layers": layers })) +} + fn select(s: &mut Session, p: &Value) -> Result { if boolp(p, "all") == Some(true) { return crate::layer_selection::select_all(s); diff --git a/crates/engine/src/layer_ops.rs b/crates/engine/src/layer_ops.rs index 7a013c37..270da841 100644 --- a/crates/engine/src/layer_ops.rs +++ b/crates/engine/src/layer_ops.rs @@ -1,9 +1,16 @@ //! Layer clipboard (copy, cut, paste across texture sets), flatten, and resampling of painted //! pixels when a texture set changes size. +use std::collections::BTreeSet; + use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelKind, LayerId, LayerKind}; -use texturecraft_texel::TileImage; +use texturecraft_compose::FlattenFolderError; +use texturecraft_compose::eval::FlatTile; +use texturecraft_core::{ + Channel, ChannelKind, ContentsOffset, Effect, EffectKind, Fill, Filtering, Layer, LayerId, LayerKind, Mask, MaskBackground, Project, Sampling, Source, +}; +use texturecraft_formats::DecodedImage; +use texturecraft_texel::{TILE, TileImage, from_u16, from_u16_signed, linear_to_srgb, to_u16}; use crate::commands::{CommandSpec, boolp, has_layer, layer_param}; use crate::session::{Document, StackTarget}; @@ -19,7 +26,7 @@ pub fn specs() -> Vec { "Flatten layer", ["Layers"], Some("Ctrl+M"), - "{layer?} — a fill or masked paint layer becomes a plain paint layer", + "{layer?} — a fill or masked paint layer becomes a plain paint layer; a folder becomes a new fill layer above it holding one image per channel (its mask baked into a painted mask) and is hidden", has_layer, flatten ), @@ -197,38 +204,224 @@ fn flatten(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.flatten", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?; let layer = s.doc.project.layer(id)?.clone(); - // An instance flattens what it draws into a plain layer of its own. + + // An instance flattens what it draws into a plain layer of its own let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?; if content.is_group() { - return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into())); + return flatten_folder(s, ts, &layer, &content); } + s.update(); let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; let flat = s.flatten(ts, id).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?; s.edit("Flatten layer", |s| { - for c in Channel::ALL { - s.doc.pixels.layers.remove(&(id, c)); + for channel in Channel::ALL { + s.doc.pixels.layers.remove(&(id, channel)); } - let effects: Vec = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()).map(|e| e.id).collect(); - s.doc.pixels.masks.retain(|e, _| !effects.contains(e)); - s.doc.pixels.layers.retain(|(e, _), _| !effects.contains(e)); - for (c, (tx, ty), data) in flat { - let img = s.doc.pixels.layer_mut(id, c, size); - img.set_tile(tx, ty, Some(std::sync::Arc::new(data))); + let effects: Vec = + layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()).map(|effect| effect.id).collect(); + s.doc.pixels.masks.retain(|effect, _| !effects.contains(effect)); + s.doc.pixels.layers.retain(|(effect, _), _| !effects.contains(effect)); + + for (channel, (tx, ty), data) in flat { + let image = s.doc.pixels.layer_mut(id, channel, size); + image.set_tile(tx, ty, Some(std::sync::Arc::new(data))); } + let channels = s.doc.project.texture_set(ts)?.channel_list(); - let l = s.doc.project.layer_mut(id)?; - l.kind = LayerKind::Paint; - l.mask = None; - l.content_effects.clear(); - l.height_mask = Default::default(); - l.channels = content.channels.into_iter().filter(|(c, _)| channels.contains(c)).collect(); + let flattened = s.doc.project.layer_mut(id)?; + flattened.kind = LayerKind::Paint; + flattened.mask = None; + flattened.content_effects.clear(); + flattened.height_mask = Default::default(); + flattened.channels = content.channels.into_iter().filter(|(channel, _)| channels.contains(channel)).collect(); s.target = StackTarget::Content; Ok(()) })?; Ok(json!({ "layer": id.0 })) } +/// Flatten `folder` (drawing `drawn`: itself, or an instance's source) of texture set `ts` into a new fill layer above it, reading one image per channel it lays down, with its mask baked into a painted mask; the folder is hidden and kept, and the new layer shows only if the folder did +fn flatten_folder(s: &mut Session, ts: usize, folder: &Layer, drawn: &Layer) -> Result { + // A single fill image would repeat on each UV tile + if s.doc.project.texture_set(ts)?.uv_tiles.len() > 1 { + return Err(EngineError::Other("flattening a folder of a texture set with several UV tiles is not supported yet".into())); + } + + // Protect visible readers that would lose an anchor + if folder.visible && anchor_read_outside(&s.doc.project, folder.id) { + return Err(EngineError::Other("a layer outside the folder reads one of its anchor points: flattening would change it".into())); + } + + s.update(); + let size = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.size; + let tiles: Vec<(u32, u32)> = s.caches.get(ts).map(|cache| cache.covered_tiles.iter().copied().collect()).unwrap_or_default(); + let flattened = s + .with_inputs(ts, |inputs| Some(texturecraft_compose::flatten_folder(inputs, folder.id, &tiles))) + .ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let (content, mask) = flattened.map_err(|error| { + EngineError::Other(match error { + FlattenFolderError::NotAFolder => "nothing to flatten".into(), + FlattenFolderError::ValueOutOfRange => "the folder's layers go past what an image holds: flattening would clip them".into(), + }) + })?; + let images = channel_images(content, size)?; + if images.is_empty() { + return Err(EngineError::Other("the folder shows nothing to flatten".into())); + } + + let (flat, decoded_images) = s.edit("Flatten folder", |s| { + let mut decoded_images = Vec::with_capacity(images.len()); + let mut fill = Fill { sampling: Sampling { filtering: Filtering::Nearest, alpha_coverage: true, ..Sampling::default() }, ..Fill::default() }; + for (channel, png, image) in images { + let file_name = format!("{} flattened {}.png", folder.name, channel.id()); + let name = s.add_image_resource_bytes(&file_name, png)?; + fill.sources.insert(channel, Source::image(name.clone())); + decoded_images.push((name, crate::resource_cmds::decoded(image))); + } + + // Cancel ancestor transforms so baked texels stay in place + let around = s.doc.project.contents_around(folder.id); + fill.projection = ContentsOffset::new(around.scale.recip(), -around.rotation).apply(&fill.projection); + + // Enabling a channel without an image would cover the stack with its default + let channels: Vec = fill.sources.keys().copied().collect(); + let mut layer = Layer::new(s.doc.project.alloc_id(), format!("{} (flattened)", folder.name), LayerKind::Fill(fill), &channels); + layer.visible = folder.visible; + for (channel, blend) in &mut layer.channels { + blend.opacity = drawn.blend(*channel).map_or(1.0, |folder_blend| folder_blend.opacity); + } + if !mask.is_empty() { + let paint = s.doc.project.alloc_id(); + let mut baked = Mask::new(MaskBackground::Black); + baked.effects.push(Effect::new(paint, EffectKind::Paint)); + layer.mask = Some(baked); + let image = s.doc.pixels.mask_mut(paint, size); + for ((tx, ty), data) in mask { + image.set_tile(tx, ty, Some(std::sync::Arc::new(data))); + } + } + + let flat = s.doc.project.insert_layer(ts, layer, Some(folder.id), false)?; + s.doc.project.layer_mut(folder.id)?.visible = false; + s.select_one(ts, flat); + s.target = StackTarget::Content; + Ok((flat, decoded_images)) + })?; + + // Cache decoded images only after the undoable document edit succeeds + s.images.extend(decoded_images); + + Ok(json!({ "layer": flat.0 })) +} + +/// Whether a layer staying on screen reads an anchor point that hiding folder `folder` (or folder instance) takes away +fn anchor_read_outside(project: &Project, folder: LayerId) -> bool { + // Hiding the folder does not hide an instance's source row elsewhere + let mut hidden = BTreeSet::new(); + let mut unvisited = vec![folder]; + while let Some(id) = unvisited.pop() { + if hidden.insert(id) { + unvisited.extend(project.layers.get(&id).into_iter().flat_map(|layer| layer.children().iter().copied())); + } + } + + // Track masks and content still drawn through outside instances + let drawn_again: Vec<_> = project + .locate(folder) + .into_iter() + .flat_map(|(ts, _, _)| project.walk(ts)) + .filter(|(id, _)| !hidden.contains(id) && project.layers.get(id).is_some_and(|layer| layer.instance_source().is_some())) + .map(|(id, _)| mask_and_content_owners(project, id)) + .collect(); + + let anchors = project.render_tree(&[folder]).into_iter().filter_map(|id| project.layers.get(&id)).flat_map(|layer| { + let effects = layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(layer.content_effects.iter()); + effects.filter(|effect| matches!(effect.kind, EffectKind::Anchor)).map(|effect| (layer.id, effect.id)) + }); + + anchors.into_iter().any(|(owner, anchor)| { + project.anchor_readers(anchor).into_iter().any(|(reader, reading)| { + !hidden.contains(&reader) || drawn_again.iter().any(|drawn| draws(project, drawn, reader, reading) && !draws(project, drawn, owner, Some(anchor))) + }) + }) +} + +/// The layers whose masks and the layers whose content drawing layer `root` reads: an instance's own mask stands in for its source's +fn mask_and_content_owners(project: &Project, root: LayerId) -> (BTreeSet, BTreeSet) { + let (mut masks, mut contents, mut visited) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + let mut unvisited = vec![root]; + while let Some(id) = unvisited.pop() { + if !visited.insert(id) { + continue; + } + + masks.insert(project.mask_owner(id)); + if let Some(content) = project.content_layer(id) { + contents.insert(content.id); + unvisited.extend(content.children().iter().copied()); + } + } + (masks, contents) +} + +/// Whether a draw reading `owners` (see [`mask_and_content_owners`]) includes `effect` of layer `layer`, or the layer's own fill when None +fn draws(project: &Project, (masks, contents): &(BTreeSet, BTreeSet), layer: LayerId, effect: Option) -> bool { + let mask = project.layers.get(&layer).and_then(|layer| layer.mask.as_ref()); + let in_mask = mask.is_some_and(|mask| mask.effects.iter().any(|other| Some(other.id) == effect)); + if in_mask { masks.contains(&layer) } else { contents.contains(&layer) } +} + +/// One flattened tile of a channel: (tile, value + coverage data) +type ChannelTile = ((u32, u32), Vec); + +/// Flattened tiles as one 16-bit RGBA PNG per channel and its decoded pixels (straight values as a fill reads them, coverage in the alpha), in channel order +fn channel_images(tiles: Vec, size: (u32, u32)) -> Result, DecodedImage)>> { + let (width, height) = size; + let mut by_channel: std::collections::BTreeMap> = Default::default(); + for (channel, tile, data) in tiles { + by_channel.entry(channel).or_default().push((tile, data)); + } + + by_channel + .into_iter() + .map(|(channel, tiles)| { + let comps = channel.components(); + let mut rgba = vec![0u16; width as usize * height as usize * 4]; + for ((tx, ty), data) in tiles { + for (offset, texel) in data.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + offset as u32 % TILE, ty * TILE + offset as u32 / TILE); + let coverage = texel.get(comps).copied().map_or(0.0, from_u16); + if x >= width || y >= height || coverage <= 0.0 { + continue; + } + + let straight = |i: usize| { + let premultiplied = texel.get(i).copied().unwrap_or(0); + let value = if channel.kind() == ChannelKind::Signed { from_u16_signed(premultiplied) } else { from_u16(premultiplied) }; + value / coverage + }; + let rgb = match channel.kind() { + ChannelKind::Color => [0, 1, 2].map(|i| linear_to_srgb(straight(i))), + ChannelKind::NormalMap => [0, 1, 2].map(straight), + ChannelKind::Scalar => [straight(0); 3], + + // A fill reads a signed channel's image gray as -1..1 + ChannelKind::Signed => [(straight(0) + 1.0) * 0.5; 3], + }; + let start = (y as usize * width as usize + x as usize) * 4; + if let Some(pixel) = rgba.get_mut(start..start + 4) { + pixel.copy_from_slice(&[to_u16(rgb[0]), to_u16(rgb[1]), to_u16(rgb[2]), to_u16(coverage)]); + } + } + } + let (png, image) = texturecraft_formats::rgba16_resource(width, height, &rgba) + .map_err(|error| EngineError::Other(format!("flattened {}: {error}", channel.id())))?; + Ok((channel, png, image)) + }) + .collect() +} + impl Session { /// Layer `id` of texture set `ts` alone (content times mask) as premultiplied tiles per /// channel over the set's covered tiles. None for folders or a set not ready. diff --git a/crates/engine/src/layer_pick.rs b/crates/engine/src/layer_pick.rs new file mode 100644 index 00000000..2020a865 --- /dev/null +++ b/crates/engine/src/layer_pick.rs @@ -0,0 +1,91 @@ +//! Picking a layer on the mesh (R + click in the viewport, `layer.layersAt` and `layer.pickAt`): the layers laying something down where the mesh is clicked, and selecting one of them + +use texturecraft_core::{Channel, LayerId, LayerKind}; +use texturecraft_geom::glam::Vec2; +use texturecraft_paint::{PickCtx, stroke::pick_filtered}; + +use crate::session::ViewMode; +use crate::{EngineError, Result, Session, StackTarget}; + +/// A texture set and the layers laying something down at one of its texels, top first, each with the channels it changes there +pub type LayersUnder = (usize, Vec<(LayerId, Vec)>); + +impl Session { + /// The texture set and texel of the mesh under `screen`, None off the mesh + pub fn texel_under(&self, screen: Vec2, viewport: Vec2) -> Option<(usize, (u32, u32))> { + let visible_set = |material| { + let ts = self.texture_set_of_material(material)?; + self.doc.project.texture_sets.get(ts).filter(|set| set.visible).map(|_| ts) + }; + let nearest = self.pick(screen, viewport)?; + let (hit, ts) = match visible_set(nearest.material) { + Some(ts) => (nearest, ts), + None => { + // Only search past the first hit when its material is hidden + let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &self.camera, viewport }; + let hit = pick_filtered(&ctx, screen, &|triangle| visible_set(self.mesh.material_of(triangle as usize).unwrap_or(0)).is_some())?; + (hit, visible_set(hit.material)?) + } + }; + + let cache = self.caches.get(ts)?; + let (width, height) = (cache.size.0 as f32, cache.size.1 as f32); + let texel = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32); + Some((ts, texel)) + } + + /// The layers laying something down at `texel` of texture set `ts` in the shown channels (every channel outside a single-channel view), top first, each with the channels it changes there + pub fn layers_at_texel(&self, ts: usize, texel: (u32, u32)) -> Vec<(LayerId, Vec)> { + let shown = match self.view { + ViewMode::Channel(channel) => vec![channel], + _ => self.doc.project.texture_set(ts).map(|set| set.channel_list()).unwrap_or_default(), + }; + // Match the visibility of the active solo view + let solo_view = self.solo_view(); + self.with_inputs(ts, |inputs| { + let inputs = + texturecraft_compose::Inputs { project: solo_view.as_ref().unwrap_or(inputs.project), block_scales: inputs.block_scales.clone(), ..*inputs }; + Some(texturecraft_compose::layers_at(&inputs, &self.projector_depth_cache, texel, &shown)) + }) + .unwrap_or_default() + } + + /// The texture set under `screen` and the layers laying something down there (see [`Session::layers_at_texel`]) + pub fn layers_under(&self, screen: Vec2, viewport: Vec2) -> Result { + let (ts, texel) = self.texel_under(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; + Ok((ts, self.layers_at_texel(ts, texel))) + } + + /// Select `wanted` when it lays something down under `screen`, else the top layer there + pub fn pick_layer(&mut self, screen: Vec2, viewport: Vec2, wanted: Option) -> Result { + let (ts, layers) = self.layers_under(screen, viewport)?; + let picked = match wanted { + Some(wanted) => layers.iter().find(|(id, _)| *id == wanted).ok_or_else(|| EngineError::Other("that layer lays nothing down here".into()))?, + None => layers.first().ok_or_else(|| EngineError::Other("no visible layer lays anything down here".into()))?, + }; + let id = picked.0; + + // Finish the current set's path and discard its clone source before switching + if ts != self.ts() { + self.finish_path()?; + self.tool.clone_source = None; + } + self.active_set = ts; + self.select_one(ts, id); + self.open_folders_holding(id); + self.target = StackTarget::Content; + self.revision = self.revision.wrapping_add(1); + Ok(id) + } + + /// Expand every collapsed folder holding `id`, so the Layers panel shows its row + fn open_folders_holding(&mut self, id: LayerId) { + let mut child = id; + while let Some((_, Some(folder), _)) = self.doc.project.locate(child) { + if let Some(LayerKind::Group { collapsed, .. }) = self.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) { + *collapsed = false; + } + child = folder; + } + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 129faa31..9285d4c7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,6 +22,7 @@ pub mod decal_cmds; pub mod distance_params; pub mod effect_blending_cmds; pub mod effect_clipboard; +mod effect_step; pub mod file_cmds; pub mod fill_alpha; pub mod fill_hit_test; @@ -39,6 +40,7 @@ pub mod inspect; pub mod instance_cmds; pub mod layer_cmds; pub mod layer_ops; +mod layer_pick; pub mod layer_selection; pub mod link_cmds; pub mod log; @@ -72,6 +74,7 @@ mod polygon_fill_mirror; mod stencil_look; // Mesh reimport reads files on native targets only mod display_padding; +mod display_seam_geometry; #[cfg(not(target_arch = "wasm32"))] mod preserve; pub mod preset_cmds; 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_cmds.rs b/crates/engine/src/mask_cmds.rs index b5b1f535..d398a812 100644 --- a/crates/engine/src/mask_cmds.rs +++ b/crates/engine/src/mask_cmds.rs @@ -10,6 +10,7 @@ use texturecraft_core::{ use crate::anchored_micro_edit::AnchoredMicroEdit; use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p}; use crate::distance_params::distance_from; +use crate::effect_step::EffectStep; use crate::generator_input::GeneratorInput; use crate::layer_cmds::{projection_from, projection_from_fields}; use crate::mask_owner::MaskOwner; @@ -118,6 +119,24 @@ pub fn specs() -> Vec { duplicate_effect ), cmd!("effect.move", "Move effect", [], None, "{effect, index: position in its stack, 0 = bottom (applied first)}", has_layer, move_effect), + cmd!( + "effect.moveUp", + "Move effect up", + ["Layers"], + Some("Alt+Up"), + "{effect?: the selected effect} — one place up its stack (applied later)", + has_layer, + |s, p| step_effect(s, p, EffectStep::Up) + ), + cmd!( + "effect.moveDown", + "Move effect down", + ["Layers"], + Some("Alt+Down"), + "{effect?: the selected effect} — one place down its stack (applied earlier)", + has_layer, + |s, p| step_effect(s, p, EffectStep::Down) + ), cmd!( "effect.histogram", "Effect input histogram", @@ -1019,6 +1038,9 @@ fn histogram(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The name every generator effect got before they were named after their kind +const FORMER_GENERATOR_NAME: &str = "Generator"; + /// Edit visibility, blending, name, effect parameters, or a filter's type pub(crate) fn set(session: &mut Session, params: &Value) -> Result { const CMD: &str = "effect.set"; @@ -1100,6 +1122,13 @@ pub(crate) fn set(session: &mut Session, params: &Value) -> Result { session.edit("Edit effect", |session| { let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?; if let Some(generator) = swapped_generator { + // Preserve custom names when swapping generator kinds + if let EffectKind::Generator(old) = &edited.kind + && (edited.name == old.kind.label() || edited.name == FORMER_GENERATOR_NAME) + { + edited.name = generator.kind.label().to_string(); + } + edited.kind = EffectKind::Generator(generator); } if let Some((kind, label)) = swapped { @@ -1389,6 +1418,28 @@ fn move_effect(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Move an effect one place in its stack (one undo step; nothing at its end) +fn step_effect(s: &mut Session, p: &Value, step: EffectStep) -> Result { + let cmd = match step { + EffectStep::Up => "effect.moveUp", + EffectStep::Down => "effect.moveDown", + }; + if p.get("effect").is_some_and(|effect| !effect.is_null()) && u64p(p, "effect").is_none() { + return Err(bad(cmd, "`effect` must be an effect id")); + } + + let effect = effect_id(s, p, cmd)?; + let (list, index) = stack_of(&mut s.doc.project, effect).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?; + let to = match step { + EffectStep::Up if index + 1 < list.len() => index + 1, + EffectStep::Down if index > 0 => index - 1, + _ => return Ok(json!({ "moved": false })), + }; + + move_effect(s, &json!({ "effect": effect.0, "index": to }))?; + Ok(json!({ "moved": true })) +} + fn remove_effect(s: &mut Session, p: &Value) -> Result { let eid = effect_id(s, p, "effect.remove")?; s.edit("Remove effect", |s| { 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 0277c6fc..780db5f2 100644 --- a/crates/engine/src/material_lib.rs +++ b/crates/engine/src/material_lib.rs @@ -74,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/material_overview.rs b/crates/engine/src/material_overview.rs index c556875b..80705805 100644 --- a/crates/engine/src/material_overview.rs +++ b/crates/engine/src/material_overview.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use texturecraft_compose::{BakedMaps, Composite, DisplayKind, Inputs, all_tiles, composite_tiles, kinds_for, tile_bytes}; -use texturecraft_core::Channel; +use texturecraft_core::{AoMixing, Channel}; use texturecraft_geom::UvGBuffer; use texturecraft_texel::TILE; @@ -28,8 +28,8 @@ impl Session { let (width, height) = ((w / step).max(1), (h / step).max(1)); let cache = self.caches.get(ts)?; let source = &cache.gbuf; - // Sample the existing UV raster. Rasterizing a many-triangle mesh again can take - // longer than evaluating the overview itself. + + // Reuse the full UV raster to avoid traversing the mesh again for an overview let positions = (0..height).flat_map(|y| { (0..width).map(move |x| { let sx = ((x as u64 * 2 + 1) * w as u64 / (2 * width as u64)) as usize; @@ -60,28 +60,31 @@ impl Session { let mut composite = Composite { block_scales: scales, ..Composite::with_size(&channels, width, height) }; let tiles = all_tiles(width, height); composite_tiles(&inputs, &mut composite, &tiles); - let padding = - crate::session::DisplayPadding::new(&gbuf, gbuf.tri.iter().any(|&t| t != texturecraft_geom::NO_TRI), (set.block_resolution() / step).max(1)); + let (block_width, block_height) = set.block_size(); + let block = ((block_width / step).max(1), (block_height / step).max(1)); + let has_coverage = gbuf.tri.iter().any(|&triangle| triangle != texturecraft_geom::NO_TRI); + let padding = crate::session::DisplayPadding::new(&self.mesh, set, &gbuf, has_coverage, block); padding.apply_to_tiles(&mut composite, &tiles); - let maps = pack_overview(&composite, baked, &channels, &tiles); + let maps = pack_overview(&composite, baked, set.ao_mixing, &channels, &tiles); Some(MaterialOverview { size: (width, height), maps }) } } -fn pack_overview(composite: &Composite, baked: &BakedMaps, channels: &[Channel], tiles: &[(u32, u32)]) -> Vec<(DisplayKind, Vec)> { +fn pack_overview(composite: &Composite, baked: &BakedMaps, ao_mixing: AoMixing, channels: &[Channel], tiles: &[(u32, u32)]) -> Vec<(DisplayKind, Vec)> { let (width, height) = (composite.resolution, composite.height); kinds_for(channels) .map(|kind| { let stride = kind.bytes_per_texel(); let mut image = vec![0; width as usize * height as usize * stride]; for &(tx, ty) in tiles { - let data = tile_bytes(composite, baked, kind, tx, ty); + let data = tile_bytes(composite, baked, ao_mixing, kind, tx, ty); let (left, top) = (tx * TILE, ty * TILE); let row_bytes = (width - left).min(TILE) as usize * stride; for (row, src) in data.chunks_exact(TILE as usize * stride).take((height - top) as usize).enumerate() { let offset = ((top as usize + row) * width as usize + left as usize) * stride; image[offset..offset + row_bytes].copy_from_slice(&src[..row_bytes]); - // A preview tile can span several mixed-resolution UDIM blocks. + + // A preview tile can span several mixed-resolution UDIM blocks if kind == DisplayKind::Extra { for (x, px) in image[offset..offset + row_bytes].chunks_exact_mut(stride).enumerate() { px[3] = (-32.0 * composite.block_scales.at(left + x as u32, top + row as u32).log2()).round().clamp(0.0, 255.0) as u8; diff --git a/crates/engine/src/materials.rs b/crates/engine/src/materials.rs index 76b821dc..e17b3f5e 100644 --- a/crates/engine/src/materials.rs +++ b/crates/engine/src/materials.rs @@ -990,7 +990,8 @@ mod tests { #[test] fn every_material_and_smart_mask_applies_on_the_sample() { let mut s = crate::sample_session(256, 256).unwrap(); - // A baseline no material matches, so every material must visibly change the composite. + + // The magenta baseline differs visibly from every material preset crate::execute(&mut s, "layer.add.fill", &serde_json::json!({"color": [1.0, 0.0, 1.0], "roughness": 0.123})).unwrap(); s.update(); let before = snapshot(&s, 0); @@ -1004,7 +1005,8 @@ mod tests { s.undo().unwrap(); } assert!(apply(&mut s, "nope").is_err()); - // Smart masks on the pedestal: it has edges and cavities (the ball is a plain sphere). + + // The pedestal exposes edges and cavities for the smart mask generators s.active_set = 1; apply(&mut s, "gold_polished").unwrap(); let layer = s.selected_layer().unwrap(); diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 991a7119..c66a90b3 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -224,15 +224,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() { @@ -247,26 +249,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 { @@ -274,9 +280,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)); @@ -285,6 +292,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) { @@ -292,7 +300,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 @@ -324,31 +332,38 @@ 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()) }; + let settings = &stroke.settings; + // A 3D view projection without a stencil was refused above; the 2D view paints without one. A path repaints its curve as a stroke let gpu_tool = matches!(tool, Tool::Paint | Tool::Projection | Tool::Path) || erase; + // Resolved once: staging, both previews and the commit paint this gray let mask_gray = self.mask_gray(); + // Symmetry copies reach the device with the stamps (a 3D copy carries its source for visibility); an Eraser with particles stays on the CPU let device = if gpu_tool && canvas.pickup.is_none() && !(erase && settings.particles.enabled) && settings.alpha_image.is_none() && settings.alpha_library.is_none() + && stencil.as_ref().is_none_or(|stencil| stencil.colors) && let Some(backend) = &self.brush_device && let Some(cache) = self.caches.get(ts) && backend.surface.ptr_eq(&std::sync::Arc::downgrade(&cache.gbuf)) @@ -393,6 +408,7 @@ impl Session { erase, stencil, before, + start_revision: self.revision, label, staging: Staging::default(), device, @@ -444,13 +460,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. @@ -581,6 +598,7 @@ impl Session { if stamps.is_empty() { return hit; } + let rctx = RasterCtx { mesh: &self.mesh, bvh: &self.bvh, @@ -602,6 +620,7 @@ impl Session { } return hit; } + Err(error) => { st.device = None; st.display_tiles.append(&mut st.canvas.dirty); @@ -763,6 +782,7 @@ impl Session { if stroke.device.is_some() { return None; } + let tiles_in_bounds; let touched = if let Some((min, max)) = texel_bounds { tiles_in_bounds = stroke @@ -815,6 +835,7 @@ impl Session { let device = self.take_device_stroke(None); let brush_tile = self.tile_demand(None).brush; 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 @@ -822,13 +843,24 @@ impl Session { return Ok(()); } + if self.painting_paths { + self.path_tiles.extend(stroke.canvas.dirty.iter().copied()); + } + 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, None, stencil_allows_stroke) { + self.mark_painted(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied(), false); + self.discard_unused_stroke_mask(&stroke); + return Ok(()); + } + let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut stroke.staging); let Some(target) = stroke.target else { with_commit_source(&stroke, gbuf.as_deref(), &mesh, &stroke.canvas.dirty, None, |src| self.commit_quick_mask(stroke.ts, size, src)); return Ok(()); }; + let pixels = &mut self.doc.pixels; let mut commit = |tiles: &BrushTiles, projection: Option<&ProjectedTiles>| { with_commit_source(&stroke, gbuf.as_deref(), &mesh, tiles, projection, |src| match target { @@ -860,10 +892,8 @@ impl Session { commit(&stroke.canvas.dirty, None); } let fed_before = self.fed_revisions(&stroke); - self.undo.push((stroke.label.clone(), stroke.before)); - if self.undo.len() > crate::session::MAX_HISTORY { - self.undo.remove(0); - } + + self.add_step(stroke.label, stroke.before); self.redo.clear(); self.mark_modified(); @@ -888,6 +918,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() { @@ -897,7 +953,8 @@ impl Session { self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1); } self.doc = st.before; - // A paint effect created by the stroke can get the same ID on a different owner. + + // A paint effect created by the stroke can get the same ID on a different owner for cache in &mut self.caches { cache.invalidate_paint_margin(); } @@ -951,6 +1008,9 @@ impl Session { /// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask. pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas, gray: &MaskGray) -> Result<()> { + if self.painting_paths { + self.path_tiles.extend(canvas.dirty.iter().copied()); + } if self.quick_mask.editing { return self.paint_fill(ts, canvas, gray); } @@ -1037,29 +1097,52 @@ 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)>, projection: Option<&ProjectedTiles>, f: impl FnOnce(CommitSource) -> R, ) -> R { - let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> { + let stencil_fn = |x: u32, y: u32| -> Option<(Option<[f32; 3]>, f32)> { if let Some(projection) = projection { let tile = projection.get(&(x / TILE, y / TILE))?; - let i = ((y % TILE) * TILE + x % TILE) as usize; - let &[r, g, b, a] = tile.get(i)?; - return Some(([r, g, b], a)); + let offset = ((y % TILE) * TILE + x % TILE) as usize; + let &[red, green, blue, alpha] = tile.get(offset)?; + return Some((Some([red, green, blue]), alpha)); } - let g = gbuf?; - let p = g.surface(mesh, (y * g.width + x) as usize)?.pos; - st.stencil.as_ref()?.sample_world(p) + + 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 b225fe27..13f2b798 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -11,7 +11,7 @@ use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use texturecraft_compose::{PaintTarget, PixelStore}; +use texturecraft_compose::{ImageRes, PaintTarget, PixelStore}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; @@ -26,6 +26,9 @@ use crate::{Document, EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go +/// first. +const CACHE_BYTES: usize = 256 << 20; /// The undo step that adds a new path pub(crate) const NEW_PATH_LABEL: &str = "Path"; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). @@ -151,23 +154,120 @@ impl PathState { } } -/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and -/// texture size they were painted for. +/// Mesh id, texture size, owner layer channels, texture set channels. +type CacheKey = (u64, Option<(u32, u32)>, Vec, Vec); +/// A path sublayer's images: its mask (`None`) and each channel. +type Snap = BTreeMap, TileImage>; +/// A stored path and the brush alpha image it was painted with. +type Painted = (PathShape, Option>); + +/// A path sublayer as last painted for `key`: its paths, its images after each path +/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that +/// path changed; None once [`evict`]ed) and the tiles each path painted. #[derive(Clone)] pub(crate) struct PathCache { pub(crate) eid: LayerId, - // Session::invalidate_changed discards the prefix when an image it reads changes - key: (u64, Option<(u32, u32)>), - below: Vec, - mask: Option, - layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, + key: CacheKey, + shapes: Vec, + snaps: Vec>, + tiles: Vec>, +} + +/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the +/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until +/// one writes, so a snapshot that diverged from the live image holds its own. +fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { + let mut bytes = 0; + for img in snap.values() { + if seen.insert(img.table_id()) { + bytes += img.table_bytes(); + } + for ty in 0..img.tiles_y() { + for tx in 0..img.tiles_x() { + if let Some(t) = img.tile_handle(tx, ty) + && seen.insert(Arc::as_ptr(t) as usize) + { + bytes += t.len() * 2; + } + } + } + } + bytes +} + +/// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent +/// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live +/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last +/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest +/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already +/// hold: what freeing it would release at most. The first (empty) and the last cost nothing. +/// Returns the bytes the kept snapshots are charged. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) -> usize { + let mut seen = BTreeSet::new(); + for k in [snaps.len().saturating_sub(1), edited] { + if let Some(Some(snap)) = snaps.get(k) { + charge(snap, &mut seen); + } + } + let mut bytes = 0; + for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { + let Some(Some(snap)) = snaps.get(k) else { continue }; + // Count into a copy: an evicted snapshot's tiles are not retained by it any more. + let mut with = seen.clone(); + let cost = charge(snap, &mut with); + if bytes + cost > budget { + snaps[k] = None; + } else { + bytes += cost; + seen = with; + } + } + bytes +} + +mod evict_pacer; + +use evict_pacer::EvictPacer; + +fn same_handle(a: Option<&Arc>, b: Option<&Arc>) -> bool { + match (a, b) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (x, y) => x.is_none() && y.is_none(), + } +} + +fn same_path(a: &Painted, b: &Painted) -> bool { + a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref()) +} + +/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always +/// gives it a new one); a missing image reads as empty. +fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool { + a.keys().chain(b.keys()).all(|k| { + let (x, y) = (a.get(k), b.get(k)); + let dims = |i: &TileImage| (i.width(), i.height(), i.comps()); + x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y)) + && tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty)))) + }) +} + +/// Copy `from`'s tiles at `tiles` into `to`. +fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) { + for (k, src) in from { + to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps())); + } + for (k, dst) in to.iter_mut() { + let src = from.get(k); + for &(x, y) in tiles { + dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned()); + } + } } impl PathCache { /// The image resources the cached paths painted their mask with pub(crate) fn images(&self) -> impl Iterator + '_ { - // Only successfully painted paths enter the prefix - self.below.iter().filter_map(|shape| shape.paint.get("mask_image")?.as_str()) + self.shapes.iter().filter_map(|(shape, _)| shape.paint.get("mask_image")?.as_str()) } } @@ -363,7 +463,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result { { shapes.remove(index); } - s.render_paths(eid, index) + s.render_paths(eid) })?; if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { s.stop_path_edit(); @@ -612,7 +712,7 @@ impl Session { if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) { paths.remove(index); } - session.render_paths(effect, index) + session.render_paths(effect) }, )?; self.cancel_path(); @@ -982,62 +1082,124 @@ impl Session { }, _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), }; - let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({})); + let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); out["effect"] = json!(eid.0); out["index"] = json!(index); Ok(out) } - /// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before - /// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are - /// cached for the next repaint otherwise, so editing a path repaints it and the paths above - /// only. Runs inside the caller's undo step. Returns each painted path's report (null for - /// the cached ones). - fn render_paths(&mut self, eid: LayerId, from: usize) -> Result> { + /// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the + /// paths before the first changed one keep their pixels, and an unchanged path above it + /// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs + /// inside the caller's undo step. Returns each painted path's report (null for the cached + /// ones). + fn render_paths(&mut self, eid: LayerId) -> Result> { let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); - let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size)); - self.doc.pixels.masks.remove(&eid); - self.doc.pixels.layers.retain(|(id, _), _| *id != eid); - let start = match &self.path_cache { - Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => { - if let Some(m) = &c.mask { - self.doc.pixels.masks.insert(eid, m.clone()); + let images = &self.images; + let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned()); + let new: Vec = shapes + .into_iter() + .map(|sh| { + let a = alpha(&sh); + (sh, a) + }) + .collect(); + let project = &self.doc.project; + let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default(); + let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set); + let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key); + let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| { + let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count(); + (p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count()) + }); + // Start from the last snapshot kept at or below the first changed path (the first one, + // empty, is always kept). + let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0)); + let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec()); + let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec()); + let mut state = snaps[start].clone().unwrap_or_default(); + let mut pacer = EvictPacer::start(&mut snaps, prefix); + // 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 (j, (sh, _)) in new.iter().enumerate().skip(start) { + // Painting is per tile: over the same tiles, an unchanged path paints the same. + let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; + if let (Some(c), Some(o)) = (&old, o) + && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) + && same_tiles(&state, below, &c.tiles[o]) + { + copy_tiles(&mut state, after, &c.tiles[o]); + tiles.push(c.tiles[o].clone()); + snaps.push(Some(state.clone())); + pacer.appended(&mut snaps, prefix, &state, c.tiles[o].len()); + out.push(Value::Null); + continue; } - self.doc.pixels.layers.extend(c.layers.iter().cloned()); - c.below.len() + s.put_snap(eid, &state); + s.path_tiles.clear(); + match s.paint_shape(sh) { + Ok(v) => out.push(v), + Err(e) => { + result = Err(e); + break; + } + } + state = s.take_snap(eid); + tiles.push(std::mem::take(&mut s.path_tiles)); + snaps.push(Some(state.clone())); + pacer.appended(&mut snaps, prefix, &state, tiles.last().map_or(0, BTreeSet::len)); } - _ => 0, - }; + s.put_snap(eid, &state); + result + }); + if result.is_ok() { + self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + } + 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 take_snap(&self, eid: LayerId) -> Snap { + let p = &self.doc.pixels; + let mask = p.masks.get(&eid).map(|m| (None, m.clone())); + mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect() + } + + fn put_snap(&mut self, eid: LayerId, snap: &Snap) { + let p = &mut self.doc.pixels; + p.masks.remove(&eid); + p.layers.retain(|(id, _), _| *id != eid); + for (k, img) in snap { + match k { + None => p.masks.insert(eid, img.clone()), + Some(c) => p.layers.insert((eid, *c), img.clone()), + }; + } } fn paint_shape(&mut self, shape: &PathShape) -> Result { @@ -1216,45 +1378,246 @@ mod tests { v } - #[test] - fn cached_repaint_matches_a_full_repaint() { - let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + /// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture. + fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap(); s.update(); execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); let mut eid = 0; - for v in [0.2, 0.5, 0.8] { - let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + for v in rows { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap(); eid = r["committed"]["effect"].as_u64().unwrap(); } - let eid = texturecraft_core::LayerId(eid); + (s, texturecraft_core::LayerId(eid)) + } - // Live edits of the middle path reuse the bottom path's pixels - execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); - for v in [0.4, 0.45] { - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); - } - - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); - - let r = s.render_paths(eid, 1).unwrap(); - - assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); - - let cached = pixels(&s, eid); + /// Move path `index` to row `v` (a live edit) and check the result against painting every + /// path. Returns which paths were repainted. + fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec { + execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap(); + let before = s.path_cache.clone(); + execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); + let cached = pixels(s, eid); + s.path_cache = before; + let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect(); + assert_eq!(cached, pixels(s, eid)); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); - - assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); + s.stop_path_edit(); + painted + } + #[test] + fn cached_repaint_matches_a_full_repaint() { + // Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows. + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints"); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles"); + assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); + } + + #[test] + fn a_filled_path_above_an_edit_keeps_its_tiles() { + // The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles. + let (mut s, eid) = with_paths(&[0.2]); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true})) + .unwrap(); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels"); + } + + #[test] + fn removing_a_path_keeps_the_paths_above() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let before = s.path_cache.clone(); + execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap(); + let cached = pixels(&s, eid); + s.path_cache = before; + assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache"); + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + } + + #[test] + fn replacing_the_brush_alpha_image_repaints() { + let (mut s, eid) = with_paths(&[0.2]); + let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes::new(2, 2, vec![[v; 4]; 4], false)); + s.images.insert("a".into(), img(1.0)); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap(); + s.render_paths(eid).unwrap(); + s.images.insert("a".into(), img(0.5)); + let r = s.render_paths(eid).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}"); + } + + #[test] + fn snapshots_stay_within_the_budget() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, usize::MAX, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4); + // The paths are on different tiles, so a snapshot costs nothing beyond its own tile table + // (the tiles are all shared with the live pixels): a budget of two tables keeps them. + let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, 2 * table, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables"); + // Drop them by hand to test the repaint from the bottom. + c.snaps[1] = None; + c.snaps[2] = None; + // Appending still paints the new path alone. + let shape = s.paths(eid).unwrap()[0].clone(); + if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { + v.push(shape); + } + let r = s.render_paths(eid).unwrap(); + assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); + // Editing above evicted snapshots repaints from the bottom and matches a full repaint. + let c = s.path_cache.as_mut().unwrap(); + assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); + assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); + // That edit kept the snapshot below path 3 within a one-table budget: its next frame starts + // there, and the snapshots above it that cost only a table keep their paths unrepainted. + let c = s.path_cache.as_mut().unwrap(); + let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, table, 2); + assert!(c.snaps[2].is_some()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); + } + + /// `prev` with the tiles in `at` replaced by new handles (what painting a path does). + fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap { + let mut next = prev.clone(); + for img in next.values_mut() { + for &(x, y) in at { + img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4]))); + } + } + next + } + + #[test] + fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + // A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &[(0, 0)]); + let s3 = painted(&s2, &all); + let s4 = painted(&s3, &[(0, 0)]); + let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)]; + // Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that + // neither the live image nor snapshot 3 has: that is over a budget of 8 tiles. + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + super::evict(&mut snaps, 8 * tile_bytes, 3); + assert!(snaps[3].is_some(), "the edited snapshot stays"); + assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); + } + + #[test] + fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() { + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))]; + let mut pacer = super::EvictPacer::start(&mut snaps, 0); + assert_eq!(pacer.held, 0, "the first and last snapshots are free"); + // A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0). + for n in 1..=3 { + pacer.appended(&mut snaps, 0, &empty, 1); + assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths"); + } + // Past the budget the estimate gives way to an exact scan. + pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1); + assert!(pacer.held < super::CACHE_BYTES, "scanned: {}", pacer.held); + } + + #[test] + fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with + // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &all); + let s3 = painted(&s2, &[(0, 0)]); + let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())]; + let kept = |snaps: &[Option]| snaps.iter().map(Option::is_some).collect::>(); + let mut snaps = fresh(); + super::evict(&mut snaps, usize::MAX, 0); + assert_eq!(kept(&snaps), [true; 4]); + let mut snaps = fresh(); + super::evict(&mut snaps, tile_bytes + table, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen"); + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 0); + assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); + // Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own. + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 1); + assert_eq!(kept(&snaps), [true, true, false, true]); + } + + #[test] + fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() { + // Big image: the table (one slot per tile position) outweighs a one-tile stroke. + let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + assert!(table >= 128 * 128 * 8, "table {table}"); + let s1 = painted(&empty, &[(0, 0)]); + let s2 = painted(&s1, &[(1, 0)]); + let s3 = painted(&s2, &[(2, 0)]); + let live = painted(&s3, &[(3, 0)]); + let mut seen = std::collections::BTreeSet::new(); + // Alone, a diverged snapshot holds its own table; charged again with the same table, it is free. + let first = super::charge(&s2, &mut seen); + assert!(first >= table, "charged {first}"); + assert_eq!(super::charge(&s2, &mut seen), 0); + // Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does. + let tile_only = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)]; + super::evict(&mut snaps, 3 * tile_only, 0); + assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots"); + } + + #[test] + fn the_quick_mask_does_not_clip_paths() { + let (mut s, eid) = with_paths(&[0.2, 0.8]); + let plain = pixels(&s, eid); + s.quick_mask.enabled = true; + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(plain, pixels(&s, eid)); + } + + #[test] + fn owner_channel_change_skips_the_cache() { + let (mut s, eid) = with_paths(&[0.3, 0.7]); + s.render_paths(eid).unwrap(); + let owner = s.doc.project.effect(eid).unwrap().0; + let layer = s.doc.project.layer_mut(owner).unwrap(); + let ch = *layer.channels.keys().next().unwrap(); + layer.channels.remove(&ch); + let r = s.render_paths(eid).unwrap(); + assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}"); + assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel"); + } + + #[test] + fn deleting_the_path_effect_releases_its_cached_tiles() { + let (mut s, eid) = with_paths(&[0.2, 0.5, 0.8]); execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap(); - let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::()); - assert!(cached_tiles > 0); - + let held = |s: &Session| { + s.path_cache.as_ref().map_or(0, |c| c.snaps.iter().flatten().flat_map(|snap| snap.values()).map(|i| i.allocated_count()).sum::()) + }; + assert!(held(&s) > 0); execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap(); - let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::()); - assert_eq!(remaining_tiles, 0); + assert_eq!(held(&s), 0); assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles"); } @@ -1278,14 +1641,14 @@ mod tests { execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.6], [0.9, 0.6]]})).unwrap(); - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1), "the bottom path is cached"); + assert_eq!(s.path_cache.as_ref().map(|c| c.shapes.len()), Some(2), "the paths are cached"); execute(&mut s, "resource.remove", &json!({"name": image})).unwrap(); execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.65], [0.9, 0.65]]})).unwrap(); let mask = |s: &Session| format!("{:?}", s.doc.pixels.masks.get(&eid)); let edited = mask(&s); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); + s.render_paths(eid).unwrap(); assert_eq!(edited, mask(&s), "the bottom path paints the mask value as a full repaint does"); } @@ -1297,7 +1660,9 @@ mod tests { let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]); let retained = Arc::downgrade(&tile); image.set_tile(0, 0, Some(tile)); - session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() }); + let snap: Snap = [(None, image)].into(); + session.path_cache = + Some(PathCache { eid: LayerId(0), key: (0, None, Vec::new(), Vec::new()), shapes: Vec::new(), snaps: vec![Some(snap)], tiles: Vec::new() }); let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into()))); @@ -1418,4 +1783,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/path_tool/evict_pacer.rs b/crates/engine/src/path_tool/evict_pacer.rs new file mode 100644 index 00000000..3a673874 --- /dev/null +++ b/crates/engine/src/path_tool/evict_pacer.rs @@ -0,0 +1,29 @@ +use super::{CACHE_BYTES, Snap, TileImage, evict}; + +/// Runs [`evict`] only when the snapshots may have outgrown the budget. `evict` charges every +/// kept snapshot, so calling it after each appended path made a repaint of n paths cost n +/// scans of up to n snapshots. A snapshot differs from the one before it only in the tiles its +/// path painted, so those tiles bound what it adds: `held` is an upper bound on the bytes +/// charged, and the scan runs once it passes the budget (then `held` is exact again). +pub(super) struct EvictPacer { + pub(super) held: usize, +} + +impl EvictPacer { + /// Scan the snapshots kept from the previous repaint once, trimming them to the budget. + pub(super) fn start(snaps: &mut [Option], edited: usize) -> Self { + Self { held: evict(snaps, CACHE_BYTES, edited) } + } + + /// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images. + pub(super) fn appended(&mut self, snaps: &mut [Option], edited: usize, state: &Snap, tiles: usize) { + let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum(); + + // The new snapshot may also own a table per image (a write after the clone copies it) + let table_bytes: usize = state.values().map(TileImage::table_bytes).sum(); + self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes); + if self.held > CACHE_BYTES { + self.held = evict(snaps, CACHE_BYTES, edited); + } + } +} 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/quick_mask.rs b/crates/engine/src/quick_mask.rs index e4321298..8d168967 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -27,13 +27,9 @@ pub struct QuickMask { pub revision: u64, } -/// Live brush coverage for the temporary mask (never written into document layers). -pub struct QuickMaskStroke<'a> { - pub alpha: &'a TileImage, - pub device: Option<&'a dyn crate::brush_device::DeviceStroke>, - pub opacity: f32, - pub erase: bool, -} +mod quick_mask_stroke; + +pub use quick_mask_stroke::QuickMaskStroke; pub fn specs() -> Vec { vec![ @@ -103,10 +99,10 @@ impl Session { } /// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the - /// quick mask is off or being edited). + /// quick mask is off or being edited, and for paths, which repaint from what they store). pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> { let q = &self.quick_mask; - (q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted)) + (q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted)) } /// Commit a stroke into the quick mask of `ts`. diff --git a/crates/engine/src/quick_mask/quick_mask_stroke.rs b/crates/engine/src/quick_mask/quick_mask_stroke.rs new file mode 100644 index 00000000..1473372c --- /dev/null +++ b/crates/engine/src/quick_mask/quick_mask_stroke.rs @@ -0,0 +1,9 @@ +use super::TileImage; + +/// Live brush coverage for the temporary mask (never written into document layers). +pub struct QuickMaskStroke<'a> { + pub alpha: &'a TileImage, + pub device: Option<&'a dyn crate::brush_device::DeviceStroke>, + pub opacity: f32, + pub erase: bool, +} diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 024243c3..326f3217 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -55,6 +55,15 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { Arc::new(ImageRes::new(d.width, d.height, d.rgba, d.srgb)) } +/// Refuse resource files over [`MAX_BYTES`] +fn within_byte_limit(file_name: &str, bytes: &[u8]) -> Result<()> { + if bytes.len() > MAX_BYTES { + return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); + } + + Ok(()) +} + /// Disambiguate a sanitized resource name without losing its archive key on save. pub(crate) fn unique_resource_name(base: String, taken: impl Fn(&str) -> bool) -> String { if !taken(&base) { @@ -95,12 +104,23 @@ impl Session { self.add_image_resource_prefixed("", file_name, bytes, max_texels) } + /// Store encoded pixels in the document during an edit; the caller can cache the decoded pixels after commit + pub(crate) fn add_image_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { + within_byte_limit(file_name, &bytes)?; + Ok(self.insert_image_resource_bytes("", file_name, bytes)) + } + fn add_image_resource_prefixed(&mut self, prefix: &str, file_name: &str, bytes: Vec, max_texels: u64) -> Result { - if bytes.len() > MAX_BYTES { - return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20))); - } + within_byte_limit(file_name, &bytes)?; let image = texturecraft_formats::decode_image_within(&bytes, max_texels).map_err(|error| EngineError::Other(format!("{file_name}: {error}")))?; + let name = self.insert_image_resource_bytes(prefix, file_name, bytes); + self.images.insert(name.clone(), decoded(image)); + Ok(name) + } + + /// Store `bytes` under a unique, sanitized name from `file_name` and `prefix`; returns the name + fn insert_image_resource_bytes(&mut self, prefix: &str, file_name: &str, bytes: Vec) -> String { let leaf = std::path::Path::new(file_name).file_name().and_then(|name| name.to_str()).unwrap_or("image"); let mut base = sanitize_resource_name(leaf); @@ -116,9 +136,7 @@ impl Session { let name = unique_resource_name(base, |name| self.doc.resources.contains_key(name) || crate::fill_alpha::library_alpha_of(name).is_some()); self.doc.resources.insert(name.clone(), Arc::new(bytes)); - self.images.insert(name.clone(), decoded(image)); - - Ok(name) + name } /// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load). @@ -341,6 +359,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 +367,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 +448,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 +564,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 0fc8b2fc..90d4a91c 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -5,8 +5,8 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles}; -use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; +use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, SeamPaddingInput, StackKey, StrokePreview, covered_tiles}; +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}; @@ -38,26 +38,11 @@ pub struct Document { pub(crate) painted_regions: BTreeMap, } -/// A released dab keeps priority until its display upload is sent. -#[derive(Clone)] -pub struct ReleasedDab { - tile: (u32, u32), - uploaded: Arc, -} +mod display_stroke_end; +mod released_dab; -impl ReleasedDab { - pub(crate) fn new(tile: (u32, u32)) -> Self { - Self { tile, uploaded: Arc::default() } - } - - pub(crate) fn pending_tile(&self) -> Option<(u32, u32)> { - (!self.uploaded.load(Ordering::Acquire)).then_some(self.tile) - } - - pub fn acknowledge_upload(&self) { - self.uploaded.store(true, Ordering::Release); - } -} +pub(crate) use display_stroke_end::DisplayStrokeEnd; +pub use released_dab::ReleasedDab; /// Derived per-texture-set data (rebuilt when the mesh or resolution changes). pub struct SetCache { @@ -65,6 +50,10 @@ pub struct SetCache { pub size: (u32, u32), pub gbuf: Arc, pub dilation: DisplayPadding, + /// The set's UV padding mode and the display padding it gives + pub uv_padding: UvPaddingMode, + /// The channels' storage formats the composite was made with + pub formats: Vec<(Channel, ChannelFormat)>, pub covered_tiles: Arc>, pub composite: Composite, /// Tiles to recomposite. @@ -89,17 +78,18 @@ pub struct SetCache { } impl SetCache { - pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache { + pub(crate) fn new(mesh: &Arc, ts: &TextureSet) -> SetCache { let (w, h) = ts.size(); let gbuf = Arc::new(UvGBuffer::new(mesh, ts.material, w, h)); - // Padding stays inside each UV tile. let covered = covered_tiles(&gbuf); - let dilation = DisplayPadding::new(&gbuf, !covered.is_empty(), ts.block_resolution()); + let dilation = DisplayPadding::new(mesh, ts, &gbuf, !covered.is_empty(), ts.block_size()); let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect(); SetCache { size: (w, h), gbuf, dilation, + uv_padding: ts.uv_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, @@ -151,6 +141,7 @@ impl SetCache { if tiles.is_empty() { return; } + let margin = match self.paint_margin { Some((cached, margin)) if cached == target => margin, _ => { @@ -170,12 +161,13 @@ impl SetCache { let left = left.saturating_sub(radius); let right = right.saturating_add(radius).min(last_x); for row in top.saturating_sub(radius)..=bottom.saturating_add(radius).min(last_y) { - // Covered tiles are sorted by row, then column. + // Covered tiles are sorted by row, then column let start = covered.partition_point(|&(tx, ty)| (ty, tx) < (row, left)); queue.extend(covered[start..].iter().take_while(|&&(tx, ty)| ty == row && tx <= right).copied()); } }; - // Coalesce expensive, overlapping halos without scanning distant atlas tiles. + + // Coalesce expensive, overlapping halos without scanning distant atlas tiles let diameter = (radius as usize).saturating_mul(2).saturating_add(1); if diameter.saturating_mul(diameter).saturating_mul(tiles.len()) >= covered.len() { let bounds = tiles.iter().fold(((last_x, last_y), (0, 0)), |((l, t), (r, b)), &(x, y)| ((l.min(x), t.min(y)), (r.max(x), b.max(y)))); @@ -190,6 +182,24 @@ 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.material_revision = self.material_revision.wrapping_add(1); self.dirty.extend(self.covered_tiles.iter().copied()); @@ -200,6 +210,15 @@ impl SetCache { } } +/// 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) +} + /// Active tool. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] pub enum Tool { @@ -220,6 +239,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", @@ -291,7 +316,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. @@ -362,7 +387,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 @@ -458,17 +483,6 @@ pub enum StackTarget { Effect(LayerId), } -/// Work left in the viewport after a stroke committed or was cancelled. -pub(crate) struct DisplayStrokeEnd { - pub id: u64, - pub ts: usize, - pub previous_revision: u64, - pub revision: u64, - pub tiles: BTreeSet<(u32, u32)>, - /// The other texture sets the stroke fed: set, revision before and revision after. - pub fed: Vec<(usize, u64, u64)>, -} - pub(crate) struct ActiveStroke { pub display_id: u64, pub display_tiles: BTreeSet<(u32, u32)>, @@ -487,10 +501,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, @@ -566,6 +582,8 @@ pub struct Session { pub caches: Vec, 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 + 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, @@ -610,8 +628,10 @@ pub struct Session { pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). pub(crate) painting_paths: bool, - /// Pixels of the paths below the one being edited, so live edits skip repainting them. + /// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach. pub(crate) path_cache: Option, + /// Tiles painted since `render_paths` cleared it (the footprint of one path). + pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>, /// A new path's live preview: the path becomes an undo step only when it is applied pub(crate) path_draft: Option, /// Point changes of the path being edited: (earlier states for undo, undone states for redo) @@ -635,7 +655,7 @@ pub struct Session { /// are unchanged, so back-to-back dabs start instantly. pub(crate) depth_cache: Option, /// Projection fill depth maps shared by this session's tile batches. - projector_depth_cache: texturecraft_compose::ProjectorDepthCache, + pub(crate) projector_depth_cache: texturecraft_compose::ProjectorDepthCache, /// The polygon fill box being dragged pub(crate) polygon_fill_drag: Option, /// The user's export presets (kept when another project opens). @@ -679,6 +699,7 @@ impl Session { caches, undo: Vec::new(), redo: Vec::new(), + steps_added: 0, merge_edits: false, tool: ToolState::default(), active_set: 0, @@ -706,6 +727,7 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_tiles: Default::default(), path_draft: None, path_steps: Default::default(), path: None, @@ -834,7 +856,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) } @@ -850,7 +873,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))); } @@ -866,15 +900,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); } @@ -891,7 +931,7 @@ impl Session { if !self.painting_paths && let Some(draft) = self.path_draft.take() { - self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base)); + self.add_step(crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base); } // Point changes of an edited path undo only until another step lands @@ -901,11 +941,22 @@ impl Session { self.mark_modified(); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { - self.undo.push((label.to_string(), before)); + self.add_step(label.to_string(), before); } + + self.redo.clear(); + } + + /// Append an undo step, dropping the oldest ones from a full history + pub(crate) fn add_step(&mut self, label: String, before: Document) { + self.undo.push((label, before)); let over = self.undo.len().saturating_sub(MAX_HISTORY); self.undo.drain(..over); - self.redo.clear(); + + // A repaint of paths runs strokes on a temporary history, none of which is a step + if !self.painting_paths { + self.steps_added = self.steps_added.wrapping_add(1); + } } /// A change from `other` to the current document that is not an undo step (a path preview) @@ -980,6 +1031,13 @@ impl Session { ) }; for (texture_set_index, cache) in self.caches.iter_mut().enumerate() { + // AO mixing changes the packed display tiles and the GPU program + 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.material_revision = cache.material_revision.wrapping_add(1); + cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1)); + } + if uses_added_resource(texture_set_index) { cache.invalidate_all(); continue; @@ -1047,24 +1105,35 @@ 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() => { - c.invalidate_paint_margin(); - c.finished_dab = None; - 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() => { + cache.invalidate_paint_margin(); + cache.finished_dab = None; + if cache.uv_padding != set.uv_padding { + cache.uv_padding = set.uv_padding; + cache.dilation = DisplayPadding::new(&self.mesh, set, &cache.gbuf, !cache.covered_tiles.is_empty(), set.block_size()); + 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); } @@ -1101,10 +1170,27 @@ 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 + pub fn steps_added(&self) -> u64 { + self.steps_added + } + + /// 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 @@ -1168,13 +1254,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; @@ -1241,8 +1331,7 @@ impl Session { pub fn update_for_view_where(&mut self, budget_ms: f64, clock: impl Fn() -> f64, demand: crate::TileDemand, include: impl Fn(usize) -> bool) -> bool { let active = self.ts(); if active != self.cache_active { - // A third material replaces the previously parked one, even when the - // interactive slice ends before the compositor visits that texture set. + // A third material replaces the parked one even when its turn falls in a later slice if let Some(displaced) = self.cache_previous.filter(|&ts| ts != active) && let Some(cache) = self.caches.get_mut(displaced) { @@ -1256,10 +1345,10 @@ impl Session { } let changed = self.update_tiles(budget_ms, clock, active, demand, include); if let Some(previous) = self.cache_previous.filter(|&ts| self.caches.get(ts).is_some_and(|c| !c.below.is_empty())) { - // Retaining an idle material spends only the remainder of the normal band - // budget. The active material always gets first use of that budget. + // Only the active material can claim the full band budget let allowance = self.caches.get(active).map_or(0, |c| c.below.limit()); - // Instances in other sets can have live bands of their own. + + // Instances in other sets can have live bands of their own let spare = self .caches .iter() @@ -1316,6 +1405,7 @@ impl Session { if Some(ts) == self.cache_previous && cache.dirty.is_empty() && cache.settle.is_empty() && !cache.below.is_empty() { continue; } + cache.below.set_hot(hot); cache.below.pass = cache.dirty.len() + cache.settle.len(); @@ -1432,14 +1522,14 @@ impl Session { if i != ts && !sets.contains(&i) { continue; } + if Some(c.size) == size { if changed_document { c.material_revision = c.material_revision.wrapping_add(1); } c.queue_painted(&self.doc.project, i, target, &tiles, |c| if settle { &mut c.settle } else { &mut c.dirty }); } else if settle || changed_document { - // Resampled instances first see paint when its source pixels are committed (a - // settled stroke, or a document edit such as a path repaint) + // Resampled instances read committed source pixels c.invalidate_all(); } } diff --git a/crates/engine/src/session/display_stroke_end.rs b/crates/engine/src/session/display_stroke_end.rs new file mode 100644 index 00000000..bbf31992 --- /dev/null +++ b/crates/engine/src/session/display_stroke_end.rs @@ -0,0 +1,12 @@ +use super::BTreeSet; + +/// Work left in the viewport after a stroke committed or was cancelled. +pub(crate) struct DisplayStrokeEnd { + pub id: u64, + pub ts: usize, + pub previous_revision: u64, + pub revision: u64, + pub tiles: BTreeSet<(u32, u32)>, + /// The other texture sets the stroke fed: set, revision before and revision after. + pub fed: Vec<(usize, u64, u64)>, +} diff --git a/crates/engine/src/session/released_dab.rs b/crates/engine/src/session/released_dab.rs new file mode 100644 index 00000000..a8c03026 --- /dev/null +++ b/crates/engine/src/session/released_dab.rs @@ -0,0 +1,22 @@ +use super::{Arc, AtomicBool, Ordering}; + +/// A released dab keeps priority until its display upload is sent. +#[derive(Clone)] +pub struct ReleasedDab { + pub(super) tile: (u32, u32), + pub(super) uploaded: Arc, +} + +impl ReleasedDab { + pub(crate) fn new(tile: (u32, u32)) -> Self { + Self { tile, uploaded: Arc::default() } + } + + pub(crate) fn pending_tile(&self) -> Option<(u32, u32)> { + (!self.uploaded.load(Ordering::Acquire)).then_some(self.tile) + } + + pub fn acknowledge_upload(&self) { + self.uploaded.store(true, Ordering::Release); + } +} diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index c4bf3c73..50eeb850 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; @@ -21,13 +21,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", @@ -38,8 +48,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", @@ -68,18 +94,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 })) } @@ -104,8 +133,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) } @@ -116,9 +149,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), } @@ -126,10 +161,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), } @@ -148,10 +185,14 @@ impl ResizeTask { mut accelerate: impl FnMut(&texturecraft_texel::TileImage, (u32, u32), &[u16]) -> Option>, ) -> Result { let start = Instant::now(); - 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(); @@ -166,6 +207,7 @@ impl ResizeTask { if cancelled() { return image.clone(); } + if old.uv_tiles.is_empty() && image.allocated_count() > 0 && (image.width(), image.height()) != size { let submitted = Instant::now(); if let Some(result) = accelerate(image, size, empty) { @@ -175,6 +217,7 @@ impl ResizeTask { gpu_images += 1; return resized; } + Err(reason) => { fallback.get_or_insert(reason); } @@ -189,6 +232,7 @@ impl ResizeTask { if cancelled() { return Err(crate::EngineError::Other("Texture set resize was cancelled".into())); } + progress.done.store(3_000, std::sync::atomic::Ordering::Relaxed); let resampled = Instant::now(); let set = doc.project.texture_set(ts)?; @@ -198,48 +242,70 @@ impl ResizeTask { log.performance(format!("GPU paint resize used CPU fallback: {reason}")); } log.performance(format!( - "Resize of texture set {} from {} to {}: paint resampling {} ms (GPU {} images in {} ms including transfers), CPU UV cache {}", + "Resize of texture set {} from {} × {} to {} × {}: paint resampling {} ms (GPU {} images in {} ms including transfers), CPU UV cache {}", ts + 1, old.resolution, + old.height(), resolution, + height, resampled.duration_since(start).as_millis(), gpu_images, gpu_ms, if cache.is_some() { format!("{} ms", resampled.elapsed().as_millis()) } else { "rebuilt on apply".into() } )); - Ok(ResizeOutput { ts, resolution, doc, cache, log, from }) + Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from }) } } impl ResizeOutput { - /// The texture set and resolution this resize is for. - pub fn target(&self) -> (usize, u32) { - (self.ts, self.resolution) + /// The texture set and requested width and height. + pub fn target(&self) -> (usize, u32, u32) { + (self.ts, self.resolution, self.height) } pub fn matches_session(&self, session: &Session) -> bool { - self.from == (session.revision, session.mesh_id) && !session.stroke_active() + self.project_id == session.project_id && self.from == (session.revision, session.mesh_id) && !session.stroke_active() } } 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.matches_session(self) { - 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 @@ -254,7 +320,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 })) } } @@ -274,15 +340,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) { @@ -321,13 +454,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(()) @@ -335,29 +480,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. @@ -371,4 +671,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].dilation.maps().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 234b57fa..1986b1fd 100644 --- a/crates/engine/src/solo.rs +++ b/crates/engine/src/solo.rs @@ -7,7 +7,7 @@ use std::borrow::Cow; use std::collections::BTreeMap; use serde_json::{Value, json}; -use texturecraft_compose::{Composite, composite_tiles}; +use texturecraft_compose::{Composite, PaddingMaps, composite_tiles}; use texturecraft_core::{Channel, LayerId, Project}; use texturecraft_geom::NO_TRI; use texturecraft_texel::TILE; @@ -82,9 +82,23 @@ impl Session { pub(crate) fn document_sample(&self, ts: usize, x: u32, y: u32) -> Option> { let cache = self.caches.get(ts)?; let needs_padding = cache.gbuf.tri.get((y * cache.size.0 + x) as usize) == Some(&NO_TRI); - let (x, y) = if needs_padding { cache.dilation.source_for_sample(x, y).unwrap_or((x, y)) } else { (x, y) }; - let composite = self.read_composite(ts, &[(x / TILE, y / TILE)], false)?; - Some(composite.channels.keys().map(|&channel| (channel, composite.value(channel, x, y))).collect()) + let flat = if needs_padding { cache.dilation.source_for_sample(false, x, y).unwrap_or((x, y)) } else { (x, y) }; + let across = if needs_padding && cache.dilation.needs_seam_padding() { cache.dilation.source_for_sample(true, x, y).unwrap_or(flat) } else { flat }; + let to_tile = |(x, y)| (x / TILE, y / TILE); + let tiles = [to_tile(flat), to_tile(across)]; + let count = if tiles[0] == tiles[1] { 1 } else { 2 }; + let composite = self.read_composite(ts, &tiles[..count], false)?; + + Some( + composite + .channels + .keys() + .map(|&channel| { + let (sx, sy) = if PaddingMaps::crosses_seams(channel) { across } else { flat }; + (channel, composite.value(channel, sx, sy)) + }) + .collect(), + ) } fn read_composite(&self, ts: usize, tiles: &[(u32, u32)], pad_output: bool) -> Option> { @@ -93,6 +107,7 @@ impl Session { if !document_in_solo && cache.dirty.is_empty() && cache.settle.is_empty() { return Some(Cow::Borrowed(&cache.composite)); } + let pending = if document_in_solo { Cow::Borrowed(tiles) } else { 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/tile_demand.rs b/crates/engine/src/tile_demand.rs index 09123e0f..0ac183de 100644 --- a/crates/engine/src/tile_demand.rs +++ b/crates/engine/src/tile_demand.rs @@ -25,6 +25,7 @@ impl Session { if w == 0 || h == 0 { return TileDemand::default(); } + let size = Vec2::new(w as f32, h as f32); let to_tile = |pixel: Vec2| ((pixel.x as u32).min(w - 1) / TILE, (pixel.y as u32).min(h - 1) / TILE); let brush = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_some()).and_then(|s| { @@ -41,12 +42,15 @@ impl Session { if !lo.is_finite() || !hi.is_finite() { return None; } + let (lo, hi) = (lo.max(Vec2::ZERO), hi.min(Vec2::ONE)); if !lo.cmplt(hi).all() { return None; } + let bounds = (to_tile(lo * size), to_tile((hi * size).ceil() - Vec2::ONE)); - // A view of the entire atlas benefits from the usual block ordering. + + // A view of the entire atlas benefits from the usual block ordering (bounds != ((0, 0), ((w - 1) / TILE, (h - 1) / TILE))).then_some(bounds) }); let brush = if self.stroke.is_some() { brush } else { cache.finished_dab.as_ref().and_then(crate::session::ReleasedDab::pending_tile) }; @@ -72,6 +76,7 @@ impl TileDemand { if limit == 0 || pending.len() <= limit { return tiles; } + if let Some((x, y)) = self.brush { if pending.remove(&(x, y)) { tiles.push((x, y)); @@ -89,7 +94,7 @@ fn take_rect(pending: &mut BTreeSet, lo: Tile, hi: Tile, limit: usize, til let mut left = lo.0; let start = tiles.len(); while left <= hi.0 && tiles.len() < limit { - // Seek to the next occupied column, then read only the requested rows in it. + // Seek to the next occupied column, then read only the requested rows in it let Some(&(x, _)) = pending.range((left, lo.1)..=(hi.0, hi.1)).next() else { break }; tiles.extend(pending.range((x, lo.1)..=(x, hi.1)).take(limit - tiles.len()).copied()); let Some(next) = x.checked_add(1) else { break }; 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 46fc30c4..4eb3c35b 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) @@ -501,14 +508,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/add_mask_items.rs b/crates/engine/tests/it/add_mask_items.rs index 1b93b325..4defde45 100644 --- a/crates/engine/tests/it/add_mask_items.rs +++ b/crates/engine/tests/it/add_mask_items.rs @@ -1,7 +1,7 @@ //! The layer toolbar's Add mask items that add a mask with an effect in it, and Add effect's colour selection: one undo step each, the new effect selected use serde_json::{Value, json}; -use texturecraft_engine::core::{Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; +use texturecraft_engine::core::{BlendMode, Channel, CompareSource, EffectKind, LayerId, MaskBackground, Source}; use texturecraft_engine::fill_alpha::resource_name; use texturecraft_engine::geom::primitives; use texturecraft_engine::paint::alphas; @@ -75,6 +75,41 @@ fn a_height_combination_is_a_mask_comparing_this_layers_height_with_the_layers_b assert_eq!(s.history_labels().last().map(String::as_str), Some("Add mask with height combination")); } +#[test] +fn a_height_combination_makes_the_layers_height_blend_normal_in_the_same_step() { + let (mut s, layer) = fill(); + execute(&mut s, "layer.blend", &json!({"layer": layer.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap(); + let height_mode = |s: &Session| s.doc.project.layer(layer).unwrap().channels.get(&Channel::Height).map(|blend| blend.mode); + let before = height_mode(&s); + assert!(before.is_some_and(|mode| mode != BlendMode::Normal), "the height starts out blending another way"); + + execute(&mut s, "mask.add.heightCombination", &json!({"layer": layer.0})).unwrap(); + assert_eq!(height_mode(&s), Some(BlendMode::Normal)); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(height_mode(&s), before, "one undo takes the mask and the blend back"); +} + +#[test] +fn an_instances_height_combination_sets_its_shared_height_blend_and_owns_its_mask() { + let (mut session, source) = fill(); + execute(&mut session, "layer.blend", &json!({"layer": source.0, "channel": "height", "enabled": true, "mode": "linearDodge"})).unwrap(); + let instance = execute(&mut session, "layer.instance", &json!({"layer": source.0})).unwrap()["layer"].as_u64().map(LayerId).unwrap(); + let original_height_mode = session.doc.project.layer(source).unwrap().blend(Channel::Height).unwrap().mode; + + execute(&mut session, "mask.add.heightCombination", &json!({"layer": instance.0})).unwrap(); + + let source_layer = session.doc.project.layer(source).unwrap(); + assert_eq!(source_layer.blend(Channel::Height).unwrap().mode, BlendMode::Normal); + assert!(source_layer.mask.is_none(), "the source keeps its own mask state"); + assert!(session.doc.project.layer(instance).unwrap().mask.is_some()); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + + assert_eq!(session.doc.project.layer(source).unwrap().blend(Channel::Height).unwrap().mode, original_height_mode); + assert!(session.doc.project.layer(instance).unwrap().mask.is_none()); +} + #[test] fn color_selections_go_in_the_mask_and_are_selected() { let (mut s, layer) = fill(); 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/content_effects.rs b/crates/engine/tests/it/content_effects.rs index c8929988..1888f557 100644 --- a/crates/engine/tests/it/content_effects.rs +++ b/crates/engine/tests/it/content_effects.rs @@ -691,3 +691,75 @@ fn a_color_histogram_has_its_components_and_luminance() { assert_eq!(counts(&histogram["bins"]), vec![2 * texels, 0, 0, texels]); assert!(roughness.get("components").is_none(), "one value has no components"); } + +#[test] +fn a_named_effect_moves_up_and_down_while_its_layer_content_is_selected() { + let mut s = session(); + let layer = LayerId(id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let add = |s: &mut Session| id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let (bottom, top) = (add(&mut s), add(&mut s)); + let order = |s: &Session| s.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap(); + s.target = StackTarget::Content; + + execute(&mut s, "effect.moveUp", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&s), [top, bottom]); + + execute(&mut s, "effect.moveDown", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&s), [bottom, top]); +} + +#[test] +fn a_malformed_named_effect_does_not_move_the_selected_effect() { + let mut session = session(); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + let add = |session: &mut Session| id(execute(session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let (bottom, _) = (add(&mut session), add(&mut session)); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": bottom})).unwrap(); + let before = session.doc.project.clone(); + + let result = execute(&mut session, "effect.moveUp", &json!({"effect": "invalid"})); + + assert!(result.unwrap_err().to_string().contains("must be an effect id")); + assert_eq!(session.doc.project, before); +} + +#[test] +fn copying_a_named_effects_blending_preserves_an_anchor_selection() { + let mut session = session(); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + let filter = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let anchor = id(execute(&mut session, "effect.add.anchor", &json!({"layer": layer})).unwrap(), "effect"); + execute(&mut session, "layer.select", &json!({"layer": layer, "target": anchor})).unwrap(); + let selection = session.selected_layer(); + + execute(&mut session, "effect.blending.copy", &json!({"effect": filter})).unwrap(); + + assert!(session.blending_clipboard.is_some(), "the command copies the named filter's blending"); + assert_eq!(session.target, StackTarget::Effect(LayerId(anchor))); + assert_eq!(session.selected_layer(), selection); +} + +#[test] +fn successive_effect_steps_can_share_one_undo_step() { + let mut session = session(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let add = |session: &mut Session| id(execute(session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let (bottom, middle, top) = (add(&mut session), add(&mut session), add(&mut session)); + let order = |session: &Session| session.doc.project.layers[&layer].content_effects.iter().map(|effect| effect.id.0).collect::>(); + let steps_before = session.history_labels().len(); + + execute(&mut session, "effect.moveUp", &json!({"effect": bottom})).unwrap(); + execute(&mut session, "effect.moveUp", &json!({"effect": bottom, "merge": true})).unwrap(); + let end = execute(&mut session, "effect.moveUp", &json!({"effect": bottom})).unwrap(); + + assert_eq!(order(&session), [middle, top, bottom]); + assert_eq!(end, json!({"moved": false})); + assert_eq!(session.history_labels().len(), steps_before + 1); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + + assert_eq!(order(&session), [bottom, middle, top]); +} 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/flatten_folder.rs b/crates/engine/tests/it/flatten_folder.rs new file mode 100644 index 00000000..8ec2da0c --- /dev/null +++ b/crates/engine/tests/it/flatten_folder.rs @@ -0,0 +1,395 @@ +//! Flattening a folder: a new fill layer above it reads one image per channel and its mask is baked, so the stack looks the same with the folder hidden + +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, StackTarget, execute}; + +/// The test project's texture size +const RESOLUTION: u32 = 256; + +/// Largest difference a flattened texel may show (16-bit images, straight values recovered from premultiplied ones) +const TOLERANCE: f32 = 4e-3; + +fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + s.update(); + s +} + +fn id(reply: Value) -> u64 { + reply["layer"].as_u64().unwrap() +} + +fn stroke(s: &mut Session, size: u32, points: [[u32; 2]; 2]) { + execute(s, "tool.brush", &json!({"size": size, "hardness": 40})).unwrap(); + execute(s, "tool.stroke", &json!({ "points": points })).unwrap(); +} + +/// Every channel's composited value at every texel +fn composite(s: &mut Session) -> Vec<[f32; 3]> { + s.update(); + let channels = s.doc.project.texture_set(0).unwrap().channel_list(); + let composite = &s.caches[0].composite; + channels.iter().flat_map(|c| (0..composite.height).flat_map(move |y| (0..composite.resolution).map(move |x| composite.value(*c, x, y)))).collect() +} + +fn largest_difference(a: &[[f32; 3]], b: &[[f32; 3]]) -> f32 { + // `f32::max` drops a NaN operand, so a broken composite would compare as equal + assert!(a.iter().chain(b).flatten().all(|value| value.is_finite()), "the composite holds only finite values"); + a.iter().zip(b).flat_map(|(a, b)| a.iter().zip(b).map(|(a, b)| (a - b).abs())).fold(0.0, f32::max) +} + +#[test] +fn a_flattened_folder_looks_the_same_as_the_folder_and_undoes_in_one_step() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "roughness": 0.2, "height": -0.3})).unwrap()); + let below = composite(&mut s); + + // A folder over it: a masked red fill and a soft roughness stroke, with a stroke in the folder's own mask + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.9, "height": 0.4})).unwrap()); + s.target = StackTarget::Mask; + stroke(&mut s, 30, [[170, 200], [230, 200]]); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "roughness", "value": 0.6})).unwrap(); + stroke(&mut s, 20, [[200, 160], [200, 240]]); + execute(&mut s, "layer.select", &json!({"layer": folder})).unwrap(); + s.target = StackTarget::Mask; + stroke(&mut s, 40, [[160, 215], [240, 215]]); + let before = composite(&mut s); + + assert!(largest_difference(&before, &below) > 0.1, "the folder shows over the layer below"); + + let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + let after = composite(&mut s); + + assert!(matches!(s.doc.project.layer(LayerId(flat)).unwrap().kind, LayerKind::Fill(_)), "the folder becomes a fill layer"); + assert!(!s.doc.project.layer(LayerId(folder)).unwrap().visible, "the folder is hidden under it"); + assert!(s.doc.project.layer(LayerId(flat)).unwrap().mask.is_some(), "the folder's mask is baked into the new layer"); + assert!(largest_difference(&after, &before) < TOLERANCE, "{}", largest_difference(&after, &before)); + + let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap(); + + assert!(largest_difference(&composite(&mut reopened), &before) < TOLERANCE, "the baked images keep their coverage when reopened"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + + assert!(s.doc.project.layer(LayerId(flat)).is_err(), "one undo step removes the flattened layer"); + assert!(s.doc.project.layer(LayerId(folder)).unwrap().visible, "and shows the folder again"); +} + +#[test] +fn a_flattened_folder_bakes_a_mask_that_reads_the_layers_below() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap(); + stroke(&mut s, 40, [[160, 200], [240, 200]]); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap()); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": folder})).unwrap(); + let before = composite(&mut s); + + id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Inside a folder, layers blending with Multiply, Screen or Overlay over the layers below the folder hide each part of the stack by a different amount: the flattened layer still shows what they did +#[test] +fn a_flattened_folder_looks_the_same_when_its_layers_blend_with_the_layers_below_it() { + for mode in ["multiply", "screen", "overlay"] { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.5, 0.8], "roughness": 0.4})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.9, 0.3, 0.1], "roughness": 0.7})).unwrap()); + for channel in ["baseColor", "roughness"] { + execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": channel, "mode": mode})).unwrap(); + } + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{mode}: {}", largest_difference(&composite(&mut s), &before)); + } +} + +/// A hidden folder shows nothing, so the layer it flattens into is hidden too +#[test] +fn a_hidden_folder_flattens_into_a_hidden_layer() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap(); + let before = composite(&mut s); + + let flat = id(execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap()); + + assert!(!s.doc.project.layer(LayerId(flat)).unwrap().visible, "the new layer is hidden like the folder"); + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "the image does not change"); +} + +/// A generator whose micro height reads an anchor point bakes as the viewport shows it +#[test] +fn a_flattened_folder_keeps_a_generators_anchor_micro_height() { + let mut s = texturecraft_engine::sample_session(128, 64).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let low = id(execute(&mut s, "layer.add.fill", &json!({"height": 1.0})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": low})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": low, "procedural": "checker", "scale": 4.0})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": low})).unwrap()["effect"].as_u64().unwrap(); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": top})).unwrap(); + let generator = execute(&mut s, "effect.add.generator", &json!({"layer": top, "generator": "curvature"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "effect.set", &json!({"effect": generator, "microAnchor": anchor, "microAmount": 1.0})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// A folder holding this one lays its Scale and Rotation on every fill inside it: the baked images stay where they were baked +#[test] +fn a_folder_flattened_inside_a_scaled_and_turned_folder_looks_the_same() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + stroke(&mut s, 30, [[170, 190], [230, 210]]); + execute(&mut s, "folder.contents.set", &json!({"layer": outer, "scale": 2.0, "rotation": 45.0})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": inner})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// A fill reads one image again on every UV tile, so a folder of a set with several tiles is refused instead of baked wrong +#[test] +fn flattening_a_folder_over_several_uv_tiles_is_refused() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": fill})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": fill, "procedural": "checker", "scale": 3.0})).unwrap(); + assert!(s.doc.project.texture_sets[0].uv_tiles.len() > 1, "the plane spans two UV tiles"); + let before = composite(&mut s); + let steps = s.history_labels().len(); + + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + if flattened.is_ok() { + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before)); + } + assert!(flattened.is_err(), "refused"); + assert_eq!(s.history_labels().len(), steps, "and nothing is changed"); +} + +/// A flatten that fails once its images are stored keeps none of their decoded pixels +#[test] +fn a_failed_folder_flatten_keeps_no_decoded_images() { + let mut s = session(); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + let decoded = s.images.len(); + + // The new layer gets a taken id, so placing it in the stack fails after its images are in + s.doc.project.next_id = folder; + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + let error = flattened.unwrap_err().to_string(); + assert!(error.contains("already exists"), "failed placing the new layer: {error}"); + assert_eq!(s.images.len(), decoded); +} + +/// A child reading an anchor point of the folder's own mask keeps what it read +#[test] +fn a_flattened_folder_keeps_what_a_child_reads_from_the_folder_mask() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": folder, "target": "mask", "value": 0.4})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// An instance of a folder draws at its source's channel opacity, so it flattens at it +#[test] +fn a_flattened_folder_instance_keeps_the_folders_opacity() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.25})).unwrap(); + + // With the folder selected the instance would go inside it + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "layer.visible", &json!({"layer": folder, "visible": false})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": instance})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Hiding a folder takes its anchor points with it, so a layer outside reading one would change: refused, nothing touched +#[test] +fn flattening_a_folder_whose_anchor_point_is_read_outside_it_is_refused() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "roughness": 0.0})).unwrap()); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": reader, "above": folder})).unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor, "anchorChannel": "roughness"})).unwrap(); + let project = s.doc.project.clone(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); + assert_eq!(s.doc.project, project, "nothing was added or hidden"); +} + +/// An instance's own mask goes with the hidden instance, and an outside layer stays on screen when only an instance of it sits in the folder +#[test] +fn flattening_is_refused_for_anchor_points_read_through_instances() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + let read = |s: &mut Session, anchor: u64| { + execute(s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap(); + }; + let anchor = |s: &mut Session, layer: u64, target: &str| { + execute(s, "effect.add.anchor", &json!({"layer": layer, "target": target})).unwrap()["effect"].as_u64().unwrap() + }; + + // The anchor point sits in the instance's own mask + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "layer.move", &json!({"layer": reader, "above": instance})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap(); + let own = anchor(&mut s, instance, "mask"); + read(&mut s, own); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": instance})).is_err(), "the instance's own anchor point is read outside it"); + + // The reader is also instanced inside the folder, and reads an anchor point there + execute(&mut s, "layer.remove", &json!({"layer": instance})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": child})).unwrap(); + execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap(); + let inside = anchor(&mut s, child, "content"); + read(&mut s, inside); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err(), "the instanced layer still reads from outside"); +} + +/// An instance above the folder draws a reader from inside it, without the anchor point that reader reads +#[test] +fn flattening_is_refused_when_an_instance_outside_draws_a_reader_from_inside() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": child})).unwrap()["effect"].as_u64().unwrap(); + let reader = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()); + execute(&mut s, "mask.add.black", &json!({"layer": reader})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": reader, "target": "mask", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": child})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": reader})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + let project = s.doc.project.clone(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); + assert_eq!(s.doc.project, project, "nothing was added or hidden"); +} + +/// An instance with its own mask draws the folder's children without the folder's mask and its anchor points +#[test] +fn flattening_is_refused_when_a_masked_instance_draws_a_reader_of_the_folder_mask() { + let mut s = session(); + let base = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let child = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0]})).unwrap()); + execute(&mut s, "mask.add.white", &json!({"layer": folder})).unwrap(); + let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": folder, "target": "mask"})).unwrap()["effect"].as_u64().unwrap(); + execute(&mut s, "mask.add.black", &json!({"layer": child})).unwrap(); + execute(&mut s, "effect.add.fill", &json!({"layer": child, "target": "mask", "anchor": anchor})).unwrap(); + execute(&mut s, "layer.select", &json!({"layer": base})).unwrap(); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder})).unwrap()); + execute(&mut s, "layer.move", &json!({"layer": instance, "above": folder})).unwrap(); + execute(&mut s, "mask.add.white", &json!({"layer": instance})).unwrap(); + + assert!(execute(&mut s, "layer.flatten", &json!({"layer": folder})).is_err()); +} + +/// A mask comparing a channel the set no longer has reads the folder's layers holding only that channel, before and after +#[test] +fn a_flattened_folder_keeps_what_its_masks_compare_in_a_removed_channel() { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0], "height": -0.3})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.material", &json!({"channel": "height", "value": 0.6})).unwrap(); + stroke(&mut s, 40, [[160, 200], [240, 200]]); + let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.2, 0.0], "height": 0.2})).unwrap()); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": top})).unwrap(); + execute(&mut s, "textureSet.channel.remove", &json!({"channel": "height"})).unwrap(); + let before = composite(&mut s); + + execute(&mut s, "layer.flatten", &json!({"layer": folder})).unwrap(); + + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "{}", largest_difference(&composite(&mut s), &before)); +} + +/// Linear dodge can take a folder's result past what an image holds, which the folder's opacity then mixes back: refused, not clipped +#[test] +fn flattening_a_folder_adding_up_past_white_is_refused() { + // The last folder's mask hides everything it adds, so nothing is clipped + for (added, masked, overflows) in [(0.25, false, false), (0.75, false, true), (0.75, true, false)] { + let mut s = session(); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.2, 0.2, 0.2], "roughness": 0.5})).unwrap()); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + let inner = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.1, 0.1, 0.1], "roughness": added})).unwrap()); + execute(&mut s, "layer.blend", &json!({"layer": inner, "channel": "roughness", "mode": "linearDodge"})).unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": folder, "channel": "all", "opacity": 0.5})).unwrap(); + if masked { + execute(&mut s, "mask.add.black", &json!({"layer": folder})).unwrap(); + } + let before = composite(&mut s); + let project = s.doc.project.clone(); + + let flattened = execute(&mut s, "layer.flatten", &json!({"layer": folder})); + + if flattened.is_ok() { + assert!(largest_difference(&composite(&mut s), &before) < TOLERANCE, "baked wrong by {}", largest_difference(&composite(&mut s), &before)); + } + assert_eq!(flattened.is_err(), overflows, "added roughness {added}, masked {masked}: {flattened:?}"); + if overflows { + assert_eq!(s.doc.project, project, "nothing was added or hidden"); + } + } +} diff --git a/crates/engine/tests/it/generator_names.rs b/crates/engine/tests/it/generator_names.rs new file mode 100644 index 00000000..f499114b --- /dev/null +++ b/crates/engine/tests/it/generator_names.rs @@ -0,0 +1,56 @@ +//! Generator effects are named after their kind, and a name taken from the kind follows a kind change + +use serde_json::{Value, json}; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::{Session, execute}; + +/// A sample session with a new generator of `kind` on its top layer's mask +fn generator(kind: &str) -> (Session, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.fill", &Value::Null).unwrap(); + let added = execute(&mut session, "effect.add.generator", &json!({"generator": kind})).unwrap(); + + (session, LayerId(added["effect"].as_u64().unwrap())) +} + +fn name(session: &Session, effect: LayerId) -> String { + session.doc.project.effect(effect).unwrap().1.name.clone() +} + +fn set(session: &mut Session, effect: LayerId, params: Value) { + let mut params = params; + params["effect"] = json!(effect.0); + execute(session, "effect.set", ¶ms).unwrap(); +} + +#[test] +fn a_new_generator_takes_its_kinds_name_and_keeps_following_it() { + let (mut session, effect) = generator("dirt"); + assert_eq!(name(&session, effect), "Dirt"); + + set(&mut session, effect, json!({"generator": "curvature"})); + + assert_eq!(name(&session, effect), "Curvature"); +} + +#[test] +fn a_chosen_name_survives_a_kind_change() { + let (mut session, effect) = generator("dirt"); + set(&mut session, effect, json!({"name": "Grime"})); + + set(&mut session, effect, json!({"generator": "curvature"})); + assert_eq!(name(&session, effect), "Grime"); + + set(&mut session, effect, json!({"generator": "dirt", "name": "Dust"})); + assert_eq!(name(&session, effect), "Dust", "a name given with the change wins"); +} + +#[test] +fn an_older_projects_generic_generator_name_follows_its_next_kind_change() { + let (mut session, effect) = generator("dirt"); + set(&mut session, effect, json!({"name": "Generator"})); + + set(&mut session, effect, json!({"generator": "curvature"})); + + assert_eq!(name(&session, effect), "Curvature"); +} diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index ba9d3b93..79e8be59 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -292,3 +292,21 @@ fn a_resampled_instance_refreshes_when_its_source_stroke_commits() { s.end_stroke().unwrap(); assert!(!s.caches[1].dirty.is_empty(), "committed source pixels must be resampled"); } + +#[test] +fn an_inherited_mask_effect_moves_from_another_texture_set_with_no_layer_selected() { + let mut s = session(); + let source = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer"); + execute(&mut s, "mask.add.black", &json!({"layer": source.0})).unwrap(); + let add = |s: &mut Session| id(execute(s, "effect.add.fill", &json!({"layer": source.0, "target": "mask", "value": 0.5})).unwrap(), "effect"); + let (lower, upper) = (add(&mut s), add(&mut s)); + execute(&mut s, "layer.instance", &json!({"layer": source.0, "ts": 1})).unwrap(); + s.active_set = 1; + s.selected.clear(); + + execute(&mut s, "effect.move", &json!({"effect": lower.0, "index": 1})).unwrap(); + + let order: Vec = s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect(); + assert_eq!(order, [upper, lower]); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); +} diff --git a/crates/engine/tests/it/layer_multi_select.rs b/crates/engine/tests/it/layer_multi_select.rs index 14c375d8..9d37db3d 100644 --- a/crates/engine/tests/it/layer_multi_select.rs +++ b/crates/engine/tests/it/layer_multi_select.rs @@ -3,7 +3,7 @@ //! act on every selected layer in one undo step. use serde_json::{Value, json}; -use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::core::{BlendMode, Channel, LayerId, LayerKind}; use texturecraft_engine::geom::primitives; use texturecraft_engine::layer_selection::stack_rows; use texturecraft_engine::{Session, execute}; @@ -523,3 +523,35 @@ fn moving_layers_into_a_folder_in_another_set_preserves_the_document() { assert_eq!(s.history_labels(), history); } } + +#[test] +fn a_rows_controls_act_on_its_layer_with_no_layer_selected() { + let mut s = session(); + let [a, ..] = four(&mut s); + // An undo can leave no layer selected; the row's eye and blend menu still name their layer + s.selected.clear(); + + execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap(); + execute(&mut s, "layer.blend", &json!({"layer": a.0, "channel": "baseColor", "mode": "Multiply"})).unwrap(); + let layer = s.doc.project.layer(a).unwrap(); + assert!(!layer.visible, "the eye hid its layer"); + assert_eq!(layer.blend(Channel::BaseColor).map(|b| b.mode), Some(BlendMode::Multiply), "the blend menu changed its layer"); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); + assert!(execute(&mut s, "layer.visible", &Value::Null).is_err(), "with no layer named, nothing is selected to act on"); +} + +#[test] +fn an_effect_rows_menu_moves_its_effect_with_no_layer_selected() { + let mut s = session(); + let [a, ..] = four(&mut s); + let add = + |s: &mut Session| execute(s, "effect.add.filter", &json!({"layer": a.0, "target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap(); + let (lower, upper) = (add(&mut s), add(&mut s)); + s.selected.clear(); + + execute(&mut s, "effect.move", &json!({"effect": lower, "index": 1})).unwrap(); + + let order: Vec = s.doc.project.layer(a).unwrap().content_effects.iter().map(|effect| effect.id.0).collect(); + assert_eq!(order, [upper, lower]); + assert_eq!(s.selected_layer(), None, "the selection stays as it was"); +} diff --git a/crates/engine/tests/it/layer_pick.rs b/crates/engine/tests/it/layer_pick.rs new file mode 100644 index 00000000..9b0e9454 --- /dev/null +++ b/crates/engine/tests/it/layer_pick.rs @@ -0,0 +1,207 @@ +//! Picking a layer on the mesh (R + click): the layers laying something down at a spot, top first, and selecting one of them + +use serde_json::{Value, json}; +use texturecraft_engine::core::{LayerId, LayerKind}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, Solo, execute}; + +/// The middle of the sphere in the test viewport, where the lower paint layer is painted +const MIDDLE: [f32; 2] = [200.0, 200.0]; + +/// A spot on the sphere left of the middle, where only the upper paint layer is painted +const LEFT: [f32; 2] = [130.0, 200.0]; + +/// The test stack: (session, the fill at the bottom, a paint layer over the middle, a paint layer over the left spot above it) +fn stack() -> (Session, u64, u64, u64) { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + let middle = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.brush", &json!({"size": 20, "hardness": 100})).unwrap(); + execute(&mut s, "tool.stroke", &json!({"points": [[190, 200], [210, 200]]})).unwrap(); + let left = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap()); + execute(&mut s, "tool.stroke", &json!({"points": [[125, 200], [135, 200]]})).unwrap(); + s.update(); + (s, fill, middle, left) +} + +fn id(reply: Value) -> u64 { + reply["layer"].as_u64().unwrap() +} + +fn click(s: &mut Session, [x, y]: [f32; 2]) -> Option { + execute(s, "layer.pickAt", &json!({"x": x, "y": y})).ok().map(id) +} + +/// The layers `layer.layersAt` lists at a spot, top first, each with the channels it changes there +fn layers_at(s: &mut Session, [x, y]: [f32; 2]) -> Vec<(u64, Vec)> { + let reply = execute(s, "layer.layersAt", &json!({"x": x, "y": y})).unwrap(); + let channels = |row: &Value| row["channels"].as_array().unwrap().iter().map(|channel| channel.as_str().unwrap().to_owned()).collect(); + reply["layers"].as_array().unwrap().iter().map(|row| (id(row.clone()), channels(row))).collect() +} + +#[test] +fn a_spot_lists_the_layers_laying_something_there_top_first_and_a_pick_selects_the_one_asked_for() { + let (mut s, fill, middle, left) = stack(); + execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "roughness", "opacity": 0.0})).unwrap(); + + let listed = layers_at(&mut s, MIDDLE); + let order: Vec = listed.iter().map(|(layer, _)| *layer).collect(); + assert_eq!(order, [middle, fill], "the layer painted elsewhere is left out; the top one comes first"); + assert!( + !listed[0].1.contains(&"roughness".to_owned()) && listed[1].1.contains(&"roughness".to_owned()), + "a channel at zero opacity is not among the ones the layer changes there" + ); + + assert_eq!(click(&mut s, MIDDLE), Some(middle), "a plain pick selects the top layer"); + assert_eq!(click(&mut s, MIDDLE), Some(middle), "the same spot again keeps the top layer"); + let picked = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": fill})).map(id).ok(); + assert_eq!(picked, Some(fill), "a listed layer is selected when asked for"); + assert_eq!(s.selected_layer_id().map(|layer| layer.0), Some(fill)); + assert!( + execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": left})).is_err(), + "a layer not laying anything down there is refused" + ); + assert_eq!(click(&mut s, LEFT), Some(left), "another spot picks its own top layer"); +} + +#[test] +fn hidden_layers_and_channels_out_of_view_lay_nothing_down() { + let (mut s, fill, middle, _) = stack(); + execute(&mut s, "layer.blend", &json!({"layer": middle, "channel": "baseColor", "opacity": 0.0})).unwrap(); + execute(&mut s, "viewport.view", &json!({"mode": "baseColor"})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(fill), "in the base colour view the layer at zero base colour opacity shows nothing"); + + execute(&mut s, "viewport.view", &json!({"mode": "material"})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(middle), "the material view counts its other channels"); + + execute(&mut s, "layer.visible", &json!({"layer": middle, "visible": false})).unwrap(); + assert_eq!(click(&mut s, MIDDLE), Some(fill), "a hidden layer is skipped"); +} + +#[test] +fn a_pick_opens_the_collapsed_folders_holding_the_picked_layer() { + let (mut s, _, middle, _) = stack(); + execute(&mut s, "layer.group", &json!({"layer": middle})).unwrap(); + let inner = s.selected_layer_id().unwrap(); + execute(&mut s, "layer.group", &json!({"layer": inner.0})).unwrap(); + let outer = s.selected_layer_id().unwrap(); + for folder in [inner, outer] { + if let Some(LayerKind::Group { collapsed, .. }) = s.doc.project.layers.get_mut(&folder).map(|layer| &mut layer.kind) { + *collapsed = true; + } + } + + assert_eq!(click(&mut s, MIDDLE), Some(middle)); + + let open = |folder| matches!(s.doc.project.layers[&folder].kind, LayerKind::Group { collapsed: false, .. }); + assert!(open(inner) && open(outer), "both folders holding the picked layer are open"); +} + +/// Each height-combination mask compares with the layers below its own layer, not below another's +#[test] +fn a_height_combination_mask_is_read_against_the_layers_below_its_own_layer() { + let (mut s, ..) = stack(); + let add = |s: &mut Session, height: f32| id(execute(s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "height": height})).unwrap()); + let base = add(&mut s, 0.0); + let lower = add(&mut s, 0.3); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": lower})).unwrap(); + let raised = add(&mut s, 0.6); + let upper = add(&mut s, 0.9); + execute(&mut s, "mask.add.heightCombination", &json!({"layer": upper})).unwrap(); + for layer in [base, raised] { + execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "height", "mode": "Normal"})).unwrap(); + } + execute(&mut s, "layer.blend", &json!({"layer": raised, "channel": "baseColor", "enabled": false})).unwrap(); + s.update(); + + let listed: Vec = layers_at(&mut s, MIDDLE).into_iter().map(|(layer, _)| layer).collect(); + + assert!(listed.contains(&lower), "the lower combination shows over the base: {listed:?}"); + assert!(listed.contains(&upper), "and so does the upper one: {listed:?}"); +} + +#[test] +fn a_pick_of_something_that_is_not_a_layer_id_is_refused() { + let (mut s, ..) = stack(); + let selected = s.selected_layer(); + + let reply = execute(&mut s, "layer.pickAt", &json!({"x": MIDDLE[0], "y": MIDDLE[1], "layer": "fill"})); + + assert!(reply.is_err(), "not silently replaced by the top layer: {reply:?}"); + assert_eq!(s.selected_layer(), selected); +} + +#[test] +fn a_soloed_layer_is_the_only_one_listed_and_picked() { + let (mut s, fill, ..) = stack(); + s.set_solo(Some(Solo { layer: LayerId(fill), ignore_mask: false })); + s.update(); + + let order: Vec = layers_at(&mut s, MIDDLE).iter().map(|(layer, _)| *layer).collect(); + + assert_eq!(order, [fill], "the layers solo hides are not on screen"); + assert_eq!(click(&mut s, MIDDLE), Some(fill)); +} + +#[test] +fn a_folder_instance_is_listed_once_and_picks_its_own_row() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + s.viewport = Vec2::splat(400.0); + let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.1, 0.1]})).unwrap()); + id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.25})).unwrap()); + let instance = id(execute(&mut s, "layer.instance", &json!({"layer": folder, "ts": 1})).unwrap()); + s.update(); + let point = (100..300) + .step_by(10) + .flat_map(|y| (100..300).step_by(10).map(move |x| [x as f32, y as f32])) + .find(|point| { + s.texel_under(Vec2::from(*point), s.viewport).is_some_and(|(ts, (x, y))| { + let gbuf = &s.caches[ts].gbuf; + ts == 1 && gbuf.surface(&s.mesh, (y * gbuf.width + x) as usize).is_some() + }) + }) + .expect("a covered texel of the ball's second texture set"); + + let listed = layers_at(&mut s, point); + let picked = click(&mut s, point); + + assert_eq!(listed.iter().map(|(layer, _)| *layer).collect::>(), [instance]); + assert!(listed[0].1.iter().any(|channel| channel == "baseColor")); + assert!(listed[0].1.iter().any(|channel| channel == "roughness")); + assert_eq!(picked, Some(instance)); + assert_eq!(s.ts(), 1); + assert_eq!(s.selected_layer(), Some(LayerId(instance))); +} + +#[test] +fn a_layer_pick_passes_through_hidden_texture_sets() { + let rear = primitives::sphere(1.0, 48, 24); + let mut mesh = rear.clone(); + for position in &mut mesh.positions { + position.z += 2.5; + } + + mesh.append(&rear); + let mut s = Session::new_project("t", mesh, "builtin:sphere", None, 128).unwrap(); + s.viewport = Vec2::splat(400.0); + s.camera.yaw = 0.0; + s.camera.pitch = 0.0; + let near = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap()); + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + let far = id(execute(&mut s, "layer.add.fill", &json!({"color": [0.0, 0.0, 1.0]})).unwrap()); + s.update(); + assert_eq!(click(&mut s, MIDDLE), Some(near), "the visible near sphere owns this pixel"); + + execute(&mut s, "textureSet.visible", &json!({"ts": 0, "visible": false})).unwrap(); + let listed = layers_at(&mut s, MIDDLE); + let picked = click(&mut s, MIDDLE); + + assert_eq!(listed.iter().map(|(layer, _)| *layer).collect::>(), [far]); + assert_eq!(picked, Some(far)); + assert_eq!(s.ts(), 1); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 01f63de0..de35b715 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -36,11 +36,13 @@ mod filter_support; mod filter_swap; mod filter_transform; mod filters; +mod flatten_folder; mod folder_contents; mod frame_selection; mod generator_custom_grunge; mod generator_inputs; mod generator_micro_details; +mod generator_names; mod generator_sections; mod generator_swap; mod generator_texture; @@ -51,6 +53,7 @@ mod high_poly_missed; mod instances; mod ior_specular; mod layer_multi_select; +mod layer_pick; mod mask_clone_smudge; mod mask_export; mod mask_fill_source; diff --git a/crates/engine/tests/it/perf.rs b/crates/engine/tests/it/perf.rs index eed62a0c..814c3a51 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(); @@ -593,7 +593,7 @@ fn bench_filtered_mask_edits() { let baked = s.doc.baked.get(&0).unwrap_or(&fallback); tiles.par_iter().for_each(|&(x, y)| { for kind in kinds_for(&channels) { - std::hint::black_box(tile_bytes(&cache.composite, baked, kind, x, y)); + std::hint::black_box(tile_bytes(&cache.composite, baked, texturecraft_core::AoMixing::Multiply, kind, x, y)); } }); if i >= 3 { diff --git a/crates/engine/tests/it/project_recovery.rs b/crates/engine/tests/it/project_recovery.rs index be3ca488..ec37dbc1 100644 --- a/crates/engine/tests/it/project_recovery.rs +++ b/crates/engine/tests/it/project_recovery.rs @@ -30,8 +30,7 @@ fn recovered_project_opens_with_a_warning_in_the_session_log() { std::fs::write(&path, &bytes).unwrap(); execute(&mut original, "file.open", &json!({"path": path})).unwrap(); - // Both entry points report the same recovery messages. The archive timing has - // a different label for path opens, and elapsed times vary between runs. + // Both open paths must report recovery independently of their timing labels let entries = |log: &texturecraft_engine::SessionLog| { log.iter().filter(|entry| entry.source != "Performance").map(|entry| (entry.level, entry.line())).collect::>() }; 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 2e8b966d..7c9ca7fd 100644 --- a/crates/engine/tests/it/uv_strokes.rs +++ b/crates/engine/tests/it/uv_strokes.rs @@ -202,3 +202,19 @@ fn filtered_stroke_refreshes_the_neighbour_on_preview_cancel_commit_and_history( assert!(!s.caches[0].dirty.contains(&(3, 3)), "redo leaves distant tiles alone"); assert!(compare_full(&mut s, "redo") == committed); } + +#[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 a85191eb..4229da6b 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(); @@ -517,6 +535,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(); @@ -714,6 +818,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(); @@ -829,6 +1151,65 @@ fn cancelling_a_mask_stroke_does_not_reuse_its_paint_margin() { assert!(incremental == recomposited, "the complete cache matches a full recomposite"); } +#[test] +fn painting_near_an_edge_refreshes_the_opposite_edge_of_a_wrapping_mask() { + use texturecraft_engine::StackTarget; + use texturecraft_engine::core::LayerId; + + let mut session = Session::new_project("Wrapping mask", primitives::plane(1.0, 1), "builtin:plane", None, 256).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + let filter = execute(&mut session, "effect.add.filter", &json!({"filter": "blur", "radius": 32.0, "wrap": true})).unwrap(); + session.target = StackTarget::Effect(LayerId(filter["effect"].as_u64().unwrap())); + session.tool.brush.size = 0.01; + session.tool.mask_value = 1.0; + session.update(); + let opposite_edge = (255, 96); + let before = session.caches[0].composite.value(Channel::BaseColor, opposite_edge.0, opposite_edge.1); + + session.begin_stroke_uv(Vec2::new(2.0 / 256.0, 96.0 / 256.0), 1.0).unwrap(); + assert_eq!(session.stroke_tiles(), 1, "the stroke must stay in the first tile"); + session.end_stroke().unwrap(); + session.update(); + let incremental = session.caches[0].composite.clone(); + + let recomposited = full(&mut session); + let expected = recomposited.value(Channel::BaseColor, opposite_edge.0, opposite_edge.1); + assert_ne!(expected, before, "the wrapped blur reaches the far edge"); + assert_eq!(incremental.value(Channel::BaseColor, opposite_edge.0, opposite_edge.1), expected, "the far edge must refresh"); + assert!(incremental == recomposited, "the entire incremental cache matches a full recomposite"); +} + +#[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] @@ -847,14 +1228,15 @@ fn background_resizes_match_the_command_and_keep_later_edits() { let progress = Progress::new(); let out = task.run(&progress).unwrap(); assert_eq!(progress.fraction(), 1.0); - assert_eq!(out.target(), (0, 512)); + assert_eq!(out.target(), (0, 512, 512)); b.apply_resize(out).unwrap(); assert_eq!(a.doc.pixels.layers, b.doc.pixels.layers); a.update(); b.update(); assert_eq!(a.caches[0].composite, b.caches[0].composite); assert_eq!(b.caches[0].size, (512, 512)); - // A stroke painted while the resize ran is kept (the resize runs again on apply). + + // Applying the resize must preserve a stroke completed after the task starts let out = b.resize_task(0, 1024).unwrap().run(&Progress::new()).unwrap(); stroke(&mut b, 260); let painted = |s: &Session| s.doc.pixels.layers.values().map(|i| i.allocated_count()).sum::(); @@ -1221,7 +1603,7 @@ fn a_budgeted_slice_composites_the_brush_then_the_visible_uv_before_the_backlog( let result = s.caches[0].composite.clone(); assert_eq!(result, full(&mut s)); - // A 3D stroke supplies the atlas UV from its existing surface hit. + // A 3D stroke supplies the atlas UV from its existing surface hit let screen = Vec2::splat(128.0); let viewport = Vec2::splat(256.0); let hit = s.pick(screen, viewport).unwrap(); @@ -1254,8 +1636,8 @@ fn switching_materials_reuses_idle_bands_within_the_active_budget() { assert_eq!(s.caches[0].below.bytes(), bytes); select(&mut s, 0); assert_eq!(s.caches[0].below.bytes(), bytes); - // The parked set alone would fit. A third set drawing an instance of - // material one's selected layer also earns bands from this pass. + + // The dependent instance shares the budget with the active and parked sets s.caches[1].below.budget = bytes + s.caches[1].below.bytes(); s.caches[2].invalidate_all(); select(&mut s, 1); @@ -1321,3 +1703,25 @@ fn interleaved_sessions_render_depth_from_their_own_mesh() { assert!((hidden[0] - hidden[1]).abs() < 0.05, "the rear surface is occluded: {hidden:?}"); assert!(visible[0] > visible[1] + 0.5, "the rear surface is exposed: {visible:?}"); } + +/// 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 session = session(); + for _ in 0..texturecraft_engine::session::MAX_HISTORY { + execute(&mut session, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + } + let (labels, added) = (session.history_labels(), session.steps_added()); + + execute(&mut session, "tool.stroke", &json!({"points": [[180, 200], [220, 200]]})).unwrap(); + + 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 = session.steps_added(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + + 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 824a37ea..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, } @@ -767,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; @@ -779,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(); @@ -909,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; @@ -944,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}\"")); } @@ -989,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. @@ -1053,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. @@ -1076,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, @@ -1085,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, @@ -1115,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) @@ -1185,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]] @@ -1267,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))) @@ -1289,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); @@ -1302,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/image_res.rs b/crates/formats/src/image_res.rs index 903b5b53..8be2475e 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -173,6 +173,21 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator Result<(Vec, DecodedImage)> { + let texels = u64::from(width) * u64::from(height); + if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS { + return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)"))); + } + + let image = Image::from_u16(width, height, ChannelLayout::Rgba, samples).map_err(|error| FormatError::Invalid(error.to_string()))?; + let png = encode_resource_png(&image)?; + + // Divide as the PNG decoder does for RGBA, so reload is bit-identical + let rgba = samples.as_chunks::<4>().0.iter().map(|pixel| pixel.map(|sample| f32::from(sample) / f32::from(u16::MAX))).collect(); + Ok((png, DecodedImage { width, height, rgba, srgb: true })) +} + fn encode_resource_png(image: &Image) -> Result> { let options = EncodeOptions { png_compression: PngCompression::Fast, ..EncodeOptions::default() }; craft_image_codecs::encode(image, Format::Png, &options).map_err(|error| FormatError::Invalid(error.to_string())) @@ -299,6 +314,23 @@ mod tests { assert!(gray16_resource(2, 1, [0.5].into_iter()).is_err()); } + #[test] + fn generated_rgba16_resource_matches_reload_for_every_sample_value() { + // Every value in each of red, green, blue and alpha, with gray pixels as scalar channels write them + let mixed = (0..=u16::MAX).flat_map(|value| [value, value.wrapping_add(1), value.wrapping_add(2), value.wrapping_mul(3)]); + let gray = (0..=u16::MAX).flat_map(|value| [value, value, value, u16::MAX - value]); + let samples: Vec = mixed.chain(gray).collect(); + + let (png, decoded) = rgba16_resource(512, 256, &samples).unwrap(); + + let reloaded = decode_image(&png).unwrap(); + assert_eq!((decoded.width, decoded.height, decoded.srgb), (reloaded.width, reloaded.height, reloaded.srgb)); + for (index, (cached, saved)) in decoded.rgba.iter().zip(&reloaded.rgba).enumerate() { + assert_eq!(cached, saved, "pixel {index}"); + } + assert!(rgba16_resource(2, 1, &[0; 4]).is_err(), "too few samples for the size"); + } + #[test] fn gray16_stops_after_one_excess_pixel() { let mut pixels_read = 0; diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 85356dce..7dbbda45 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -45,7 +45,7 @@ pub use export::{ Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MAX_PREVIEW_SIDE, MapOverride, MapPreview, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names, }; -pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource}; +pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource, rgba16_resource}; pub use mesh_export::{ GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings, 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/mesh.rs b/crates/geom/src/mesh.rs index 395e6c5e..bd99e01f 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -58,6 +58,9 @@ const QUAD_SECOND_MARK: u8 = 0b001; /// Hard cap on mesh size accepted from files (triangles). pub const MAX_TRIANGLES: usize = 20_000_000; +/// Largest UV coordinate a mesh may carry (UDIM tiles stop at 10 columns; this is far beyond any +/// real layout). Texel lookups turn UVs into integers, which a UV like 1e30 would overflow. +pub const MAX_UV: f32 = 1.0e6; impl Mesh { pub fn triangle_count(&self) -> usize { @@ -220,6 +223,12 @@ impl Mesh { if self.positions.iter().any(|p| !p.is_finite()) { return Err(GeomError::Invalid("mesh has non-finite positions".into())); } + if self.normals.iter().any(|n| !n.is_finite()) { + return Err(GeomError::Invalid("mesh has non-finite normals".into())); + } + if self.uvs.iter().any(|uv| !uv.is_finite() || uv.x.abs() > MAX_UV || uv.y.abs() > MAX_UV) { + return Err(GeomError::Invalid(format!("mesh has non-finite UVs or UVs beyond ±{MAX_UV}"))); + } for s in &self.submeshes { if s.start as usize + s.count as usize > self.indices.len() || s.material >= self.materials.len().max(1) { return Err(GeomError::Invalid(format!("submesh {} is out of range", s.name))); @@ -895,6 +904,27 @@ mod tests { assert!(m.validate().is_err()); } + /// Validation rejects non-finite normals and non-finite or beyond-limit UVs, but accepts UDIM-style UVs. + #[test] + fn validate_refuses_non_finite_normals_and_absurd_uvs() { + assert!(quad().validate().is_ok()); + for bad in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1.0e30, -2.0e6] { + let mut m = quad(); + m.uvs[1].x = bad; + assert!(m.validate().is_err(), "uv {bad}"); + let mut m = quad(); + m.uvs[2].y = bad; + assert!(m.validate().is_err(), "uv {bad}"); + } + let mut m = quad(); + m.normals[0].z = f32::NAN; + assert!(m.validate().is_err()); + // Large but real UDIM-style layouts stay valid. + let mut m = quad(); + m.uvs[0] = Vec2::new(1009.5, 0.5); + assert!(m.validate().is_ok()); + } + #[test] fn append_offsets_indices_and_materials() { let mut a = quad(); 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 d5c3190b..9cb2bad9 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), @@ -331,8 +342,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)] @@ -341,7 +352,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/raster.rs b/crates/paint/src/raster.rs index 1d515924..4eeabf79 100644 --- a/crates/paint/src/raster.rs +++ b/crates/paint/src/raster.rs @@ -802,10 +802,10 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s } let (cx, cy, r) = (s.center.x * w as f32, s.center.y * h as f32, s.radius * w as f32); - let x0 = (cx - r * 1.42).floor().max(0.0) as u32; - let x1 = ((cx + r * 1.42).ceil().max(0.0) as u32).min(w); - let y0 = (cy - r * 1.42).floor().max(0.0) as u32; - let y1 = ((cy + r * 1.42).ceil().max(0.0) as u32).min(h); + let x0 = (cx - r * Stamp::PLANAR_RADIUS_SCALE).floor().max(0.0) as u32; + let x1 = ((cx + r * Stamp::PLANAR_RADIUS_SCALE).ceil().max(0.0) as u32).min(w); + let y0 = (cy - r * Stamp::PLANAR_RADIUS_SCALE).floor().max(0.0) as u32; + let y1 = ((cy + r * Stamp::PLANAR_RADIUS_SCALE).ceil().max(0.0) as u32).min(h); let (sn, cs) = s.angle.to_radians().sin_cos(); let shape = shape.at_radius(r); for y in y0..y1 { diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index b2da8205..4db995e8 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -30,10 +30,15 @@ pub struct SurfaceHit { /// Pick the mesh at a viewport pixel (origin top-left). pub fn pick(ctx: &PickCtx, screen: Vec2) -> Option { + pick_filtered(ctx, screen, &|_| true) +} + +/// Pick the nearest triangle accepted by `filter` at a viewport pixel. +pub fn pick_filtered(ctx: &PickCtx, screen: Vec2, filter: &dyn Fn(u32) -> bool) -> Option { let vp = ctx.viewport.max(Vec2::ONE); let ndc = Vec2::new(screen.x / vp.x * 2.0 - 1.0, 1.0 - screen.y / vp.y * 2.0); let ray = ctx.camera.ray(ndc, vp.x / vp.y); - let hit = ctx.bvh.closest(ray.origin, ray.dir, f32::MAX)?; + let hit = ctx.bvh.closest_filtered(ray.origin, ray.dir, f32::MAX, filter)?; let s = surface_at(ctx.mesh, hit.tri, hit.u, hit.v)?; Some(SurfaceHit { pos: s.pos, nrm: s.nrm, tri: hit.tri, uv: s.uv, material: ctx.mesh.material_of(hit.tri as usize).unwrap_or(0), screen }) } @@ -70,12 +75,15 @@ pub struct Stamp { } impl Stamp { + /// Conservative radius multiplier covering the corners of a rotated square dab. + pub const PLANAR_RADIUS_SCALE: f32 = 1.42; + /// World-space half-extents of the volume tested by the stamp rasterizers. pub fn world_extent(&self) -> Vec3 { - // Project the tangent-plane disk of radius sqrt(2) and the normal slab onto each world axis. + // Project the tangent-plane disk of radius sqrt(2) and the normal slab onto each world axis let squared = self.tangent * self.tangent + self.bitangent * self.bitangent; let planar = Vec3::new(squared.x.sqrt(), squared.y.sqrt(), squared.z.sqrt()); - (planar * 1.42 + self.normal.abs() * self.depth) * self.radius + (planar * Self::PLANAR_RADIUS_SCALE + self.normal.abs() * self.depth) * self.radius } } @@ -135,11 +143,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 b14ebb33..193fd731 100644 --- a/crates/render/Cargo.toml +++ b/crates/render/Cargo.toml @@ -17,7 +17,6 @@ test-support = [] texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } -texturecraft-paint = { workspace = true } texturecraft-compose = { workspace = true } wgpu = { workspace = true } bytemuck = { workspace = true } @@ -28,6 +27,7 @@ serde = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] texturecraft-bake = { workspace = true } +texturecraft-paint = { workspace = true } pollster = "0.4" # The browser's WebGPU resolves error scopes later: their results are awaited on the page. @@ -39,3 +39,7 @@ image = { workspace = true } texturecraft-formats = { workspace = true } # The version wgpu uses: checks the composite and neighbourhood WGSL and its GLSL output without an adapter naga = { version = "30.0.1", features = ["wgsl-in", "glsl-out"] } + +# 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/build.rs b/crates/render/build.rs deleted file mode 100644 index 2f4c0627..00000000 --- a/crates/render/build.rs +++ /dev/null @@ -1,16 +0,0 @@ -//! Test executables of this crate on Windows (MSVC) reserve 8 MiB for each thread that does not -//! ask for a stack size of its own. Mesa's lavapipe, which the Windows CI gate renders with, -//! runs our compute shaders on its own threads, and Windows gives those the executable's -//! default of 1 MiB, which the larger composite programs overflow. Linux gives them 8 MiB. - -/// Bytes each thread reserves for its stack when it asks for none. -const THREAD_STACK_RESERVE: u32 = 8 * 1024 * 1024; - -fn main() { - println!("cargo:rerun-if-changed=build.rs"); - let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(); - if target_os == "windows" && target_env == "msvc" { - println!("cargo:rustc-link-arg=/STACK:{THREAD_STACK_RESERVE}"); - } -} diff --git a/crates/render/src/composite_group/group_plan.rs b/crates/render/src/composite_group/group_plan.rs new file mode 100644 index 00000000..25536b2e --- /dev/null +++ b/crates/render/src/composite_group/group_plan.rs @@ -0,0 +1,41 @@ +use super::{Channel, Operation, channel_slot, is_group}; + +#[derive(Debug, Default)] +pub(in super::super) struct GroupPlan { + pub(in super::super) depth: u32, + pub(in super::super) channels: u32, + pub(in super::super) words_per_level: u32, + pub(super) markers: u64, +} + +impl GroupPlan { + pub(in super::super) fn finish(&mut self, operations: &[Operation]) { + if self.depth == 0 { + return; + } + + for op in operations { + if is_group(op) { + self.markers += 1; + } else if let Some(bit) = 1u32.checked_shl(op.ids[0]) { + self.channels |= bit; + } + } + + // One word for the mask, then compact snapshots of the channels that can change + self.words_per_level = 1 + Channel::ALL + .iter() + .take(Channel::SHADED_COUNT) + .filter(|&&channel| self.channels & (1 << channel_slot(channel)) != 0) + .map(|channel| channel.components() as u32) + .sum::(); + } + + pub(in super::super) fn words(&self, pixels: u64) -> u64 { + pixels * u64::from(self.depth) * u64::from(self.words_per_level) + } + + pub(in super::super) fn work_per_pixel(&self) -> u64 { + self.markers * u64::from(self.words_per_level) + } +} diff --git a/crates/render/src/composite_group/stack_work.rs b/crates/render/src/composite_group/stack_work.rs new file mode 100644 index 00000000..4ef454f3 --- /dev/null +++ b/crates/render/src/composite_group/stack_work.rs @@ -0,0 +1,6 @@ +use super::LayerId; + +pub(in super::super) enum StackWork { + Layer(LayerId, usize, u32), + EndGroup(usize), +} diff --git a/crates/render/src/composite_package/shader_flags.rs b/crates/render/src/composite_package/shader_flags.rs new file mode 100644 index 00000000..65b24310 --- /dev/null +++ b/crates/render/src/composite_package/shader_flags.rs @@ -0,0 +1,41 @@ +use super::{CompositeProgram, brush, fill_projection, lighting, point, stack, udim}; + +/// Which package WGSL files a program compiles in full; the others compile as stubs so that +/// Mesa does not inline unused code (gpu_composite_pipelines.rs). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub(in super::super) struct ShaderFlags { + pub(super) projection: bool, + pub(super) point: bool, + pub(super) stack: bool, + pub(super) lighting: bool, + pub(super) brush: bool, + pub(super) udim: bool, +} + +impl ShaderFlags { + pub(in super::super) fn of(program: &CompositeProgram) -> Self { + Self { + projection: fill_projection::uses_shader(program), + point: point::uses_shader(program), + stack: stack::uses_shader(program), + lighting: lighting::uses_shader(program), + brush: brush::uses_shader(program), + udim: udim::uses_shader(program), + } + } + + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(in super::super) const ALL: Self = Self { projection: true, point: true, stack: true, lighting: true, brush: true, udim: true }; + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(super) const NONE: Self = Self { projection: false, point: false, stack: false, lighting: false, brush: false, udim: false }; + /// Each package's file in full, the others as stubs. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(in super::super) const EACH: [Self; 6] = [ + Self { projection: true, ..Self::NONE }, + Self { point: true, ..Self::NONE }, + Self { stack: true, ..Self::NONE }, + Self { lighting: true, ..Self::NONE }, + Self { brush: true, ..Self::NONE }, + Self { udim: true, ..Self::NONE }, + ]; +} diff --git a/crates/render/src/composite_pipeline/composite_pipelines.rs b/crates/render/src/composite_pipeline/composite_pipelines.rs new file mode 100644 index 00000000..aa64fcf4 --- /dev/null +++ b/crates/render/src/composite_pipeline/composite_pipelines.rs @@ -0,0 +1,119 @@ +use std::collections::BTreeMap; +use std::sync::{Arc, Mutex}; + +#[cfg(not(target_arch = "wasm32"))] +use std::sync::mpsc; + +use super::super::CompositeProgram; +use super::pipeline_features::PipelineFeatures; +use super::pipeline_slot::PipelineSlot; +use super::pipeline_variants::PipelineVariants; + +pub(in crate::gpu_composite) struct CompositePipelines { + pub(super) supports_curvature: bool, + pub(super) supports_id: bool, + variants: BTreeMap, +} + +/// The pipelines a compositor uses: its own, or when `shared` (a compositor on the device tests +/// share, [`crate::headless::Headless::for_tests`]) one set for every such compositor, so a test +/// does not compile the variants an earlier one compiled (llvmpipe keeps what it compiled until +/// the process ends, and compiling dominates its tests' time). +pub(in crate::gpu_composite) fn shared(shared: bool, supports_curvature: bool, supports_id: bool) -> Arc> { + #[cfg(all(any(test, feature = "test-support"), not(target_arch = "wasm32")))] + if shared { + static SHARED: std::sync::OnceLock>> = std::sync::OnceLock::new(); + return SHARED.get_or_init(|| Arc::new(Mutex::new(CompositePipelines::new(supports_curvature, supports_id)))).clone(); + } + + #[cfg(not(all(any(test, feature = "test-support"), not(target_arch = "wasm32"))))] + let _ = shared; + Arc::new(Mutex::new(CompositePipelines::new(supports_curvature, supports_id))) +} + +impl CompositePipelines { + pub(in crate::gpu_composite) fn new(supports_curvature: bool, supports_id: bool) -> Self { + Self { supports_curvature, supports_id, variants: BTreeMap::new() } + } + + /// Start compiling `program`'s pipelines without waiting (`get` returns them once ready). + pub(in crate::gpu_composite) fn prewarm(&mut self, device: &wgpu::Device, layout: &wgpu::PipelineLayout, program: &CompositeProgram) { + let _ = self.get(device, layout, program, !cfg!(target_arch = "wasm32")); + } + + /// The program's compose and prepare pipelines; None while one still compiles (new ones + /// compile on worker threads when `asynchronous`: the viewport keeps its last result), an + /// error when a worker's compile failed. + pub(in crate::gpu_composite) fn get( + &mut self, + device: &wgpu::Device, + layout: &wgpu::PipelineLayout, + program: &CompositeProgram, + asynchronous: bool, + ) -> Result)>, String> { + let features = PipelineFeatures::of(program); + let supports_curvature = self.supports_curvature; + let supports_id = self.supports_id; + let variants = self.variants.entry(features).or_insert_with(|| PipelineVariants { + module: device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_gpu_composite"), + source: wgpu::ShaderSource::Wgsl(features.source(supports_curvature, supports_id).into()), + }), + render: [None, None], + prepare: [None, None], + }); + let module = variants.module.clone(); + let pipeline = |entry: &'static str, label: &'static str, grouped: bool| { + let compile = { + let (device, layout, module) = (device.clone(), layout.clone(), module.clone()); + move || { + #[cfg(not(target_arch = "wasm32"))] + let started = std::time::Instant::now(); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(label), + layout: Some(&layout), + module: &module, + entry_point: Some(entry), + compilation_options: wgpu::PipelineCompilationOptions { constants: &features.constants(grouped), ..Default::default() }, + cache: None, + }); + #[cfg(not(target_arch = "wasm32"))] + log::debug!("GPU pipeline {label} compiled in {:.1} ms ({:?})", started.elapsed().as_secs_f64() * 1000.0, device.adapter_info().backend); + pipeline + } + }; + #[cfg(not(target_arch = "wasm32"))] + if asynchronous { + let (sender, compiled) = mpsc::sync_channel(1); + rayon::spawn(move || { + // Report panics from the device error handler as a failed compilation + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(compile)).map_err(|panic| { + let message = panic.downcast_ref::().cloned().or_else(|| panic.downcast_ref::<&str>().map(|text| text.to_string())); + format!("GPU pipeline {label} failed to compile: {}", message.unwrap_or_default()) + }); + let _ = sender.send(result); + }); + return PipelineSlot::Compiling(compiled); + } + + PipelineSlot::Ready(compile()) + }; + + let grouped = program.groups.depth != 0; + let render = variants.render[usize::from(grouped)].get_or_insert_with(|| pipeline("compose", "tc_gpu_composite", grouped)).ready(!asynchronous)?; + + // Only material anchors need the group structure in the prepare pass + let grouped_capture = grouped && features.material_anchors; + let prepare = match features.spatial { + true => match variants.prepare[usize::from(grouped_capture)] + .get_or_insert_with(|| pipeline("prepare_filter", "tc_spatial_source", grouped_capture)) + .ready(!asynchronous)? + { + Some(prepare) => Some(prepare), + None => return Ok(None), + }, + false => None, + }; + Ok(render.map(|render| (render, prepare))) + } +} diff --git a/crates/render/src/composite_pipeline/mod.rs b/crates/render/src/composite_pipeline/mod.rs new file mode 100644 index 00000000..e90dbd60 --- /dev/null +++ b/crates/render/src/composite_pipeline/mod.rs @@ -0,0 +1,317 @@ +mod composite_pipelines; +mod pipeline_features; +mod pipeline_slot; +mod pipeline_variants; + +pub(super) use composite_pipelines::{CompositePipelines, shared}; + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::super::packages::ShaderFlags; + use super::pipeline_features::PipelineFeatures; + use crate::gpu_composite::{GpuCompositor, oracle}; + use crate::gpu_neighbourhood::NeighbourhoodGpu; + + /// Every package stub, each package in full alone and all in full, each with and without + /// neighbourhood fields, plus a mask preview and a program using every other feature. + fn variants() -> Vec { + let mut packages = vec![ShaderFlags::default(), ShaderFlags::ALL]; + packages.extend(ShaderFlags::EACH); + let mut variants: Vec = packages + .into_iter() + .flat_map(|packages| { + [false, true].map(|spatial| PipelineFeatures { spatial, mask_effects: true, content_effects: true, packages, ..PipelineFeatures::default() }) + }) + .collect(); + variants.push(PipelineFeatures { mask_preview: true, spatial: true, mask_effects: true, packages: ShaderFlags::ALL, ..PipelineFeatures::default() }); + variants.push(PipelineFeatures { + patterns: true, + extended_patterns: true, + tile_generator: true, + authored_images: true, + mask_preview: false, + extended_blend_modes: true, + generators: true, + curvature: true, + sampled_generator_inputs: true, + spatial: true, + mask_effects: true, + content_effects: true, + height_mask: true, + anchors: true, + material_anchors: true, + color_selection: true, + packages: ShaderFlags::ALL, + }); + variants + } + + fn entry_points(features: PipelineFeatures) -> Vec<&'static str> { + if features.spatial { vec!["compose", "prepare_filter"] } else { vec!["compose"] } + } + + #[allow(clippy::panic)] // A test helper: a shader that does not translate fails the test + /// Parse and validate `source`, then write GLSL (GLES 3.1 and desktop 4.3, the GL backends' + /// path) for every entry point with the override constants of both group variants. + fn naga_check(label: &str, source: &str, entries: &[&str], constants: &[Vec<(&'static str, f64)>]) { + let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|error| panic!("{label}: {}", error.emit_to_string(source))); + let info = naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::default() | naga::valid::Capabilities::SHADER_FLOAT16_IN_FLOAT32, + ) + .validate(&module) + .unwrap_or_else(|error| panic!("{label}: {error:?}")); + for constants in constants { + let mut values = naga::back::PipelineConstants::default(); + values.extend(constants.iter().map(|&(name, value)| (name.to_owned(), value))); + for &entry in entries { + let (module, info) = naga::back::pipeline_constants::process_overrides(&module, &info, Some((naga::ShaderStage::Compute, entry)), &values) + .unwrap_or_else(|error| panic!("{label} {entry}: {error}")); + for version in [naga::back::glsl::Version::new_gles(310), naga::back::glsl::Version::Desktop(430)] { + let options = naga::back::glsl::Options { version, ..Default::default() }; + let pipeline = + naga::back::glsl::PipelineOptions { shader_stage: naga::ShaderStage::Compute, entry_point: entry.to_owned(), multiview: None }; + let mut glsl = String::new(); + naga::back::glsl::Writer::new(&mut glsl, &module, &info, &options, &pipeline, naga::proc::BoundsCheckPolicies::default()) + .and_then(|mut writer| writer.write()) + .unwrap_or_else(|error| panic!("{label} {entry} {version:?} {constants:?}: {error}")); + } + } + } + } + + /// Every package WGSL file and stub, in the composite and the neighbourhood shader, without + /// an adapter: so this never skips. + #[test] + fn package_shaders_validate_and_write_glsl_without_an_adapter() { + for features in variants() { + for (curvature, id) in [(false, false), (true, true)] { + let constants = [false, true].map(|grouped| features.constants(grouped).to_vec()); + naga_check(&format!("{features:?} curvature {curvature} id {id}"), &features.source(curvature, id), &entry_points(features), &constants); + } + } + naga_check("neighbourhood", &NeighbourhoodGpu::source(), &NeighbourhoodGpu::ENTRY_POINTS, &[Vec::new()]); + } + + /// With asynchronous compiles a new program first answers GPU_PIPELINES_PENDING, leaving the + /// set's textures as they are, then composites once its pipelines are ready; a pre-warmed + /// program composites at once. + #[test] + #[allow(clippy::unwrap_used)] // A test: a program that does not build fails it + fn new_pipelines_compile_on_worker_threads() { + use std::collections::BTreeMap; + + use texturecraft_compose::PixelStore; + use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Project, Source, TextureSet}; + + use crate::gpu_composite::{CompositeProgram, GPU_PIPELINES_PENDING}; + + // A device of its own: the tests share their pipelines per device + let Ok(mut gpu) = crate::headless::Headless::with_limits(crate::device_limits) else { return }; + let project = |radius: f32| { + let mut project = Project::new("Asynchronous", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 64)); + let id = project.alloc_id(); + let fill = Fill { sources: BTreeMap::from([(Channel::BaseColor, Source::Uniform([0.6, 0.3, 0.2]))]), ..Default::default() }; + let mut layer = Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]); + layer.content_effects.push(Effect::new(project.alloc_id(), EffectKind::Filter(Filter::Blur { radius, wrap: false }))); + project.insert_layer(0, layer, None, false).unwrap(); + project + }; + let mesh = std::sync::Arc::new(texturecraft_geom::primitives::plane(1.0, 1)); + let gbuf = std::sync::Arc::new(texturecraft_geom::UvGBuffer::new(&mesh, 0, 64, 64)); + let program = |project: &Project| { + let mut program = CompositeProgram::compile(project, &PixelStore::default(), 0).unwrap(); + program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); + program + }; + gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((64, 64), 0)], 1); + gpu.renderer.set_asynchronous_compile(true); + let first = program(&project(8.0)); + assert_eq!(gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &first), Err(GPU_PIPELINES_PENDING.to_string())); + let started = std::time::Instant::now(); + loop { + match gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &first) { + Err(error) if error == GPU_PIPELINES_PENDING => { + assert!(started.elapsed() < std::time::Duration::from_secs(300), "the pipelines never finished"); + std::thread::yield_now(); + } + result => { + assert_eq!(result, Ok(())); + break; + } + } + } + + // The same features again: ready at once + assert_eq!(gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program(&project(16.0))), Ok(())); + } + + /// Cold compile times of realistic programs' pipelines (run with the driver's shader cache + /// off, e.g. `__GL_SHADER_DISK_CACHE=0` on NVIDIA): a material of fills with Blur, Levels and + /// lighting under a generator mask, a mask comparing the layers below and this layer, and the + /// test variant with every package and feature. + #[test] + #[ignore = "a measurement: cold pipeline compiles"] + #[allow(clippy::unwrap_used)] // A measurement: a program that does not build fails it + fn bench_cold_pipeline_compile() { + use std::collections::BTreeMap; + + use texturecraft_compose::PixelStore; + use texturecraft_core::{ + Channel, CompareOp, CompareSource, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerKind, Levels, Mask, MaskBackground, Project, + Source, StylizedLighting, TextureSet, + }; + + use crate::gpu_composite::CompositeProgram; + + let Some(gpu) = oracle::headless() else { return }; + let channels = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Normal, Channel::Height]; + let fill = |values: [f32; 3]| Fill { + sources: channels.iter().map(|&channel| (channel, Source::Uniform(values))).collect::>(), + ..Default::default() + }; + let project = |content: Vec, mask: Vec| { + let mut project = Project::new("Compile", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 256)); + let below = project.alloc_id(); + project.insert_layer(0, Layer::new(below, "Below", LayerKind::Fill(fill([0.3; 3])), &channels), None, false).unwrap(); + let owner = project.alloc_id(); + let mut layer = Layer::new(owner, "Layer", LayerKind::Fill(fill([0.6; 3])), &channels); + for kind in content { + layer.content_effects.push(Effect::new(project.alloc_id(), kind)); + } + if !mask.is_empty() { + let mut layer_mask = Mask::new(MaskBackground::White); + for kind in mask { + layer_mask.effects.push(Effect::new(project.alloc_id(), kind)); + } + layer.mask = Some(layer_mask); + } + project.insert_layer(0, layer, None, false).unwrap(); + project + }; + let lighting = Filter::BakedLighting { + azimuth: 30.0, + elevation: 50.0, + light: 1.0, + ambient: 1.0, + occlusion: 0.4, + stylized: Some(Box::new(StylizedLighting::library())), + }; + let uv_tiles = |mut project: Project| { + let set = &mut project.texture_sets[0]; + set.uv_tiles = vec![1001, 1002, 1011, 1012]; + set.tile_resolutions.extend([(1002, 128), (1012, 64)]); + project + }; + let compare = |left| EffectKind::Compare { + op: CompareOp::GreaterThan, + value: 0.4, + tolerance: 0.1, + left, + right: CompareSource::Constant, + channel: Channel::Roughness, + hardness: 0.5, + }; + let cases = [ + ( + "material: Blur, Levels, lighting, generator mask", + project( + vec![ + EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }), + EffectKind::Levels(Levels::default()), + EffectKind::Filter(lighting.clone()), + ], + vec![EffectKind::Generator(crate::gpu_composite::oracle::earlier_generator(GeneratorKind::Dirt))], + ), + ), + ("mask comparing Layers Below and This Layer", project(Vec::new(), vec![compare(CompareSource::LayersBelow), compare(CompareSource::ThisLayer)])), + ("plain fill", project(Vec::new(), Vec::new())), + // P8: the same material on a UV tile atlas with three tile scales + ( + "UV tile atlas: Blur, Levels, lighting, generator mask", + uv_tiles(project( + vec![ + EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }), + EffectKind::Levels(Levels::default()), + EffectKind::Filter(lighting.clone()), + ], + vec![EffectKind::Generator(crate::gpu_composite::oracle::earlier_generator(GeneratorKind::Dirt))], + )), + ), + ("UV tile atlas: plain fill", uv_tiles(project(Vec::new(), Vec::new()))), + ]; + let compositor = GpuCompositor::new(&gpu.device); + let (curvature, id) = { + let pipelines = compositor.pipelines(); + (pipelines.supports_curvature, pipelines.supports_id) + }; + let programs = cases + .map(|(label, project)| (label, PipelineFeatures::of(&CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap()))); + let everything = + variants().into_iter().filter(|features| features.mask_preview || (features.spatial && !features.generators)).map(|features| ("variant", features)); + for (label, features) in programs.into_iter().chain(everything) { + let module = gpu.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_bench"), + source: wgpu::ShaderSource::Wgsl(features.source(curvature, id).into()), + }); + for entry in entry_points(features) { + let started = std::time::Instant::now(); + let _pipeline = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&compositor.pipeline_layout), + module: &module, + entry_point: Some(entry), + compilation_options: wgpu::PipelineCompilationOptions { constants: &features.constants(false), ..Default::default() }, + cache: None, + }); + let memory = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + let peak = memory.lines().filter(|line| line.starts_with("VmHWM") || line.starts_with("VmRSS")).collect::>().join(" "); + eprintln!("COMPILE {label} {:?} preview {}, {entry}: {:?} {peak}", features.packages, features.mask_preview, started.elapsed()); + } + } + } + + /// The programs with every package in full and with every package as a stub as compute + /// pipelines on the adapter, as `CompositePipelines::get` creates them (both group variants), + /// and the neighbourhood pipelines. The variants with one package in full are checked by naga + /// above: on the adapter they only repeat these compiles. + #[test] + fn package_shaders_build_compute_pipelines_in_full_and_as_stubs() { + let Some(gpu) = oracle::headless() else { return }; + let compositor = GpuCompositor::new(&gpu.device); + let (curvature, id) = { + let pipelines = compositor.pipelines(); + (pipelines.supports_curvature, pipelines.supports_id) + }; + + // Leave the all-feature prepare pipeline to Naga because llvmpipe exhausts 28 GB + let one_package = |features: &PipelineFeatures| ShaderFlags::EACH.contains(&features.packages); + for features in variants().into_iter().filter(|features| !features.generators && !one_package(features)) { + let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); + let module = gpu.device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_gpu_composite_packages"), + source: wgpu::ShaderSource::Wgsl(features.source(curvature, id).into()), + }); + for grouped in [false, true] { + for entry in entry_points(features) { + let _pipeline = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: Some(&compositor.pipeline_layout), + module: &module, + entry_point: Some(entry), + compilation_options: wgpu::PipelineCompilationOptions { constants: &features.constants(grouped), ..Default::default() }, + cache: None, + }); + } + } + let error = pollster::block_on(scope.pop()); + assert!(error.is_none(), "{features:?} on {}: {error:?}", gpu.adapter_name); + } + let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); + let _neighbourhood = NeighbourhoodGpu::new(&gpu.device); + let error = pollster::block_on(scope.pop()); + assert!(error.is_none(), "neighbourhood on {}: {error:?}", gpu.adapter_name); + } +} diff --git a/crates/render/src/composite_pipeline/pipeline_features.rs b/crates/render/src/composite_pipeline/pipeline_features.rs new file mode 100644 index 00000000..f0829138 --- /dev/null +++ b/crates/render/src/composite_pipeline/pipeline_features.rs @@ -0,0 +1,171 @@ +use super::super::packages::{self, ShaderFlags}; +use super::super::{ + ANCHOR_PUBLISH_LAYER, ANCHOR_SOURCE, COLOR_SELECTION_OPCODE, CompositeProgram, FIRST_EXTENDED_PATTERN, FIRST_GENERATOR, TILE_GENERATOR_OPCODE, +}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub(super) struct PipelineFeatures { + pub(super) patterns: bool, + pub(super) extended_patterns: bool, + pub(super) tile_generator: bool, + pub(super) authored_images: bool, + pub(super) mask_preview: bool, + pub(super) extended_blend_modes: bool, + pub(super) generators: bool, + pub(super) curvature: bool, + pub(super) sampled_generator_inputs: bool, + pub(super) spatial: bool, + pub(super) mask_effects: bool, + pub(super) content_effects: bool, + pub(super) height_mask: bool, + pub(super) anchors: bool, + pub(super) material_anchors: bool, + pub(super) color_selection: bool, + // The GPU port packages' WGSL files compiled in full (gpu_composite_packages.rs) + pub(super) packages: ShaderFlags, +} + +impl PipelineFeatures { + pub(super) fn of(program: &CompositeProgram) -> Self { + let mut features = Self { + authored_images: !program.material_images.is_empty(), + mask_preview: program.is_mask_preview(), + spatial: !program.filters.stages.is_empty(), + packages: ShaderFlags::of(program), + ..Self::default() + }; + + features.material_anchors = program.filters.stages.iter().any(|stage| stage.anchor.is_some()); + + // A capture stage (an anchor or a stack read) runs the prepare pass's anchor path + features.anchors |= features.material_anchors; + for op in program.operations.iter().take(program.layer_count as usize).filter(|op| op.ids[1] != ANCHOR_PUBLISH_LAYER) { + features.mask_effects |= op.effects[1] != 0; + features.content_effects |= op.effects[3] != 0; + features.height_mask |= op.constraints[2] != 0; + } + + // Include sources referenced by generator overrides and mask preview fills + for op in &program.operations { + let kind = op.ids[1]; + features.extended_blend_modes |= op.balance[2] > 8.0; + features.anchors |= kind == ANCHOR_SOURCE; + features.color_selection |= kind == COLOR_SELECTION_OPCODE; + features.patterns |= matches!(kind, 1..=9 | 11..=13 | FIRST_EXTENDED_PATTERN..=TILE_GENERATOR_OPCODE); + features.extended_patterns |= (FIRST_EXTENDED_PATTERN..TILE_GENERATOR_OPCODE).contains(&kind); + features.tile_generator |= kind == TILE_GENERATOR_OPCODE; + if (FIRST_GENERATOR..FIRST_EXTENDED_PATTERN).contains(&kind) { + features.generators = true; + features.curvature |= op.uv[1] != 0.0; + if let Some(source) = op.effects[3].checked_sub(1).and_then(|index| program.operations.get(index as usize)) { + features.sampled_generator_inputs |= source.ids[1] != 0; + } + } + } + + features + } + + pub(super) fn source(self, supports_curvature: bool, supports_id: bool) -> String { + fn include(enabled: bool, full: &'static str, stub: &'static str) -> &'static str { + if enabled { full } else { stub } + } + + // Omit inactive helpers before Mesa can inline them on GL + let channel_defaults = super::super::channel_defaults_wgsl(); + [ + "override enable_authored_images: bool = false;\n override enable_generators: bool = false;\n override enable_curvature_detail: bool = false;\n override enable_spatial_fields: bool = false;\n override enable_anchor_reads: bool = false;", + include_str!("../shaders/noise.wgsl"), + // Keep the gradient fallback when the program has no extended patterns + include( + self.extended_patterns, + include_str!("../shaders/procedural_extra.wgsl"), + "fn extended_pattern(kind: u32, p: vec3, seed: u32) -> f32 { return fract(p.x); }", + ), + include( + self.tile_generator, + include_str!("../shaders/tile_generator.wgsl"), + "fn tile_generator(offset: u32, uv: vec2) -> f32 { return 0.0; }", + ), + include( + self.patterns, + include_str!("../shaders/composite_patterns.wgsl"), + "fn procedural_value(layer: Operation, uv: vec2, surface: Surface) -> vec3 { return layer.low.rgb; }", + ), + include( + self.authored_images, + include_str!("../shaders/material_image.wgsl"), + "fn authored_image_value(layer: Operation, uv: vec2, surface: Surface) -> vec3 { return layer.low.rgb; }\n fn decal_fill_value(layer: Operation, uv: vec2, surface: Surface) -> vec4 { return vec4(layer.low.rgb, 1.0); }\n fn material_image_texel(image: u32, pixel: vec2, size: vec2) -> vec4 { return vec4(0.0); }\n const MISSING_IMAGE: u32 = 0xffffffffu;\n fn decode_image_sample(layer: Operation, rgb: vec3) -> vec3 { return rgb; }", + ), + include_str!("../shaders/stencil_projection.wgsl"), + include( + self.curvature && supports_curvature, + include_str!("../shaders/curvature_sample.wgsl"), + "fn curvature_level_at(pixel: vec2, level: u32) -> f32 { return 0.0; }", + ), + include( + self.curvature, + include_str!("../shaders/composite_curvature_detail.wgsl"), + "fn generator_curvature(effect: Operation, pixel: vec2, finest: f32, mode: u32, micro: f32) -> f32 { return 0.0; }", + ), + include( + self.sampled_generator_inputs, + "fn generator_source_value(index: u32, texel: LayerTexel) -> f32 {\n return fill_value(layers[index], texel.uv, texel.surface).x;\n }", + "fn generator_source_value(index: u32, texel: LayerTexel) -> f32 { return layers[index].low.x; }", + ), + include( + self.generators, + include_str!("../shaders/composite_generators.wgsl"), + "fn generator_ramp(effect: Operation, texel: LayerTexel) -> f32 { return 0.0; }\n fn finish_generator(effect: Operation, ramp: f32) -> f32 { return ramp; }", + ), + include( + self.spatial, + include_str!("../shaders/composite_spatial.wgsl"), + "fn previous_field(start: u32, count: u32) -> u32 { return 0u; }\n fn filter_value(slot: u32, pixel: vec2) -> vec4 { return vec4(0.0); }\n var preceding_field: u32 = 0xffffffffu;\n fn preceding_stage_word(pixel: vec2) -> f32 { return 0.0; }", + ), + include( + self.color_selection && supports_id, + include_str!("../shaders/id_sample.wgsl"), + "fn id_color_at(pixel: vec2) -> vec3 { return vec3(0.0); }", + ), + include( + self.mask_effects, + include_str!("../shaders/composite_mask_effects.wgsl"), + "fn layer_mask(layer: Operation, texel: LayerTexel, count: u32) -> f32 { return layer.balance.y; }", + ), + include( + self.content_effects, + include_str!("../shaders/composite_content_effects.wgsl"), + "fn layer_content(layer: Operation, texel: LayerTexel, count: u32) -> vec4 { + let content = base_content(layer, texel); + return select(vec4(0.0), content, content.a > 0.0); + }", + ), + include( + self.height_mask, + include_str!("../shaders/composite_height_mask.wgsl"), + "fn mask_with_height(layer: Operation, texel: LayerTexel, mask: f32) -> f32 { return mask; }", + ), + include_str!("../shaders/composite_groups.wgsl"), + include_str!("../shaders/composite.wgsl"), + ] + .into_iter() + .chain(packages::shader_sources(self.packages)) + .chain(std::iter::once(channel_defaults.as_str())) + .collect::>() + .join("\n") + } + + pub(super) fn constants(self, grouped: bool) -> [(&'static str, f64); 8] { + [ + ("enable_authored_images", f64::from(u8::from(self.authored_images))), + ("enable_generators", f64::from(u8::from(self.generators))), + ("enable_curvature_detail", f64::from(u8::from(self.curvature))), + ("enable_spatial_fields", f64::from(u8::from(self.spatial))), + ("enable_anchor_reads", f64::from(u8::from(self.anchors))), + ("composite_groups", f64::from(u8::from(grouped))), + ("composite_mask_preview", f64::from(u8::from(self.mask_preview))), + ("enable_extended_blend_modes", f64::from(u8::from(self.extended_blend_modes))), + ] + } +} diff --git a/crates/render/src/composite_pipeline/pipeline_slot.rs b/crates/render/src/composite_pipeline/pipeline_slot.rs new file mode 100644 index 00000000..a3cfb74e --- /dev/null +++ b/crates/render/src/composite_pipeline/pipeline_slot.rs @@ -0,0 +1,39 @@ +#[cfg(not(target_arch = "wasm32"))] +use std::sync::mpsc::{Receiver, TryRecvError}; + +/// A pipeline awaiting compilation or holding its result +pub(super) enum PipelineSlot { + Ready(wgpu::ComputePipeline), + #[cfg(not(target_arch = "wasm32"))] + Compiling(Receiver>), + #[cfg(not(target_arch = "wasm32"))] + Failed(String), +} + +impl PipelineSlot { + /// The pipeline once compiled (None while it compiles), or why it never will be; `wait` + /// waits for a compile in flight (a caller that compiles in place, after a pre-warm started + /// one on a worker thread) + pub(super) fn ready(&mut self, wait: bool) -> Result, String> { + #[cfg(not(target_arch = "wasm32"))] + if let PipelineSlot::Compiling(compiled) = self { + let result = if wait { compiled.recv().map_err(|_| TryRecvError::Disconnected) } else { compiled.try_recv() }; + *self = match result { + Ok(Ok(pipeline)) => PipelineSlot::Ready(pipeline), + Ok(Err(error)) => PipelineSlot::Failed(error), + Err(TryRecvError::Empty) => return Ok(None), + Err(TryRecvError::Disconnected) => PipelineSlot::Failed("GPU pipeline compilation ended without a result".into()), + }; + } + + #[cfg(target_arch = "wasm32")] + let _ = wait; + match self { + PipelineSlot::Ready(pipeline) => Ok(Some(pipeline.clone())), + #[cfg(not(target_arch = "wasm32"))] + PipelineSlot::Compiling(_) => Ok(None), + #[cfg(not(target_arch = "wasm32"))] + PipelineSlot::Failed(error) => Err(error.clone()), + } + } +} diff --git a/crates/render/src/composite_pipeline/pipeline_variants.rs b/crates/render/src/composite_pipeline/pipeline_variants.rs new file mode 100644 index 00000000..569300ca --- /dev/null +++ b/crates/render/src/composite_pipeline/pipeline_variants.rs @@ -0,0 +1,7 @@ +use super::pipeline_slot::PipelineSlot; + +pub(super) struct PipelineVariants { + pub(super) module: wgpu::ShaderModule, + pub(super) render: [Option; 2], + pub(super) prepare: [Option; 2], +} diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index f2e2b19a..59e3956d 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -117,6 +117,10 @@ impl Heights { if !(fx.is_finite() && fy.is_finite()) { return 0.0; } + // Past one texel outside, every lookup clamps to the same edge texel, so clamping the + // position first changes no result but keeps `x0 + 1` far from overflowing: a huge finite + // UV saturates the `as isize` cast, and isize is 32 bits on wasm32. + let (fx, fy) = (fx.clamp(-1.0, self.w as f32), fy.clamp(-1.0, self.h as f32)); let (x0, y0) = (fx.floor(), fy.floor()); let (tx, ty) = (fx - x0, fy - y0); let (x0, y0) = (x0 as isize, y0 as isize); @@ -141,7 +145,30 @@ 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, + } + } + + /// Far-off UVs clamp to the nearest edge texel without overflow; NaN gives 0 and in-range sampling is unchanged. + #[test] + fn sampling_at_huge_or_far_uvs_clamps_to_the_edge_without_overflow() { + let heights = Heights { w: 2, h: 2, data: vec![1.0, 2.0, 3.0, 4.0] }; + // x0 + 1 used to overflow for these (the cast to isize saturates at isize::MAX). + for far in [1.0e30_f32, -1.0e30, f32::MAX, f32::MIN, 1.0e10] { + assert!(heights.sample(Vec2::new(far, far)).is_finite()); + } + assert_eq!(heights.sample(Vec2::new(1.0e30, 1.0e30)), 4.0); + assert_eq!(heights.sample(Vec2::new(-1.0e30, -1.0e30)), 1.0); + assert_eq!(heights.sample(Vec2::new(1.0e30, -1.0e30)), 2.0); + assert_eq!(heights.sample(Vec2::new(f32::NAN, 0.5)), 0.0); + // In range, bilinear is unchanged: the centre of the 2 x 2 is the mean. + assert!((heights.sample(Vec2::new(0.5, 0.5)) - 2.5).abs() < 1e-6); } #[test] diff --git a/crates/render/src/gpu_bake.rs b/crates/render/src/gpu_bake.rs index 00d7e991..28adee5e 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"); } @@ -468,7 +466,7 @@ mod tests { #[test] fn gpu_respects_secondary_ray_filters_and_ground_plane() { - let _turn = crate::headless::serial::Turn::take(); + let _turn = crate::headless::TestGpuTurn::take(); let Some(gpu) = gpu() else { return }; let mut mesh = primitives::material_ball(); @@ -497,7 +495,7 @@ mod tests { #[test] fn gpu_bake_matches_the_cpu() { - let _turn = crate::headless::serial::Turn::take(); + let _turn = crate::headless::TestGpuTurn::take(); let Some(gpu) = gpu() else { return }; // Low poly: the material ball (self-occluding); every ray map with its own settings @@ -566,7 +564,7 @@ mod tests { #[test] #[ignore] fn gpu_bake_speed() { - let _turn = crate::headless::serial::Turn::take(); + let _turn = crate::headless::TestGpuTurn::take(); let Some(g) = gpu() else { return }; let ball = primitives::material_ball(); let rays = RaySettings { rays: 64, ..RaySettings::default() }; diff --git a/crates/render/src/gpu_brush.rs b/crates/render/src/gpu_brush.rs index 1c8f2aad..652a932b 100644 --- a/crates/render/src/gpu_brush.rs +++ b/crates/render/src/gpu_brush.rs @@ -27,538 +27,21 @@ const CHUNK: usize = 256; const PROJECTION_TILE_BYTES: u64 = (TILE * TILE) as u64 * size_of::<[f32; 4]>() as u64; const PROJECTION_READBACK_TILES: usize = 64; -pub struct BrushInput { - pub mesh: Arc, - pub bvh: Arc, - pub uv: Arc, - pub material: usize, - pub depth: Option>, - pub settings: BrushSettings, - pub stencil: Option, - pub limit: Option<(TileImage, bool)>, -} +mod brush_input; +mod brush_pipeline; +mod dab; +mod gpu_brush_stroke; +mod parameters; +mod visibility; -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Parameters { - camera: [[f32; 4]; 4], - eye: [f32; 4], - view_scale: [f32; 4], - mesh: [f32; 4], - ortho: [f32; 4], - shape: [f32; 4], - flags: [u32; 4], -} +pub use brush_input::BrushInput; +pub(crate) use brush_pipeline::BrushPipeline; +use dab::Dab; +pub use gpu_brush_stroke::GpuBrushStroke; +use parameters::Parameters; +use visibility::Visibility; -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Dab { - center: [f32; 4], - normal: [f32; 4], - tangent: [f32; 4], - bitangent: [f32; 4], - seed: u32, - padding: [u32; 3], - /// A symmetry copy's source origin with w 1, zero for any other dab. - source: [f32; 4], - /// The columns of the copy's `StampSource::to_source`. - to_source: [[f32; 4]; 3], -} - -struct Visibility { - nodes: wgpu::Buffer, - triangles: wgpu::Buffer, - depth: wgpu::TextureView, -} - -pub(crate) struct BrushPipeline { - shader: wgpu::ShaderModule, - layout: wgpu::PipelineLayout, - pipelines: BTreeMap, - rays: Option<(Weak, wgpu::Buffer, wgpu::Buffer)>, - depth: Option<(Weak, wgpu::TextureView)>, - stencil_image: Option<(Weak, wgpu::TextureView)>, - projection_readback: Option, - spare_alpha: SpareAlpha, -} - -impl BrushPipeline { - pub(crate) fn clear_visibility(&mut self) { - self.rays = None; - self.depth = None; - self.stencil_image = None; - } - - pub fn new(device: &wgpu::Device) -> Self { - use crate::gpu_trace::{entry, storage}; - let texture_entry = |binding, sample_type| { - entry(binding, wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }) - }; - let inputs = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("tc_brush_inputs"), - entries: &[ - entry(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }), - storage(1, true), - storage(2, true), - texture_entry(3, wgpu::TextureSampleType::Uint), - storage(4, true), - texture_entry(5, wgpu::TextureSampleType::Uint), - texture_entry(6, wgpu::TextureSampleType::Float { filterable: false }), - storage(7, true), - storage(8, true), - storage(9, false), - ], - }); - let layout = - device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("tc_brush"), bind_group_layouts: &[Some(&inputs)], immediate_size: 0 }); - let source = concat!(include_str!("shaders/rays.wgsl"), "\n", include_str!("shaders/noise.wgsl"), "\n", include_str!("shaders/brush.wgsl")); - let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("tc_brush"), source: wgpu::ShaderSource::Wgsl(source.into()) }); - Self { - shader, - layout, - pipelines: BTreeMap::new(), - rays: None, - depth: None, - stencil_image: None, - projection_readback: None, - spare_alpha: SpareAlpha::default(), - } - } - - fn pipeline(&mut self, device: &wgpu::Device, alpha: BrushAlpha) -> wgpu::ComputePipeline { - // Specialize by shape so the simple brushes keep their smaller GPU kernels. - let alpha_kind = match alpha { - BrushAlpha::Round => 0, - BrushAlpha::Square => 1, - BrushAlpha::Spray => 2, - BrushAlpha::Grunge => 3, - BrushAlpha::Cloud => 4, - BrushAlpha::Star => 5, - BrushAlpha::Streaks => 6, - }; - self.pipelines - .entry(alpha_kind) - .or_insert_with(|| { - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("tc_brush"), - layout: Some(&self.layout), - module: &self.shader, - entry_point: Some("brush"), - compilation_options: wgpu::PipelineCompilationOptions { constants: &[("alpha_kind", f64::from(alpha_kind))], ..Default::default() }, - cache: None, - }) - }) - .clone() - } - - fn visibility(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, input: &BrushInput) -> Result { - let key = Arc::downgrade(&input.bvh); - if self.rays.as_ref().is_none_or(|(last, ..)| !last.ptr_eq(&key)) { - let (nodes, triangles) = crate::gpu_trace::bvh_rows(&input.bvh, (0, 0), |_| ([0; 3], [0; 4])); - let bytes = (nodes.len().max(triangles.len()) * 16) as u64; - if bytes > device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size) { - return Err("mesh visibility buffers exceed this adapter's limits".into()); - } - self.rays = Some((key, storage(device, "tc_brush_nodes", &nodes), storage(device, "tc_brush_triangles", &triangles))); - } - let (_, nodes, triangles) = self.rays.as_ref().ok_or("brush meshes are missing")?; - let depth = if let Some(depth) = &input.depth { - let key = Arc::downgrade(depth); - if self.depth.as_ref().is_none_or(|(last, _)| !last.ptr_eq(&key)) { - let surface = texture(device, [depth.width, depth.height], wgpu::TextureFormat::R32Float); - queue.write_texture( - surface.as_image_copy(), - bytemuck::cast_slice(&depth.dist), - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(depth.width * 4), rows_per_image: None }, - extent(depth.width, depth.height), - ); - self.depth = Some((key, surface.create_view(&Default::default()))); - } - self.depth.as_ref().ok_or("brush depth is missing")?.1.clone() - } else { - texture(device, [1, 1], wgpu::TextureFormat::R32Float).create_view(&Default::default()) - }; - Ok(Visibility { nodes: nodes.clone(), triangles: triangles.clone(), depth }) - } - - pub fn begin( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - input: BrushInput, - surface: (wgpu::TextureView, wgpu::Buffer), - ) -> Result { - let size = [input.uv.width, input.uv.height]; - if size.into_iter().any(|edge| !edge.is_multiple_of(TILE) || edge > device.limits().max_texture_dimension_2d) { - return Err("unsupported GPU brush texture size".into()); - } - if input.limit.as_ref().is_some_and(|(mask, _)| [mask.width(), mask.height()] != size || mask.comps() != 1) { - return Err("The quick mask does not match the GPU brush texture size.".into()); - } - let visibility = self.visibility(device, queue, &input)?; - let spare = self.spare_alpha.lock().ok().and_then(|mut spare| spare.take()); - let alpha = match spare { - Some((alpha, written)) if [alpha.width(), alpha.height()] == size => { - clear_tiles(queue, &alpha, &written); - alpha - } - _ => texture(device, size, wgpu::TextureFormat::R16Uint), - }; - let view = alpha.create_view(&Default::default()); - let (lo, hi) = input.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = (hi - lo).length().mul_add(0.5, 0.0).max(1e-4); - self.stencil_image.take_if(|(source, _)| source.strong_count() == 0); - let projection = if let Some(stencil) = &input.stencil { - let key = Arc::downgrade(&stencil.image); - if self.stencil_image.as_ref().is_none_or(|(previous, _)| !previous.ptr_eq(&key)) { - self.stencil_image = None; - self.stencil_image = Some((key, gpu_stencil::upload_image(device, queue, &stencil.image)?)); - } - let (_, image) = self.stencil_image.as_ref().ok_or("projection image missing")?; - let stencil = GpuStencil::new(device, image.clone(), stencil, center, radius); - let readback = self.projection_readback.get_or_insert_with(|| gpu_stencil::readback_pipeline(device)).clone(); - Some((stencil, readback)) - } else { - None - }; - let settings = &input.settings; - let pipeline = self.pipeline(device, settings.alpha); - let mut params = Parameters { - camera: Mat4::IDENTITY.to_cols_array_2d(), - eye: [0.0; 4], - view_scale: [0.0, settings.angle_fade.1.to_radians().cos(), settings.angle_fade.0.to_radians().cos(), 0.0], - mesh: center.extend(radius).to_array(), - ortho: [0.0; 4], - shape: [settings.alpha_params.size_x, settings.alpha_params.size_y, settings.alpha_params.roundness, settings.alpha_params.contrast], - flags: [ - 0, - u32::from(settings.backface_culling), - u32::from(settings.alpha_params.invert), - input.limit.as_ref().map_or(0, |(_, invert)| 1 + u32::from(*invert)), - ], - }; - if let Some(depth) = &input.depth { - params.camera = depth.view_proj.to_cols_array_2d(); - params.eye = depth.eye.extend(depth.bias).to_array(); - params.view_scale[0] = (depth.height as f32 * depth.view_proj.row(1).truncate().length()).max(f32::EPSILON); - params.view_scale[3] = 1.0; - if let Some(to_eye) = depth.orthographic_to_eye { - params.ortho = to_eye.extend(1.0).to_array(); - } - } - Ok(GpuBrushStroke { - input, - pipeline, - device: device.clone(), - queue: queue.clone(), - surface, - visibility, - alpha, - view, - params, - scratch: None, - projection, - written: Tiles::new(), - spare_alpha: self.spare_alpha.clone(), - }) - } -} - -pub struct GpuBrushStroke { - input: BrushInput, - pipeline: wgpu::ComputePipeline, - device: wgpu::Device, - queue: wgpu::Queue, - surface: (wgpu::TextureView, wgpu::Buffer), - visibility: Visibility, - alpha: wgpu::Texture, - view: wgpu::TextureView, - params: Parameters, - scratch: Option, - projection: Option<(GpuStencil, wgpu::ComputePipeline)>, - /// The alpha tiles the stroke wrote, cleared when the next stroke reuses its map - written: Tiles, - spare_alpha: SpareAlpha, -} - -impl Drop for GpuBrushStroke { - fn drop(&mut self) { - if let Ok(mut spare) = self.spare_alpha.lock() { - *spare = Some((self.alpha.clone(), std::mem::take(&mut self.written))); - } - } -} - -impl GpuBrushStroke { - pub fn view(&self) -> wgpu::TextureView { - self.view.clone() - } - - pub fn stencil(&self) -> Option { - self.projection.as_ref().map(|(stencil, _)| stencil.clone()) - } - - pub fn append_world(&mut self, stamps: &[Stamp]) -> Result { - let mut bins = TileDabs::new(); - let input = &self.input; - let size = Vec2::new(input.uv.width as f32, input.uv.height as f32); - let mut dabs = Vec::new(); - for stamp in stamps { - if !stamp.radius.is_finite() || stamp.radius <= 0.0 || !stamp.center.is_finite() { - continue; - } - let (source, to_source) = match stamp.source { - Some(source) => (source.origin.extend(1.0).to_array(), source.to_source.to_cols_array_2d().map(|[x, y, z]| [x, y, z, 0.0])), - None => ([0.0; 4], [[0.0; 4]; 3]), - }; - let index = dabs.len() as u32; - dabs.push(Dab { - center: stamp.center.extend(stamp.radius).to_array(), - normal: stamp.normal.extend(stamp.depth).to_array(), - tangent: stamp.tangent.extend(stamp.flow).to_array(), - bitangent: stamp.bitangent.extend(stamp.hardness).to_array(), - seed: stamp.seed, - padding: [0; 3], - source, - to_source, - }); - let extent = stamp.world_extent(); - let mut touched = Tiles::new(); - input.bvh.query_box(stamp.center - extent, stamp.center + extent, |triangle| { - if input.mesh.material_of(triangle as usize) == Some(input.material) - && let Some((lo, hi)) = footprint(&input.mesh, triangle, stamp) - { - add_tiles(&mut touched, lo * size, hi * size, size); - } - }); - for tile in touched { - bins.entry(tile).or_default().push(index); - } - } - self.dispatch(&bins, &dabs, false)?; - Ok(bins.into_keys().collect()) - } - - pub fn append_uv(&mut self, stamps: &[UvStamp]) -> Result { - let mut bins = TileDabs::new(); - let size = Vec2::new(self.input.uv.width as f32, self.input.uv.height as f32); - let mut dabs = Vec::new(); - for stamp in stamps { - if !stamp.radius.is_finite() || stamp.radius <= 0.0 || !stamp.center.is_finite() { - continue; - } - let center = stamp.center * size; - let radius = stamp.radius * size.x; - let (sin, cos) = stamp.angle.to_radians().sin_cos(); - let index = dabs.len() as u32; - dabs.push(Dab { - center: [center.x, center.y, 0.0, radius], - normal: [0.0; 4], - tangent: [cos, sin, 0.0, stamp.flow], - bitangent: [0.0, 0.0, 0.0, stamp.hardness], - seed: stamp.seed, - padding: [0; 3], - source: [0.0; 4], - to_source: [[0.0; 4]; 3], - }); - let reach = Vec2::splat(radius * 1.42); - let mut touched = Tiles::new(); - add_tiles(&mut touched, center - reach, center + reach, size); - for tile in touched { - bins.entry(tile).or_default().push(index); - } - } - self.dispatch(&bins, &dabs, true)?; - Ok(bins.into_keys().collect()) - } - - fn dispatch(&mut self, tiles: &TileDabs, dabs: &[Dab], uv: bool) -> Result<(), String> { - if tiles.is_empty() || dabs.is_empty() { - return Ok(()); - } - let mut params = self.params; - params.flags[0] = u32::from(uv); - self.written.extend(tiles.keys()); - let coordinates: Vec<_> = tiles.iter().collect(); - let (device, queue) = (&self.device, &self.queue); - crate::gpu_trace::scoped(device, "GPU brush dispatch", || { - let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_brush_parameters"), - contents: bytemuck::bytes_of(¶ms), - usage: wgpu::BufferUsages::UNIFORM, - }); - let dabs = storage(device, "tc_brush_dabs", dabs); - let bytes = coordinates.len().min(CHUNK) as u64 * TILE_BYTES; - if self.scratch.as_ref().is_none_or(|buffer| buffer.size() < bytes) { - self.scratch = Some(buffer(device, "tc_brush_scratch", bytes.next_power_of_two(), wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC)); - } - let scratch = self.scratch.as_ref().ok_or("brush scratch buffer missing")?; - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_brush") }); - for chunk in coordinates.chunks(CHUNK) { - // Origins, dab offsets/counts and optional quick-mask offsets. - let mut cells = vec![0; chunk.len() * 5]; - for (tile, (&(x, y), indices)) in chunk.iter().copied().enumerate() { - let first = cells.len() as u32; - cells.extend(indices); - let mask = self.input.limit.as_ref().and_then(|(mask, _)| mask.tile(x, y)); - let limit = mask.map_or(0, |mask| { - let offset = cells.len() as u32; - cells.extend(mask.as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); - offset - }); - cells[tile * 5..tile * 5 + 5].copy_from_slice(&[x * TILE, y * TILE, first, indices.len() as u32, limit]); - } - let cells = storage(device, "tc_brush_tiles", &cells); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_brush_inputs"), - layout: &self.pipeline.get_bind_group_layout(0), - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: self.visibility.nodes.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 2, resource: self.visibility.triangles.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, - wgpu::BindGroupEntry { binding: 4, resource: self.surface.1.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&self.view) }, - wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&self.visibility.depth) }, - wgpu::BindGroupEntry { binding: 7, resource: dabs.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 8, resource: cells.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 9, resource: scratch.as_entire_binding() }, - ], - }); - { - let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(&self.pipeline); - pass.set_bind_group(0, &bind, &[]); - pass.dispatch_workgroups(TILE / 16, TILE / 8, chunk.len() as u32); - } - for (i, (&(x, y), _)) in chunk.iter().copied().enumerate() { - encoder.copy_buffer_to_texture(buffer_copy(scratch, i), tile_copy(&self.alpha, x * TILE, y * TILE), extent(TILE, TILE)); - } - } - queue.submit([encoder.finish()]); - Ok::<_, String>(()) - })? - } - - pub fn read_alpha(&self, tiles: &Tiles) -> Result { - let mut alpha = TileImage::new(self.input.uv.width, self.input.uv.height, 1); - if tiles.is_empty() { - return Ok(alpha); - } - let (device, queue) = (&self.device, &self.queue); - let read = crate::gpu_trace::scoped(device, "GPU brush readback buffer", || { - buffer(device, "tc_brush_read_alpha", tiles.len().min(CHUNK) as u64 * TILE_BYTES, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ) - })?; - let coords: Vec<_> = tiles.iter().copied().collect(); - for chunk in coords.chunks(CHUNK) { - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_brush_read_alpha") }); - for (i, &(x, y)) in chunk.iter().enumerate() { - encoder.copy_texture_to_buffer(tile_copy(&self.alpha, x * TILE, y * TILE), buffer_copy(&read, i), extent(TILE, TILE)); - } - let index = queue.submit([encoder.finish()]); - let slice = read.slice(..chunk.len() as u64 * TILE_BYTES); - let (send, receive) = std::sync::mpsc::channel(); - slice.map_async(wgpu::MapMode::Read, move |result| { - let _ = send.send(result); - }); - device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).map_err(|e| e.to_string())?; - receive.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; - { - let mapped = slice.get_mapped_range().map_err(|e| e.to_string())?; - for (bytes, &(x, y)) in mapped.as_chunks::<{ TILE_BYTES as usize }>().0.iter().zip(chunk) { - let samples: Vec<_> = bytes - .as_chunks::<{ ROW_BYTES as usize }>() - .0 - .iter() - .flat_map(|row| row[..(TILE * 2) as usize].as_chunks::<2>().0.iter().map(|&value| u16::from_le_bytes(value))) - .collect(); - if samples.iter().any(|&a| a != 0) { - alpha.set_tile(x, y, Some(Arc::new(samples))); - } - } - } - read.unmap(); - } - Ok(alpha) - } - /// Read the projected linear RGB and image alpha of the touched tiles. - /// The stroke's geometric coverage remains in the separate alpha map. - pub fn read_projection(&self, tiles: &Tiles) -> Result { - let Some((stencil, pipeline)) = &self.projection else { return Err("The stroke has no GPU projection.".into()) }; - if tiles.is_empty() { - return Ok(BTreeMap::new()); - } - let (device, queue) = (&self.device, &self.queue); - let limits = device.limits(); - let tiles_per_batch = PROJECTION_READBACK_TILES - .min((limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) / PROJECTION_TILE_BYTES) as usize) - .min(limits.max_compute_workgroups_per_dimension as usize); - if tiles_per_batch == 0 { - return Err("The GPU projection readback exceeds the adapter's buffer limits.".into()); - } - let coords: Vec<_> = tiles.iter().copied().collect(); - if coords.iter().any(|&(x, y)| x >= self.input.uv.width / TILE || y >= self.input.uv.height / TILE) { - return Err("A GPU projection tile is outside the texture set.".into()); - } - let bytes = tiles.len().min(tiles_per_batch) as u64 * PROJECTION_TILE_BYTES; - let (output, read) = crate::gpu_trace::scoped(device, "GPU projection readback buffers", || { - ( - buffer(device, "tc_projected_tiles", bytes, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC), - buffer(device, "tc_read_projected_tiles", bytes, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ), - ) - })?; - let layout = pipeline.get_bind_group_layout(0); - let mut samples = BTreeMap::new(); - for chunk in coords.chunks(tiles_per_batch) { - let bytes = chunk.len() as u64 * PROJECTION_TILE_BYTES; - let origins: Vec<_> = chunk.iter().map(|&(x, y)| [x * TILE, y * TILE]).collect(); - let submitted = crate::gpu_trace::scoped(device, "GPU projection readback", || { - let tile_origins = storage(device, "tc_projected_tile_origins", &origins); - let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_projected_tiles"), - layout: &layout, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&self.view) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, - wgpu::BindGroupEntry { binding: 2, resource: self.surface.1.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&stencil.image) }, - wgpu::BindGroupEntry { binding: 4, resource: stencil.uniforms.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 5, resource: tile_origins.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 6, resource: output.as_entire_binding() }, - ], - }); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_read_projected_tiles") }); - { - let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(pipeline); - pass.set_bind_group(0, &bindings, &[]); - pass.dispatch_workgroups(TILE / 8, TILE / 8, chunk.len() as u32); - } - encoder.copy_buffer_to_buffer(&output, 0, &read, 0, Some(bytes)); - queue.submit([encoder.finish()]) - })?; - let slice = read.slice(..bytes); - let (sender, receiver) = std::sync::mpsc::channel(); - slice.map_async(wgpu::MapMode::Read, move |result| { - let _ = sender.send(result); - }); - device.poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }).map_err(|e| e.to_string())?; - receiver.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; - { - let mapping = slice.get_mapped_range().map_err(|e| e.to_string())?; - let rgba: &[[f32; 4]] = bytemuck::try_cast_slice(&mapping).map_err(|e| e.to_string())?; - for (&tile, texels) in chunk.iter().zip(rgba.as_chunks::<{ texturecraft_texel::TILE_AREA }>().0) { - samples.insert(tile, texels.to_vec()); - } - } - read.unmap(); - } - Ok(samples) - } -} - -// Clip the triangle to the dab's enclosing volume before binning its projected texels. +// Clip the triangle to the dab's enclosing volume before binning its projected texels fn footprint(mesh: &Mesh, triangle: u32, stamp: &Stamp) -> Option<(Vec2, Vec2)> { let corners = mesh.tri(triangle as usize)?; let mut polygon = Vec::with_capacity(9); @@ -567,7 +50,7 @@ fn footprint(mesh: &Mesh, triangle: u32, stamp: &Stamp) -> Option<(Vec2, Vec2)> } let mut next = Vec::with_capacity(9); let r = stamp.radius; - for (axis, limit) in [(stamp.tangent, r * 1.42), (stamp.bitangent, r * 1.42), (stamp.normal, r * stamp.depth)] { + for (axis, limit) in [(stamp.tangent, r * Stamp::PLANAR_RADIUS_SCALE), (stamp.bitangent, r * Stamp::PLANAR_RADIUS_SCALE), (stamp.normal, r * stamp.depth)] { for axis in [axis, -axis] { next.clear(); let mut prev = *polygon.last()?; @@ -591,14 +74,12 @@ fn footprint(mesh: &Mesh, triangle: u32, stamp: &Stamp) -> Option<(Vec2, Vec2)> Some(polygon.iter().fold((first, first), |(lo, hi), &(_, uv)| (lo.min(uv), hi.max(uv)))) } -fn add_tiles(tiles: &mut Tiles, lo: Vec2, hi: Vec2, size: Vec2) { +fn covered_tiles(lo: Vec2, hi: Vec2, size: Vec2) -> impl Iterator { let lo = (lo - Vec2::ONE).floor().max(Vec2::ZERO).as_uvec2() / TILE; let hi = (hi + Vec2::ONE).ceil().min(size).max(Vec2::ZERO).as_uvec2(); - for y in lo.y..hi.y.div_ceil(TILE) { - for x in lo.x..hi.x.div_ceil(TILE) { - tiles.insert((x, y)); - } - } + let end_y = hi.y.div_ceil(TILE); + + (lo.x..hi.x.div_ceil(TILE)).flat_map(move |x| (lo.y..end_y).map(move |y| (x, y))) } /// Zero `tiles` of a reused alpha map, so a new stroke starts with no coverage. @@ -674,6 +155,7 @@ mod tests { half: [0.18, 0.23], rotation: 0.37, tile, + colors: true, }; let input = BrushInput { mesh: mesh.clone(), @@ -703,6 +185,7 @@ mod tests { skipped += 1; continue; } + let cpu = uv.surface(&mesh, (y * SIZE + x) as usize).and_then(|surface| stencil.sample_world(surface.pos)); if let Some(([r, g, b], alpha)) = cpu.filter(|&(_, alpha)| alpha > 0.0) { assert!(gpu.iter().zip([r, g, b, alpha]).all(|(gpu, cpu)| (gpu - cpu).abs() <= 1e-5), "{x}, {y}: {gpu:?} vs {cpu:?}"); @@ -718,6 +201,55 @@ mod tests { } } + #[test] + fn brush_start_rejects_incomplete_uv_surfaces() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(primitives::plane(1.0, 1)); + let grid = UvGBuffer::new(&mesh, 0, TILE, TILE); + let mut empty = grid.clone(); + empty.width = 0; + let mut incomplete = grid.clone(); + incomplete.bary.pop(); + + for invalid in [empty, incomplete] { + let input = BrushInput { + bvh: Arc::new(Bvh::new(&mesh)), + mesh: mesh.clone(), + uv: Arc::new(invalid), + material: 0, + depth: None, + settings: BrushSettings::default(), + stencil: None, + limit: None, + }; + assert!(gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).is_err()); + } + } + + #[test] + fn readback_rejects_tiles_outside_a_rectangular_brush_surface() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(primitives::plane(1.0, 1)); + let input = BrushInput { + bvh: Arc::new(Bvh::new(&mesh)), + uv: Arc::new(UvGBuffer::new(&mesh, 0, 2 * TILE, TILE)), + mesh, + material: 0, + depth: None, + settings: BrushSettings::default(), + stencil: None, + limit: None, + }; + let stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); + + for outside in [(2, 0), (0, 1)] { + let tiles = Tiles::from([(1, 0), outside]); + assert!(stroke.read_alpha(&tiles).is_err()); + } + + assert!(stroke.read_alpha(&Tiles::from([(1, 0)])).is_ok()); + } + #[test] fn a_new_stroke_reuses_the_alpha_map_without_the_old_coverage() { let Ok(mut gpu) = Headless::new() else { return }; @@ -833,8 +365,8 @@ mod tests { } } assert!(covered > 0, "{alpha:?} must stamp in {view}"); - // Barycentric quantization and different floating-point math can move a few texels - // across a shape edge or the spray threshold. + + // Quantized barycentrics can move an edge texel across the spray threshold assert!(differing * 100 <= covered, "{alpha:?} in {view}: {differing}/{covered} alpha values differ"); } @@ -881,7 +413,8 @@ mod tests { seed: 0, source: None, }; - // The second island fits in the rotated dab, but lies outside the old 1.42-radius world box. + + // The second island fits in the rotated dab, but lies outside the old 1.42-radius world box let positions = [Vec3::ZERO, Vec3::X * 1.6].into_iter().flat_map(|center| [center, center + Vec3::X * 0.01, center + Vec3::Y * 0.01]).collect::>(); for far_island_x in [24, 88] { @@ -925,7 +458,8 @@ mod tests { let settings = BrushSettings { backface_culling: true, ..Default::default() }; let camera = OrbitCamera { pitch: 0.0, ..OrbitCamera::default() }; let (cpu, actual) = world_brush_coverage(&mut gpu, mesh, settings, Some(camera), &[back, front]); - // Exact weights (1/2, 1/4, 1/4) cancel here. Only the front-facing dab should paint. + + // Exact weights (1/2, 1/4, 1/4) cancel here. Only the front-facing dab should paint let expected = cpu.get(32, 32)[0]; assert!(expected > 0 && expected < u16::MAX); assert_eq!(actual.get(32, 32)[0], expected); diff --git a/crates/render/src/gpu_brush/brush_input.rs b/crates/render/src/gpu_brush/brush_input.rs new file mode 100644 index 00000000..e6fac473 --- /dev/null +++ b/crates/render/src/gpu_brush/brush_input.rs @@ -0,0 +1,12 @@ +use super::{Arc, BrushSettings, Bvh, EyeDepth, Mesh, Stencil, TileImage, UvGBuffer}; + +pub struct BrushInput { + pub mesh: Arc, + pub bvh: Arc, + pub uv: Arc, + pub material: usize, + pub depth: Option>, + pub settings: BrushSettings, + pub stencil: Option, + pub limit: Option<(TileImage, bool)>, +} diff --git a/crates/render/src/gpu_brush/brush_pipeline.rs b/crates/render/src/gpu_brush/brush_pipeline.rs new file mode 100644 index 00000000..e2417498 --- /dev/null +++ b/crates/render/src/gpu_brush/brush_pipeline.rs @@ -0,0 +1,201 @@ +use super::{ + Arc, BTreeMap, BrushAlpha, BrushInput, Bvh, EyeDepth, GpuBrushStroke, GpuStencil, ImageRes, Mat4, Parameters, SpareAlpha, TILE, Tiles, Visibility, Weak, + clear_tiles, extent, gpu_stencil, storage, texture, +}; + +pub(crate) struct BrushPipeline { + pub(super) shader: wgpu::ShaderModule, + pub(super) layout: wgpu::PipelineLayout, + pub(super) pipelines: BTreeMap, + pub(super) rays: Option<(Weak, wgpu::Buffer, wgpu::Buffer)>, + pub(super) depth: Option<(Weak, wgpu::TextureView)>, + pub(super) stencil_image: Option<(Weak, wgpu::TextureView)>, + pub(super) projection_readback: Option, + pub(super) spare_alpha: SpareAlpha, +} + +impl BrushPipeline { + pub(crate) fn clear_visibility(&mut self) { + self.rays = None; + self.depth = None; + self.stencil_image = None; + } + + pub fn new(device: &wgpu::Device) -> Self { + use crate::gpu_trace::{entry, storage}; + let texture_entry = |binding, sample_type| { + entry(binding, wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }) + }; + let inputs = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tc_brush_inputs"), + entries: &[ + entry(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }), + storage(1, true), + storage(2, true), + texture_entry(3, wgpu::TextureSampleType::Uint), + storage(4, true), + texture_entry(5, wgpu::TextureSampleType::Uint), + texture_entry(6, wgpu::TextureSampleType::Float { filterable: false }), + storage(7, true), + storage(8, true), + storage(9, false), + ], + }); + let layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("tc_brush"), bind_group_layouts: &[Some(&inputs)], immediate_size: 0 }); + let source = concat!(include_str!("../shaders/rays.wgsl"), "\n", include_str!("../shaders/noise.wgsl"), "\n", include_str!("../shaders/brush.wgsl")); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("tc_brush"), source: wgpu::ShaderSource::Wgsl(source.into()) }); + Self { + shader, + layout, + pipelines: BTreeMap::new(), + rays: None, + depth: None, + stencil_image: None, + projection_readback: None, + spare_alpha: SpareAlpha::default(), + } + } + + pub(super) fn pipeline(&mut self, device: &wgpu::Device, alpha: BrushAlpha) -> wgpu::ComputePipeline { + // Specialize by shape so the simple brushes keep their smaller GPU kernels + let alpha_kind = match alpha { + BrushAlpha::Round => 0, + BrushAlpha::Square => 1, + BrushAlpha::Spray => 2, + BrushAlpha::Grunge => 3, + BrushAlpha::Cloud => 4, + BrushAlpha::Star => 5, + BrushAlpha::Streaks => 6, + }; + self.pipelines + .entry(alpha_kind) + .or_insert_with(|| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("tc_brush"), + layout: Some(&self.layout), + module: &self.shader, + entry_point: Some("brush"), + compilation_options: wgpu::PipelineCompilationOptions { constants: &[("alpha_kind", f64::from(alpha_kind))], ..Default::default() }, + cache: None, + }) + }) + .clone() + } + + pub(super) fn visibility(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, input: &BrushInput) -> Result { + let key = Arc::downgrade(&input.bvh); + if self.rays.as_ref().is_none_or(|(last, ..)| !last.ptr_eq(&key)) { + let (nodes, triangles) = crate::gpu_trace::bvh_rows(&input.bvh, (0, 0), |_| ([0; 3], [0; 4])); + let bytes = (nodes.len().max(triangles.len()) * 16) as u64; + if bytes > device.limits().max_storage_buffer_binding_size.min(device.limits().max_buffer_size) { + return Err("mesh visibility buffers exceed this adapter's limits".into()); + } + + self.rays = Some((key, storage(device, "tc_brush_nodes", &nodes), storage(device, "tc_brush_triangles", &triangles))); + } + let (_, nodes, triangles) = self.rays.as_ref().ok_or("brush meshes are missing")?; + let depth = if let Some(depth) = &input.depth { + let key = Arc::downgrade(depth); + if self.depth.as_ref().is_none_or(|(last, _)| !last.ptr_eq(&key)) { + let surface = texture(device, [depth.width, depth.height], wgpu::TextureFormat::R32Float); + queue.write_texture( + surface.as_image_copy(), + bytemuck::cast_slice(&depth.dist), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(depth.width * 4), rows_per_image: None }, + extent(depth.width, depth.height), + ); + self.depth = Some((key, surface.create_view(&Default::default()))); + } + self.depth.as_ref().ok_or("brush depth is missing")?.1.clone() + } else { + texture(device, [1, 1], wgpu::TextureFormat::R32Float).create_view(&Default::default()) + }; + Ok(Visibility { nodes: nodes.clone(), triangles: triangles.clone(), depth }) + } + + pub fn begin( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + input: BrushInput, + surface: (wgpu::TextureView, wgpu::Buffer), + ) -> Result { + let size = [input.uv.width, input.uv.height]; + if size.into_iter().any(|edge| !edge.is_multiple_of(TILE) || edge > device.limits().max_texture_dimension_2d) { + return Err("unsupported GPU brush texture size".into()); + } + + if input.limit.as_ref().is_some_and(|(mask, _)| [mask.width(), mask.height()] != size || mask.comps() != 1) { + return Err("The quick mask does not match the GPU brush texture size.".into()); + } + + let visibility = self.visibility(device, queue, &input)?; + let spare = self.spare_alpha.lock().ok().and_then(|mut spare| spare.take()); + let alpha = match spare { + Some((alpha, written)) if [alpha.width(), alpha.height()] == size => { + clear_tiles(queue, &alpha, &written); + alpha + } + _ => texture(device, size, wgpu::TextureFormat::R16Uint), + }; + let view = alpha.create_view(&Default::default()); + let (lo, hi) = input.mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = (hi - lo).length().mul_add(0.5, 0.0).max(1e-4); + self.stencil_image.take_if(|(source, _)| source.strong_count() == 0); + let projection = if let Some(stencil) = &input.stencil { + let key = Arc::downgrade(&stencil.image); + if self.stencil_image.as_ref().is_none_or(|(previous, _)| !previous.ptr_eq(&key)) { + self.stencil_image = None; + self.stencil_image = Some((key, gpu_stencil::upload_image(device, queue, &stencil.image)?)); + } + let (_, image) = self.stencil_image.as_ref().ok_or("projection image missing")?; + let stencil = GpuStencil::new(device, image.clone(), stencil, center, radius); + let readback = self.projection_readback.get_or_insert_with(|| gpu_stencil::readback_pipeline(device)).clone(); + Some((stencil, readback)) + } else { + None + }; + let settings = &input.settings; + let pipeline = self.pipeline(device, settings.alpha); + let mut params = Parameters { + camera: Mat4::IDENTITY.to_cols_array_2d(), + eye: [0.0; 4], + view_scale: [0.0, settings.angle_fade.1.to_radians().cos(), settings.angle_fade.0.to_radians().cos(), 0.0], + mesh: center.extend(radius).to_array(), + ortho: [0.0; 4], + shape: [settings.alpha_params.size_x, settings.alpha_params.size_y, settings.alpha_params.roundness, settings.alpha_params.contrast], + flags: [ + 0, + u32::from(settings.backface_culling), + u32::from(settings.alpha_params.invert), + input.limit.as_ref().map_or(0, |(_, invert)| 1 + u32::from(*invert)), + ], + }; + if let Some(depth) = &input.depth { + params.camera = depth.view_proj.to_cols_array_2d(); + params.eye = depth.eye.extend(depth.bias).to_array(); + params.view_scale[0] = (depth.height as f32 * depth.view_proj.row(1).truncate().length()).max(f32::EPSILON); + params.view_scale[3] = 1.0; + if let Some(to_eye) = depth.orthographic_to_eye { + params.ortho = to_eye.extend(1.0).to_array(); + } + } + Ok(GpuBrushStroke { + input, + pipeline, + device: device.clone(), + queue: queue.clone(), + surface, + visibility, + alpha, + view, + params, + scratch: None, + projection, + written: Tiles::new(), + spare_alpha: self.spare_alpha.clone(), + }) + } +} diff --git a/crates/render/src/gpu_brush/dab.rs b/crates/render/src/gpu_brush/dab.rs new file mode 100644 index 00000000..088bda5b --- /dev/null +++ b/crates/render/src/gpu_brush/dab.rs @@ -0,0 +1,16 @@ +use super::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Dab { + pub(super) center: [f32; 4], + pub(super) normal: [f32; 4], + pub(super) tangent: [f32; 4], + pub(super) bitangent: [f32; 4], + pub(super) seed: u32, + pub(super) padding: [u32; 3], + /// A symmetry copy's source origin with w 1, zero for any other dab. + pub(super) source: [f32; 4], + /// The columns of the copy's `StampSource::to_source`. + pub(super) to_source: [[f32; 4]; 3], +} diff --git a/crates/render/src/gpu_brush/gpu_brush_stroke.rs b/crates/render/src/gpu_brush/gpu_brush_stroke.rs new file mode 100644 index 00000000..e0c2ad8a --- /dev/null +++ b/crates/render/src/gpu_brush/gpu_brush_stroke.rs @@ -0,0 +1,311 @@ +use super::{ + Arc, BTreeMap, BrushInput, CHUNK, Dab, DeviceExt, GpuStencil, PROJECTION_READBACK_TILES, PROJECTION_TILE_BYTES, Parameters, ProjectedTiles, ROW_BYTES, + SpareAlpha, Stamp, TILE, TILE_BYTES, TileDabs, TileImage, Tiles, UvStamp, Vec2, Visibility, buffer, buffer_copy, covered_tiles, extent, footprint, storage, + tile_copy, +}; + +pub struct GpuBrushStroke { + pub(super) input: BrushInput, + pub(super) pipeline: wgpu::ComputePipeline, + pub(super) device: wgpu::Device, + pub(super) queue: wgpu::Queue, + pub(super) surface: (wgpu::TextureView, wgpu::Buffer), + pub(super) visibility: Visibility, + pub(super) alpha: wgpu::Texture, + pub(super) view: wgpu::TextureView, + pub(super) params: Parameters, + pub(super) scratch: Option, + pub(super) projection: Option<(GpuStencil, wgpu::ComputePipeline)>, + /// The alpha tiles the stroke wrote, cleared when the next stroke reuses its map + pub(super) written: Tiles, + pub(super) spare_alpha: SpareAlpha, +} + +impl Drop for GpuBrushStroke { + fn drop(&mut self) { + if let Ok(mut spare) = self.spare_alpha.lock() { + *spare = Some((self.alpha.clone(), std::mem::take(&mut self.written))); + } + } +} + +impl GpuBrushStroke { + pub fn view(&self) -> wgpu::TextureView { + self.view.clone() + } + + pub fn stencil(&self) -> Option { + self.projection.as_ref().map(|(stencil, _)| stencil.clone()) + } + + pub fn append_world(&mut self, stamps: &[Stamp]) -> Result { + let mut bins = TileDabs::new(); + let input = &self.input; + let size = Vec2::new(input.uv.width as f32, input.uv.height as f32); + let mut dabs = Vec::new(); + for stamp in stamps { + if !stamp.radius.is_finite() || stamp.radius <= 0.0 || !stamp.center.is_finite() { + continue; + } + + let (source, to_source) = match stamp.source { + Some(source) => (source.origin.extend(1.0).to_array(), source.to_source.to_cols_array_2d().map(|[x, y, z]| [x, y, z, 0.0])), + None => ([0.0; 4], [[0.0; 4]; 3]), + }; + let index = dabs.len() as u32; + dabs.push(Dab { + center: stamp.center.extend(stamp.radius).to_array(), + normal: stamp.normal.extend(stamp.depth).to_array(), + tangent: stamp.tangent.extend(stamp.flow).to_array(), + bitangent: stamp.bitangent.extend(stamp.hardness).to_array(), + seed: stamp.seed, + padding: [0; 3], + source, + to_source, + }); + let extent = stamp.world_extent(); + let mut touched = Tiles::new(); + input.bvh.query_box(stamp.center - extent, stamp.center + extent, |triangle| { + if input.mesh.material_of(triangle as usize) == Some(input.material) + && let Some((lo, hi)) = footprint(&input.mesh, triangle, stamp) + { + touched.extend(covered_tiles(lo * size, hi * size, size)); + } + }); + for tile in touched { + bins.entry(tile).or_default().push(index); + } + } + self.dispatch(&bins, &dabs, false)?; + Ok(bins.into_keys().collect()) + } + + pub fn append_uv(&mut self, stamps: &[UvStamp]) -> Result { + let mut bins = TileDabs::new(); + let size = Vec2::new(self.input.uv.width as f32, self.input.uv.height as f32); + let mut dabs = Vec::new(); + for stamp in stamps { + if !stamp.radius.is_finite() || stamp.radius <= 0.0 || !stamp.center.is_finite() { + continue; + } + + let center = stamp.center * size; + let radius = stamp.radius * size.x; + let (sin, cos) = stamp.angle.to_radians().sin_cos(); + let index = dabs.len() as u32; + dabs.push(Dab { + center: [center.x, center.y, 0.0, radius], + normal: [0.0; 4], + tangent: [cos, sin, 0.0, stamp.flow], + bitangent: [0.0, 0.0, 0.0, stamp.hardness], + seed: stamp.seed, + padding: [0; 3], + source: [0.0; 4], + to_source: [[0.0; 4]; 3], + }); + let reach = Vec2::splat(radius * Stamp::PLANAR_RADIUS_SCALE); + for tile in covered_tiles(center - reach, center + reach, size) { + bins.entry(tile).or_default().push(index); + } + } + self.dispatch(&bins, &dabs, true)?; + Ok(bins.into_keys().collect()) + } + + pub(super) fn dispatch(&mut self, tiles: &TileDabs, dabs: &[Dab], uv: bool) -> Result<(), String> { + if tiles.is_empty() || dabs.is_empty() { + return Ok(()); + } + + let mut params = self.params; + params.flags[0] = u32::from(uv); + self.written.extend(tiles.keys()); + let coordinates: Vec<_> = tiles.iter().collect(); + let (device, queue) = (&self.device, &self.queue); + crate::gpu_trace::scoped(device, "GPU brush dispatch", || { + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_brush_parameters"), + contents: bytemuck::bytes_of(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + let dabs = storage(device, "tc_brush_dabs", dabs); + let bytes = coordinates.len().min(CHUNK) as u64 * TILE_BYTES; + if self.scratch.as_ref().is_none_or(|buffer| buffer.size() < bytes) { + self.scratch = Some(buffer(device, "tc_brush_scratch", bytes.next_power_of_two(), wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC)); + } + let scratch = self.scratch.as_ref().ok_or("brush scratch buffer missing")?; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_brush") }); + for chunk in coordinates.chunks(CHUNK) { + // Origins, dab offsets/counts and optional quick-mask offsets + let mut cells = vec![0; chunk.len() * 5]; + for (tile, (&(x, y), indices)) in chunk.iter().copied().enumerate() { + let first = cells.len() as u32; + cells.extend(indices); + let mask = self.input.limit.as_ref().and_then(|(mask, _)| mask.tile(x, y)); + let limit = mask.map_or(0, |mask| { + let offset = cells.len() as u32; + cells.extend(mask.as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); + offset + }); + cells[tile * 5..tile * 5 + 5].copy_from_slice(&[x * TILE, y * TILE, first, indices.len() as u32, limit]); + } + let cells = storage(device, "tc_brush_tiles", &cells); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_brush_inputs"), + layout: &self.pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: self.visibility.nodes.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: self.visibility.triangles.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, + wgpu::BindGroupEntry { binding: 4, resource: self.surface.1.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&self.view) }, + wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&self.visibility.depth) }, + wgpu::BindGroupEntry { binding: 7, resource: dabs.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 8, resource: cells.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 9, resource: scratch.as_entire_binding() }, + ], + }); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &bind, &[]); + pass.dispatch_workgroups(TILE / 16, TILE / 8, chunk.len() as u32); + } + for (i, (&(x, y), _)) in chunk.iter().copied().enumerate() { + encoder.copy_buffer_to_texture(buffer_copy(scratch, i), tile_copy(&self.alpha, x * TILE, y * TILE), extent(TILE, TILE)); + } + } + queue.submit([encoder.finish()]); + Ok::<_, String>(()) + })? + } + + pub(super) fn validate_readback_tiles(&self, tiles: &Tiles) -> Result<(), String> { + let width = self.input.uv.width / TILE; + let height = self.input.uv.height / TILE; + if tiles.iter().any(|&(x, y)| x >= width || y >= height) { + return Err("A GPU brush readback tile is outside the texture set.".into()); + } + + Ok(()) + } + + pub fn read_alpha(&self, tiles: &Tiles) -> Result { + self.validate_readback_tiles(tiles)?; + let mut alpha = TileImage::new(self.input.uv.width, self.input.uv.height, 1); + if tiles.is_empty() { + return Ok(alpha); + } + + let (device, queue) = (&self.device, &self.queue); + let read = crate::gpu_trace::scoped(device, "GPU brush readback buffer", || { + buffer(device, "tc_brush_read_alpha", tiles.len().min(CHUNK) as u64 * TILE_BYTES, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ) + })?; + let coords: Vec<_> = tiles.iter().copied().collect(); + for chunk in coords.chunks(CHUNK) { + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_brush_read_alpha") }); + for (i, &(x, y)) in chunk.iter().enumerate() { + encoder.copy_texture_to_buffer(tile_copy(&self.alpha, x * TILE, y * TILE), buffer_copy(&read, i), extent(TILE, TILE)); + } + let index = queue.submit([encoder.finish()]); + let slice = read.slice(..chunk.len() as u64 * TILE_BYTES); + let (send, receive) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = send.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(index), timeout: None }).map_err(|e| e.to_string())?; + receive.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + { + let mapped = slice.get_mapped_range().map_err(|e| e.to_string())?; + for (bytes, &(x, y)) in mapped.as_chunks::<{ TILE_BYTES as usize }>().0.iter().zip(chunk) { + let samples: Vec<_> = bytes + .as_chunks::<{ ROW_BYTES as usize }>() + .0 + .iter() + .flat_map(|row| row[..(TILE * 2) as usize].as_chunks::<2>().0.iter().map(|&value| u16::from_le_bytes(value))) + .collect(); + if samples.iter().any(|&a| a != 0) { + alpha.set_tile(x, y, Some(Arc::new(samples))); + } + } + } + read.unmap(); + } + Ok(alpha) + } + /// Read the projected linear RGB and image alpha of the touched tiles. + /// The stroke's geometric coverage remains in the separate alpha map. + pub fn read_projection(&self, tiles: &Tiles) -> Result { + let Some((stencil, pipeline)) = &self.projection else { return Err("The stroke has no GPU projection.".into()) }; + if tiles.is_empty() { + return Ok(BTreeMap::new()); + } + + let (device, queue) = (&self.device, &self.queue); + let limits = device.limits(); + let tiles_per_batch = PROJECTION_READBACK_TILES + .min((limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) / PROJECTION_TILE_BYTES) as usize) + .min(limits.max_compute_workgroups_per_dimension as usize); + if tiles_per_batch == 0 { + return Err("The GPU projection readback exceeds the adapter's buffer limits.".into()); + } + + self.validate_readback_tiles(tiles)?; + let coords: Vec<_> = tiles.iter().copied().collect(); + let bytes = tiles.len().min(tiles_per_batch) as u64 * PROJECTION_TILE_BYTES; + let (output, read) = crate::gpu_trace::scoped(device, "GPU projection readback buffers", || { + ( + buffer(device, "tc_projected_tiles", bytes, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC), + buffer(device, "tc_read_projected_tiles", bytes, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ), + ) + })?; + let layout = pipeline.get_bind_group_layout(0); + let mut samples = BTreeMap::new(); + for chunk in coords.chunks(tiles_per_batch) { + let bytes = chunk.len() as u64 * PROJECTION_TILE_BYTES; + let origins: Vec<_> = chunk.iter().map(|&(x, y)| [x * TILE, y * TILE]).collect(); + let submitted = crate::gpu_trace::scoped(device, "GPU projection readback", || { + let tile_origins = storage(device, "tc_projected_tile_origins", &origins); + let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_projected_tiles"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&self.view) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, + wgpu::BindGroupEntry { binding: 2, resource: self.surface.1.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&stencil.image) }, + wgpu::BindGroupEntry { binding: 4, resource: stencil.uniforms.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 5, resource: tile_origins.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 6, resource: output.as_entire_binding() }, + ], + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_read_projected_tiles") }); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bindings, &[]); + pass.dispatch_workgroups(TILE / 8, TILE / 8, chunk.len() as u32); + } + encoder.copy_buffer_to_buffer(&output, 0, &read, 0, Some(bytes)); + queue.submit([encoder.finish()]) + })?; + let slice = read.slice(..bytes); + let (sender, receiver) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = sender.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }).map_err(|e| e.to_string())?; + receiver.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + { + let mapping = slice.get_mapped_range().map_err(|e| e.to_string())?; + let rgba: &[[f32; 4]] = bytemuck::try_cast_slice(&mapping).map_err(|e| e.to_string())?; + for (&tile, texels) in chunk.iter().zip(rgba.as_chunks::<{ texturecraft_texel::TILE_AREA }>().0) { + samples.insert(tile, texels.to_vec()); + } + } + read.unmap(); + } + Ok(samples) + } +} diff --git a/crates/render/src/gpu_brush/parameters.rs b/crates/render/src/gpu_brush/parameters.rs new file mode 100644 index 00000000..cbc9e02b --- /dev/null +++ b/crates/render/src/gpu_brush/parameters.rs @@ -0,0 +1,13 @@ +use super::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Parameters { + pub(super) camera: [[f32; 4]; 4], + pub(super) eye: [f32; 4], + pub(super) view_scale: [f32; 4], + pub(super) mesh: [f32; 4], + pub(super) ortho: [f32; 4], + pub(super) shape: [f32; 4], + pub(super) flags: [u32; 4], +} diff --git a/crates/render/src/gpu_brush/visibility.rs b/crates/render/src/gpu_brush/visibility.rs new file mode 100644 index 00000000..65bafe09 --- /dev/null +++ b/crates/render/src/gpu_brush/visibility.rs @@ -0,0 +1,5 @@ +pub(super) struct Visibility { + pub(super) nodes: wgpu::Buffer, + pub(super) triangles: wgpu::Buffer, + pub(super) depth: wgpu::TextureView, +} diff --git a/crates/render/src/gpu_composite.rs b/crates/render/src/gpu_composite.rs index e2056fd2..bdcd7dc9 100644 --- a/crates/render/src/gpu_composite.rs +++ b/crates/render/src/gpu_composite.rs @@ -30,10 +30,10 @@ use wgpu::util::DeviceExt; #[path = "gpu_composite_groups.rs"] mod groups; -#[path = "gpu_composite_pipelines.rs"] +#[path = "composite_pipeline/mod.rs"] mod pipelines; -// The GPU port packages (texturecraft #713): the hub chains every package's hooks, each package -// owns its module. See gpu_composite_packages.rs for the ownership table and shared layouts. + +// Shader package hooks share the registration table in gpu_composite_packages #[path = "gpu_composite_brush.rs"] mod brush; #[path = "gpu_composite_projection.rs"] @@ -70,17 +70,15 @@ const MASK_ANCHOR_STAGE: u32 = 1 << 28; const ANCHOR_SOURCE: u32 = 15; const ANCHOR_PUBLISH_MASK: u32 = 16; const ANCHOR_PUBLISH_LAYER: u32 = 17; -// Opcodes are classified by range, in the shaders too (`is_fill_opcode` in -// composite_packages.wgsl): fills and patterns below 20 and from 48 below 128, built-in effects -// 20..40, generators 40..48, the GPU port packages' effects 128..192 (`packages::EXTENDED_EFFECTS`, -// one block per package), group markers 200 and 201. Never renumber an existing opcode. -// Extended procedural sources follow the filter and generator opcodes. + +// Keep opcode ranges in sync with is_fill_opcode in composite_packages.wgsl +// Existing opcodes retain their values across extensions const FIRST_GENERATOR: u32 = 40; const FIRST_EXTENDED_PATTERN: u32 = 48; pub(crate) const ROWS: u32 = 64; const WORKGROUP: u32 = 8; -// Keep costly fills (Tile Generator overlap, symmetry copies) from monopolizing a dispatch or a -// submission: an update of any cost runs in more bands and submissions instead. + +// Bound submission work even when a fill has many overlapping or symmetric copies const MAX_TILE_WORK_PER_BAND: u64 = 64 << 20; const MAX_TILE_WORK_PER_SUBMISSION: u64 = 256 << 20; const BAKE_MAPS: [BakedMap; 4] = [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature, BakedMap::Thickness]; @@ -93,18 +91,53 @@ const ENVIRONMENT_WORDS: usize = 28; const MAX_ID_BAKE_BYTES: u64 = 1 << 30; const MAX_ID_UPLOAD_BYTES: usize = 64 << 20; -#[derive(Debug)] -struct BakedInputs { - width: u32, - /// The maps' common height; with maps of different heights ([`Self::separate`]) the - /// Curvature's, else the first baked map's - height: u32, - maps: [Option>>; BAKE_MAPS.len()], - /// The second row block's maps ([`BAKE_ROW_MAPS`]), only in programs that read them - rows: [Option>>; BAKE_ROW_MAPS.len()], - /// P8: each map's height in texels, [`BAKE_MAPS`] then [`BAKE_ROW_MAPS`] (0 where not baked) - heights: [u32; SEPARATE_MAPS], -} +mod anchor_inputs; +mod bake_cache; +mod baked_inputs; +mod composite_program; +mod composite_region; +mod curvature_cache; +mod curvature_resources; +mod filter_plan; +mod filter_stage; +mod geometry_masks; +mod gpu_compositor; +mod id_bake; +mod id_bake_cache; +mod late_environment; +mod live_brush; +mod live_brush_target; +mod operation; +mod paint_inputs; +mod procedural_inputs; +mod surface_cache; +mod whole_pass; +mod whole_set; +mod whole_set_pass; + +use anchor_inputs::AnchorInputs; +use bake_cache::BakeCache; +use baked_inputs::BakedInputs; +pub use composite_program::CompositeProgram; +pub use composite_region::CompositeRegion; +use curvature_cache::CurvatureCache; +use curvature_resources::CurvatureResources; +use filter_plan::FilterPlan; +use filter_stage::FilterStage; +use geometry_masks::GeometryMasks; +pub(crate) use gpu_compositor::GpuCompositor; +use id_bake::IdBake; +use id_bake_cache::IdBakeCache; +use late_environment::LateEnvironment; +pub use live_brush::LiveBrush; +pub use live_brush_target::LiveBrushTarget; +use operation::Operation; +use paint_inputs::PaintInputs; +use procedural_inputs::ProceduralInputs; +use surface_cache::SurfaceCache; +use whole_pass::WholePass; +use whole_set::WholeSet; +use whole_set_pass::WholeSetPass; /// P8: the maps of the bake texture with maps of different heights, [`BAKE_MAPS`] then /// [`BAKE_ROW_MAPS`], as `udim_separate_bake` in WGSL numbers them @@ -112,101 +145,33 @@ const SEPARATE_MAPS: usize = BAKE_MAPS.len() + BAKE_ROW_MAPS.len(); /// P8: the order their rows take: the Curvature's first, where the curvature detail sizes read them const SEPARATE_ORDER: [usize; SEPARATE_MAPS] = [2, 0, 1, 3, 4, 5]; -impl BakedInputs { - /// The bakes a program reads: the built-in maps, and with `rows` the second row block's. Maps - /// of different heights each keep their own (P8, [`Self::separate`]). - fn new(baked: &BakedMaps, rows: bool) -> Result, &'static str> { - let present = |map: &BakedMap| baked.maps.get(map).filter(|data| !data.is_empty()).cloned(); - let maps = BAKE_MAPS.map(|map| present(&map)); - let rows = BAKE_ROW_MAPS.map(|map| present(&map).filter(|_| rows)); - let all = BAKE_MAPS.iter().zip(&maps).chain(BAKE_ROW_MAPS.iter().zip(&rows)); - let Some(first) = all.clone().find_map(|(&map, data)| data.as_ref().map(|_| map)) else { return Ok(None) }; - if baked.resolution == 0 || all.clone().any(|(&map, data)| data.is_some() && baked.height(map) == 0) { - return Err("A baked map has no whole row of texels and uses CPU compositing."); - } - - let mut heights = [0; SEPARATE_MAPS]; - for (height, (&map, data)) in heights.iter_mut().zip(all) { - *height = if data.is_some() { baked.height(map) } else { 0 }; - } - let curvature = baked.height(BakedMap::Curvature); - let height = if maps[2].is_some() && curvature != 0 { curvature } else { baked.height(first) }; - Ok(Some(Self { width: baked.resolution, height, maps, rows, heights })) - } - - /// Row blocks of the bake texture: the built-in maps', and the second block's when a map of it is baked - fn blocks(&self) -> u32 { - if self.rows.iter().any(Option::is_some) { 2 } else { 1 } - } - - /// The band uniform's bake words (`params.id_bake.zw`): rows per block (0: one block, the - /// whole texture; the Curvature's rows with maps of different heights) and the second - /// block's presence bits - fn uniform_words(&self) -> [u32; 2] { - let present = self.rows.iter().enumerate().filter(|(_, data)| data.is_some()).fold(0, |bits, (index, _)| bits | 1 << index); - [if self.blocks() > 1 || self.separate() { self.height } else { 0 }, present] - } - - /// P8: whether the baked maps have different heights. Each height's maps then take rows of - /// their own, with a header row after them ([`Self::separate_layout`]). - fn separate(&self) -> bool { - let mut heights = self.heights.iter().filter(|&&height| height != 0); - let first = heights.next(); - heights.any(|height| Some(height) != first) - } - - /// P8: the rows of baked maps of different heights: each map's first row and height - /// ([`BAKE_MAPS`] then [`BAKE_ROW_MAPS`], no rows where not baked), and the header row after - /// them. The built-in maps of one height share rows, the row maps of one height too. - fn separate_layout(&self) -> ([[u32; 2]; SEPARATE_MAPS], u32) { - let mut groups: Vec<((bool, u32), u32)> = Vec::new(); - let mut next = 0u32; - let mut entries = [[0; 2]; SEPARATE_MAPS]; - for index in SEPARATE_ORDER { - let height = self.heights[index]; - if height == 0 { - continue; - } - let key = (index >= BAKE_MAPS.len(), height); - let first = match groups.iter().find(|(group, _)| *group == key) { - Some(&(_, first)) => first, - None => { - groups.push((key, next)); - next = next.saturating_add(height); - next - height - } - }; - entries[index] = [first, height]; - } - (entries, next) - } -} - /// P8: upload baked maps of different heights ([`BakedInputs::separate_layout`]): each height's /// maps in rows of their own, laid as the one-height texture lays them (a map of another height /// keeps its fallback there), then each map's first row and height in the header rows, texel /// `map` (`udim_separate_bake` in WGSL). fn write_separate_bakes(queue: &wgpu::Queue, texture: &wgpu::Texture, baked: &BakedInputs, (entries, header): ([[u32; 2]; SEPARATE_MAPS], u32)) { let width = baked.width; + let mut texels = Vec::new(); let mut written: Vec = Vec::new(); for (index, &[first, height]) in entries.iter().enumerate() { if height == 0 || written.contains(&first) { continue; } + written.push(first); let row_maps = index >= BAKE_MAPS.len(); let own = |map: usize| entries[map] == [first, height]; for top in (0..height).step_by(ROWS as usize) { let end = (top + ROWS).min(height); let indices = top as usize * width as usize..end as usize * width as usize; - let texels: Vec<[u32; 4]> = if row_maps { + if row_maps { // Height in x, the stored world normal in yzw; zeros where a map is not baked here let row = |map: usize, i: usize, component: usize| { let components = BAKE_ROW_MAPS[map].components(); let data = baked.rows[map].as_ref().filter(|_| own(BAKE_MAPS.len() + map)); data.and_then(|data| data.get(i * components + component).copied()).unwrap_or(0.0).to_bits() }; - indices.into_par_iter().map(|i| [row(0, i, 0), row(1, i, 0), row(1, i, 1), row(1, i, 2)]).collect() + indices.into_par_iter().map(|i| [row(0, i, 0), row(1, i, 0), row(1, i, 1), row(1, i, 2)]).collect_into_vec(&mut texels) } else { let value = |map: usize, i: usize, fallback: f32| { baked.maps[map].as_ref().filter(|_| own(map)).and_then(|data| data.get(i).copied()).unwrap_or(fallback) @@ -221,467 +186,21 @@ fn write_separate_bakes(queue: &wgpu::Queue, texture: &wgpu::Texture, baked: &Ba }; [value(0, i, 1.0).to_bits(), value(2, i, 0.5).to_bits(), value(3, i, 1.0).to_bits(), normal] }) - .collect() + .collect_into_vec(&mut texels) }; write_input(queue, texture, (width, end - top), (first + top, 0), &texels); } } let header_rows = SEPARATE_MAPS.div_ceil(width.max(1) as usize) as u32; - let mut texels = vec![[0u32; 4]; width as usize * header_rows as usize]; + texels.clear(); + texels.resize(width as usize * header_rows as usize, [0; 4]); for (texel, [first, height]) in texels.iter_mut().zip(entries) { *texel = [first, height, 0, 0]; } write_input(queue, texture, (width, header_rows), (header, 0), &texels); } -#[derive(Debug)] -struct IdBake { - size: [u32; 2], - data: Arc>, -} - -impl IdBake { - fn new(baked: &BakedMaps) -> Option { - let data = baked.maps.get(&BakedMap::Id)?; - let height = baked.height(BakedMap::Id); - (height > 0).then(|| Self { size: [baked.resolution.max(1), height], data: data.clone() }) - } -} - -#[repr(C)] -#[derive(Clone, Copy, Debug, Pod, Zeroable)] -struct Operation { - // Destination, source kind, noise seed, invert. - ids: [u32; 4], - // RGB low and layer weight. - low: [f32; 4], - high: [f32; 4], - // UV rotation and scale, or the pigment source in W for live paint (1: brush, 2: stencil). - projection: [f32; 4], - // UV offset XY, procedural scale and contrast, live-brush values and opacity, or curvature weights and mode in XY. - uv: [f32; 4], - balance: [f32; 4], - // Offsets and counts of the mask and content effects. - effects: [u32; 4], - // Sampling resolution, color-ramp offset and count, projection selector. - procedural: [u32; 4], - // First content field, content has fields, mask has fields, content can add coverage. - spatial: [u32; 4], - // Geometry mask row (resolved to a lookup offset at upload), height operation plus one, - // height-mask contrast and offset encoded as floats. - constraints: [u32; 4], - // The GPU port packages' word, zero everywhere else (layout in gpu_composite_packages.rs): - // side-table offset (0: none), P1 projection flags, P2/P3/P6/P7 flag bytes, P8 word. - ext: [u32; 4], -} - -#[derive(Debug, Default)] -struct GeometryMasks { - parts: Vec>, - words: Vec, - stride: usize, -} - -#[derive(Default)] -struct PaintInputs { - images: Vec, - indices: BTreeMap<(LayerId, Option), u32>, -} - -impl PaintInputs { - fn register(&mut self, id: LayerId, channel: Option, image: &TileImage) -> u32 { - *self.indices.entry((id, channel)).or_insert_with(|| { - let index = self.images.len() as u32; - self.images.push(image.clone()); - index - }) - } -} - -impl GeometryMasks { - /// Zero allows every part. A passthrough folder restricts every child to its own allowed parts. - fn register(&mut self, inherited: u32, own: Option<&[String]>) -> u32 { - let Some(own) = own else { return inherited }; - let mut names = match inherited.checked_sub(1).and_then(|index| self.parts.get(index as usize)) { - Some(parent) => own.iter().filter(|name| parent.binary_search(name).is_ok()).cloned().collect(), - None => own.to_vec(), - }; - names.sort_unstable(); - names.dedup(); - if let Some(index) = self.parts.iter().position(|mask| *mask == names) { - return index as u32 + 1; - } - self.parts.push(names); - self.parts.len() as u32 - } - - fn resolve(&mut self, mesh: &Mesh) { - if self.parts.is_empty() { - return; - } - let triangles = mesh.triangle_count(); - self.stride = triangles.div_ceil(32).max(1); - self.words.clear(); - self.words.resize(self.parts.len() * self.stride, u32::MAX); - let parts = &mesh.submeshes; - let ordered = parts.windows(2).all(|pair| pair[0].start.saturating_add(pair[0].count) <= pair[1].start); - for (names, row) in self.parts.iter().zip(self.words.chunks_exact_mut(self.stride)) { - if ordered { - for part in parts.iter().filter(|part| names.binary_search(&part.name).is_err()) { - let first = part.start.div_ceil(3) as usize; - let end = (part.start.saturating_add(part.count).div_ceil(3) as usize).min(triangles); - if first >= end { - continue; - } - for (index, word) in row.iter_mut().enumerate().take(end.div_ceil(32)).skip(first / 32) { - let start_bit = first.saturating_sub(index * 32); - let end_bit = (end - index * 32).min(32); - *word &= !((u32::MAX << start_bit) & (u32::MAX >> (32 - end_bit))); - } - } - } else { - // Match the CPU's lookup even for overlapping or out-of-order submeshes. - for triangle in 0..triangles { - let first = triangle as u32 * 3; - let holds = |index: usize| parts.get(index).is_some_and(|part| part.start <= first && first < part.start.saturating_add(part.count)); - let part = parts - .partition_point(|part| part.start <= first) - .checked_sub(1) - .filter(|index| holds(*index)) - .or_else(|| (0..parts.len()).find(|index| holds(*index))); - if part.and_then(|index| parts.get(index)).is_some_and(|part| names.binary_search(&part.name).is_err()) { - row[triangle / 32] &= !(1 << (triangle % 32)); - } - } - } - } - } -} - -struct ProceduralInputs { - /// Texels per side of a UV tile at the base stage's scale (the set's resolution, or a UV - /// tile atlas's block) - resolution: u32, - /// The set's own resolution, the texture set size of `OutputResolution::output_size` - texture_set: u32, - /// The working atlas's longest side, which caps filter radii - longest_side: u32, - /// P8: a UV tile atlas's block side, where a whole-tile stage finds its tile - block: u32, - /// P8: the tile resolutions of a UV tile atlas's further scales (`udim::UdimLayout::levels`), - /// each a neighbourhood stage of its own after the base stage - levels: Vec, - /// P8: each generator stage's (filter, cell) at those further scales, by generator stage - generator_levels: Vec, u32)>>, - ramp_words: Vec, - curvature_sizes: [bool; CurvatureDetail::BLURRED_SIZES], - filters: Vec<(Filter, f32)>, - materials: MaterialImages, - generator_stages: Vec<(Option, u32)>, - generator_sources: Vec, - anchors: AnchorInputs, - /// A neighbourhood stage a package lowering asked to run right before the effect's own - /// operation ([`Self::precede_with_stage`]); the callers of `point_effect` push it first. - preceding_stage: Option, - /// Source operations effects read as image inputs (`register_input`), appended after the - /// effects like the generators' sources. - input_sources: Vec, - /// Side-table words that hold an image's record offset once the atlas is laid out - /// (`pack_image`): (word index in the side table, image index). - image_words: Vec<(u32, u32)>, - /// The side-table word where the environment's diffuse light starts, filled at upload - /// (`reserve_environment`). - environment_word: Option, - /// A lowering reads the Height and World Normal bake rows (`read_bake_rows`). - bake_rows: bool, - /// The image inputs (`register_input` references) read as colour (`register_color_input`). - color_inputs: BTreeSet, -} - -#[derive(Default)] -struct AnchorInputs { - visible: BTreeMap, - reads: Vec<(u32, Channel)>, - draw_ranges: Vec>, - next: u32, -} - -impl AnchorInputs { - fn publish(&mut self, id: LayerId, mask: bool) -> u32 { - let publish = self.next; - self.next += 1; - self.visible.insert(id, (publish, mask)); - publish - } - - fn read(&mut self, id: LayerId, channel: Channel) -> (u32, bool) { - let Some(&(publish, mask)) = self.visible.get(&id) else { return (0, false) }; - let channel = if mask { Channel::BaseColor } else { channel }; - let read = (publish, channel); - let index = self.reads.iter().position(|existing| *existing == read).unwrap_or_else(|| { - let index = self.reads.len(); - self.reads.push(read); - index - }); - (index as u32 + 1, mask) - } -} - -impl ProceduralInputs { - fn new(resolution: u32) -> Self { - Self { - resolution, - texture_set: resolution, - longest_side: resolution, - block: resolution, - levels: Vec::new(), - generator_levels: Vec::new(), - ramp_words: Vec::new(), - curvature_sizes: [false; CurvatureDetail::BLURRED_SIZES], - filters: Vec::new(), - materials: MaterialImages::default(), - generator_stages: Vec::new(), - generator_sources: Vec::new(), - anchors: AnchorInputs::default(), - preceding_stage: None, - input_sources: Vec::new(), - image_words: Vec::new(), - environment_word: None, - bake_rows: false, - color_inputs: BTreeSet::new(), - } - } - - /// [`Self::register_input`] for an input read as colour: a neighbourhood stage's field then - /// carries its RGB in words 5..8 (`input_color_at` in neighbourhood.wgsl), and a point - /// operation reads it with `effect_input_color(effect, texel)`. P5: Color Match's inputs. - #[allow(dead_code)] // Used by the GPU port packages - fn register_color_input(&mut self, source: Operation) -> u32 { - let reference = self.register_input(source); - self.color_inputs.insert(reference); - reference - } - - /// Reserve the [`ENVIRONMENT_WORDS`] side-table words that hold the viewport environment's - /// diffuse light (`EnvironmentSh`): its nine RGB coefficients as f32 bits in `sh_basis` order - /// (coefficient `i`, component `k` at word `3 i + k`), then the environment rotation in - /// radians. The program keeps the project's display settings from compile and fills the words - /// when it learns the images (`CompositeProgram::set_tile_images`), so a turned or changed - /// environment needs no other lowering. Returns their absolute offset (like `pack_words`); a - /// second reservation returns the same words. P6: Baked Lighting Environment. - #[allow(dead_code)] // Used by the GPU port packages - fn reserve_environment(&mut self) -> Option { - if let Some(word) = self.environment_word { - return LOOKUP_WORDS.checked_add(word); - } - let word = u32::try_from(self.ramp_words.len()).ok()?; - let offset = self.pack_words(&[0; ENVIRONMENT_WORDS])?; - self.environment_word = Some(word); - Some(offset) - } - - /// Ask for the bake rows after the built-in maps: the baked Height and World Normal at - /// `baked_block_at(pixel, 1u)` in WGSL (x the height, yzw the stored world normal, f32 bits), - /// present when `bake_has(BAKED_HEIGHT)` / `bake_has(BAKED_WORLD_NORMAL)`. The rows exist only - /// in programs that ask and only for the maps that are baked. P6: lighting's height slope and - /// detail normal. - #[allow(dead_code)] // Used by the GPU port packages - fn read_bake_rows(&mut self) { - self.bake_rows = true; - } - - /// Register `source` (a `source_operation`) as an effect's image input: the returned - /// reference goes in the effect operation's `effects[3]`. The program appends the source - /// after the effects and rebinds the reference to its operation index plus one, which a - /// neighbourhood stage then evaluates into its field's sixth word (`FilterStage::input`) and - /// a point operation reads with `effect_input(effect, texel)` in WGSL. The CPU reads inputs - /// with `Sampling::default()` (Bilinear HQ): build the source with P1's sampling. - #[allow(dead_code)] // Used by the GPU port packages - fn register_input(&mut self, source: Operation) -> u32 { - self.input_sources.push(source); - self.input_sources.len() as u32 - } - - /// A side-table word that will hold image `name`'s record offset (the atlas layout of - /// `MaterialImages`, `u32::MAX` while the image is missing): the returned offset goes where - /// the operation's shader reads it with `param_word`, and `image_texel_nearest` reads the - /// image there (P3: a Color Selection's ID map). - #[allow(dead_code)] // Used by the GPU port packages - fn pack_image(&mut self, name: &str, usage: ImageUse) -> Option { - let image = self.materials.register_image(name, usage); - let word = u32::try_from(self.ramp_words.len()).ok()?; - let offset = self.pack_words(&[u32::MAX])?; - self.image_words.push((word, image)); - Some(offset) - } - - /// Lets a package lowering (in `packages::lower_filter`) run the neighbourhood stage of - /// `filter` right before the effect's own operation: one effect, two operations. This is the - /// seam of the Gradient's `input.blur` (P4 defines the stage, P2 the gradient that follows). - /// The point operation then reads the stage's output field in place of the content, so a - /// stage that must keep the original colour (for the opacity mix) passes its derived value in - /// a component or the sixth field word, as P4 defines it. None, and nothing queued, when the - /// GPU has no stage for `filter` or its size reaches nothing. - #[allow(dead_code)] // Used by the GPU port packages - fn precede_with_stage(&mut self, filter: &Filter, opacity: f32) -> Option<()> { - NeighbourhoodFilter::new(filter, self.resolution, self.longest_side, opacity, None)?; - let ids = [0, NEIGHBOURHOOD_OPCODE, u32::try_from(self.filters.len()).ok()?, 0]; - self.filters.push((filter.clone(), opacity)); - self.preceding_stage = Some(Operation { ids, low: [0.0, 0.0, 0.0, opacity.clamp(0.0, 1.0)], ..Operation::zeroed() }); - Some(()) - } - - fn pack_rgb(&mut self, colors: &[[f32; 3]]) -> Option<[u32; 2]> { - if colors.iter().flatten().any(|value| !value.is_finite()) { - return None; - } - let offset = LOOKUP_WORDS.checked_add(u32::try_from(self.ramp_words.len()).ok()?)?; - let count = u32::try_from(colors.len()).ok()?; - self.ramp_words.extend(colors.iter().flatten().map(|value| value.to_bits())); - Some([offset, count]) - } - - /// Append finite `values` to the parameter side table (the words after the sRGB lookup in - /// binding 2, shared with [`Self::pack_rgb`]) and return their absolute word offset for - /// `Operation::ext[0]`. The shader reads them with `param(op, i)`. None for a non-finite value. - #[allow(dead_code)] // Used by the GPU port packages - fn pack_params(&mut self, values: &[f32]) -> Option { - if values.iter().any(|value| !value.is_finite()) { - return None; - } - let words: Vec = values.iter().map(|value| value.to_bits()).collect(); - self.pack_words(&words) - } - - /// [`Self::pack_params`] for raw words (counts, packed flags, offsets); read with `param_word(op, i)`. - #[allow(dead_code)] // Used by the GPU port packages - fn pack_words(&mut self, words: &[u32]) -> Option { - let offset = LOOKUP_WORDS.checked_add(u32::try_from(self.ramp_words.len()).ok()?)?; - self.ramp_words.extend_from_slice(words); - Some(offset) - } - - fn pack_curvature(&mut self, detail: &CurvatureDetail, derive_levels: bool) -> Option<[f32; 2]> { - let offset = LOOKUP_WORDS.checked_add(u32::try_from(self.ramp_words.len()).ok()?)?; - if offset >= 1 << 24 || detail.weights.iter().any(|weight| !weight.is_finite()) { - return None; - } - self.ramp_words.extend(detail.weights.map(|weight| weight.clamp(0.0, 1.0).to_bits())); - for (size, needed) in self.curvature_sizes.iter_mut().zip(detail.blurred_sizes_in_use()) { - *size |= derive_levels && needed; - } - let mode = match detail.mode { - CurvatureMode::Edges => 1.0, - CurvatureMode::Cavities => 2.0, - CurvatureMode::Both => 3.0, - CurvatureMode::Raw => 4.0, - }; - Some([offset as f32, mode]) - } -} - -#[derive(Clone, Debug)] -struct FilterStage { - layer: u32, - preceding: u32, - filter: Option, - cell: u32, - anchor: Option<(Channel, u32, u32)>, - /// The operation (index plus one, 0: none) the prepare pass evaluates into the field's sixth - /// word: an image input's gray (P3) or the layer's own Height (P5, Height To Normal). - input: u32, - /// How the prepare pass reads `input` ([`INPUT_LAYER`], [`INPUT_COLOR`]; 0: an input source's gray) - input_kind: u32, - /// A second input source (operation index plus one, 0: none), read as colour into words - /// 8..11 (`input2_color_at` in neighbourhood.wgsl): an effect's `effects[2]` on a - /// neighbourhood operation (P5: Color Match's Input and Image Input both linked). - input2: u32, - /// The prepare pass reads the set periodically outside it (P4: Blur and Bevel `wrap`), and - /// the fields of the program may start below zero ([`FilterPlan::wraps`]). - wrap: bool, - /// Evaluated once per update by the whole-set pre-pass ([`FilterPlan::whole_set`]) instead - /// of in every band: a stage with a large reach, or one that needs the whole set. - whole: bool, - /// How the prepare pass views the content (bits of its `field_layout.w`): [`OWN_VIEW`], the - /// layer's own material read as the channels' defaults (a mask's This Layer of a lit Base - /// Color), and [`NO_FIELDS`], every neighbourhood stage as identity. - view: u32, - /// The prepare pass's `mask_view` (`FilterPlan::add_lit_mask_views`), zero for most stages - mask_view: [u32; 4], - /// P8: 0 for a stage of its own; `n` for the stage of the base stage `n` slots before it at a - /// UV tile atlas's level `n` (a smaller tile scale), whose output the texels of that level's - /// blocks read instead (`udim_level_slot` in WGSL) - level: u32, -} - -/// The whole-set pre-pass of a program: the stages it evaluates (the whole-set stages and the -/// lower stages of their stacks), the whole-set stages whose outputs the bands read, and the -/// reach of the pre-pass fields. -#[derive(Debug, PartialEq)] -struct WholeSet { - stages: Vec, - outputs: Vec, - /// The outputs the band uniform names (indices into `outputs`): every output but a level - /// stage, whose results follow its base stage's (P8) - entries: Vec, - /// The largest pass's reach - reach: u32, - /// One pass per stack, run one after another in the same working space - passes: Vec, -} - -/// The whole-set pre-pass of one stack: its stages (a contiguous run of slots), the outputs of -/// [`WholeSet::outputs`] among them, the reach of its fields, and how far past the set's edges -/// its fields reach in a wrapping program (the stages at and below its topmost wrapping stage; -/// a stage that does not wrap reads only the set, its own copy). -#[derive(Debug, PartialEq)] -struct WholePass { - stages: Vec, - outputs: Vec, - reach: u32, - past_edges: u32, - /// The working fields its kernels use besides the original ([`NeighbourhoodFilter::blur_fields`]) - blur_fields: u32, -} - -impl WholePass { - /// The compact slot table (`whole_compact` in composite.wgsl): the pass's stages take slots - /// 0.., the working fields the next three. Not active when its stages are not contiguous. - fn compact(&self, fields: u32) -> [u32; 4] { - let (Some(&first), Some(&last)) = (self.stages.first(), self.stages.last()) else { return [0; 4] }; - if last + 1 - first != self.stages.len() { - return [0, 0, fields, 0]; - } - [first as u32, self.stages.len() as u32, fields, 1] - } - - /// The slot `slot` takes in the pass's working space ([`Self::compact`]). - fn slot(&self, slot: u32, fields: u32) -> u32 { - match self.compact(fields) { - [_, count, fields, 1] if slot >= fields => count + slot - fields, - [base, _, _, 1] => slot - base, - _ => slot, - } - } - - /// Field slots of the pass's working space: its stages, the original and the working fields - /// its kernels use - fn slots(&self, fields: u32) -> u64 { - match self.compact(fields) { - [_, count, _, 1] => u64::from(count) + 1 + u64::from(self.blur_fields), - _ => u64::from(fields) + 3, - } - } - - /// The kernels' working fields: the ones the pass has, else the original (never read then) - fn blur(&self, fields: u32, offset: impl Fn(u32) -> u32) -> [u32; 2] { - let compact = self.compact(fields)[3] == 1; - let field = |index: u32| if !compact || self.blur_fields > index { offset(fields + 1 + index) } else { offset(fields) }; - [field(0), field(1)] - } -} - /// `FilterStage::input_kind`, also the bits of the prepare pass's `field_layout.w`: the input is a /// layer operation whose content times coverage the prepare pass evaluates (Height To Normal's /// own Height, `layer_content`), or an input source read as colour into words 5..8. @@ -698,588 +217,10 @@ const INPUT2: u32 = 16; /// Whole-set stages the band uniform can address (`whole_slots` in composite.wgsl) const MAX_WHOLE_SET_STAGES: usize = 4; -impl FilterStage { - fn reach(&self) -> u32 { - // A level stage runs beside its base stage, which reaches at least as far - if self.level != 0 { - return 0; - } - - self.filter.map_or(0, NeighbourhoodFilter::reach).saturating_add(if self.cell > 1 { self.cell * 2 } else { 0 }) - } - - /// The stack the stage belongs to: its layer operation and whether it filters the mask. - fn stack(&self) -> (u32, bool) { - (self.layer, self.preceding & MASK_STAGE != 0) - } - - fn anchors(&self) -> bool { - self.anchor.is_some() || self.preceding & (MATERIAL_ANCHOR_STAGE | MASK_ANCHOR_STAGE) != 0 - } -} - /// What `FilterPlan::compile` has done so far: the layer operations whose content is planned, the /// capture stages of the stack reads by (end operation, channel), and the effects bound to one. type ContentProgress<'a> = (&'a mut BTreeSet, &'a mut BTreeMap<(u32, Channel), u32>, &'a mut BTreeSet); -#[derive(Debug, Default)] -struct FilterPlan { - stages: Vec, - reach: u32, - anchor_slots: Vec, - /// The operation index of the first input source (`bind_input_sources`), while compiling - input_base: u32, -} - -impl FilterPlan { - fn compile(operations: &mut [Operation], layer_count: u32, inputs: &ProceduralInputs) -> Self { - let reads_stack = operations.iter().skip(layer_count as usize).any(|op| stack_reads(op) != [0; 2]); - if inputs.filters.is_empty() && inputs.generator_stages.is_empty() && inputs.anchors.reads.is_empty() && !reads_stack { - return Self::default(); - } - let mut plan = Self { input_base: (operations.len() - inputs.input_sources.len()) as u32, ..Self::default() }; - let (layers, effects) = operations.split_at_mut(layer_count as usize); - let mut masks = BTreeMap::new(); - plan.anchor_slots.resize(inputs.anchors.reads.len(), 0); - let mut stack_reads = BTreeMap::new(); - let mut read_effects = BTreeSet::new(); - let mut prepared = BTreeSet::new(); - for index in 0..layers.len() { - let run = layer_run(&inputs.anchors.draw_ranges, index); - if layers[index].ids[1] != ANCHOR_PUBLISH_LAYER { - plan.bind_stack_reads(layers, effects, index, run.clone(), false, (&mut stack_reads, &mut read_effects)); - } - let layer = &mut layers[index]; - if layer.ids[1] == ANCHOR_PUBLISH_LAYER { - plan.add_anchor(layer.ids[2], index as u32, MATERIAL_ANCHOR_STAGE, &inputs.anchors, Some((layer.effects[0], layer.effects[1]))); - continue; - } - let [mask, mask_count, _, _] = layer.effects; - // A mask reading its own layer's content: that layer's content stacks first, so the - // mask's prepare pass resumes from prepared content fields. A Base Color that reads - // the layer's material waits for the mask too, which the material's capture reads. - if mask_count > 0 && !masks.contains_key(&mask) && effects.iter().skip(mask as usize).take(mask_count as usize).any(packages::mask_reads_own_layer) - { - let lit = own_material_base(layers, effects, run.clone()); - for own in run.clone() { - if lit == Some(own) { - plan.bind_stack_reads(layers, effects, own, run.clone(), false, (&mut stack_reads, &mut read_effects)); - } else { - plan.add_layer_content(layers, effects, own, run.clone(), inputs, (&mut prepared, &mut stack_reads, &mut read_effects)); - } - } - // A mask comparing its lit Base Color, which has stages: two masks (M1, M2) - let base_stages = |base: usize| { - let [_, _, content, count] = layers[base].effects.map(|word| word as usize); - effects.iter().skip(content).take(count).any(|op| op.ids[1] == NEIGHBOURHOOD_OPCODE) - }; - let reads_base = |base: usize| { - effects - .iter() - .skip(mask as usize) - .take(mask_count as usize) - .any(|op| packages::mask_reads_own_layer(op) && op.effects[0] == base as u32 + 1) - }; - match lit.filter(|&base| base_stages(base) && reads_base(base)) { - Some(base) => { - let progress = (&mut prepared, &mut stack_reads, &mut read_effects); - let mask_base = plan.add_lit_mask_views(layers, effects, (index, base, run.clone()), (mask, mask_count), inputs, progress); - masks.insert(mask, mask_base); - } - None => { - plan.add_this_layer_reads(layers, effects, (mask, mask_count), lit, |_| true); - } - } - } - // The mask stack's first slot plus one (0: no fields), read by `layer_mask` - let mask_base = if mask_count == 0 { - 0 - } else { - *masks.entry(mask).or_insert_with(|| { - let before = plan.stages.len(); - plan.add_stack(effects, (mask, mask_count), (index as u32, None), None, inputs); - if plan.stages.len() != before { before as u32 + 1 } else { 0 } - }) - }; - // The layer's own material is captured after its mask and its other channels' stacks - plan.bind_stack_reads(layers, effects, index, run.clone(), true, (&mut stack_reads, &mut read_effects)); - plan.add_layer_content(layers, effects, index, run, inputs, (&mut prepared, &mut stack_reads, &mut read_effects)); - layers[index].spatial[2] = mask_base; - } - // An anchor can carry a filter's footprint into the next layer. Independent - // channels within a layer share a footprint instead of adding to one another. - if !inputs.anchors.reads.is_empty() { - let mut draw_reach = BTreeMap::<(u32, bool), u32>::new(); - for stage in &plan.stages { - let reach = draw_reach.entry((stage.layer, stage.preceding & MASK_STAGE != 0)).or_default(); - *reach = reach.saturating_add(stage.reach()); - } - let across_layers = inputs.anchors.draw_ranges.iter().fold(0u32, |reach, range| { - let layer = draw_reach.range((range.start, false)..(range.end, false)).map(|(_, reach)| *reach).max().unwrap_or(0); - reach.saturating_add(layer) - }); - plan.reach = plan.reach.max(across_layers); - } - // A stack read's field holds every layer below it at the texel, filters included - if !stack_reads.is_empty() { - let total = plan.stages.iter().fold(0u32, |sum, stage| sum.saturating_add(stage.reach())); - plan.reach = plan.reach.max(total); - } - // The pre-pass resumes no anchor reads, and the band uniform addresses a few outputs - let anchors = plan.stages.iter().any(FilterStage::anchors); - let mut entries = 0; - for stage in plan.stages.iter_mut().filter(|stage| stage.whole) { - // P8: a stage's level stages share its entry, their results right after its own - entries += usize::from(stage.level == 0); - stage.whole = !anchors && entries <= MAX_WHOLE_SET_STAGES; - } - plan - } - - /// The whole-set pre-pass, None when no stage is whole-set (every program before the - /// packages mark one). Each whole-set stage takes the lower stages of its stack along. - fn whole_set(&self) -> Option { - let outputs: Vec = self.stages.iter().enumerate().filter(|(_, stage)| stage.whole).map(|(index, _)| index).collect(); - if outputs.is_empty() { - return None; - } - let mut stacks = BTreeMap::<(u32, bool), (BTreeSet, Vec)>::new(); - for &output in &outputs { - let stack = self.stages[output].stack(); - let lower = (0..=output).filter(|&index| { - self.stages[index].stack() == stack && !self.stages[index].anchors() && self.stages[index].view == 0 && self.stages[index].mask_view == [0; 4] - }); - let (stages, own) = stacks.entry(stack).or_default(); - stages.extend(lower); - own.push(output); - } - let passes: Vec = stacks - .into_values() - .map(|(stages, outputs)| { - let stages: Vec = stages.into_iter().collect(); - let reach = stages.iter().fold(0u32, |sum, &index| sum.saturating_add(self.stages[index].reach())); - let topmost = stages.iter().rposition(|&index| self.stages[index].wrap); - let past_edges = topmost.map_or(0, |top| stages[..=top].iter().fold(0u32, |sum, &index| sum.saturating_add(self.stages[index].reach()))); - let blur_fields = stages - .iter() - .map(|&index| { - let stage = &self.stages[index]; - stage.filter.map_or(0, NeighbourhoodFilter::blur_fields).max(u32::from(stage.cell > 1)) - }) - .max() - .unwrap_or(0); - WholePass { stages, outputs, reach, past_edges, blur_fields } - }) - .collect(); - let mut stages: Vec = passes.iter().flat_map(|pass| pass.stages.iter().copied()).collect(); - stages.sort_unstable(); - let reach = passes.iter().map(|pass| pass.reach).max().unwrap_or(0); - let entries = outputs.iter().enumerate().filter(|&(_, &output)| self.stages[output].level == 0).map(|(index, _)| index).collect(); - Some(WholeSet { stages, outputs, entries, reach, passes }) - } - - /// The halo of a band: every stack's reach, without the stages the whole-set pre-pass - /// evaluates (their reach is the pre-pass's). The plan's reach without a pre-pass. - fn band_reach(&self) -> u32 { - let Some(whole) = self.whole_set() else { return self.reach }; - let mut stacks = BTreeMap::<(u32, bool), u32>::new(); - for (index, stage) in self.stages.iter().enumerate() { - let reach = stacks.entry(stage.stack()).or_default(); - if !whole.stages.contains(&index) { - *reach = reach.saturating_add(stage.reach()); - } - } - stacks.into_values().max().unwrap_or(0) - } - - /// Bind the stack reads of layer operation `index`'s mask and content effects: an effect - /// operation that sets `spatial[3]` to a channel slot plus one asks for the material of that - /// channel at the texel, accumulated over every layer below its layer (`effects[1]` 0) or - /// also over its layer's operations before Base Color (`effects[1]` 1, P6's material reads). - /// A stage captures it (a material-anchor capture without a cut), `spatial[3]` becomes that - /// stage's slot plus one (`stack_at` in WGSL), and `effects[0]` the layer's own operation of - /// that channel plus one (0: none; `this_layer_content` in WGSL). P3: Compare reading This - /// Layer and Layers Below; P6: lighting's material. - /// - /// A package effect (`packages::EXTENDED_EFFECTS`) may ask for a second channel in - /// `spatial[2]` the same way, read with `stack_at_second` (P6: Stylized lighting's Metallic - /// and Roughness, or Glossiness and Specular). It is bound like the first, up to the same - /// operation, and shares a stage with any read of the same channel there; it gets no - /// `this_layer_content`. - /// - /// With `own_material` false it binds the reads of operation `index`'s own effects that stop - /// below the layer (`effects[1]` 0). With it true, at the layer's Base Color operation, it - /// binds every read of the layer's material (each channel operation's copy), so the capture - /// follows the layer's mask and the stacks of its other channels; a layer without a Base - /// Color operation has nothing for them to read, and they read nothing. - #[allow(clippy::too_many_arguments)] - fn bind_stack_reads( - &mut self, - layers: &[Operation], - effects: &mut [Operation], - index: usize, - run: std::ops::Range, - own_material: bool, - (stages, done): (&mut BTreeMap<(u32, Channel), u32>, &mut BTreeSet), - ) { - let base_color = (run.start..run.end).find(|&own| layers[own].ids[0] == channel_slot(Channel::BaseColor)); - let reads: BTreeSet = if own_material { - if base_color.is_some_and(|base| base != index) { - return; - } - // A set: operations sharing a content range list its effects once each - run.clone() - .flat_map(|own| effect_ranges(&layers[own])) - .filter(|&effect| effects.get(effect).is_some_and(|op| stack_reads(op) != [0; 2] && op.effects[1] == 1)) - .collect() - } else { - effect_ranges(&layers[index]).filter(|&effect| effects.get(effect).is_some_and(|op| stack_reads(op) != [0; 2] && op.effects[1] != 1)).collect() - }; - for effect in reads { - if !done.insert(effect) { - continue; - } - let op = &mut effects[effect]; - let until = if op.effects[1] == 1 { base_color } else { Some(run.start) }; - let Some(until) = until else { - op.spatial[3] = 0; - if packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { - op.spatial[2] = 0; - } - continue; - }; - let [first_read, second_read] = stack_reads(op); - let mut bind = |read: u32| { - let slot = read.checked_sub(1)?; - let channel = Channel::ALL.into_iter().find(|&channel| channel_slot(channel) == slot)?; - let stage = *stages.entry((until as u32, channel)).or_insert_with(|| { - self.stages.push(FilterStage { - layer: until as u32, - preceding: MATERIAL_ANCHOR_STAGE, - filter: None, - cell: 1, - anchor: Some((channel, u32::MAX, 0)), - input: 0, - input_kind: 0, - input2: 0, - wrap: false, - whole: false, - view: 0, - mask_view: [0; 4], - level: 0, - }); - self.stages.len() as u32 - }); - Some((slot, stage)) - }; - // An own-material read keeps its channels for the mask's view of the layer, where it - // reads the defaults (`stack_at` while `reading_own_layer`) - if op.effects[1] == 1 && packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { - op.effects[2] = first_read | (second_read << 16); - } - let first_stage = bind(first_read); - let second_stage = bind(second_read); - op.spatial[3] = first_stage.map_or(0, |(_, stage)| stage); - if packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { - op.spatial[2] = second_stage.map_or(0, |(_, stage)| stage); - } - if let Some((slot, _)) = first_stage { - op.effects[0] = run.clone().find(|&own| layers[own].ids[0] == slot).map_or(0, |own| own as u32 + 1); - } - } - } - - /// The layer's own content as its mask reads it (This Layer, `this_layer_content` in WGSL): - /// one stage per read channel operation (`reads` picks which), prepared from its whole - /// content stack before the mask stack, its slot plus one in the reading effect's - /// `effects[2]`. The mask then reads a field instead of evaluating the content inline, which - /// keeps the content's code out of the mask's (the driver inlines every call site). - /// - /// The lit Base Color `lit`: the CPU evaluates the mask with no lit material (`Texel::lit` - /// is None while `node_mask` runs), so its own-material reads give the defaults there - /// (`OWN_VIEW`) past its last field. - #[allow(clippy::too_many_arguments)] - fn add_this_layer_reads( - &mut self, - layers: &[Operation], - effects: &mut [Operation], - (mask, mask_count): (u32, u32), - lit: Option, - reads: impl Fn(u32) -> bool, - ) -> BTreeMap { - let mut views = BTreeMap::::new(); - for effect in mask as usize..(mask + mask_count) as usize { - let Some(op) = effects.get(effect).filter(|op| packages::mask_reads_own_layer(op)) else { continue }; - let Some(own) = op.effects[0].checked_sub(1).filter(|&own| reads(own)) else { continue }; - let slot = *views.entry(own).or_insert_with(|| self.add_this_layer(layers, own, if lit == Some(own as usize) { OWN_VIEW } else { 0 })); - effects[effect].effects[2] = slot; - } - views - } - - /// A This Layer stage of layer operation `own` viewed as `view`: its slot plus one. - fn add_this_layer(&mut self, layers: &[Operation], own: u32, view: u32) -> u32 { - self.stages.push(FilterStage { - layer: own, - preceding: layers[own as usize].effects[3], - filter: None, - cell: 1, - anchor: None, - input: 0, - input_kind: 0, - input2: 0, - wrap: false, - whole: false, - view, - mask_view: [0; 4], - level: 0, - }); - self.stages.len() as u32 - } - - /// A mask that compares its lit Base Color `base` (This Layer) on a layer whose Base Color - /// has stages. The CPU (`fields_of`) builds the content fields first, Base Color last; the - /// material its lighting reads lies under a first mask M1, whose This Layer reads the Base - /// Color with no fields (its stages as identity, `Filter::point`) and no lit material. Then - /// it builds the mask field M2, whose This Layer resumes from the finished Base Color - /// field; the composite uses M2. So: the other This Layer stages, the Base Color's view V1 - /// (`OWN_VIEW | NO_FIELDS`), M1 (a copy of the mask stack), the material's capture, the Base - /// Color's stack, its view V2 (`OWN_VIEW`), and M2, the layer's mask stack. M1's stages and - /// the capture read M1 and V1 in M2's and V2's place (`mask_view`). Returns M2's base plus one. - #[allow(clippy::too_many_arguments)] - fn add_lit_mask_views( - &mut self, - layers: &mut [Operation], - effects: &mut [Operation], - (index, base, run): (usize, usize, std::ops::Range), - (mask, mask_count): (u32, u32), - inputs: &ProceduralInputs, - (prepared, stages, done): ContentProgress, - ) -> u32 { - self.add_this_layer_reads(layers, effects, (mask, mask_count), None, |own| own as usize != base); - let first_view = self.add_this_layer(layers, base as u32, OWN_VIEW | NO_FIELDS); - let first_mask = self.stages.len(); - self.add_stack(effects, (mask, mask_count), (index as u32, None), None, inputs); - let first_end = self.stages.len(); - self.bind_stack_reads(layers, effects, base, run.clone(), true, (stages, done)); - let capture_end = self.stages.len(); - self.add_layer_content(layers, effects, base, run, inputs, (prepared, stages, done)); - let views = self.add_this_layer_reads(layers, effects, (mask, mask_count), Some(base), |own| own as usize == base); - let view = views.get(&(base as u32)).copied(); - let mask_base = self.stages.len(); - let copy: Vec = self.stages[first_mask..first_end].to_vec(); - self.stages.extend(copy); - let mask_view = [mask_base as u32 + 1, first_mask as u32 + 1, first_view, view.unwrap_or(0)]; - for stage in &mut self.stages[first_mask..capture_end] { - stage.mask_view = mask_view; - stage.whole = false; - } - if first_end == first_mask { 0 } else { mask_base as u32 + 1 } - } - - /// The stack reads and the content stack of layer operation `index`, once: its first stage - /// and whether it has any in the layer's `spatial[0..2]`. A Normal operation whose stack has a - /// Height To Normal stage reads its layer's own Height operation (`INPUT_LAYER`), whose stack - /// goes first so the Normal stage's prepare pass reads prepared Height fields. - #[allow(clippy::too_many_arguments)] - fn add_layer_content( - &mut self, - layers: &mut [Operation], - effects: &mut [Operation], - index: usize, - run: std::ops::Range, - inputs: &ProceduralInputs, - (prepared, stages, done): ContentProgress, - ) { - if !prepared.insert(index) { - return; - } - let height = layer_height(layers, effects, index, run.clone(), inputs); - if let Some(height) = height.filter(|&height| height != index) { - self.add_layer_content(layers, effects, height, run.clone(), inputs, (prepared, stages, done)); - } - self.bind_stack_reads(layers, effects, index, run, false, (stages, done)); - let [_, _, content, content_count] = layers[index].effects; - let first = self.stages.len(); - self.add_stack(effects, (content, content_count), (index as u32, height.map(|height| height as u32)), Some(slot_kind(layers[index].ids[0])), inputs); - layers[index].spatial[..2].copy_from_slice(&[first as u32, u32::from(first != self.stages.len())]); - } - - fn add_anchor(&mut self, publication: u32, layer: u32, preceding: u32, inputs: &AnchorInputs, material: Option<(u32, u32)>) { - for (read, &(producer, channel)) in inputs.reads.iter().enumerate().filter(|(_, (producer, _))| *producer == publication) { - debug_assert_eq!(producer, publication); - self.anchor_slots[read] = self.stages.len() as u32 + 1; - self.stages.push(FilterStage { - layer, - preceding, - filter: None, - cell: 1, - anchor: material.map(|(first, cut)| (channel, first, cut)), - input: 0, - input_kind: 0, - input2: 0, - wrap: false, - whole: false, - view: 0, - mask_view: [0; 4], - level: 0, - }); - } - } - - fn bind_anchors(&self, operations: &mut [Operation]) { - for operation in operations.iter_mut().filter(|op| op.ids[1] == ANCHOR_SOURCE && op.ids[2] != 0) { - operation.ids[2] = self.anchor_slots[operation.ids[2] as usize - 1]; - } - } - - #[allow(clippy::too_many_arguments)] - /// The stages of one effect stack: a mask's when `channel` is None, else the content of a - /// channel of that kind (the stage context the packages' stages read). - /// `height` is the layer's own Height operation a Height To Normal stage reads (`layer_height`). - fn add_stack( - &mut self, - effects: &mut [Operation], - (start, count): (u32, u32), - (layer, height): (u32, Option), - channel: Option, - inputs: &ProceduralInputs, - ) { - let mask = channel.is_none(); - let first = self.stages.len(); - let mut reach: u32 = 0; - for (preceding, effect) in effects.iter_mut().skip(start as usize).take(count as usize).enumerate() { - if mask && effect.ids[1] == ANCHOR_PUBLISH_MASK { - self.add_anchor(effect.ids[2], layer, preceding as u32 | MASK_STAGE | MASK_ANCHOR_STAGE, &inputs.anchors, None); - continue; - } - if (FIRST_GENERATOR..FIRST_EXTENDED_PATTERN).contains(&effect.ids[1]) && effect.spatial[1] != 0 { - let generator = effect.spatial[1] as usize - 1; - let (filter, cell) = inputs.generator_stages[generator]; - // Relative to the stack's first stage, as a mask stack's fields are read - // (`layer_mask` adds the layer's mask base, `spatial[2]`) - effect.spatial[1] = (self.stages.len() - first) as u32 + 1; - reach = reach.saturating_add(filter.map_or(0, NeighbourhoodFilter::reach)); - if cell > 1 { - reach = reach.saturating_add(cell * 2); - } - // P8: the generator at each further UV tile scale follows its base stage - let levels = inputs.generator_levels.get(generator).map_or(&[][..], Vec::as_slice); - for (level, &(filter, cell)) in std::iter::once(&(filter, cell)).chain(levels).enumerate() { - self.stages.push(FilterStage { - layer, - preceding: preceding as u32 | MASK_STAGE | GENERATOR_STAGE, - filter, - cell, - anchor: None, - input: 0, - input_kind: 0, - input2: 0, - wrap: false, - whole: false, - view: 0, - mask_view: [0; 4], - level: level as u32, - }); - } - continue; - } - if effect.ids[1] != NEIGHBOURHOOD_OPCODE { - continue; - } - let (effect_filter, opacity) = &inputs.filters[effect.ids[2] as usize]; - let Some(filter) = NeighbourhoodFilter::new(effect_filter, inputs.resolution, inputs.longest_side, *opacity, channel) else { continue }; - // P8: the same filter at each further UV tile scale, each a stage after this one - let level_filters = udim::level_filters(effect_filter, filter, (*opacity, channel), inputs); - let slot = self.stages.len(); - let whole = filter.whole_set(inputs.resolution); - effect.spatial[0] = (slot - first) as u32; - let preceding = preceding as u32 | if mask { MASK_STAGE } else { 0 }; - // An image input the effect registered (`ProceduralInputs::register_input`), read as - // colour when registered so; Height To Normal on a Normal operation reads the layer's - // own Height in its place - let (input, input_kind) = match height.filter(|_| matches!(inputs.filters[effect.ids[2] as usize].0, Filter::HeightToNormal(_))) { - Some(height) => (height + 1, INPUT_LAYER), - None => { - let input = effect.effects[3]; - let color = input != 0 && inputs.color_inputs.contains(&input.saturating_sub(self.input_base)); - (input, if color { INPUT_COLOR } else { 0 }) - } - }; - // The pre-pass carries the lower stages of the stage's own stack only, not the Height's - let whole = whole && input_kind != INPUT_LAYER; - // P4: Blur and Bevel with Wrap read the set periodically past its edges - let wrap = gpu_neighbourhood::box_family::wraps(filter); - let input2 = effect.effects[2]; - for (level, filter) in std::iter::once(filter).chain(level_filters).map(Some).enumerate() { - self.stages.push(FilterStage { - layer, - preceding, - filter, - cell: 1, - anchor: None, - input, - input_kind, - input2, - wrap, - whole, - view: 0, - mask_view: [0; 4], - level: level as u32, - }); - } - reach = reach.saturating_add(filter.reach()); - } - self.reach = self.reach.max(reach); - } - - /// The update `region` grown by the stages' reach on a set of `size`; None (a full update) - /// when a wrapping stage's reach crosses the set's edge, as an edit there changes the - /// opposite edge too - fn expand(&self, region: Option, (width, height): (u32, u32)) -> Option { - let region = region?; - let crosses = |min: u32, max: u32, side: u32| min < self.reach || max.saturating_add(self.reach) > side; - if self.wraps() && (crosses(region.min[0], region.max[0], width) || crosses(region.min[1], region.max[1], height)) { - return None; - } - Some(region.expanded(self.reach)) - } - - fn words(&self, area: u64) -> u64 { - if self.stages.is_empty() { 0 } else { (self.stages.len() as u64 + 3) * u64::from(self.field_words()) * area } - } - - /// Whether a stage wraps: the fields then extend by the halo past the set's edges, with an - /// origin below zero, and the prepare pass fills the wrapping stages periodically there. - fn wraps(&self) -> bool { - self.stages.iter().any(|stage| stage.wrap) - } - - /// Words per field texel: four premultiplied components and the UV coverage, plus a sixth - /// word when a stage carries an input ([`FilterStage::input`]), or three when one reads its - /// input as colour. One stride for every field of the program; the shaders read it from the - /// uniform, never from a literal. - fn field_words(&self) -> u32 { - if self.stages.iter().any(|stage| stage.input2 != 0) { - FIELD_WORDS + 6 - } else if self.stages.iter().any(|stage| stage.input_kind == INPUT_COLOR) { - FIELD_WORDS + 3 - } else if self.stages.iter().any(|stage| stage.input != 0) { - FIELD_WORDS + 1 - } else { - FIELD_WORDS - } - } - - /// The kernels' `NeighbourhoodRegion::input` bits for `stage`: the fields carry input words - /// (1), the stage has an input of its own (2), the fields carry colour words 5..8 (4), the - /// stage has a second input in words 8..11 (8). - fn input_bits(&self, stage: &FilterStage) -> u32 { - let words = self.field_words(); - u32::from(words > FIELD_WORDS) | (u32::from(stage.input != 0) << 1) | (u32::from(words >= FIELD_WORDS + 3) << 2) | (u32::from(stage.input2 != 0) << 3) - } -} - /// The layer's own Height operation (in `run`, the draw of layer operation `index`) when /// `index` is a Normal operation whose content has a Height To Normal stage: the CPU's stage /// reads the layer's Height content times its coverage as its gray (`plan_in(.., Height)`). @@ -1288,6 +229,7 @@ fn layer_height(layers: &[Operation], effects: &[Operation], index: usize, run: if layer.ids[0] != channel_slot(Channel::Normal) { return None; } + let [_, _, content, count] = layer.effects.map(|word| word as usize); let reads = effects.iter().skip(content).take(count).any(|op| { op.ids[1] == NEIGHBOURHOOD_OPCODE && inputs.filters.get(op.ids[2] as usize).is_some_and(|(filter, _)| matches!(filter, Filter::HeightToNormal(_))) @@ -1295,6 +237,7 @@ fn layer_height(layers: &[Operation], effects: &[Operation], index: usize, run: if !reads { return None; } + run.into_iter().find(|&own| layers[own].ids[0] == channel_slot(Channel::Height)) } @@ -1305,6 +248,7 @@ fn stack_reads(op: &Operation) -> [u32; 2] { if (FIRST_GENERATOR..FIRST_EXTENDED_PATTERN).contains(&op.ids[1]) { return [0; 2]; } + [op.spatial[3], if packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { op.spatial[2] } else { 0 }] } @@ -1337,11 +281,13 @@ fn bind_input_sources(operations: &mut Vec, layer_count: u32, sources if sources.is_empty() { return; } + let offset = operations.len() as u32; for op in operations.iter_mut().skip(layer_count as usize).filter(|op| !(FIRST_GENERATOR..FIRST_EXTENDED_PATTERN).contains(&op.ids[1])) { if op.effects[3] != 0 { op.effects[3] += offset; } + // A neighbourhood stage's second input (`FilterStage::input2`) if op.ids[1] == NEIGHBOURHOOD_OPCODE && op.effects[2] != 0 { op.effects[2] += offset; @@ -1362,161 +308,11 @@ fn bind_generator_sources(operations: &mut Vec, sources: &[Operation] operations.extend_from_slice(sources); } -/// Inclusive origin and exclusive end of a material update, in document texels. -#[derive(Clone, Copy, Debug)] -pub struct CompositeRegion { - pub(crate) min: [u32; 2], - pub(crate) max: [u32; 2], -} - -impl CompositeRegion { - pub fn from_tiles(tiles: impl IntoIterator) -> Option { - let mut tiles = tiles.into_iter(); - let (x, y) = tiles.next()?; - let mut region = Self { min: [x * TILE, y * TILE], max: [(x + 1) * TILE, (y + 1) * TILE] }; - for (x, y) in tiles { - region.min = [region.min[0].min(x * TILE), region.min[1].min(y * TILE)]; - region.max = [region.max[0].max((x + 1) * TILE), region.max[1].max((y + 1) * TILE)]; - } - Some(region) - } - - fn union(self, other: Self) -> Self { - Self { min: [self.min[0].min(other.min[0]), self.min[1].min(other.min[1])], max: [self.max[0].max(other.max[0]), self.max[1].max(other.max[1])] } - } - - pub fn expanded(self, texels: u32) -> Self { - Self { min: self.min.map(|x| x.saturating_sub(texels)), max: self.max.map(|x| x.saturating_add(texels)) } - } - - pub fn bounds(self) -> ([u32; 2], [u32; 2]) { - (self.min, self.max) - } - - pub(crate) fn viewport(self, shift: u32, size: (u32, u32)) -> Self { - Self { min: [self.min[0] >> shift, self.min[1] >> shift], max: [(self.max[0] >> shift).min(size.0), (self.max[1] >> shift).min(size.1)] } - } -} - -/// The active stroke's GPU alpha, sampled in the corresponding paint layer or mask effect. -pub struct LiveBrush { - pub target: LiveBrushTarget, - pub opacity: f32, - /// The Eraser: the stroke scales the target's paint and coverage down. A layer target then - /// lists the channels the commit erases, with unused values. - pub erase: bool, - pub alpha: wgpu::TextureView, - /// Supplies opacity modulation and Base Color for a projection stroke. - pub stencil: Option, -} - -pub enum LiveBrushTarget { - Layer { - layer: LayerId, - values: BTreeMap, - }, - /// `image`: the image resource whose gray the stroke paints per texel instead of `value`. - Mask { - effect: LayerId, - value: f32, - image: Option, - }, -} - -impl LiveBrush { - fn validate(&self, size: (u32, u32)) -> Result<(), &'static str> { - let alpha = self.alpha.texture(); - if (alpha.width(), alpha.height()) != size || alpha.format() != wgpu::TextureFormat::R16Uint { - return Err("The live brush alpha does not match the texture set."); - } - let valid = match &self.target { - LiveBrushTarget::Layer { values, .. } => values.values().flatten().all(|v| v.is_finite()), - LiveBrushTarget::Mask { value, .. } => value.is_finite(), - }; - if !valid || !self.opacity.is_finite() { - return Err("The live brush has invalid paint values."); - } - Ok(()) - } - - /// The live paint of `channel` on paint layer or content paint effect `id`: its value, the - /// stroke opacity and whether it erases. - fn value_for_layer(&self, id: LayerId, channel: Channel) -> Option<([f32; 3], f32, bool)> { - let LiveBrushTarget::Layer { layer, values } = &self.target else { return None }; - if *layer != id { - return None; - } - values.get(&channel).map(|&value| (value, self.opacity.clamp(0.0, 1.0), self.erase)) - } -} - -#[derive(Debug)] -pub struct CompositeProgram { - operations: Vec, - layer_count: u32, - filters: FilterPlan, - groups: GroupPlan, - geometry: GeometryMasks, - paint: Vec, - ramp_words: Vec, - curvature_sizes: [bool; CurvatureDetail::BLURRED_SIZES], - tile_patterns: TilePatterns, - material_images: MaterialImages, - brush_alpha: Option, - brush_stencil: Option, - pub(crate) region: Option, - coverage: Option<(Arc, u32)>, - surface: Option<(Arc, Arc)>, - needs_surface: bool, - baked: Option, - id_bake: Option, - display_outputs: u32, - glossiness: bool, - mask_preview: bool, - mask_layer: u32, - /// The first operation of each draw of a layer with a mask, with the draw's placement - mask_layers: Vec<(LayerId, ContentsOffset, u32)>, - /// Side-table words to fill with image record offsets at upload (`ProceduralInputs::pack_image`) - image_words: Vec<(u32, u32)>, - /// The environment's diffuse light the program reads (`ProceduralInputs::reserve_environment`) - environment: Option, - /// Upload the second bake row block (`ProceduralInputs::read_bake_rows`) - bake_rows: bool, - /// P8: the side-table record of a UV tile atlas (`udim::bind`), 0 for a classic set - udim: u32, - /// P8: the UV tile atlas's blocks, which say where a level stage has texels to filter - udim_layout: Option, -} - -/// A program's late-bound environment words: where they start in the side table, the display -/// settings of the compiled project (environment and rotation) and, once the images are known, -/// the words. -#[derive(Debug)] -struct LateEnvironment { - word: u32, - display: DisplaySettings, - words: Option<[u32; ENVIRONMENT_WORDS]>, -} - -impl LateEnvironment { - fn new(word: Option, display: &DisplaySettings) -> Option { - word.map(|word| Self { word, display: display.clone(), words: None }) - } - - fn set(&mut self, environment: &EnvironmentSh) { - let mut words = [0; ENVIRONMENT_WORDS]; - for (word, value) in words.iter_mut().zip(environment.coefficients().iter().flatten().chain([environment.rotation()].iter())) { - *word = value.to_bits(); - } - self.words = Some(words); - } -} - fn display_bit(kind: DisplayKind) -> u32 { 1 << kind as u32 } -// Destination slots match the channel groups consumed by composite.wgsl. +// Destination slots match the channel groups consumed by composite.wgsl fn channel_slot(channel: Channel) -> u32 { use Channel::*; match channel { @@ -1541,6 +337,7 @@ fn channel_slot(channel: Channel) -> u32 { AnisotropyAngle => 18, Transmission => 19, Glossiness => 20, + _ => channel.index() as u32, } } @@ -1562,582 +359,6 @@ fn slot_kind(slot: u32) -> ChannelKind { Channel::ALL.into_iter().find(|&channel| channel_slot(channel) == slot).map_or(ChannelKind::Scalar, Channel::kind) } -impl CompositeProgram { - pub fn is_neutral(&self) -> bool { - !self.mask_preview - && !self.glossiness - && self.layer_count == 0 - && self.baked.as_ref().is_none_or(|baked| baked.maps[0].is_none() && baked.maps[1].is_none()) - } - - pub fn is_mask_preview(&self) -> bool { - self.mask_preview - } - - /// Work per output texel that sizes bands and submissions: Tile Generator placements per - /// plane and sample, and what P1 declares for its fills (`fill_projection::work_per_texel`: - /// symmetry copies times sampling cost). - fn tile_work_per_pixel(&self) -> Result { - self.operations.iter().try_fold(0u64, |work, op| { - let mut own = 0; - if op.ids[1] == TILE_GENERATOR_OPCODE { - let tile_work = self.tile_patterns.work_per_sample(op.high[3] as usize).ok_or("A Tile Generator operation has no settings.")?; - let planes = if op.procedural[3] == 1 { 3 } else { 1 }; - let samples = if op.procedural[0] == 0 { 1 } else { 4 }; - own = tile_work.saturating_mul(planes * samples); - } - Ok(work.saturating_add(fill_projection::work_per_texel(op, own))) - }) - } - - pub(crate) fn writes_display(&self, kind: DisplayKind) -> bool { - self.display_outputs & display_bit(kind) != 0 - } - - /// Let the shader sample the nearest covered UV texel for island padding. - pub fn set_coverage(&mut self, coverage: Arc, radius: u32) { - self.coverage = Some((coverage, if self.mask_preview { 0 } else { radius.min(15) })); - } - - /// Resolve named images used by authored fills, decals and Tile Generators, and the - /// environment's diffuse light (an imported environment is an image). - pub fn set_tile_images(&mut self, images: &ImageStore) { - self.tile_patterns.set_images(images); - self.material_images.set_images(images); - if let Some(environment) = &mut self.environment { - environment.set(&EnvironmentSh::of(&environment.display, images)); - } - } - - /// The environment and rotation (degrees) the program lights with, from the compiled - /// project's display settings; None when nothing reads the environment. A viewport compiles - /// again when either changes (or the imported environment image does). - pub fn environment(&self) -> Option<(&str, f32)> { - self.environment.as_ref().map(|environment| (environment.display.environment.as_str(), environment.display.env_rotation)) - } - - /// Tests: the stage of the layer's Height operation and the stage reading it as its input. - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) fn input_stages(&self) -> (usize, usize) { - let stages = &self.filters.stages; - let height = stages.iter().position(|stage| self.operations[stage.layer as usize].ids[0] == channel_slot(Channel::Height)); - let reader = stages.iter().position(|stage| stage.input_kind == INPUT_LAYER); - (height.unwrap_or(usize::MAX), reader.unwrap_or(usize::MAX)) - } - - /// Tests: each whole-set pass's stage count and reach past the set's edges. - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) fn whole_set_passes(&self) -> Vec<(usize, u32)> { - self.filters.whole_set().map_or_else(Vec::new, |whole| whole.passes.iter().map(|pass| (pass.stages.len(), pass.past_edges)).collect()) - } - - /// Tests: the last stage's input and input kind. - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) fn input_of_last_stage(&self) -> (u32, u32) { - self.filters.stages.last().map_or((u32::MAX, u32::MAX), |stage| (stage.input, stage.input_kind)) - } - - /// Replace the environment's diffuse light (tests: a stub reader instead of `EnvironmentSh::of`). - #[cfg(test)] - fn set_environment(&mut self, environment: &EnvironmentSh) { - if let Some(late) = &mut self.environment { - late.set(environment); - } - } - - /// Mesh-space projections and generators share the viewport's surface and bake inputs. - pub fn set_surface_inputs(&mut self, mesh: &Arc, gbuf: &Arc, baked: Option<&BakedMaps>) -> Result<(), &'static str> { - // P1's projector depth grids, before the atlas reads them - self.material_images.set_surface(mesh); - if self.needs_surface || !self.geometry.parts.is_empty() { - self.surface = Some((mesh.clone(), gbuf.clone())); - } - self.geometry.resolve(mesh); - // Texels no triangle covers keep the channels' defaults, as the CPU leaves them - let partly_covered = gbuf.tri.contains(&NO_TRI); - if self.mask_preview || ((partly_covered || !self.filters.stages.is_empty() || !self.geometry.parts.is_empty()) && self.coverage.is_none()) { - self.set_coverage(gbuf.clone(), 0); - } - self.baked = baked.map(|baked| BakedInputs::new(baked, self.bake_rows)).transpose()?.flatten(); - self.id_bake = baked.filter(|_| self.operations.iter().any(|op| op.ids[1] == COLOR_SELECTION_OPCODE && op.procedural[2] != 0)).and_then(IdBake::new); - if !self.mask_preview && self.baked.as_ref().is_some_and(|baked| baked.maps[1].is_some()) { - self.display_outputs |= display_bit(DisplayKind::Normal); - } - Ok(()) - } - - /// A flat stack of sparse paint, solid and UV procedural fills, masks and point effects. - /// Disabled layers need no work. Stacks outside this evaluator's domain use the CPU. - pub fn compile(project: &Project, pixels: &PixelStore, ts: usize) -> Option { - Self::compile_region(project, pixels, ts, None) - } - - pub fn compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option) -> Option { - Self::try_compile_region(project, pixels, ts, region).ok() - } - - /// Also provide the reason the viewport must select its CPU compositor. - pub fn try_compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option) -> Result { - Self::try_compile_with_brush(project, pixels, ts, region, None) - } - - pub fn try_compile_with_brush( - project: &Project, - pixels: &PixelStore, - ts: usize, - region: Option, - brush: Option, - ) -> Result { - let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; - packages::check_set(set, false)?; - if let Some(brush) = &brush { - brush.validate(set.size())?; - } - let mut operations: Vec = Vec::new(); - let mut paint = PaintInputs::default(); - let mut tile_patterns = TilePatterns::default(); - let mut effects = Vec::new(); - let mut procedural = ProceduralInputs::new(set.resolution); - // P8: a UV tile atlas's block, its tile scales and the set's own resolution - let layout = udim::UdimLayout::of(set); - udim::prepare(layout.as_ref(), &mut procedural); - let mut geometry = GeometryMasks::default(); - let mut groups = GroupPlan::default(); - let mut group_depth = 0; - let mut mask_layers = Vec::new(); - let mut non_default = [false; Channel::ALL.len()]; - let stencil_pigment = brush.as_ref().is_some_and(|brush| brush.stencil.is_some()); - // Each draw carries the Scale and Rotation of the folders holding it (an instanced folder's too) - let mut layers: Vec<_> = set.stack.iter().rev().map(|&id| (StackWork::Layer(id, 0, 0), ContentsOffset::NONE)).collect(); - while let Some((work, around)) = layers.pop() { - let (id, depth, inherited_geometry) = match work { - StackWork::Layer(id, depth, geometry) => (id, depth, geometry), - StackWork::EndGroup(start) => { - let end = operations.len() as u32 + 1; - let weights = operations[start].ids[2]; - operations[start].ids[3] = end; - operations.push(Operation { ids: [0, END_GROUP, weights, 0], ..Operation::zeroed() }); - group_depth -= 1; - continue; - } - }; - let own = project.layers.get(&id).ok_or("A layer is missing from the material.")?; - if !own.visible { - continue; - } - let Some(layer) = project.content_layer(id) else { continue }; - let geometry_mask = geometry.register(inherited_geometry, own.geometry_mask.as_deref()); - let mask = project.layers.get(&project.mask_owner(id)).and_then(|owner| owner.mask.as_ref()).filter(|m| m.enabled); - if let LayerKind::Group { children, contents, .. } = &layer.kind { - if depth > texturecraft_core::project::MAX_DEPTH { - continue; - } - // A folder's Scale and Rotation (an instanced folder's too) re-place every fill inside it - let children_around = around.then(*contents); - // A full-weight group sees the incoming stack and returns it exactly - // as its children changed it. A geometry restriction must stay on the - // group boundary when children publish anchors outside that restriction. - if mask.is_none() - && set.channels.iter().all(|&(channel, _)| { - layer.blend(channel).is_some_and(|blend| blend.mode != BlendMode::Disable && blend.opacity.is_finite() && blend.opacity >= 1.0) - }) - && (geometry_mask == 0 || !groups::children_publish_anchors(project, children, depth + 1)) - { - layers.extend(children.iter().rev().map(|&child| (StackWork::Layer(child, depth + 1, geometry_mask), children_around))); - continue; - } - let mut weights = [0.0f32; Channel::ALL.len()]; - for &(channel, _) in &set.channels { - if let Some(blend) = layer.blend(channel).filter(|blend| blend.mode != BlendMode::Disable) { - if !blend.opacity.is_finite() { - return Err("A group has an invalid opacity."); - } - weights[channel_slot(channel) as usize] = blend.opacity.clamp(0.0, 1.0); - } - } - if weights.iter().all(|&opacity| opacity == 0.0) - && mask.is_none_or(|mask| !mask.effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor))) - { - continue; - } - let begin = effects.len() as u32; - let background = compile_mask(mask, around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut effects)?; - let count = effects.len() as u32 - begin; - - // A folder's This Layer is the stack below it, as the CPU reads it - effects[begin as usize..].iter_mut().for_each(stack::read_folder_layers); - - let height = layer.height_mask; - let height_params = if height.enabled && count != 0 { - if !height.contrast.is_finite() || !height.offset.is_finite() { - return Err("A group's height mask has invalid parameters."); - } - [height.contrast.to_bits(), height.offset.to_bits()] - } else { - [0; 2] - }; - let weight_offset = u32::try_from(procedural.ramp_words.len()) - .ok() - .and_then(|len| LOOKUP_WORDS.checked_add(len)) - .ok_or("The GPU group settings are too large.")?; - procedural.ramp_words.extend(weights.map(f32::to_bits)); - let open = operations.len(); - let mut op = Operation { - ids: [0, BEGIN_GROUP, weight_offset, 0], - effects: [begin, count, 0, 0], - constraints: [geometry_mask, 0, height_params[0], height_params[1]], - ..Operation::zeroed() - }; - op.balance[1] = background; - operations.push(op); - mask_layers.push((id, around, open as u32)); - procedural.anchors.draw_ranges.push(open as u32..open as u32 + 1); - group_depth += 1; - groups.depth = groups.depth.max(group_depth); - layers.push((StackWork::EndGroup(open), ContentsOffset::NONE)); - // The group tests its geometry before entering. Children still apply their own masks. - layers.extend(children.iter().rev().map(|&child| (StackWork::Layer(child, depth + 1, 0), children_around))); - continue; - } - let mask_start = effects.len() as u32; - let mask_background = compile_mask(mask, around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut effects)?; - let shared_content = effects.len() as u32; - let mask_count = shared_content - mask_start; - let has_content_anchors = layer.content_effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor)); - if mask_background == 0.0 && mask_count == 0 && !has_content_anchors { - continue; - } - let mut content_anchors = Vec::new(); - let mut visible_cut = 0u32; - let per_channel = layer.content_effects.iter().any(|effect| effect.visible && (content_depends_on_channel(effect) || blends_per_channel(effect))); - let mut templates = Vec::new(); - for effect in layer.content_effects.iter().filter(|e| e.visible) { - if matches!(effect.kind, EffectKind::Anchor) { - content_anchors.push((effect.id, visible_cut)); - continue; - } - visible_cut += 1; - let first_input = procedural.input_sources.len(); - - // A filter laid on each channel apart is lowered once per channel of the set - let channel_ops = if blends_per_channel(effect) && !content_depends_on_channel(effect) { - let mut ops = BTreeMap::new(); - for &(channel, _) in &set.channels { - let op = channel_filter(effect, channel, &mut procedural).ok_or("A layer effect uses CPU compositing.")?; - ops.insert(channel, (procedural.preceding_stage.take(), op)); - } - Some(ops) - } else { - None - }; - let op = if content_depends_on_channel(effect) || channel_ops.is_some() { - None - } else { - Some(content_filter(effect, &mut procedural).ok_or("A layer effect uses CPU compositing.")?) - }; - stack::bind_input_tiles(effect, &mut procedural.input_sources[first_input..], &mut tile_patterns); - - // A lowering with a stage before its operation takes two operations, on every channel alike - let mut stage = procedural.preceding_stage.take(); - if channel_ops.as_ref().is_some_and(|ops| ops.values().any(|(channel_stage, _)| channel_stage.is_some())) { - stage = Some(Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() }); - } - visible_cut += u32::from(stage.is_some()); - if per_channel { - templates.push((effect, stage, op, channel_ops)); - } else if let Some(op) = op { - effects.extend(stage); - effects.push(op); - } - } - let fill = match &layer.kind { - LayerKind::Fill(fill) => Some(fill), - LayerKind::Paint => None, - _ => return Err("A group or another layer type uses CPU compositing."), - }; - let decal = fill.map(|fill| register_decal(fill, &mut procedural.materials)).transpose()?.flatten(); - - let height = layer.height_mask; - let height_params = if height.enabled && mask_count != 0 { - if !height.contrast.is_finite() || !height.offset.is_finite() { - return Err("A layer's height mask has invalid parameters."); - } - [height.contrast.to_bits(), height.offset.to_bits()] - } else { - [0; 2] - }; - let first_op = operations.len(); - let mut height_op = 0; - for &(channel, _) in &set.channels { - if mask_background == 0.0 && mask_count == 0 { - break; - } - let Some(blend) = layer.blend(channel) else { continue }; - if blend.mode == BlendMode::Disable || blend.opacity <= 0.0 { - continue; - } - if !blend.opacity.is_finite() { - return Err("A layer has an invalid opacity."); - } - let (painted, brush_value) = if fill.is_none() { - (sparse_channel(pixels, layer.id, channel)?, brush.as_ref().and_then(|brush| brush.value_for_layer(layer.id, channel))) - } else { - (None, None) - }; - let content_start = if per_channel { effects.len() as u32 } else { shared_content }; - let mut adds_coverage = false; - for (effect, shared_stage, shared_template, channel_ops) in &templates { - // A channel without a stage of its own keeps the placeholder, so an anchor's content cut holds on every channel - let (stage, template) = match channel_ops.as_ref().and_then(|ops| ops.get(&channel)) { - Some((channel_stage, op)) => (shared_stage.map(|placeholder| channel_stage.unwrap_or(placeholder)), Some(*op)), - None => (*shared_stage, *shared_template), - }; - effects.extend(stage); - let op = if let Some(op) = template { - op - } else if let Some(op) = - content_deposit(effect, (channel, around), pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns))? - { - adds_coverage = true; - op - } else { - Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() } - }; - effects.push(op); - } - if fill.is_none() && painted.is_none() && brush_value.is_none() && !adds_coverage { - if per_channel { - effects.truncate(content_start as usize); - } - continue; - } - let content_count = effects.len() as u32 - content_start; - let default = channel.default_value(); - let source = fill.and_then(|fill| fill.sources.get(&channel)); - let slot = channel_slot(channel); - // Adding a channel to the set also adds it to the earlier layers. Skip - // their neutral values until the accumulator can contain something else. - // After a real contribution, neutral fills can still reset the channel. - if !non_default[slot as usize] - && painted.is_none() - && brush_value.is_none() - && content_count == 0 - && matches!(blend.mode, BlendMode::Normal | BlendMode::Passthrough | BlendMode::Replace) - && source.is_none_or(|source| matches!(source, Source::Uniform(value) if *value == default)) - { - continue; - } - non_default[slot as usize] = true; - let mut op = if fill.is_none() { - content_paint(layer.id, channel, painted, brush_value, stencil_pigment, &mut paint) - } else { - fill.and_then(|fill| source_operation(source, &placed(around, &fill.projection), fill.sampling, default, channel.kind(), &mut procedural)) - .ok_or("A fill source or projection uses CPU compositing.")? - }; - if let Some(decal) = decal { - op.uv[0] = decal as f32; - } - bind_tile_source(&mut op, source, &mut tile_patterns); - op.ids[0] = slot; - op.low[3] = blend.opacity.min(1.0); - op.balance[1] = mask_background; - op.balance[2] = blend_code(blend.mode) as f32; - op.effects = [mask_start, mask_count, content_start, content_count]; - op.spatial[3] = u32::from(adds_coverage); - if height_params[0] != 0 && channel == Channel::Height { - height_op = operations.len() as u32 + 1; - } - operations.push(op); - } - - packages::order_layer_operations(&mut operations[first_op..]); - if height_op != 0 { - // The reorder can move the Height operation that the height mask reads - let height = operations[first_op..].iter().position(|op| op.ids[0] == channel_slot(Channel::Height)); - height_op = height.map_or(0, |index| (first_op + index) as u32 + 1); - } - for op in &mut operations[first_op..] { - op.constraints = [geometry_mask, height_op, height_params[0], height_params[1]]; - } - if first_op != operations.len() { - mask_layers.push((id, around, first_op as u32)); - } else if mask.as_ref().is_some_and(|mask| { - mask.effects.iter().any(|effect| effect.visible && (!effect.kind.anchors_read().is_empty() || matches!(effect.kind, EffectKind::Anchor))) - }) { - // A layer with no display channels can still publish anchors in its mask. - mask_layers.push((id, around, first_op as u32)); - operations.push(Operation { - ids: [u32::MAX, ANCHOR_PUBLISH_MASK, 0, 0], - effects: [mask_start, mask_count, 0, 0], - balance: [0.0, mask_background, 0.0, 0.0], - constraints: [geometry_mask, 0, 0, 0], - ..Operation::zeroed() - }); - } - procedural.anchors.draw_ranges.push(first_op as u32..operations.len() as u32); - if !content_anchors.is_empty() { - let has_channels = - set.channels.iter().any(|&(channel, _)| layer.blend(channel).is_some_and(|blend| blend.mode != BlendMode::Disable && blend.opacity > 0.0)); - if !has_channels && mask.is_none_or(|mask| !mask.effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor))) { - continue; - } - } - for (anchor, cut) in content_anchors { - let publication = procedural.anchors.publish(anchor, false); - operations.push(Operation { - ids: [u32::MAX, ANCHOR_PUBLISH_LAYER, publication, 0], - effects: [first_op as u32, cut, 0, 0], - ..Operation::zeroed() - }); - } - } - let mut display_outputs = display_bit(DisplayKind::BaseColor) | display_bit(DisplayKind::Orm); - for channel in Channel::ALL { - let slot = channel_slot(channel); - if operations.iter().any(|op| { - !groups::is_group(op) - && op.ids[0] == slot - && (op.ids[1] != 0 || op.low[..3] != channel.default_value() || op.effects[3] != 0 || op.balance[2] != 0.0) - }) { - display_outputs |= display_bit(DisplayKind::of_channel(channel)); - } - } - groups.finish(&operations); - let layer_count = operations.len() as u32; - if !operations.iter().any(|op| op.constraints[0] != 0) { - geometry.parts.clear(); - } - operations.extend(effects); - bind_input_sources(&mut operations, layer_count, &procedural.input_sources); - let mut filters = FilterPlan::compile(&mut operations, layer_count, &procedural); - bind_generator_sources(&mut operations, &procedural.generator_sources); - filters.bind_anchors(&mut operations); - let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; - // A UV tile smaller than its block shades its height slopes at its own scale (Extra's alpha) - if layout.as_ref().is_some_and(|layout| layout.scaled) { - display_outputs |= display_bit(DisplayKind::Extra); - } - let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); - let (brush_alpha, brush_stencil) = brush.map_or((None, None), |brush| (Some(brush.alpha), brush.stencil)); - let needs_surface = brush_stencil.is_some() || needs_surface(&operations); - Ok(Self { - operations, - layer_count, - filters, - groups, - geometry, - paint: paint.images, - ramp_words: procedural.ramp_words, - curvature_sizes: procedural.curvature_sizes, - tile_patterns, - material_images: procedural.materials, - brush_alpha, - brush_stencil, - region, - coverage: None, - surface: None, - needs_surface, - baked: None, - id_bake: None, - display_outputs, - glossiness: set.has_channel(Channel::Glossiness), - mask_preview: false, - mask_layer: 0, - mask_layers, - image_words: procedural.image_words, - environment: LateEnvironment::new(procedural.environment_word, &project.display), - bake_rows: procedural.bake_rows, - udim, - udim_layout: layout, - }) - } - - /// Compose one layer's enabled mask into the standalone grayscale view. - pub fn try_compile_mask_preview( - project: &Project, - pixels: &PixelStore, - ts: usize, - owner: LayerId, - region: Option, - brush: Option, - ) -> Result { - let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; - packages::check_set(set, true)?; - // The folders around the requested layer (an instance's own, as the CPU places it) re-place its mask fills - let requested = owner; - let owner = project.mask_owner(owner); - let around = project.contents_around(requested); - let mask = project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).filter(|mask| mask.enabled); - let mask = mask.ok_or("The layer has no enabled mask.")?; - - // A mask reading anchors or the layers needs the stack below it: the material program - let reads_below = |effect: &Effect| { - !effect.kind.anchors_read().is_empty() || effect.inputs.values().any(|source| source.reads_anchor(None)) || effect.kind.reads_stack() - }; - if mask.effects.iter().any(|effect| effect.visible && reads_below(effect)) { - // The material program draws the owner once per placement: show the draw where the requested layer sits - let mut program = Self::try_compile_with_brush(project, pixels, ts, region, brush)?; - let draw = program.mask_layers.iter().rev().find(|&&(id, offset, _)| (id == requested || id == owner) && offset == around); - program.mask_layer = draw.ok_or("The mask's GPU anchor stack is missing.")?.2; - program.mask_preview = true; - program.display_outputs = display_bit(DisplayKind::BaseColor); - return Ok(program); - } - if let Some(brush) = &brush { - brush.validate(set.size())?; - } - let mut operations = vec![Operation::zeroed()]; - let mut paint = PaintInputs::default(); - let mut procedural = ProceduralInputs::new(set.resolution); - // P8: a UV tile atlas's block, its tile scales and the set's own resolution - let layout = udim::UdimLayout::of(set); - udim::prepare(layout.as_ref(), &mut procedural); - let mut tile_patterns = TilePatterns::default(); - let background = compile_mask(Some(mask), around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut operations)?; - operations[0].effects[1] = operations.len() as u32 - 1; - operations[0].balance[1] = background; - bind_input_sources(&mut operations, 1, &procedural.input_sources); - let mut filters = FilterPlan::compile(&mut operations, 1, &procedural); - bind_generator_sources(&mut operations, &procedural.generator_sources); - filters.bind_anchors(&mut operations); - let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; - let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); - let (brush_alpha, brush_stencil) = brush.map_or((None, None), |brush| (Some(brush.alpha), brush.stencil)); - let needs_surface = brush_stencil.is_some() || needs_surface(&operations); - Ok(Self { - operations, - layer_count: 1, - filters, - groups: GroupPlan::default(), - geometry: GeometryMasks::default(), - paint: paint.images, - ramp_words: procedural.ramp_words, - curvature_sizes: procedural.curvature_sizes, - tile_patterns, - material_images: procedural.materials, - brush_alpha, - brush_stencil, - region, - coverage: None, - surface: None, - needs_surface, - baked: None, - id_bake: None, - // Reuse the first four-byte display slot for linear grayscale. - display_outputs: display_bit(DisplayKind::BaseColor), - glossiness: false, - mask_preview: true, - mask_layer: 0, - mask_layers: Vec::new(), - image_words: procedural.image_words, - environment: LateEnvironment::new(procedural.environment_word, &project.display), - bake_rows: procedural.bake_rows, - udim, - udim_layout: layout, - }) - } -} - /// Filter library ids that still composite on the CPU with their library defaults, as /// (package, id). The GPU port's library gate (crates/ui-egui/src/gpu_port_gate.rs) checks this /// against the compiler; at the end of the port it is empty. @@ -2160,6 +381,7 @@ fn sparse_channel(pixels: &PixelStore, id: LayerId, channel: Channel) -> Result< if image.is_some_and(|image| image.comps() != channel.components() + 1) { return Err("A paint layer has a layout that uses CPU compositing."); } + Ok(image) } @@ -2194,7 +416,7 @@ fn content_depends_on_channel(effect: &Effect) -> bool { fn content_filter(effect: &Effect, procedural: &mut ProceduralInputs) -> Option { let noop = Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() }; match &effect.kind { - // A mask-only effect authored in this stack leaves its content alone. + // A mask-only effect authored in this stack leaves its content alone EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection(_) | EffectKind::Compare { .. } => Some(noop), // A blending effect set to Disable leaves the content as it is kind if kind.blends() && effect.blend == BlendMode::Disable && uniform_blend(effect) => Some(noop), @@ -2257,6 +479,7 @@ fn content_deposit( if blend.opacity <= 0.0 || blend.mode == BlendMode::Disable { return Ok(None); } + let mut op = if let EffectKind::Material(fill) = &effect.kind { let Some(source) = fill.sources.get(&channel) else { return Ok(None) }; let mut op = source_operation(Some(source), &placed(around, &fill.projection), fill.sampling, channel.default_value(), channel.kind(), procedural) @@ -2273,6 +496,7 @@ fn content_deposit( if image.is_none() && value.is_none() { return Ok(None); } + content_paint(effect.id, channel, image, value, brush.is_some_and(|brush| brush.stencil.is_some()), paint) }; op.low[3] = blend.opacity.min(1.0); @@ -2312,9 +536,11 @@ fn compile_mask( if image.is_none() && live.is_none() { continue; } + if image.is_some_and(|image| image.comps() != 2) { return Err("A painted mask has a layout that uses CPU compositing."); } + let image_index = image.map_or(NO_PAINT_IMAGE, |image| paint.register(effect.id, None, image)); let mut op = Operation { ids: [0, 10, image_index, 2], ..Operation::zeroed() }; if let Some((value, opacity, erase, mask_image)) = live { @@ -2336,6 +562,7 @@ fn compile_mask( if !tolerance.is_finite() { return Err("A color selection has invalid tolerance."); } + let mut operation = Operation { ids: [0, COLOR_SELECTION_OPCODE, 0, 0], low: [*tolerance, 0.0, 0.0, 0.0], @@ -2353,6 +580,7 @@ fn compile_mask( if !value.is_finite() || !tolerance.is_finite() { return Err("A mask comparison has invalid parameters."); } + let compare = match op { CompareOp::LesserThan => 0, CompareOp::WithinTolerance => 1, @@ -2361,15 +589,14 @@ fn compile_mask( let mut operation = Operation { ids: [0, COMPARE_OPCODE, compare, 0], low: [*value, *tolerance, 0.0, 0.0], ..Operation::zeroed() }; stack::soften_compare(&mut operation, *hardness); - // A side reading the layers below or this layer reads the material of the channel at - // the texel; any pair but the mask against the constant names its sides too + // Stack reads resolve against the material channel at the sampled texel if left.reads_stack() || right.reads_stack() || (*left, *right) != (CompareSource::ThisMask, CompareSource::Constant) { stack::read_layers(&mut operation, *left, *right, *channel); } operation } - // Lighting and PBR Validate read the base color, which a mask does not have: the CPU - // leaves the mask as it is (`Filter::point` is None), so they lower to nothing here + + // Mask operations have no base color for lighting or PBR validation EffectKind::Filter(Filter::BakedLighting { .. } | Filter::EnvironmentLighting { .. } | Filter::PbrValidate(_)) => continue, _ => { let first_input = procedural.input_sources.len(); @@ -2383,11 +610,13 @@ fn compile_mask( if !effect.opacity.is_finite() { return Err("A mask effect has an invalid opacity."); } + if let EffectKind::Fill { source, .. } = &effect.kind { bind_tile_source(&mut op, Some(source), tile_patterns); } op.low[3] = effect.opacity.clamp(0.0, 1.0); op.balance[2] = blend_code(effect.blend) as f32; + // A lowering with a stage before its operation (`ProceduralInputs::precede_with_stage`) effects.extend(procedural.preceding_stage.take()); effects.push(op); @@ -2395,7 +624,7 @@ fn compile_mask( Ok(if mask.background == MaskBackground::White { 1.0 } else { 0.0 }) } -// Bytecode values used by composite.wgsl. Keep these stable if BlendMode is reordered. +// Bytecode values used by composite.wgsl. Keep these stable if BlendMode is reordered fn blend_code(mode: BlendMode) -> u32 { use BlendMode::*; match mode { @@ -2539,6 +768,7 @@ fn source_operation( op.uv[3] = pattern.contrast.max(0.0); op.balance[0] = pattern.balance; op.procedural[0] = pattern_pixels(pattern, inputs.resolution, inputs.texture_set).unwrap_or(0); + // P8: a UV tile atlas's smaller tiles reduce the pattern at their own resolution op.ext[3] = udim::pattern_levels(pattern, inputs)?; if channel == ChannelKind::Color && !ramp.is_empty() { @@ -2547,14 +777,14 @@ fn source_operation( fill_projection::place_procedural(projection, sampling, &mut op, inputs)?; } } + // Coverage of every source kind (wrap, crop, backface, depth culling, decals) fill_projection::place_cover(projection, sampling, &mut op, inputs)?; op.low.iter().chain(&op.high).chain(&op.projection).chain(&op.uv).chain(&op.balance).all(|v| v.is_finite()).then_some(op) } fn generator_operation(generator: &Generator, inputs: &mut ProceduralInputs, patterns: &mut TilePatterns) -> Option { - // The GPU has the earlier model alone: the wear, section, light and kind controls, a texture, - // a grunge, Micro Details and the kinds without an earlier model compose on the CPU + // Only the earlier generator model runs on the GPU if !generator.on_earlier_model() || generator.controls.is_some() || generator.texture.is_some() @@ -2563,6 +793,7 @@ fn generator_operation(generator: &Generator, inputs: &mut ProceduralInputs, pat { return None; } + let kind = match generator.kind { GeneratorKind::EdgeWear => 40, GeneratorKind::Dirt => 41, @@ -2581,6 +812,7 @@ fn generator_operation(generator: &Generator, inputs: &mut ProceduralInputs, pat projection: [generator.noise_scale.max(1e-3), generator.offset, generator.global.balance, generator.global.contrast], ..Operation::zeroed() }; + // The map the earlier model reads (GeneratorKind::inputs lists the newer controls' maps too) let earlier_input = match generator.kind { GeneratorKind::EdgeWear | GeneratorKind::Curvature => Some(BakedMap::Curvature), @@ -2594,6 +826,7 @@ fn generator_operation(generator: &Generator, inputs: &mut ProceduralInputs, pat inputs.generator_sources.push(source_op); op.effects[3] = inputs.generator_sources.len() as u32; } + // A micro detail saved before Micro Details: its anchor's height times the amount if let Some((anchor, amount)) = generator.earlier_micro() { let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() }; @@ -2607,6 +840,7 @@ fn generator_operation(generator: &Generator, inputs: &mut ProceduralInputs, pat if let (Some(_), _) | (None, 2..) = (blur, cell) { inputs.generator_stages.push((blur, cell)); op.spatial[1] = inputs.generator_stages.len() as u32; + // P8: the generator's cells and blur at each further UV tile scale let levels: Vec<_> = inputs.levels.iter().map(|&resolution| generator_stage(generator, resolution, inputs)).collect(); inputs.generator_levels.push(levels); @@ -2633,10 +867,12 @@ fn generator_stage(generator: &Generator, resolution: u32, inputs: &ProceduralIn /// the GPU program does not evaluate as the CPU does, so the stack composites on the CPU. fn point_effect(effect: &Effect, inputs: &mut ProceduralInputs) -> Option { use Filter::*; + // Per-channel blends are checked by the content caller; a mask ignores them if !effect.opacity.is_finite() { return None; } + let mut op = Operation::zeroed(); let (kind, params) = match &effect.kind { EffectKind::Levels(levels) => { @@ -2670,6 +906,7 @@ fn point_effect(effect: &Effect, inputs: &mut ProceduralInputs) -> Option { op.procedural[1..3].copy_from_slice(&inputs.pack_rgb(colors)?); @@ -2686,6 +923,7 @@ fn point_effect(effect: &Effect, inputs: &mut ProceduralInputs) -> Option (NOOP_EFFECT_OPCODE, [0.0; 3]), filter if gpu_neighbourhood::supports(filter) => { @@ -2697,6 +935,7 @@ fn point_effect(effect: &Effect, inputs: &mut ProceduralInputs) -> Option packages::lower_filter(filter, effect, &mut op, inputs)?, }, @@ -2707,18 +946,29 @@ fn point_effect(effect: &Effect, inputs: &mut ProceduralInputs) -> Option u32 { if !normal.iter().all(|value| (0.0..=1.0).contains(value)) { return 0; } - // An even scale preserves the flat normal's exact 0.5 components. + + // An even scale preserves the flat normal's exact 0.5 components let [x, y, z] = [normal[0], normal[1], normal[2].sqrt()].map(|value| (value * 1022.0 + 0.5) as u32); - // Square-root encoding preserves precision near zero, where RNM is most sensitive. + + // Square-root encoding preserves precision near zero, where RNM is most sensitive let z = z.max(u32::from(normal[2] > 0.0)); x | (y << 10) | (z << 20) | (1 << 30) } +fn validate_triangle_grid(grid: &UvGBuffer) -> Result<(), String> { + let texels = u64::from(grid.width) * u64::from(grid.height); + if texels == 0 || grid.tri.len() as u64 != texels { + return Err("The UV triangle data does not match the texture dimensions.".into()); + } + + Ok(()) +} + fn coverage_word(triangles: &[u32]) -> u32 { triangles.iter().enumerate().fold(0, |word, (bit, &triangle)| word | (u32::from(triangle != NO_TRI) << bit)) } @@ -2745,1236 +995,6 @@ fn write_input(queue: &wgpu::Queue, texture: &wgpu::Texture, size: (u32, ); } -struct SurfaceCache { - gbuf: Weak, - view: wgpu::TextureView, - vertices: Option, -} - -struct BakeCache { - size: (u32, u32), - /// The built-in maps, then the second row block's - maps: Vec>>>, - view: wgpu::TextureView, -} - -struct IdBakeCache { - size: [u32; 2], - data: Weak>, - view: wgpu::TextureView, -} - -struct CurvatureCache { - gbuf: Weak, - map: Weak>, - size: [u32; 2], - needed: [bool; CurvatureDetail::BLURRED_SIZES], - levels: CurvatureLevels, -} - -struct CurvatureResources { - gpu: Option, - empty: CurvatureLevels, - cache: BTreeMap, -} - -pub(crate) struct GpuCompositor { - pipelines: Arc>, - /// Compile new pipelines on worker threads (`set_asynchronous_compile`) - asynchronous: bool, - bindings: wgpu::BindGroupLayout, - pipeline_layout: wgpu::PipelineLayout, - filter_gpu: Option, - /// Take the neighbourhood kernels the tests on the shared device share - shared_test_kernels: bool, - lookup: wgpu::Buffer, - uniform_coverage: wgpu::Buffer, - coverage: Vec<(Weak, wgpu::Buffer)>, - surfaces: Vec, - baked: BTreeMap, - id_bakes: BTreeMap, - curvature: Option, - default_surface: wgpu::TextureView, - default_vertices: wgpu::Buffer, - default_baked: wgpu::TextureView, - default_id_bake: Option, - default_brush_alpha: wgpu::TextureView, - default_brush_stencil: GpuStencil, - default_tile_images: wgpu::TextureView, - tile_images: BTreeMap, - paint_upload: Option, - /// The working buffer of the last update, reused while the next one fits it - scratch: Option, - /// Bytes of the last update's working space and paint upload (tests report them) - update_bytes: [u64; 2], -} - -impl GpuCompositor { - pub(crate) fn supports(device: &wgpu::Device) -> bool { - let limits = device.limits(); - limits.max_storage_buffers_per_shader_stage >= 6 - && limits.max_sampled_textures_per_shader_stage >= 5 - && limits.max_uniform_buffers_per_shader_stage >= 2 - && limits.max_bindings_per_bind_group >= 13 - && limits.max_compute_invocations_per_workgroup >= WORKGROUP * WORKGROUP - && limits.max_compute_workgroup_size_x >= WORKGROUP - && limits.max_compute_workgroup_size_y >= WORKGROUP - } - - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) fn new(device: &wgpu::Device) -> Self { - Self::new_with(device, false) - } - - /// [`GpuCompositor::new`], taking the pipelines and kernels the tests on the shared device - /// share when `shared` ([`crate::headless::Headless::for_tests`]) - pub(crate) fn new_with(device: &wgpu::Device, shared: bool) -> Self { - let binding = |binding, ty| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }; - let buffer = |ty| wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }; - let uniform = buffer(wgpu::BufferBindingType::Uniform); - let read = buffer(wgpu::BufferBindingType::Storage { read_only: true }); - let write = buffer(wgpu::BufferBindingType::Storage { read_only: false }); - let texture = |sample_type, view_dimension| wgpu::BindingType::Texture { sample_type, view_dimension, multisampled: false }; - let uint = texture(wgpu::TextureSampleType::Uint, wgpu::TextureViewDimension::D2); - let array = texture(wgpu::TextureSampleType::Uint, wgpu::TextureViewDimension::D2Array); - let float = texture(wgpu::TextureSampleType::Float { filterable: false }, wgpu::TextureViewDimension::D2); - let limits = device.limits(); - let supports_curvature = limits.max_sampled_textures_per_shader_stage >= 6 - && limits.max_uniform_buffers_per_shader_stage >= 3 - && limits.max_bindings_per_bind_group >= 15 - && limits.max_storage_textures_per_shader_stage >= 1 - && limits.max_compute_workgroup_size_x >= 64; - let supports_id = limits.max_sampled_textures_per_shader_stage >= 6 + u32::from(supports_curvature) && limits.max_bindings_per_bind_group >= 16; - let mut entries = vec![ - binding(0, uniform), - binding(1, read), - binding(2, read), - binding(3, write), - binding(4, read), - binding(5, read), - binding(6, uint), - binding(7, read), - binding(8, uint), - binding(9, uint), - binding(10, array), - binding(11, float), - binding(12, uniform), - ]; - if supports_curvature { - entries.extend([binding(13, uint), binding(14, uniform)]); - } - if supports_id { - entries.push(binding(15, uint)); - } - let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("tc_gpu_composite_bindings"), entries: &entries }); - let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("tc_gpu_composite_layout"), - bind_group_layouts: &[Some(&bindings)], - immediate_size: 0, - }); - let values = texturecraft_texel::srgb_lut().map(u32::from); - let lookup = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_srgb"), - contents: bytemuck::cast_slice(&values), - usage: wgpu::BufferUsages::STORAGE, - }); - let uniform_coverage = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_uniform_coverage"), - contents: &[0; 4], - usage: wgpu::BufferUsages::STORAGE, - }); - let default_surface = input_texture(device, "tc_composite_empty_surface", (1, 1), 1, wgpu::TextureFormat::Rg32Uint).create_view(&Default::default()); - let default_vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_empty_vertices"), - contents: &[0; 32], - usage: wgpu::BufferUsages::STORAGE, - }); - let default_baked = input_texture(device, "tc_composite_empty_bakes", (1, 1), 1, wgpu::TextureFormat::Rgba32Uint).create_view(&Default::default()); - let default_brush_alpha = - input_texture(device, "tc_composite_empty_brush_alpha", (1, 1), 1, wgpu::TextureFormat::R16Uint).create_view(&Default::default()); - Self { - pipelines: pipelines::shared(shared, supports_curvature, supports_id), - shared_test_kernels: shared, - asynchronous: false, - bindings, - pipeline_layout, - filter_gpu: None, - lookup, - uniform_coverage, - coverage: Vec::new(), - surfaces: Vec::new(), - baked: BTreeMap::new(), - id_bakes: BTreeMap::new(), - curvature: supports_curvature.then(|| CurvatureResources { gpu: None, empty: CurvatureLevels::empty(device), cache: BTreeMap::new() }), - default_surface, - default_vertices, - default_baked, - default_id_bake: supports_id - .then(|| input_texture(device, "tc_composite_empty_id_bake", (1, 1), 1, wgpu::TextureFormat::Rgba32Uint).create_view(&Default::default())), - default_brush_alpha, - default_brush_stencil: GpuStencil::empty(device), - default_tile_images: TileImageAtlas::empty_view(device), - tile_images: BTreeMap::new(), - paint_upload: None, - scratch: None, - update_bytes: [0; 2], - } - } - - fn surface_inputs(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, program: &CompositeProgram) -> Result<(wgpu::TextureView, wgpu::Buffer), String> { - let Some((mesh, gbuf)) = &program.surface else { - if program.needs_surface || !program.geometry.parts.is_empty() { - return Err("Missing UV surface inputs for GPU layer composition".into()); - } - return Ok((self.default_surface.clone(), self.default_vertices.clone())); - }; - if program.needs_surface { - return self.uv_surface(device, queue, mesh, gbuf); - } - - // A geometry-only mask needs triangle IDs but no barycentrics or surface vertices. - self.release_unused_surfaces(); - let key = Arc::downgrade(gbuf); - if let Some(cache) = self.surfaces.iter().find(|cache| cache.gbuf.ptr_eq(&key)) { - return Ok((cache.view.clone(), self.default_vertices.clone())); - } - let size = (gbuf.width, gbuf.height); - if size.0.max(size.1) > device.limits().max_texture_dimension_2d { - return Err("UV triangle data exceeds the GPU limits".into()); - } - let texture = input_texture(device, "tc_composite_uv_triangles", size, 1, wgpu::TextureFormat::R32Uint); - for (band, triangles) in gbuf.tri.chunks((size.0 * ROWS) as usize).enumerate() { - write_input(queue, &texture, (size.0, triangles.len() as u32 / size.0), (band as u32 * ROWS, 0), triangles); - } - let view = texture.create_view(&Default::default()); - self.surfaces.push(SurfaceCache { gbuf: key, view: view.clone(), vertices: None }); - Ok((view, self.default_vertices.clone())) - } - - pub(crate) fn uv_surface( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - mesh: &Arc, - gbuf: &Arc, - ) -> Result<(wgpu::TextureView, wgpu::Buffer), String> { - self.release_unused_surfaces(); - let key = Arc::downgrade(gbuf); - if let Some((view, vertices)) = - self.surfaces.iter().find(|cache| cache.gbuf.ptr_eq(&key)).and_then(|cache| cache.vertices.as_ref().map(|vertices| (&cache.view, vertices))) - { - return Ok((view.clone(), vertices.clone())); - } - let limits = device.limits(); - // Two vec4 per vertex, then the tangents two per 32-byte element (`surface_tangent` in WGSL) - let vertex_bytes = (mesh.indices.len() as u64 + (mesh.indices.len() as u64).div_ceil(2)) * 32; - if gbuf.width.max(gbuf.height) > limits.max_texture_dimension_2d || vertex_bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err("UV surface data exceeds the GPU limits".into()); - } - self.surfaces.retain(|cache| !cache.gbuf.ptr_eq(&key)); - let (lo, hi) = mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = ((hi - lo).length() * 0.5).max(1e-4); - let mut vertex_data: Vec<[[f32; 4]; 2]> = mesh - .indices - .iter() - .map(|&index| { - let index = index as usize; - let pos = (mesh.positions.get(index).copied().unwrap_or_default() - center) / radius; - let normal = mesh.normals.get(index).copied().unwrap_or(Vec3::Y); - let uv = mesh.uvs.get(index).copied().unwrap_or_default(); - [pos.extend(uv.x).to_array(), normal.extend(uv.y).to_array()] - }) - .collect(); - // The MikkTSpace tangents after the vertices, two per element: the brush and the stencil - // read the vertices at the same stride - let tangent = |index: Option<&u32>| index.and_then(|&index| mesh.tangents.get(index as usize)).copied().unwrap_or_default().to_array(); - vertex_data.extend(mesh.indices.chunks(2).map(|pair| [tangent(pair.first()), tangent(pair.get(1))])); - let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_surface_vertices"), - contents: bytemuck::cast_slice(&vertex_data), - usage: wgpu::BufferUsages::STORAGE, - }); - let texture = input_texture(device, "tc_composite_uv_surface", (gbuf.width, gbuf.height), 1, wgpu::TextureFormat::Rg32Uint); - let stride = (gbuf.width * ROWS) as usize; - for (band, (tri, bary)) in gbuf.tri.chunks(stride).zip(gbuf.bary.chunks(stride)).enumerate() { - let pixels: Vec<[u32; 2]> = tri - .par_iter() - .zip(bary) - .map(|(&tri, &[u, v])| { - let pack = |x: f32| u32::from(texturecraft_texel::to_u16(x)); - [tri, pack(u) | (pack(v) << 16)] - }) - .collect(); - write_input(queue, &texture, (gbuf.width, tri.len() as u32 / gbuf.width), (band as u32 * ROWS, 0), &pixels); - } - let view = texture.create_view(&Default::default()); - self.surfaces.push(SurfaceCache { gbuf: key, view: view.clone(), vertices: Some(vertices.clone()) }); - Ok((view, vertices)) - } - - pub(crate) fn retain_texture_sets(&mut self, count: usize) { - self.release_unused_surfaces(); - self.baked.retain(|&ts, _| ts < count); - self.id_bakes.retain(|&ts, _| ts < count); - if let Some(curvature) = &mut self.curvature { - curvature.cache.retain(|&ts, _| ts < count); - } - self.tile_images.retain(|&ts, _| ts < count); - } - - pub(crate) fn release_unused_surfaces(&mut self) { - self.tile_images.retain(|_, atlas| atlas.is_live()); - self.surfaces.retain(|cache| cache.gbuf.strong_count() != 0); - self.id_bakes.retain(|_, cache| cache.data.strong_count() != 0); - if let Some(curvature) = &mut self.curvature { - curvature.cache.retain(|_, cache| cache.map.strong_count() != 0 && cache.gbuf.strong_count() != 0); - } - } - - pub(crate) fn clear_baked_inputs(&mut self) { - self.baked.clear(); - self.id_bakes.clear(); - if let Some(curvature) = &mut self.curvature { - curvature.cache.clear(); - } - } - - pub(crate) fn release_inputs(&mut self, ts: usize) { - self.baked.remove(&ts); - self.id_bakes.remove(&ts); - if let Some(curvature) = &mut self.curvature { - curvature.cache.remove(&ts); - } - self.tile_images.remove(&ts); - } - - fn id_bake_input(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, id_bake: Option<&IdBake>) -> Result, String> { - let Some(id_bake) = id_bake else { - self.id_bakes.remove(&ts); - return Ok(self.default_id_bake.clone()); - }; - if self.default_id_bake.is_none() { - return Err("Color selection exceeds the adapter's sampled-texture limit.".into()); - } - let data = Arc::downgrade(&id_bake.data); - if let Some(cache) = self.id_bakes.get(&ts).filter(|cache| cache.size == id_bake.size && cache.data.ptr_eq(&data)) { - return Ok(Some(cache.view.clone())); - } - - let [width, height] = id_bake.size; - // Pack the RGB floats across all four lanes of each GPU texel. This avoids wasting - // one word per source texel and allows complete rows to upload directly from the bake. - let packed_height = (u64::from(height) * 3).div_ceil(4) as u32; - let dimensions = device.limits().max_texture_dimension_2d; - if width.max(packed_height) > dimensions || u64::from(width) * u64::from(packed_height) * 16 > MAX_ID_BAKE_BYTES { - return Err("The ID map exceeds the adapter's GPU texture budget.".into()); - } - self.id_bakes.remove(&ts); - let texture = input_texture(device, "tc_composite_id_bake", (width, packed_height), 1, wgpu::TextureFormat::Rgba32Uint); - let row_words = width as usize * 4; - let word_count = width as usize * height as usize * 3; - let mut tail_row = Vec::new(); - let mut pending = 0; - for (band, source) in id_bake.data[..word_count].chunks(row_words * ROWS as usize).enumerate() { - let rows = source.len() / row_words; - let top = band as u32 * ROWS; - let (full, tail) = source.split_at(rows * row_words); - if rows > 0 { - let full: &[[f32; 4]] = bytemuck::cast_slice(full); - write_input(queue, &texture, (width, rows as u32), (top, 0), full); - } - if !tail.is_empty() { - tail_row.extend_from_slice(tail); - tail_row.resize(row_words, 0.0); - let padded: &[[f32; 4]] = bytemuck::cast_slice(&tail_row); - write_input(queue, &texture, (width, 1), (top + rows as u32, 0), padded); - } - pending += std::mem::size_of_val(source); - if pending >= MAX_ID_UPLOAD_BYTES { - let submission = queue.submit([]); - #[cfg(not(target_arch = "wasm32"))] - device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None }).map_err(|error| error.to_string())?; - #[cfg(target_arch = "wasm32")] - let _ = submission; - pending = 0; - } - } - let view = texture.create_view(&Default::default()); - self.id_bakes.insert(ts, IdBakeCache { size: id_bake.size, data, view: view.clone() }); - Ok(Some(view)) - } - - fn baked_input(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, baked: Option<&BakedInputs>) -> Result { - let Some(baked) = baked else { - self.baked.remove(&ts); - return Ok(self.default_baked.clone()); - }; - let size = (baked.width, baked.height); - let refs: Vec<_> = baked.maps.iter().chain(&baked.rows).map(|map| map.as_ref().map(Arc::downgrade)).collect(); - if let Some(cache) = self.baked.get(&ts).filter(|cache| { - size == cache.size - && refs.len() == cache.maps.len() - && refs.iter().zip(&cache.maps).all(|(a, b)| match (a, b) { - (Some(a), Some(b)) => a.ptr_eq(b), - (None, None) => true, - _ => false, - }) - }) { - return Ok(cache.view.clone()); - } - // The second row block (Height and World Normal) sits below the built-in maps; P8: maps of - // different heights take rows of their own, the header rows after them - let separate = baked.separate().then(|| baked.separate_layout()); - let rows = match separate { - Some((_, header)) => header.checked_add(SEPARATE_MAPS.div_ceil(size.0.max(1) as usize) as u32), - None => size.1.checked_mul(baked.blocks()), - } - .ok_or("Baked maps exceed the GPU texture dimensions")?; - if size.0.max(rows) > device.limits().max_texture_dimension_2d { - return Err("Baked maps exceed the GPU texture dimensions".into()); - } - self.baked.remove(&ts); - // Keep all three scalar inputs at f32 precision for narrow generator ramps. The - // normal uses the remaining word, keeping the atlas at 16 bytes per texel. - let texture = input_texture(device, "tc_composite_bakes", (size.0, rows), 1, wgpu::TextureFormat::Rgba32Uint); - if let Some(layout) = separate { - write_separate_bakes(queue, &texture, baked, layout); - let view = texture.create_view(&Default::default()); - self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone() }); - return Ok(view); - } - let value = |map: usize, i: usize, fallback: f32| baked.maps[map].as_ref().and_then(|data| data.get(i).copied()).unwrap_or(fallback); - for top in (0..size.1).step_by(ROWS as usize) { - let end = (top + ROWS).min(size.1); - let indices = top as usize * size.0 as usize..end as usize * size.0 as usize; - let texels: Vec<[u32; 4]> = indices - .into_par_iter() - .map(|i| { - let normal = if baked.maps[1].is_some() { - encode_baked_normal([value(1, i * 3, 0.5), value(1, i * 3 + 1, 0.5), value(1, i * 3 + 2, 1.0)]) - } else { - 0 - }; - [value(0, i, 1.0).to_bits(), value(2, i, 0.5).to_bits(), value(3, i, 1.0).to_bits(), normal] - }) - .collect(); - write_input(queue, &texture, (size.0, end - top), (top, 0), &texels); - } - if baked.blocks() > 1 { - // Height in x, the stored world normal in yzw; zeros where a map is not baked - let row = |map: usize, i: usize, component: usize| { - let components = BAKE_ROW_MAPS[map].components(); - baked.rows[map].as_ref().and_then(|data| data.get(i * components + component).copied()).unwrap_or(0.0).to_bits() - }; - for top in (0..size.1).step_by(ROWS as usize) { - let end = (top + ROWS).min(size.1); - let indices = top as usize * size.0 as usize..end as usize * size.0 as usize; - let texels: Vec<[u32; 4]> = indices.into_par_iter().map(|i| [row(0, i, 0), row(1, i, 0), row(1, i, 1), row(1, i, 2)]).collect(); - write_input(queue, &texture, (size.0, end - top), (size.1 + top, 0), &texels); - } - } - let view = texture.create_view(&Default::default()); - self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone() }); - Ok(view) - } - - fn coverage_buffer(&mut self, device: &wgpu::Device, map: Option<&Arc>) -> Result { - let Some(map) = map else { return Ok(self.uniform_coverage.clone()) }; - let key = Arc::downgrade(map); - self.coverage.retain(|(cached, _)| cached.strong_count() != 0); - if let Some((_, buffer)) = self.coverage.iter().find(|(cached, _)| key.ptr_eq(cached)) { - return Ok(buffer.clone()); - } - let width = map.width as usize; - let words_per_row = width.div_ceil(32); - let count = words_per_row * map.height as usize; - let limits = device.limits(); - if (count * 4) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err("UV padding data exceeds the adapter's storage-buffer limit".into()); - } - // Each word packs 32 coverage samples. The same buffer serves every display resolution. - let words: Vec = if width.is_multiple_of(32) { - map.tri.par_chunks(32).map(coverage_word).collect() - } else { - (0..count) - .into_par_iter() - .map(|i| { - let row = i / words_per_row * width; - let start = row + i % words_per_row * 32; - coverage_word(&map.tri[start..(start + 32).min(row + width)]) - }) - .collect() - }; - let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_coverage"), - contents: bytemuck::cast_slice(&words), - usage: wgpu::BufferUsages::STORAGE, - }); - self.coverage.push((key, buffer.clone())); - Ok(buffer) - } - - fn curvature_inputs( - &mut self, - device: &wgpu::Device, - queue: &wgpu::Queue, - ts: usize, - program: &CompositeProgram, - baked_view: &wgpu::TextureView, - ) -> Result, String> { - let source = program.baked.as_ref().and_then(|baked| baked.maps[2].as_ref().map(|map| (baked, map))); - let Some((baked, map)) = source else { - return Ok(self.curvature.as_mut().map(|curvature| { - curvature.cache.remove(&ts); - curvature.empty.clone() - })); - }; - let needed = program.curvature_sizes; - if !needed.contains(&true) { - return Ok(self.curvature.as_ref().map(|curvature| curvature.empty.clone())); - } - let Some(curvature) = &self.curvature else { - return Err("Curvature detail sizes exceed the GPU adapter's binding or dispatch limits.".into()); - }; - let (_, gbuf) = program.surface.as_ref().ok_or("Curvature detail is missing its UV coverage.")?; - let key = Arc::downgrade(gbuf); - let map = Arc::downgrade(map); - let size = [baked.width, baked.height]; - if let Some(cache) = curvature.cache.get(&ts).filter(|cache| cache.gbuf.ptr_eq(&key) && cache.map.ptr_eq(&map) && cache.size == size) - && needed.iter().zip(cache.needed).all(|(&required, present)| !required || present) - { - return Ok(Some(cache.levels.clone())); - } - // P8: a UV tile atlas pads, blurs and coarsens each block of the bake alone, and a tile smaller - // than its block covers only its share of the bake - let layout = program.udim_layout.as_ref(); - let block = layout.map_or(size, |layout| [size[0] / layout.grid.cols.max(1), size[1] / layout.grid.rows.max(1)]); - let scales = layout.filter(|layout| layout.scaled).map_or((0, &[][..]), |layout| (layout.block, layout.scales.as_slice())); - let partly_covered = gbuf.covered_count() != gbuf.tri.len() || !scales.1.is_empty(); - let coverage = partly_covered.then(|| self.coverage_buffer(device, Some(gbuf))).transpose()?; - let curvature = self.curvature.as_mut().ok_or("The GPU curvature adapter is unavailable.")?; - curvature.cache.remove(&ts); - let gpu = curvature.gpu.get_or_insert_with(|| CurvatureGpu::new(device)); - let working_size = [gbuf.width, gbuf.height]; - let levels = - gpu.build(device, queue, CurvatureInput { baked: baked_view, bake_size: size, coverage: coverage.as_ref(), working_size, needed, block, scales })?; - curvature.cache.insert(ts, CurvatureCache { gbuf: key, map, size, needed, levels: levels.clone() }); - Ok(Some(levels)) - } - - fn tile_atlas(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, program: &CompositeProgram) -> Result, String> { - let gray: Vec<_> = program.tile_patterns.image_sources().collect(); - let color: Vec<_> = program.material_images.atlas_images().collect(); - let raw = program.material_images.raw_planes(); - if gray.is_empty() && color.is_empty() && raw.is_empty() { - self.tile_images.remove(&ts); - return Ok(None); - } - if self.tile_images.get(&ts).is_none_or(|atlas| !atlas.matches(&gray, &color, raw)) { - self.tile_images.remove(&ts); - let atlas = TileImageAtlas::new(device, queue, &gray, &color, raw)?; - self.tile_images.insert(ts, atlas); - } - Ok(self.tile_images.get(&ts)) - } - - /// Compose bands into reusable GPU scratch space, then copy them into display textures. - /// Indexed/SRGB and floating-point maps use the same formats as the CPU uploader. - pub(crate) fn compose( - &mut self, - gpu: (&wgpu::Device, &wgpu::Queue), - program: &CompositeProgram, - target: (usize, (u32, u32), u32, Option), - textures: &[&wgpu::Texture], - submitted: &mut Option, - ) -> Result<(), String> { - let (device, queue) = gpu; - let (ts, source_size, shift, region) = target; - let base = textures.first().ok_or("The GPU output textures are missing.")?; - let extent = (base.width(), base.height()); - let region = region.map(|r| r.viewport(shift, extent)).unwrap_or(CompositeRegion { min: [0; 2], max: [extent.0, extent.1] }); - let width = region.max[0].saturating_sub(region.min[0]); - let height = region.max[1].saturating_sub(region.min[1]); - if width == 0 || height == 0 { - return Ok(()); - } - let selection_work = if program.id_bake.is_some() { - program.operations.iter().filter(|op| op.ids[1] == COLOR_SELECTION_OPCODE).map(|op| u64::from(op.procedural[2])).sum() - } else { - 0 - }; - let pattern_work = program.tile_work_per_pixel()?; - check_texel_work(pattern_work)?; - let tile_work = pattern_work.saturating_add(program.groups.work_per_pixel()).saturating_add(selection_work); - let grouped = program.groups.depth != 0; - let radius = program.coverage.as_ref().map_or(0, |(_, radius)| *radius); - // A band's halo leaves out the stages the whole-set pre-pass evaluates - let halo = radius.saturating_add(program.filters.band_reach()); - let whole = program.filters.whole_set(); - let limits = device.limits(); - // The other buffers an update keeps alive: paint, operations and the parameter lookup - let live = self.paint_upload.as_ref().map_or(0, wgpu::Buffer::size) - + (program.operations.len() * size_of::()) as u64 - + (u64::from(LOOKUP_WORDS) + program.ramp_words.len() as u64 + program.geometry.words.len() as u64) * 4; - let scratch_limit = scratch_limit(&limits, live); - let (mut band_width, mut band_rows) = composite_band_size(width, tile_work); - let filtered = !program.filters.stages.is_empty(); - if filtered { - if limits.max_compute_workgroup_size_x < 64 { - return Err("The GPU cannot run the neighbourhood filter workgroups.".into()); - } - if tile_work == 0 { - band_rows = height.min(256); - } - let shared = self.shared_test_kernels; - self.filter_gpu.get_or_insert_with(|| NeighbourhoodGpu::for_device(device, shared)); - } - let (pipeline, prepare) = self.pipelines().get(device, &self.pipeline_layout, program, self.asynchronous)?.ok_or(GPU_PIPELINES_PENDING)?; - let coverage = self.coverage_buffer(device, program.coverage.as_ref().map(|(map, _)| map))?; - let (surface, vertices) = self.surface_inputs(device, queue, program)?; - let baked = self.baked_input(device, queue, ts, program.baked.as_ref())?; - let curvature = self.curvature_inputs(device, queue, ts, program, &baked)?; - let id_bake = self.id_bake_input(device, queue, ts, program.id_bake.as_ref())?; - let [id_width, id_height] = program.id_bake.as_ref().map_or([0; 2], |id| id.size); - let bake_words = program.baked.as_ref().map_or([0; 2], BakedInputs::uniform_words); - let mut words_per_pixel = 0; - let copies = DisplayKind::ALL.map(|kind| { - if !program.writes_display(kind) { - return None; - } - let bytes_per_texel = kind.bytes_per_texel() as u32; - let offset = words_per_pixel; - words_per_pixel += u64::from(bytes_per_texel / 4); - Some((offset, bytes_per_texel)) - }); - // A wrapping stage's fields extend past the set's edges (FilterPlan::wraps) - let wraps = program.filters.wraps(); - let field_area = |width: u32, rows: u32| { - let side = |pixels: u32, limit: u32| { - let side = (pixels << shift).saturating_add(halo.saturating_mul(2)); - if wraps { side } else { side.min(limit) } - }; - u64::from(side(width, source_size.0)) * u64::from(side(rows, source_size.1)) - }; - let band_area = |width: u32, rows: u32| u64::from(width.next_multiple_of(64) * rows); - let display_words = |width, rows| band_area(width, rows) * words_per_pixel; - let group_start = |width, rows| display_words(width, rows) + program.filters.words(field_area(width, rows)); - let required = |width, rows| (group_start(width, rows) + program.groups.words(band_area(width, rows))) * 4; - let filter_work: u64 = - program.filters.stages.iter().map(|stage| stage.filter.map_or(1, NeighbourhoodFilter::work_per_texel) + if stage.cell > 1 { 6 } else { 0 }).sum(); - let texel_words = program.filters.field_words(); - // The whole-set pre-pass: its result region (what the bands read around the update), its - // stripes and the scratch it needs besides the bands' - let whole = whole.map(|whole| WholeSetPass::plan(whole, (region, shift), source_size, halo, wraps, texel_words, program.filters.stages.len())); - let whole_bytes = whole.as_ref().map_or(0, WholeSetPass::result_bytes); - if whole_bytes >= scratch_limit { - return Err("The whole-set filter results exceed the adapter's working memory limit.".into()); - } - let scratch_limit = scratch_limit - whole_bytes; - let whole = whole.map(|whole| whole.with_stripes(scratch_limit)).transpose()?; - // Color Match's Average reduces its whole field to one mean: in stripes each stripe would - // apply its own, so a set that needs stripes composites it on the CPU - if let Some(whole) = &whole - && whole.stripe_rows < whole.region[3] - whole.region[1] - && whole - .stages - .stages - .iter() - .filter_map(|&stage| program.filters.stages.get(stage)?.filter) - .any(crate::gpu_neighbourhood::gather::reads_whole_set_mean) - { - return Err("Color Match's Average over a set that needs stripes uses CPU compositing.".into()); - } - // A filtered band includes its source halo. Folder snapshots use only its output area. - while required(band_width, band_rows) > scratch_limit { - if band_width == 1 && band_rows == 1 { - return Err("Composite inputs for one GPU texel exceed the adapter's working memory limit.".into()); - } - if band_width >= band_rows { - band_width = band_width.div_ceil(2); - } else { - band_rows = band_rows.div_ceil(2); - } - } - let pitch = band_width.next_multiple_of(64); - // A costly update submits its bands in parts of the submission budget - let update_work = (u64::from(width) * u64::from(height)).saturating_mul(tile_work); - let submit_budget = if grouped || filtered || band_width < width || band_rows < ROWS || update_work > MAX_TILE_WORK_PER_SUBMISSION { - MAX_TILE_WORK_PER_SUBMISSION - } else { - u64::MAX - }; - let area = pitch * band_rows; - let stride = u64::from(area) * 4; - let field_base = (display_words(band_width, band_rows)) as u32; - let group_base = group_start(band_width, band_rows) as u32; - // The whole-set results follow the larger of the bands' and the pre-pass's working space - let working = whole.as_ref().map_or(0, WholeSetPass::stripe_bytes).max(required(band_width, band_rows)); - let whole_base = u32::try_from(working / 4).map_err(|_| "The GPU working memory exceeds 32-bit word addressing.")?; - // The working buffer of the last update when it is large enough and at most four times - // this one's size (a larger one is released), cleared as a new buffer would be - let size = working + whole_bytes; - let scratch = match &self.scratch { - Some(buffer) if buffer.size() >= size && buffer.size() / 4 <= size => { - let mut clear = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_composite_clear") }); - clear.clear_buffer(buffer, 0, Some(size)); - queue.submit([clear.finish()]); - buffer.clone() - } - _ => { - self.scratch = None; - let buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("tc_composite_scratch"), - size, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - self.scratch = Some(buffer.clone()); - buffer - } - }; - self.update_bytes = [size, 0]; - let atlas = self.tile_atlas(device, queue, ts, program)?; - let tile_images = atlas.map(|atlas| atlas.view.clone()); - let (operations, lookup) = - if program.tile_patterns.is_empty() && program.ramp_words.is_empty() && program.geometry.words.is_empty() && program.material_images.is_empty() { - (Cow::Borrowed(program.operations.as_slice()), self.lookup.clone()) - } else { - let mut words = texturecraft_texel::srgb_lut().map(u32::from).to_vec(); - words.extend(&program.ramp_words); - let geometry_start = words.len(); - words.extend(&program.geometry.words); - let offsets = program.tile_patterns.append_words(&mut words, atlas); - let mesh = program.surface.as_ref().map(|(mesh, _)| mesh.as_ref()); - let (images, decals) = program.material_images.append_words(&mut words, atlas, mesh); - // Side-table words that name an image hold its record offset (`pack_image`) - for &(word, image) in &program.image_words { - let at = LOOKUP_WORDS as usize + word as usize; - words[at] = images.get(image as usize).copied().unwrap_or(u32::MAX); - } - // The environment's diffuse light, late-bound (`reserve_environment`) - if let Some(LateEnvironment { word, words: Some(light), .. }) = &program.environment { - let at = LOOKUP_WORDS as usize + *word as usize; - words[at..at + ENVIRONMENT_WORDS].copy_from_slice(light); - } - let limits = device.limits(); - // The operation stores the offset as an exactly represented float. - if ((!offsets.is_empty() || !decals.is_empty()) && words.len() >= 1 << 24) - || (words.len() * 4) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) - { - return Err("Procedural settings exceed the GPU parameter buffer limit.".into()); - } - let mut operations = program.operations.clone(); - for op in operations.iter_mut().filter(|op| op.constraints[0] != 0) { - let row = (op.constraints[0] - 1) as usize; - op.constraints[0] = - u32::try_from(geometry_start + row * program.geometry.stride).map_err(|_| "The GPU geometry mask offset is too large.")?; - } - for op in operations.iter_mut().filter(|op| op.ids[1] == TILE_GENERATOR_OPCODE) { - let index = op.high[3] as usize; - op.high[3] = *offsets.get(index).ok_or("A Tile Generator operation has no settings.")? as f32; - } - for op in &mut operations { - if op.ids[1] == IMAGE_SOURCE_OPCODE { - op.ids[2] = *images.get(op.ids[2] as usize).ok_or("An image source has no binding.")?; - } - // Placed planars and warps (the first of P1's selectors) read their frame record - if op.procedural[3] == DECAL_PROJECTION || op.procedural[3] == packages::PROJECTION_SELECTORS.start { - op.uv[0] = *decals.get(op.uv[0] as usize).ok_or("A decal has no frame.")? as f32; - } - } - let lookup = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_tile_patterns"), - contents: bytemuck::cast_slice(&words), - usage: wgpu::BufferUsages::STORAGE, - }); - (Cow::Owned(operations), lookup) - }; - let tile_images = tile_images.as_ref().unwrap_or(&self.default_tile_images); - let brush_alpha = program.brush_alpha.as_ref().unwrap_or(&self.default_brush_alpha); - let brush_stencil = program.brush_stencil.as_ref().unwrap_or(&self.default_brush_stencil); - let empty_operation = Operation::zeroed(); - let limits = device.limits(); - if (operations.len() * size_of::()) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err("The layer program exceeds the adapter's storage-buffer limit".into()); - } - let ops = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_operations"), - contents: if operations.is_empty() { bytemuck::bytes_of(&empty_operation) } else { bytemuck::cast_slice(operations.as_ref()) }, - usage: wgpu::BufferUsages::STORAGE, - }); - let max_words = MAX_PAINT_WORDS.min((limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) / 4) as usize); - let windows = paint_windows(program, region, source_size, shift, halo, max_words)?; - // The band uniform: the positional words, the field layout and the package vec4s - let band_values = - |(width, rows, top, left): (u32, u32, u32, u32), [paint_x, paint_y, paint_columns, paint_rows]: [u32; 4], field_rect: [u32; 4], field_base: u32| { - let mut values = [0; packages::UNIFORM_WORDS]; - values[..packages::FIELD_LAYOUT].copy_from_slice(&[ - width, - rows, - top, - area, - source_size.0, - source_size.1, - 1 << shift, - u32::from(program.glossiness), - program.layer_count, - pitch, - program.display_outputs, - left, - u32::from(program.coverage.is_some()), - source_size.0.div_ceil(32), - radius, - u32::from(program.needs_surface) - | (u32::from(program.baked.is_some()) << 1) - | (u32::from(program.brush_stencil.is_some()) << 2) - | (u32::from(!program.geometry.words.is_empty()) << 3), - paint_x, - paint_y, - paint_columns, - paint_rows, - field_rect[0], - field_rect[1], - field_rect[2], - field_rect[3], - field_base, - group_base, - program.groups.words_per_level, - program.groups.channels, - 0, - 0, - field_rect[2], - field_rect[3], - id_width, - id_height, - bake_words[0], - bake_words[1], - 0, - 0, - 0, - program.mask_layer, - 0, - 0, - 0, - 0, - ]); - // Words per field texel and whether the sixth (input) word is present; the - // prepare pass adds its stage's input operation in the third word. - values[packages::FIELD_LAYOUT..packages::FIELD_LAYOUT + 2].copy_from_slice(&[texel_words, u32::from(texel_words > FIELD_WORDS)]); - packages::write_band_uniform(program, &mut values); - values - }; - let make_bindings = |values: &[u32], paint: &wgpu::Buffer| { - let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_composite_band"), - contents: bytemuck::cast_slice(values), - usage: wgpu::BufferUsages::UNIFORM, - }); - let mut entries = [ - wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: ops.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 2, resource: lookup.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 3, resource: scratch.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 4, resource: paint.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 5, resource: coverage.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&surface) }, - wgpu::BindGroupEntry { binding: 7, resource: vertices.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(&baked) }, - wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(brush_alpha) }, - wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(tile_images) }, - wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(&brush_stencil.image) }, - wgpu::BindGroupEntry { binding: 12, resource: brush_stencil.uniforms.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 13, resource: wgpu::BindingResource::TextureView(curvature.as_ref().map_or(&baked, |levels| &levels.image)) }, - wgpu::BindGroupEntry { - binding: 14, - resource: curvature.as_ref().map_or_else(|| lookup.as_entire_binding(), |levels| levels.layout.as_entire_binding()), - }, - wgpu::BindGroupEntry { binding: 15, resource: wgpu::BindingResource::TextureView(id_bake.as_ref().unwrap_or(&baked)) }, - ]; - let mut count = if curvature.is_some() { 15 } else { 13 }; - if id_bake.is_some() { - entries.swap(count, 15); - count += 1; - } - device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_composite_band"), layout: &self.bindings, entries: &entries[..count] }) - }; - let mut packed = Vec::new(); - let mut pending_bytes = 0; - let mut last_submission = None; - let make_encoder = || device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_composite") }); - let submit = |encoder: wgpu::CommandEncoder, bounds: CompositeRegion, submitted: &mut Option| { - let submission = queue.submit([encoder.finish()]); - *submitted = Some(submitted.map_or(bounds, |region| region.union(bounds))); - submission - }; - // The whole-set pre-pass: its stages once over the region the bands read, in stripes, - // one stack after another in the same working space, their outputs copied into the - // results the bands read through `filter_value` - if let (Some(whole), Some(prepare), Some(kernels)) = (&whole, &prepare, &self.filter_gpu) { - let [x0, y0, x1, y1] = whole.region; - let fields = program.filters.stages.len() as u32; - let paint_limit = (max_words * 4) as u64; - // Pack and upload a paint window, after submitting what reads the previous one - let upload = |window: &CompositePaintWindow, - words: usize, - encoder: &mut wgpu::CommandEncoder, - (buffer, packed): (&mut Option, &mut Vec)| { - queue.submit([std::mem::replace(encoder, make_encoder()).finish()]); - window.pack(&program.paint, words, packed); - let bytes = (words * 4) as u64; - let paint = match buffer { - Some(paint) if paint.size() >= bytes => paint, - _ => buffer.insert(device.create_buffer(&wgpu::BufferDescriptor { - label: Some("tc_composite_paint"), - size: bytes.next_power_of_two().min(paint_limit), - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - })), - }; - queue.write_buffer(paint, 0, bytemuck::cast_slice(packed)); - }; - for top in (y0..y1).step_by(whole.stripe_rows as usize) { - let rows = whole.stripe_rows.min(y1 - top); - let mut encoder = make_encoder(); - // One paint window for the stripe when it fits the upload budget, else one per - // source chunk of each stage (a whole-tile stripe reads the whole set) - let (low, high) = whole.paint_window(source_size, top, rows); - let stripe_window = CompositePaintWindow::covering(low, high, [source_size.0, source_size.1], &program.paint); - let paint_words = pre_pass_paint_words(max_words); - let stripe_words = stripe_window.words(&program.paint, paint_words); - if let Some(words) = stripe_words { - upload(&stripe_window, words, &mut encoder, (&mut self.paint_upload, &mut packed)); - } - for pass in &whole.stages.passes { - let field_rect = whole.field_rect(pass, top, rows); - let set_bounds = field_bounds(field_rect, source_size); - let field_words = field_rect[2] * field_rect[3] * texel_words; - let offset = |slot: u32| pass.slot(slot, fields) * field_words; - let values = |paint_params: [u32; 4]| { - let mut values = band_values((0, 0, 0, 0), paint_params, field_rect, 0); - values[packages::WHOLE_COMPACT..packages::WHOLE_COMPACT + 4].copy_from_slice(&pass.compact(fields)); - values - }; - let (source_width, source_rows) = - if tile_work == 0 { (field_rect[2], field_rect[3]) } else { composite_band_size(field_rect[2], tile_work) }; - let mut work = 0u64; - for &output in &pass.stages { - let stage = &program.filters.stages[output]; - // P8: a level stage runs only where a block of its tile scale lies, on its base stage's field - if !udim::runs_over(program.udim_layout.as_ref(), stage.level, field_rect, (source_size, wraps)) { - continue; - } - let reuses_field = udim::reuses_base_field(&program.filters.stages, output); - let direct = stage.filter.is_none() && stage.cell == 1; - let slot = if direct { output as u32 } else { fields }; - let stage_values = |paint_params: [u32; 4]| { - let mut source = values(paint_params); - source[25..28].copy_from_slice(&[slot, stage.layer, stage.preceding]); - source[packages::FIELD_LAYOUT + 2] = stage.input; - source[packages::FIELD_LAYOUT + 3] = u32::from(wraps) | stage.input_kind | stage.view | if stage.input2 != 0 { INPUT2 } else { 0 }; - // A second input source (operation plus one), the mask views - source[38] = stage.input2; - source[packages::MASK_VIEW..packages::MASK_VIEW + 4].copy_from_slice(&stage.mask_view); - source - }; - let source_rows_total = if reuses_field { 0 } else { field_rect[3] }; - let mut chunks: Vec<[u32; 4]> = (0..source_rows_total) - .step_by(source_rows as usize) - .flat_map(|y| { - (0..field_rect[2]) - .step_by(source_width as usize) - .map(move |x| [x, y, source_width.min(field_rect[2] - x), source_rows.min(field_rect[3] - y)]) - }) - .rev() - .collect(); - while let Some(chunk @ [x, y, columns, chunk_rows]) = chunks.pop() { - let paint_params = if stripe_words.is_some() { - stripe_window.params() - } else { - // The chunk's own paint, split in two while it does not fit - let (low, high) = chunk_paint(field_rect, chunk, source_size, wraps); - let window = CompositePaintWindow::covering(low, high, [source_size.0, source_size.1], &program.paint); - let Some(words) = window.words(&program.paint, paint_words) else { - if chunk_rows < 2 { - return Err("Paint inputs of the whole-set filter exceed the adapter's upload budget.".into()); - } - let half = chunk_rows / 2; - chunks.extend([[x, y + half, columns, chunk_rows - half], [x, y, columns, half]]); - continue; - }; - upload(&window, words, &mut encoder, (&mut self.paint_upload, &mut packed)); - #[cfg(all(test, not(target_arch = "wasm32")))] - PRE_PASS_CHUNK_WINDOWS.set(PRE_PASS_CHUNK_WINDOWS.get() + 1); - work = 0; - window.params() - }; - let work_here = u64::from(columns).saturating_mul(u64::from(chunk_rows)).saturating_mul(tile_work); - if work > 0 && work.saturating_add(work_here) > MAX_TILE_WORK_PER_SUBMISSION { - queue.submit([std::mem::replace(&mut encoder, make_encoder()).finish()]); - work = 0; - } - let mut source = stage_values(paint_params); - source[28..32].copy_from_slice(&chunk); - let paint = self.paint_upload.as_ref().ok_or("paint upload buffer is missing")?; - let source_bindings = make_bindings(&source, paint); - let mut compute = - encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_whole_set_source"), timestamp_writes: None }); - compute.set_pipeline(prepare); - compute.set_bind_group(0, &source_bindings, &[]); - compute.dispatch_workgroups(columns.div_ceil(WORKGROUP), chunk_rows.div_ceil(WORKGROUP), 1); - drop(compute); - work = work.saturating_add(work_here); - } - let region = NeighbourhoodRegion { - rect: field_rect, - original: offset(fields), - blur: pass.blur(fields, offset), - output: offset(output as u32), - field_words: texel_words, - input: program.filters.input_bits(stage), - wrap: stage.wrap, - bounds: set_bounds, - }; - // The stage's kernels over the whole field, the gathers in row chunks - // within the submission budget - queue.submit([std::mem::replace(&mut encoder, make_encoder()).finish()]); - work = 0; - if reuses_field && direct { - let field = (field_rect[2], field_rect[3]); - kernels.encode_copy( - device, - &mut encoder, - &scratch, - (region.original, field.0, [0; 2]), - (region.output, field.0, 0), - [field.0, field.1], - texel_words, - ); - } - let _budget = kernels.budget(queue, stage.filter.map_or(1, NeighbourhoodFilter::work_per_texel), pre_pass_budget()); - if stage.cell > 1 { - let target = if stage.filter.is_some() { region.original } else { region.output }; - kernels.encode_cells(device, &mut encoder, &scratch, NeighbourhoodRegion { output: target, ..region }, stage.cell); - } - if let Some(filter) = stage.filter { - kernels.encode(device, &mut encoder, &scratch, region, filter); - } - } - // The stripe's rows of the pass's outputs, from their fields into the results - let from = [(x0 as i32 - field_rect[0] as i32) as u32, (top as i32 - field_rect[1] as i32) as u32]; - for &output in &pass.outputs { - let index = whole.stages.outputs.iter().position(|&own| own == output).ok_or("A whole-set output has no result.")?; - let result = whole.result_base(whole_base, index); - kernels.encode_copy( - device, - &mut encoder, - &scratch, - (offset(output as u32), field_rect[2], from), - (result, x1 - x0, top - y0), - [x1 - x0, rows], - texel_words, - ); - } - queue.submit([std::mem::replace(&mut encoder, make_encoder()).finish()]); - } - } - } - for (chunk, window, words) in windows { - let bytes = (words * 4) as u64; - window.pack(&program.paint, words, &mut packed); - let [paint_x, paint_y, paint_columns, paint_rows] = window.params(); - if pending_bytes + bytes > (max_words * 4) as u64 { - device.poll(wgpu::PollType::Wait { submission_index: last_submission.take(), timeout: None }).map_err(|e| e.to_string())?; - pending_bytes = 0; - } - let upload_size = bytes.next_power_of_two().min((max_words * 4) as u64); - if self.paint_upload.as_ref().is_none_or(|buffer| buffer.size() < bytes) { - self.paint_upload = Some(device.create_buffer(&wgpu::BufferDescriptor { - label: Some("tc_composite_paint"), - size: upload_size, - usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - })); - } - let paint = self.paint_upload.as_ref().ok_or("paint upload buffer is missing")?; - queue.write_buffer(paint, 0, bytemuck::cast_slice(&packed)); - let mut encoder = make_encoder(); - let mut work = 0u64; - let mut bounds: Option = None; - let bands = (chunk.min[1]..chunk.max[1]) - .step_by(band_rows as usize) - .flat_map(|top| (chunk.min[0]..chunk.max[0]).step_by(band_width as usize).map(move |left| (left, top))); - for (left, top) in bands { - let width = band_width.min(chunk.max[0] - left); - let rows = band_rows.min(chunk.max[1] - top); - let source_work = u64::from(width).saturating_mul(u64::from(rows)).saturating_mul(tile_work); - let band_work = source_work.saturating_add(field_area(width, rows).saturating_mul(filter_work)); - if let Some(written) = bounds.take_if(|_| work.saturating_add(band_work) > submit_budget) { - let previous = std::mem::replace(&mut encoder, make_encoder()); - submit(previous, written, submitted); - work = 0; - } - let field = CompositeRegion { min: [left << shift, top << shift], max: [(left + width) << shift, (top + rows) << shift] }.expanded(halo); - let mut field_rect = - [field.min[0], field.min[1], field.max[0].min(source_size.0) - field.min[0], field.max[1].min(source_size.1) - field.min[1]]; - if wraps { - // The whole halo on every side; the origin can lie below zero (i32 bits) - let start = |pixel: u32| (i64::from(pixel << shift) - i64::from(halo)) as i32 as u32; - field_rect = [start(left), start(top), (width << shift).saturating_add(halo * 2), (rows << shift).saturating_add(halo * 2)]; - } - // The set in field-local texels: a stage that does not wrap never reads across its - // edges (the CPU's region stops there), a wrapping one reads the periodic copy - let set_bounds = field_bounds(field_rect, source_size); - let mut values = band_values((width, rows, top, left), [paint_x, paint_y, paint_columns, paint_rows], field_rect, field_base); - if let Some(whole) = &whole { - whole.write_uniform(&mut values, whole_base); - } - let bindings = |values: &[u32]| make_bindings(values, paint); - if let (Some(prepare), Some(kernels)) = (&prepare, &self.filter_gpu) { - let fields = program.filters.stages.len() as u32; - let field_words = field_rect[2] * field_rect[3] * texel_words; - let offset = |slot| field_base + slot * field_words; - let (source_width, source_rows) = - if tile_work == 0 { (field_rect[2], field_rect[3]) } else { composite_band_size(field_rect[2], tile_work) }; - for (output, stage) in program.filters.stages.iter().enumerate() { - // The whole-set pre-pass evaluated this stage for the bands - if whole.as_ref().is_some_and(|whole| whole.stages.stages.contains(&output)) { - continue; - } - // P8: a level stage runs only where a block of its tile scale lies, on its base stage's field - if !udim::runs_over(program.udim_layout.as_ref(), stage.level, field_rect, (source_size, wraps)) { - continue; - } - let reuses_field = udim::reuses_base_field(&program.filters.stages, output); - let mut source = values; - let direct = stage.filter.is_none() && stage.cell == 1; - let slot = if direct { output as u32 } else { fields }; - source[25..28].copy_from_slice(&[slot, stage.layer, stage.preceding]); - source[packages::FIELD_LAYOUT + 2] = stage.input; - // In a wrapping program every stage's field is a periodic copy of the set - // past its edges; the stages keep apart what lies across a seam (`bounds`) - source[packages::FIELD_LAYOUT + 3] = u32::from(wraps) | stage.input_kind | stage.view | if stage.input2 != 0 { INPUT2 } else { 0 }; - // A second input source (operation plus one), the mask views - source[38] = stage.input2; - source[packages::MASK_VIEW..packages::MASK_VIEW + 4].copy_from_slice(&stage.mask_view); - if let Some((channel, first, cut)) = stage.anchor { - source[36..39].copy_from_slice(&[channel_slot(channel), first, cut]); - source[40..43].copy_from_slice(&channel.default_value().map(f32::to_bits)); - } - let source_chunks = if reuses_field { 0 } else { field_rect[3] }; - for y in (0..source_chunks).step_by(source_rows as usize) { - for x in (0..field_rect[2]).step_by(source_width as usize) { - let columns = source_width.min(field_rect[2] - x); - let rows = source_rows.min(field_rect[3] - y); - let work_here = u64::from(columns).saturating_mul(u64::from(rows)).saturating_mul(tile_work); - if work > 0 && work.saturating_add(work_here) > submit_budget { - let previous = std::mem::replace(&mut encoder, make_encoder()); - last_submission = Some(match bounds.take() { - Some(written) => submit(previous, written, submitted), - None => queue.submit([previous.finish()]), - }); - work = 0; - } - source[28..32].copy_from_slice(&[x, y, columns, rows]); - let source_bindings = bindings(&source); - let mut pass = - encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_spatial_source"), timestamp_writes: None }); - pass.set_pipeline(prepare); - pass.set_bind_group(0, &source_bindings, &[]); - pass.dispatch_workgroups(columns.div_ceil(WORKGROUP), rows.div_ceil(WORKGROUP), 1); - work = work.saturating_add(work_here); - } - } - let region = NeighbourhoodRegion { - rect: field_rect, - original: offset(fields), - blur: [offset(fields + 1), offset(fields + 2)], - output: offset(output as u32), - field_words: texel_words, - input: program.filters.input_bits(stage), - wrap: stage.wrap, - bounds: set_bounds, - }; - if reuses_field && direct { - let field = (field_rect[2], field_rect[3]); - kernels.encode_copy( - device, - &mut encoder, - &scratch, - (region.original, field.0, [0; 2]), - (region.output, field.0, 0), - [field.0, field.1], - texel_words, - ); - } - if stage.cell > 1 { - let target = if stage.filter.is_some() { region.original } else { region.output }; - kernels.encode_cells(device, &mut encoder, &scratch, NeighbourhoodRegion { output: target, ..region }, stage.cell); - } - if let Some(filter) = stage.filter { - kernels.encode(device, &mut encoder, &scratch, region, filter); - } - } - } - let bindings = bindings(&values); - { - let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_composite"), timestamp_writes: None }); - pass.set_pipeline(&pipeline); - pass.set_bind_group(0, &bindings, &[]); - pass.dispatch_workgroups(width.div_ceil(WORKGROUP), rows.div_ceil(WORKGROUP), 1); - } - for (texture, copy) in textures.iter().copied().zip(copies) { - let Some((offset, bytes_per_texel)) = copy else { continue }; - encoder.copy_buffer_to_texture( - wgpu::TexelCopyBufferInfo { - buffer: &scratch, - layout: wgpu::TexelCopyBufferLayout { offset: stride * offset, bytes_per_row: Some(pitch * bytes_per_texel), rows_per_image: None }, - }, - wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: left, y: top, z: 0 }, ..texture.as_image_copy() }, - wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 }, - ); - } - let band = CompositeRegion { min: [left, top], max: [left + width, top + rows] }; - bounds = Some(bounds.map_or(band, |region| region.union(band))); - work = work.saturating_add(band_work); - } - if let Some(written) = bounds { - last_submission = Some(submit(encoder, written, submitted)); - } - pending_bytes += bytes; - } - self.update_bytes[1] = self.paint_upload.as_ref().map_or(0, wgpu::Buffer::size); - Ok(()) - } - - /// Whether `program`'s pipelines are compiled; starts compiling them otherwise (on worker - /// threads when [`Self::set_asynchronous_compile`] is on). An error when their compile failed. - pub(crate) fn pipelines_ready(&mut self, device: &wgpu::Device, program: &CompositeProgram) -> Result { - Ok(self.pipelines().get(device, &self.pipeline_layout, program, self.asynchronous)?.is_some()) - } - - /// Start compiling `program`'s pipelines on worker threads without compositing. - pub(crate) fn prewarm(&mut self, device: &wgpu::Device, program: &CompositeProgram) { - self.pipelines().prewarm(device, &self.pipeline_layout, program); - } - - /// Compile new pipelines on worker threads (the app's viewport) or in place (tests, wasm). - pub(crate) fn set_asynchronous_compile(&mut self, asynchronous: bool) { - self.asynchronous = asynchronous && !cfg!(target_arch = "wasm32"); - } - - fn pipelines(&self) -> std::sync::MutexGuard<'_, CompositePipelines> { - self.pipelines.lock().unwrap_or_else(std::sync::PoisonError::into_inner) - } - - /// Bytes of the last update's working buffer and paint upload buffer. - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) fn update_bytes(&self) -> [u64; 2] { - self.update_bytes - } -} - /// What `Renderer::composite_on_gpu` answers while a new program's pipelines compile on worker /// threads: neither a failure nor a reason for the CPU; the viewport keeps its last result and /// asks again. @@ -3986,6 +1006,7 @@ fn pre_pass_budget() -> u64 { if let Some(budget) = PRE_PASS_TEST_BUDGET.get() { return budget; } + MAX_TILE_WORK_PER_SUBMISSION } @@ -3995,6 +1016,7 @@ fn pre_pass_paint_words(max_words: usize) -> usize { if let Some(words) = PRE_PASS_TEST_PAINT_WORDS.get() { return words; } + max_words } @@ -4008,133 +1030,10 @@ thread_local! { pub(crate) static PRE_PASS_CHUNK_WINDOWS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// A later user-set limit on the GPU memory one update of the compositor may hold (bytes). -/// None: the adapter's reported limits alone (the default). -fn user_memory_limit() -> Option { - None -} - -/// The bytes the working buffer of an update may take: the adapter's binding and buffer limits, -/// the shaders' 32-bit word addressing (16 GiB), and a user-set memory limit less the `live` -/// bytes of the update's other buffers. -fn scratch_limit(limits: &wgpu::Limits, live: u64) -> u64 { +/// Bound scratch by the adapter limits and the shader's 32-bit word addressing. +fn scratch_limit(limits: &wgpu::Limits) -> u64 { let addressable = (u64::from(u32::MAX) + 1) * 4; - let limit = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size).min(addressable); - user_memory_limit().map_or(limit, |memory| limit.min(memory.saturating_sub(live))) -} - -/// The whole-set pre-pass of one update ([`FilterPlan::whole_set`]): the region of results the -/// bands read (source texels [x0, y0, x1, y1]: the update plus the bands' halo, a whole axis -/// where a wrapping program crosses the set's edge) and the stripes it is evaluated in. -struct WholeSetPass { - stages: WholeSet, - region: [u32; 4], - size: (u32, u32), - wraps: bool, - texel_words: u32, - /// The program's stage count: its first working field's slot - fields: u32, - stripe_rows: u32, -} - -impl WholeSetPass { - fn plan(stages: WholeSet, (region, shift): (CompositeRegion, u32), size: (u32, u32), halo: u32, wraps: bool, texel_words: u32, stage_count: usize) -> Self { - let axis = |min: u32, max: u32, side: u32| { - let (low, high) = ((min << shift).saturating_sub(halo), (max << shift).saturating_add(halo)); - if wraps && ((min << shift) < halo || high > side) { [0, side] } else { [low, high.min(side)] } - }; - let [x0, x1] = axis(region.min[0], region.max[0], size.0); - let [y0, y1] = axis(region.min[1], region.max[1], size.1); - Self { region: [x0, y0, x1, y1], size, wraps, texel_words, fields: stage_count as u32, stripe_rows: (y1 - y0).max(1), stages } - } - - fn result_words(&self) -> u64 { - let [x0, y0, x1, y1] = self.region; - u64::from(x1 - x0) * u64::from(y1 - y0) * u64::from(self.texel_words) - } - - fn result_bytes(&self) -> u64 { - self.result_words() * self.stages.outputs.len() as u64 * 4 - } - - /// First word of output `index`'s results, after the working space ending at word `base`. - fn result_base(&self, base: u32, index: usize) -> u32 { - (u64::from(base) + self.result_words() * index as u64) as u32 - } - - /// The field of `pass` for the stripe of `rows` from row `top`: the pass's reach on every - /// side, clamped to the set, or in a wrapping program to the set plus how far the pass's - /// fields reach past its edges (origin as i32 bits). - fn field_rect(&self, pass: &WholePass, top: u32, rows: u32) -> [u32; 4] { - let [x0, _, x1, _] = self.region; - let (left, right) = self.span(pass, x0, x1, self.size.0); - let (upper, lower) = self.span(pass, top, top + rows, self.size.1); - [left as i32 as u32, upper as i32 as u32, (right - left) as u32, (lower - upper) as u32] - } - - /// `low..high` plus the pass's reach on both sides, clamped to the set (`side`) widened by - /// the pass's reach past the edges in a wrapping program (periodic copies there). - fn span(&self, pass: &WholePass, low: u32, high: u32, side: u32) -> (i64, i64) { - let reach = i64::from(pass.reach); - let past = if self.wraps { i64::from(pass.past_edges) } else { 0 }; - ((i64::from(low) - reach).max(-past), (i64::from(high) + reach).min(i64::from(side) + past)) - } - - /// Bytes of the largest stripe's fields: the largest pass's slots over the stripe plus its - /// reach, as `field_rect` clamps it. - fn stripe_bytes(&self) -> u64 { - let [x0, _, x1, _] = self.region; - self.stages - .passes - .iter() - .map(|pass| { - let (left, right) = self.span(pass, x0, x1, self.size.0); - let past = if self.wraps { u64::from(pass.past_edges) } else { 0 }; - let rows = (u64::from(self.stripe_rows) + 2 * u64::from(pass.reach)).min(u64::from(self.size.1) + 2 * past); - (right - left) as u64 * rows * pass.slots(self.fields) * u64::from(self.texel_words) * 4 - }) - .max() - .unwrap_or(0) - } - - /// The tallest stripes whose fields fit in `limit` bytes beside the results. - fn with_stripes(mut self, limit: u64) -> Result { - while self.stripe_bytes() > limit { - if self.stripe_rows <= 1 { - return Err("A whole-set filter's stripe exceeds the adapter's working memory limit.".into()); - } - self.stripe_rows = self.stripe_rows.div_ceil(2); - } - Ok(self) - } - - /// The paint the stripe of `rows` from `top` reads: the stripe plus the pre-pass reach, the - /// whole axis where a wrapping program crosses the set's edge. - fn paint_window(&self, size: (u32, u32), top: u32, rows: u32) -> ([u32; 2], [u32; 2]) { - let reach = self.stages.reach; - let [x0, _, x1, _] = self.region; - let (y0, y1) = (top, top + rows); - let axis = |low: u32, high: u32, side: u32| { - if self.wraps && (low < reach || high.saturating_add(reach) > side) { - (0, side) - } else { - (low.saturating_sub(reach), high.saturating_add(reach).min(side)) - } - }; - let ((left, right), (upper, lower)) = (axis(x0, x1, size.0), axis(y0, y1, size.1)); - ([left, upper], [right, lower]) - } - - /// The band uniform's whole-set table: each output's slot plus one, its first word, the region. - fn write_uniform(&self, values: &mut [u32; packages::UNIFORM_WORDS], base: u32) { - let table = &mut values[packages::WHOLE_SET..packages::WHOLE_SET + 12]; - for (entry, &index) in self.stages.entries.iter().enumerate() { - table[entry] = self.stages.outputs[index] as u32 + 1; - table[4 + entry] = self.result_base(base, index); - } - let [x0, y0, x1, y1] = self.region; - table[8..].copy_from_slice(&[x0, y0, x1 - x0, y1 - y0]); - } + limits.max_storage_buffer_binding_size.min(limits.max_buffer_size).min(addressable) } /// The source texels [low, high) a prepare chunk `[x, y, columns, rows]` of a pre-pass field at @@ -4148,10 +1047,12 @@ fn chunk_paint(field_rect: [u32; 4], [x, y, columns, rows]: [u32; 4], size: (u32 if !wraps { return (low.clamp(0, side) as u32, high.clamp(0, side) as u32); } + let copy = low.div_euclid(side); if (high - 1).div_euclid(side) != copy { return (0, side as u32); } + ((low - copy * side) as u32, (high - copy * side) as u32) }; let (left, right) = axis(field_rect[0], x, columns, size.0); @@ -4172,12 +1073,14 @@ fn check_texel_work(work_per_pixel: u64) -> Result<(), &'static str> { if work_per_pixel > MAX_TILE_WORK_PER_BAND { return Err("The fill work of one texel exceeds what a GPU dispatch may hold."); } + Ok(()) } fn composite_band_size(width: u32, tile_work_per_pixel: u64) -> (u32, u32) { let texels = MAX_TILE_WORK_PER_BAND / tile_work_per_pixel.max(1); - // Leave room for a full workgroup of rows when a costly pattern needs narrower bands. + + // Leave room for a full workgroup of rows when a costly pattern needs narrower bands let width = width.min((texels / u64::from(WORKGROUP)).max(1) as u32); let rows = (texels / u64::from(width)).clamp(1, u64::from(ROWS)) as u32; (width, rows) @@ -4210,6 +1113,7 @@ fn paint_windows( windows.push((chunk, window, words)); continue; } + let width = chunk.max[0] - chunk.min[0]; let height = chunk.max[1] - chunk.min[1]; let axis = usize::from(height >= width); @@ -4217,6 +1121,7 @@ fn paint_windows( if length < 2 { return Err("Paint inputs for one GPU texel exceed the adapter's upload budget".into()); } + let mut first = chunk; let mut second = chunk; let middle = chunk.min[axis] + length / 2; @@ -4321,7 +1226,7 @@ mod procedural_tests { }; let mut oracle = Composite::new(&channels, SIZE); composite_tiles(&inputs, &mut oracle, &[(0, 0)]); - let expected = tile_bytes(&oracle, &baked, DisplayKind::BaseColor, 0, 0); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((SIZE, SIZE), 0)], 1); let mut program = CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); @@ -4420,7 +1325,7 @@ mod procedural_tests { program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); for kind in [DisplayKind::BaseColor, DisplayKind::Orm] { - let expected = tile_bytes(&cpu, &baked, kind, 0, 0); + let expected = tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0); let texture = gpu.renderer.display_textures()[0][kind as usize]; let (_, _, actual) = Readback::blocking(&gpu.device, &gpu.queue, texture).unwrap(); for (part, texel) in probes.into_iter().enumerate() { @@ -4620,7 +1525,7 @@ mod procedural_tests { program.set_tile_images(&images); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); for kind in [DisplayKind::BaseColor, DisplayKind::Height] { - let expected = tile_bytes(&cpu, &baked, kind, 0, 0); + let expected = tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0); let texture = gpu.renderer.display_textures()[0][kind as usize]; let (_, _, actual) = Readback::blocking_level(&gpu.device, &gpu.queue, texture, 0).unwrap(); assert_eq!(actual.len(), expected.len()); @@ -4667,6 +1572,7 @@ mod procedural_tests { Filter::SlopeBlur { radius: 64.0, scale: 6.0, seed: 11, divider: 1 }, Filter::Mosaic { size: 64.0, alpha: true }, ]; + // A filter set to Disable leaves content alone; a mask filter applies whatever its blend let cases = filters.into_iter().map(|filter| (filter, BlendMode::Normal, BlendMode::Normal)).chain([ (Filter::Blur { radius: 64.0, wrap: false }, BlendMode::Replace, BlendMode::Normal), @@ -4719,13 +1625,14 @@ mod procedural_tests { composite_tiles(&inputs, &mut oracle, &tiles); let mut program = CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); + // A disabled content filter is no stage assert_eq!(program.filters.stages.len(), if effect_blend == BlendMode::Disable { 3 } else { 4 }); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); let texture = gpu.renderer.display_textures()[0][DisplayKind::BaseColor as usize]; let (_, _, full) = Readback::blocking(&gpu.device, &gpu.queue, texture).unwrap(); for (tx, ty) in tiles { - let expected = tile_bytes(&oracle, &baked, DisplayKind::BaseColor, tx, ty); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, tx, ty); for (y, row) in expected.as_chunks::<{ (TILE * 4) as usize }>().0.iter().enumerate() { let start = ((ty * TILE + y as u32) * SIZE * 4 + tx * TILE * 4) as usize; let actual = &full[start..start + row.len()]; @@ -4820,10 +1727,12 @@ mod procedural_tests { use texturecraft_core::{TileGenerator, TileSizeMode}; let Ok(mut gpu) = Headless::new() else { return }; + // About 39 G placements: seconds on a GPU, far longer on a software rasterizer if gpu.device.adapter_info().device_type == wgpu::DeviceType::Cpu { return; } + const SIZE: u32 = 4096; let overlapping = TileGenerator { amount: [12, 8], size_mode: TileSizeMode::Absolute, size_absolute: [1.0; 2], ..TileGenerator::default() }; let mut project = Project::new("Costly fill", "builtin:plane"); @@ -4851,10 +1760,7 @@ mod procedural_tests { eprintln!("4K fill of {work} per texel: {:?}", started.elapsed()); } - // The CPU fallback tables of the GPU port live with each package (`still_on_cpu` in - // gpu_composite_point.rs, gpu_composite_stack.rs, gpu_composite_lighting.rs, - // gpu_neighbourhood_box.rs, gpu_neighbourhood_gather.rs, …); the stacks that must stay on the - // GPU are checked in gpu_composite_packages.rs. + // Per-package fallback tests complement the rendering assertions in gpu_composite_packages #[test] fn point_filters_match_cpu_for_material_channels_and_mask_preview() { @@ -4903,10 +1809,12 @@ mod procedural_tests { Filter::InvertOff, Filter::Empty, ]; + // Levels from older saves clamp; new ones keep values outside the input range on the line through it let levels = |clamp| Levels { in_low: 0.38, in_high: 0.52, gamma: 1.6, out_low: 0.1, out_high: 0.85, affects: None, clamp }; let kinds = filters.into_iter().map(EffectKind::Filter).chain([EffectKind::Levels(levels(true)), EffectKind::Levels(levels(false))]); gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((SIZE, SIZE), 0)], 1); + // Each once more set to Disable: content filters then change nothing, mask filters apply anyway for (filter, disabled) in kinds.flat_map(|kind| [(kind.clone(), false), (kind, true)]) { let mut project = Project::new("Point filters", "builtin:plane"); @@ -4950,7 +1858,7 @@ mod procedural_tests { material.set_surface_inputs(&mesh, &gbuf, Some(&baked)).unwrap(); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &material).unwrap(); for kind in [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Height, DisplayKind::Normal] { - let expected = tile_bytes(&oracle, &baked, kind, 0, 0); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0); let texture = gpu.renderer.display_textures()[0][kind as usize]; let (_, _, actual) = Readback::blocking_level(&gpu.device, &gpu.queue, texture, 0).unwrap(); assert_eq!(actual.len(), expected.len()); @@ -5036,7 +1944,7 @@ mod procedural_tests { }; let mut oracle = Composite::new(&[color], SIZE); composite_tiles(&inputs, &mut oracle, &[(0, 0)]); - let expected = tile_bytes(&oracle, baked, DisplayKind::BaseColor, 0, 0); + let expected = tile_bytes(&oracle, baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); let mut program = CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, Some(baked)).unwrap(); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); @@ -5135,7 +2043,7 @@ mod procedural_tests { let (_, _, actual) = Readback::blocking(&gpu.device, &gpu.queue, texture).unwrap(); let bytes = kind.bytes_per_texel(); for &(x, y) in &tiles { - let expected = tile_bytes(&oracle, &baked, kind, x, y); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, kind, x, y); for (row, expected) in expected.chunks_exact(TILE as usize * bytes).enumerate() { let offset = ((y * TILE + row as u32) * SIZE + x * TILE) as usize * bytes; let actual = &actual[offset..offset + expected.len()]; @@ -5277,7 +2185,7 @@ mod procedural_tests { }; let mut oracle = Composite::new(&channels, SIZE); composite_tiles(&inputs, &mut oracle, &[(0, 0)]); - let expected = tile_bytes(&oracle, &baked, DisplayKind::BaseColor, 0, 0); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); let mut program = CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); @@ -5305,6 +2213,7 @@ mod procedural_tests { for (&expected, &[r, g, b, a]) in expected.iter().zip(actual.as_chunks::<4>().0) { assert!(r.abs_diff(expected) <= 1 && r == g && r == b && a == 255, "mask: {op:?} {value} ± {tolerance}"); } + // The comparison multiplies: a pass keeps the fill's 0.375, a fail halves it at opacity 0.5 assert_eq!(expected[shared], if passes { 96 } else { 48 }); assert_eq!(expected[shared], expected[layer_only]); @@ -5339,8 +2248,7 @@ mod procedural_tests { let group = |id, name| Layer::new(id, name, LayerKind::folder(), &channels); let mut folder = group(outer, "Masked folder"); for blend in folder.channels.values_mut() { - // The CPU uses the group's channel opacity with the completed inner - // stack. Modes other than Disable do not blend it a second time. + // Apply group opacity once to the completed inner stack blend.mode = BlendMode::Screen; blend.opacity = 0.68; } @@ -5395,7 +2303,7 @@ mod procedural_tests { gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((SIZE, SIZE), 0)], 1); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); for kind in [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Normal, DisplayKind::Height] { - let expected = tile_bytes(&oracle, &baked, kind, 0, 0); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0); let texture = gpu.renderer.display_textures()[0][kind as usize]; let (_, _, actual) = Readback::blocking_level(&gpu.device, &gpu.queue, texture, 0).unwrap(); assert_eq!(actual.len(), expected.len()); @@ -5446,7 +2354,7 @@ mod procedural_tests { layer.content_effects.push(Effect::new(project.alloc_id(), EffectKind::Filter(filter))); project.insert_layer(0, layer, None, false).unwrap(); - // The gutter is in a different baked AO cell from its covered source. + // The gutter is in a different baked AO cell from its covered source let ao = BakedMaps { resolution: 4, maps: BTreeMap::from([(BakedMap::AmbientOcclusion, Arc::new([0.05, 0.6, 0.4, 0.2].repeat(4)))]) }; let empty = BakedMaps::default(); let pixels = PixelStore::default(); @@ -5468,8 +2376,8 @@ mod procedural_tests { }; let mut oracle = Composite::new(&channels, SIZE); composite_tiles(&inputs, &mut oracle, &[(0, 0)]); - pad_tiles(&mut oracle, &padding, &[(0, 0)]); - let expected = tile_bytes(&oracle, inputs.baked, DisplayKind::BaseColor, 0, 0); + pad_tiles(&mut oracle, &texturecraft_compose::PaddingMaps::from_flat(padding.clone()), &[(0, 0)]); + let expected = tile_bytes(&oracle, inputs.baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); let mut program = CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, baked).unwrap(); @@ -5484,6 +2392,82 @@ mod procedural_tests { assert!(reds[0] > reds[1], "missing AO leaves the ambient light at full strength in the gutter"); } + #[test] + fn coverage_upload_rejects_an_incomplete_final_row() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mesh = primitives::plane(1.0, 1); + let mut grid = UvGBuffer::new(&mesh, 0, 33, 2); + grid.tri.pop(); + let mut compositor = GpuCompositor::new(&gpu.device); + + let result = compositor.coverage_buffer(&gpu.device, Some(&Arc::new(grid))); + + assert!(result.is_err()); + } + + #[test] + fn dropping_sets_and_curvature_readers_releases_gpu_inputs() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let (device, queue) = (&gpu.device, &gpu.queue); + let mut compositor = GpuCompositor::new(device); + let mesh = Arc::new(primitives::plane(1.0, 1)); + let grids = [128, 256].map(|side| Arc::new(UvGBuffer::new(&mesh, 0, side, side))); + for grid in &grids { + compositor.coverage_buffer(device, Some(grid)).unwrap(); + } + + let coverage_bytes = |compositor: &GpuCompositor| compositor.coverage.iter().map(|(_, buffer)| buffer.size()).sum::(); + let coverage_before = coverage_bytes(&compositor); + drop(grids); + compositor.retain_texture_sets(0); + let coverage_after = coverage_bytes(&compositor); + + const BAKE_SIDE: u32 = 512; + let baked = BakedMaps { resolution: BAKE_SIDE, maps: BTreeMap::from([(BakedMap::Curvature, Arc::new(vec![0.5; (BAKE_SIDE * BAKE_SIDE) as usize]))]) }; + let mut project = Project::new("Curvature ownership", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 128)); + let mut programs = [128, 256].map(|side| { + let mut program = CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap(); + let grid = Arc::new(UvGBuffer::new(&mesh, 0, side, side)); + program.needs_surface = true; + program.curvature_sizes.fill(true); + program.set_surface_inputs(&mesh, &grid, Some(&baked)).unwrap(); + program + }); + for (set, program) in programs.iter().enumerate() { + let view = compositor.baked_input(device, queue, set, program.baked.as_ref()).unwrap(); + compositor.curvature_inputs(device, queue, set, program, &view).unwrap(); + } + + let curvature_bytes = |compositor: &GpuCompositor| { + compositor + .curvature + .as_ref() + .unwrap() + .cache + .values() + .map(|cache| { + let texture = cache.levels.image.texture(); + u64::from(texture.width()) * u64::from(texture.height()) * size_of::() as u64 + cache.levels.layout.size() + }) + .sum::() + }; + let curvature_before = curvature_bytes(&compositor); + for (set, program) in programs.iter_mut().enumerate() { + program.curvature_sizes.fill(false); + let view = compositor.baked_input(device, queue, set, program.baked.as_ref()).unwrap(); + compositor.curvature_inputs(device, queue, set, program, &view).unwrap(); + } + + let curvature_after = curvature_bytes(&compositor); + eprintln!( + "GPU adapter {:?}, retained coverage buffer bytes {coverage_before} -> {coverage_after}, derived curvature bytes {curvature_before} -> {curvature_after}", + device.adapter_info() + ); + assert!(coverage_before > 0 && curvature_before > 0); + assert_eq!((coverage_after, curvature_after), (0, 0), "unused GPU buffer and texture owners must be released"); + } + #[test] fn narrow_gpu_generator_ramp_preserves_baked_scalar_precision() { use texturecraft_compose::eval::{Inputs, mask_image}; @@ -5559,8 +2543,8 @@ mod procedural_tests { let pixels = PixelStore::default(); let images = ImageStore::default(); gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((SIZE, SIZE), 0)], 1); - // Changing the mode or generator shares the blurred bake. Removing the bake - // at the end must go back to neutral curvature even after these cached reads. + + // Removing a shared bake must also retire its cached curvature for bake in [&baked, &absent] { for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] { let mut mode_checks = Vec::new(); @@ -5915,7 +2899,7 @@ mod procedural_tests { program.set_surface_inputs(&mesh, &gbuf, Some(&baked)).unwrap(); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); for kind in [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Height, DisplayKind::Normal] { - let expected = tile_bytes(&cpu, &baked, kind, 0, 0); + let expected = tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0); let texture = gpu.renderer.display_textures()[0][kind as usize]; let (_, _, actual) = Readback::blocking_level(&gpu.device, &gpu.queue, texture, 0).unwrap(); assert_eq!(actual.len(), expected.len()); @@ -5978,6 +2962,7 @@ mod paint_window_tests { id_bake: None, display_outputs: 0, glossiness: false, + mix_baked_ao: false, mask_preview: false, mask_layer: 0, mask_layers: Vec::new(), diff --git a/crates/render/src/gpu_composite/anchor_inputs.rs b/crates/render/src/gpu_composite/anchor_inputs.rs new file mode 100644 index 00000000..1cf988c0 --- /dev/null +++ b/crates/render/src/gpu_composite/anchor_inputs.rs @@ -0,0 +1,30 @@ +use super::{BTreeMap, Channel, LayerId}; + +#[derive(Default)] +pub(super) struct AnchorInputs { + pub(super) visible: BTreeMap, + pub(super) reads: Vec<(u32, Channel)>, + pub(super) draw_ranges: Vec>, + pub(super) next: u32, +} + +impl AnchorInputs { + pub(super) fn publish(&mut self, id: LayerId, mask: bool) -> u32 { + let publish = self.next; + self.next += 1; + self.visible.insert(id, (publish, mask)); + publish + } + + pub(super) fn read(&mut self, id: LayerId, channel: Channel) -> (u32, bool) { + let Some(&(publish, mask)) = self.visible.get(&id) else { return (0, false) }; + let channel = if mask { Channel::BaseColor } else { channel }; + let read = (publish, channel); + let index = self.reads.iter().position(|existing| *existing == read).unwrap_or_else(|| { + let index = self.reads.len(); + self.reads.push(read); + index + }); + (index as u32 + 1, mask) + } +} diff --git a/crates/render/src/gpu_composite/bake_cache.rs b/crates/render/src/gpu_composite/bake_cache.rs new file mode 100644 index 00000000..851dea89 --- /dev/null +++ b/crates/render/src/gpu_composite/bake_cache.rs @@ -0,0 +1,8 @@ +use super::Weak; + +pub(super) struct BakeCache { + pub(super) size: (u32, u32), + /// The built-in maps, then the second row block's + pub(super) maps: Vec>>>, + pub(super) view: wgpu::TextureView, +} diff --git a/crates/render/src/gpu_composite/baked_inputs.rs b/crates/render/src/gpu_composite/baked_inputs.rs new file mode 100644 index 00000000..d9e297e5 --- /dev/null +++ b/crates/render/src/gpu_composite/baked_inputs.rs @@ -0,0 +1,85 @@ +use super::{Arc, BAKE_MAPS, BAKE_ROW_MAPS, BakedMap, BakedMaps, SEPARATE_MAPS, SEPARATE_ORDER}; + +#[derive(Debug)] +pub(super) struct BakedInputs { + pub(super) width: u32, + /// The maps' common height; with maps of different heights ([`Self::separate`]) the + /// Curvature's, else the first baked map's + pub(super) height: u32, + pub(super) maps: [Option>>; BAKE_MAPS.len()], + /// The second row block's maps ([`BAKE_ROW_MAPS`]), only in programs that read them + pub(super) rows: [Option>>; BAKE_ROW_MAPS.len()], + /// P8: each map's height in texels, [`BAKE_MAPS`] then [`BAKE_ROW_MAPS`] (0 where not baked) + pub(super) heights: [u32; SEPARATE_MAPS], +} + +impl BakedInputs { + /// The bakes a program reads: the built-in maps, and with `rows` the second row block's. Maps + /// of different heights each keep their own (P8, [`Self::separate`]). + pub(super) fn new(baked: &BakedMaps, rows: bool) -> Result, &'static str> { + let present = |map: &BakedMap| baked.maps.get(map).filter(|data| !data.is_empty()).cloned(); + let maps = BAKE_MAPS.map(|map| present(&map)); + let rows = BAKE_ROW_MAPS.map(|map| present(&map).filter(|_| rows)); + let all = BAKE_MAPS.iter().zip(&maps).chain(BAKE_ROW_MAPS.iter().zip(&rows)); + let Some(first) = all.clone().find_map(|(&map, data)| data.as_ref().map(|_| map)) else { return Ok(None) }; + if baked.resolution == 0 || all.clone().any(|(&map, data)| data.is_some() && baked.height(map) == 0) { + return Err("A baked map has no whole row of texels and uses CPU compositing."); + } + + let mut heights = [0; SEPARATE_MAPS]; + for (height, (&map, data)) in heights.iter_mut().zip(all) { + *height = if data.is_some() { baked.height(map) } else { 0 }; + } + let curvature = baked.height(BakedMap::Curvature); + let height = if maps[2].is_some() && curvature != 0 { curvature } else { baked.height(first) }; + Ok(Some(Self { width: baked.resolution, height, maps, rows, heights })) + } + + /// Row blocks of the bake texture: the built-in maps', and the second block's when a map of it is baked + pub(super) fn blocks(&self) -> u32 { + if self.rows.iter().any(Option::is_some) { 2 } else { 1 } + } + + /// The band uniform's bake words (`params.id_bake.zw`): rows per block (0: one block, the + /// whole texture; the Curvature's rows with maps of different heights) and the second + /// block's presence bits + pub(super) fn uniform_words(&self) -> [u32; 2] { + let present = self.rows.iter().enumerate().filter(|(_, data)| data.is_some()).fold(0, |bits, (index, _)| bits | 1 << index); + [if self.blocks() > 1 || self.separate() { self.height } else { 0 }, present] + } + + /// P8: whether the baked maps have different heights. Each height's maps then take rows of + /// their own, with a header row after them ([`Self::separate_layout`]). + pub(super) fn separate(&self) -> bool { + let mut heights = self.heights.iter().filter(|&&height| height != 0); + let first = heights.next(); + heights.any(|height| Some(height) != first) + } + + /// P8: the rows of baked maps of different heights: each map's first row and height + /// ([`BAKE_MAPS`] then [`BAKE_ROW_MAPS`], no rows where not baked), and the header row after + /// them. The built-in maps of one height share rows, the row maps of one height too. + pub(super) fn separate_layout(&self) -> ([[u32; 2]; SEPARATE_MAPS], u32) { + let mut groups: Vec<((bool, u32), u32)> = Vec::new(); + let mut next = 0u32; + let mut entries = [[0; 2]; SEPARATE_MAPS]; + for index in SEPARATE_ORDER { + let height = self.heights[index]; + if height == 0 { + continue; + } + + let key = (index >= BAKE_MAPS.len(), height); + let first = match groups.iter().find(|(group, _)| *group == key) { + Some(&(_, first)) => first, + None => { + groups.push((key, next)); + next = next.saturating_add(height); + next - height + } + }; + entries[index] = [first, height]; + } + (entries, next) + } +} diff --git a/crates/render/src/gpu_composite/composite_program.rs b/crates/render/src/gpu_composite/composite_program.rs new file mode 100644 index 00000000..8edd6df9 --- /dev/null +++ b/crates/render/src/gpu_composite/composite_program.rs @@ -0,0 +1,650 @@ +#[cfg(all(test, not(target_arch = "wasm32")))] +use super::INPUT_LAYER; + +use super::{ + ANCHOR_PUBLISH_LAYER, ANCHOR_PUBLISH_MASK, Arc, BEGIN_GROUP, BTreeMap, BakedInputs, BakedMaps, BlendMode, COLOR_SELECTION_OPCODE, Channel, CompositeRegion, + ContentsOffset, CurvatureDetail, DisplayKind, END_GROUP, Effect, EffectKind, EnvironmentSh, FilterPlan, GeometryMasks, GpuStencil, GroupPlan, IdBake, + ImageStore, LOOKUP_WORDS, LateEnvironment, LayerId, LayerKind, LiveBrush, MaterialImages, Mesh, NO_TRI, NOOP_EFFECT_OPCODE, Operation, PaintInputs, + PixelStore, ProceduralInputs, Project, Source, StackWork, TILE_GENERATOR_OPCODE, TileImage, TilePatterns, UvGBuffer, Zeroable, bind_generator_sources, + bind_input_sources, bind_tile_source, blend_code, blends_per_channel, channel_filter, channel_slot, compile_mask, content_depends_on_channel, + content_deposit, content_filter, content_paint, display_bit, fill_projection, groups, needs_surface, packages, placed, register_decal, source_operation, + sparse_channel, stack, udim, +}; + +#[derive(Debug)] +pub struct CompositeProgram { + pub(super) operations: Vec, + pub(super) layer_count: u32, + pub(super) filters: FilterPlan, + pub(super) groups: GroupPlan, + pub(super) geometry: GeometryMasks, + pub(super) paint: Vec, + pub(super) ramp_words: Vec, + pub(super) curvature_sizes: [bool; CurvatureDetail::BLURRED_SIZES], + pub(super) tile_patterns: TilePatterns, + pub(super) material_images: MaterialImages, + pub(super) brush_alpha: Option, + pub(super) brush_stencil: Option, + pub(crate) region: Option, + pub(super) coverage: Option<(Arc, u32)>, + pub(super) surface: Option<(Arc, Arc)>, + pub(super) needs_surface: bool, + pub(super) baked: Option, + pub(super) id_bake: Option, + pub(super) display_outputs: u32, + pub(super) glossiness: bool, + pub(super) mix_baked_ao: bool, + pub(super) mask_preview: bool, + pub(super) mask_layer: u32, + /// The first operation of each draw of a layer with a mask, with the draw's placement + pub(super) mask_layers: Vec<(LayerId, ContentsOffset, u32)>, + /// Side-table words to fill with image record offsets at upload (`ProceduralInputs::pack_image`) + pub(super) image_words: Vec<(u32, u32)>, + /// The environment's diffuse light the program reads (`ProceduralInputs::reserve_environment`) + pub(super) environment: Option, + /// Upload the second bake row block (`ProceduralInputs::read_bake_rows`) + pub(super) bake_rows: bool, + /// P8: the side-table record of a UV tile atlas (`udim::bind`), 0 for a classic set + pub(super) udim: u32, + /// P8: the UV tile atlas's blocks, which say where a level stage has texels to filter + pub(super) udim_layout: Option, +} + +impl CompositeProgram { + pub fn is_neutral(&self) -> bool { + !self.mask_preview + && !self.glossiness + && self.layer_count == 0 + && self.baked.as_ref().is_none_or(|baked| baked.maps[0].is_none() && baked.maps[1].is_none()) + } + + pub fn is_mask_preview(&self) -> bool { + self.mask_preview + } + + /// Work per output texel that sizes bands and submissions: Tile Generator placements per + /// plane and sample, and what P1 declares for its fills (`fill_projection::work_per_texel`: + /// symmetry copies times sampling cost). + pub(super) fn tile_work_per_pixel(&self) -> Result { + self.operations.iter().try_fold(0u64, |work, op| { + let mut own = 0; + if op.ids[1] == TILE_GENERATOR_OPCODE { + let tile_work = self.tile_patterns.work_per_sample(op.high[3] as usize).ok_or("A Tile Generator operation has no settings.")?; + let planes = if op.procedural[3] == 1 { 3 } else { 1 }; + let samples = if op.procedural[0] == 0 { 1 } else { 4 }; + own = tile_work.saturating_mul(planes * samples); + } + Ok(work.saturating_add(fill_projection::work_per_texel(op, own))) + }) + } + + pub(crate) fn writes_display(&self, kind: DisplayKind) -> bool { + self.display_outputs & display_bit(kind) != 0 + } + + /// Let the shader sample the nearest covered UV texel for island padding. + pub fn set_coverage(&mut self, coverage: Arc, radius: u32) { + self.coverage = Some((coverage, if self.mask_preview { 0 } else { radius.min(15) })); + } + + /// Resolve named images used by authored fills, decals and Tile Generators, and the + /// environment's diffuse light (an imported environment is an image). + pub fn set_tile_images(&mut self, images: &ImageStore) { + self.tile_patterns.set_images(images); + self.material_images.set_images(images); + if let Some(environment) = &mut self.environment { + environment.set(&EnvironmentSh::of(&environment.display, images)); + } + } + + /// The environment and rotation (degrees) the program lights with, from the compiled + /// project's display settings; None when nothing reads the environment. A viewport compiles + /// again when either changes (or the imported environment image does). + pub fn environment(&self) -> Option<(&str, f32)> { + self.environment.as_ref().map(|environment| (environment.display.environment.as_str(), environment.display.env_rotation)) + } + + /// Tests: the stage of the layer's Height operation and the stage reading it as its input. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn input_stages(&self) -> (usize, usize) { + let stages = &self.filters.stages; + let height = stages.iter().position(|stage| self.operations[stage.layer as usize].ids[0] == channel_slot(Channel::Height)); + let reader = stages.iter().position(|stage| stage.input_kind == INPUT_LAYER); + (height.unwrap_or(usize::MAX), reader.unwrap_or(usize::MAX)) + } + + /// Tests: each whole-set pass's stage count and reach past the set's edges. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn whole_set_passes(&self) -> Vec<(usize, u32)> { + self.filters.whole_set().map_or_else(Vec::new, |whole| whole.passes.iter().map(|pass| (pass.stages.len(), pass.past_edges)).collect()) + } + + /// Tests: the last stage's input and input kind. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn input_of_last_stage(&self) -> (u32, u32) { + self.filters.stages.last().map_or((u32::MAX, u32::MAX), |stage| (stage.input, stage.input_kind)) + } + + /// Replace the environment's diffuse light (tests: a stub reader instead of `EnvironmentSh::of`). + #[cfg(test)] + pub(super) fn set_environment(&mut self, environment: &EnvironmentSh) { + if let Some(late) = &mut self.environment { + late.set(environment); + } + } + + /// Mesh-space projections and generators share the viewport's surface and bake inputs. + pub fn set_surface_inputs(&mut self, mesh: &Arc, gbuf: &Arc, baked: Option<&BakedMaps>) -> Result<(), &'static str> { + // P1's projector depth grids, before the atlas reads them + self.material_images.set_surface(mesh); + if self.needs_surface || !self.geometry.parts.is_empty() { + self.surface = Some((mesh.clone(), gbuf.clone())); + } + self.geometry.resolve(mesh); + + // Texels no triangle covers keep the channels' defaults, as the CPU leaves them + let partly_covered = gbuf.tri.contains(&NO_TRI); + if self.mask_preview || ((partly_covered || !self.filters.stages.is_empty() || !self.geometry.parts.is_empty()) && self.coverage.is_none()) { + self.set_coverage(gbuf.clone(), 0); + } + self.baked = baked.map(|baked| BakedInputs::new(baked, self.bake_rows)).transpose()?.flatten(); + self.id_bake = baked.filter(|_| self.operations.iter().any(|op| op.ids[1] == COLOR_SELECTION_OPCODE && op.procedural[2] != 0)).and_then(IdBake::new); + if !self.mask_preview && self.baked.as_ref().is_some_and(|baked| baked.maps[1].is_some()) { + self.display_outputs |= display_bit(DisplayKind::Normal); + } + Ok(()) + } + + /// A flat stack of sparse paint, solid and UV procedural fills, masks and point effects. + /// Disabled layers need no work. Stacks outside this evaluator's domain use the CPU. + pub fn compile(project: &Project, pixels: &PixelStore, ts: usize) -> Option { + Self::compile_region(project, pixels, ts, None) + } + + pub fn compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option) -> Option { + Self::try_compile_region(project, pixels, ts, region).ok() + } + + /// Also provide the reason the viewport must select its CPU compositor. + pub fn try_compile_region(project: &Project, pixels: &PixelStore, ts: usize, region: Option) -> Result { + Self::try_compile_with_brush(project, pixels, ts, region, None) + } + + pub fn try_compile_with_brush( + project: &Project, + pixels: &PixelStore, + ts: usize, + region: Option, + brush: Option, + ) -> Result { + let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; + packages::check_set(set, false)?; + if let Some(brush) = &brush { + brush.validate(set.size())?; + } + let mut operations: Vec = Vec::new(); + let mut paint = PaintInputs::default(); + let mut tile_patterns = TilePatterns::default(); + let mut effects = Vec::new(); + let mut procedural = ProceduralInputs::new(set.resolution); + + // P8: a UV tile atlas's block, its tile scales and the set's own resolution + let layout = udim::UdimLayout::of(set); + udim::prepare(layout.as_ref(), &mut procedural); + let mut geometry = GeometryMasks::default(); + let mut groups = GroupPlan::default(); + let mut group_depth = 0; + let mut mask_layers = Vec::new(); + let mut non_default = [false; Channel::ALL.len()]; + let stencil_pigment = brush.as_ref().is_some_and(|brush| brush.stencil.is_some()); + + // Each draw carries the Scale and Rotation of the folders holding it (an instanced folder's too) + let mut layers: Vec<_> = set.stack.iter().rev().map(|&id| (StackWork::Layer(id, 0, 0), ContentsOffset::NONE)).collect(); + while let Some((work, around)) = layers.pop() { + let (id, depth, inherited_geometry) = match work { + StackWork::Layer(id, depth, geometry) => (id, depth, geometry), + StackWork::EndGroup(start) => { + let end = operations.len() as u32 + 1; + let weights = operations[start].ids[2]; + operations[start].ids[3] = end; + operations.push(Operation { ids: [0, END_GROUP, weights, 0], ..Operation::zeroed() }); + group_depth -= 1; + continue; + } + }; + let own = project.layers.get(&id).ok_or("A layer is missing from the material.")?; + if !own.visible { + continue; + } + + let Some(layer) = project.content_layer(id) else { continue }; + let geometry_mask = geometry.register(inherited_geometry, own.geometry_mask.as_deref()); + let mask = project.layers.get(&project.mask_owner(id)).and_then(|owner| owner.mask.as_ref()).filter(|m| m.enabled); + if let LayerKind::Group { children, contents, .. } = &layer.kind { + if depth > texturecraft_core::project::MAX_DEPTH { + continue; + } + + // A folder's Scale and Rotation (an instanced folder's too) re-place every fill inside it + let children_around = around.then(*contents); + + // Keep the group boundary when anchors escape its geometry restriction + if mask.is_none() + && set.channels.iter().all(|&(channel, _)| { + layer.blend(channel).is_some_and(|blend| blend.mode != BlendMode::Disable && blend.opacity.is_finite() && blend.opacity >= 1.0) + }) + && (geometry_mask == 0 || !groups::children_publish_anchors(project, children, depth + 1)) + { + layers.extend(children.iter().rev().map(|&child| (StackWork::Layer(child, depth + 1, geometry_mask), children_around))); + continue; + } + + let mut weights = [0.0f32; Channel::ALL.len()]; + for &(channel, _) in &set.channels { + if let Some(blend) = layer.blend(channel).filter(|blend| blend.mode != BlendMode::Disable) { + if !blend.opacity.is_finite() { + return Err("A group has an invalid opacity."); + } + + weights[channel_slot(channel) as usize] = blend.opacity.clamp(0.0, 1.0); + } + } + if weights.iter().all(|&opacity| opacity == 0.0) + && mask.is_none_or(|mask| !mask.effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor))) + { + continue; + } + + let begin = effects.len() as u32; + let background = compile_mask(mask, around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut effects)?; + let count = effects.len() as u32 - begin; + + // A folder's This Layer is the stack below it, as the CPU reads it + effects[begin as usize..].iter_mut().for_each(stack::read_folder_layers); + + let height = layer.height_mask; + let height_params = if height.enabled && count != 0 { + if !height.contrast.is_finite() || !height.offset.is_finite() { + return Err("A group's height mask has invalid parameters."); + } + + [height.contrast.to_bits(), height.offset.to_bits()] + } else { + [0; 2] + }; + let weight_offset = u32::try_from(procedural.ramp_words.len()) + .ok() + .and_then(|len| LOOKUP_WORDS.checked_add(len)) + .ok_or("The GPU group settings are too large.")?; + procedural.ramp_words.extend(weights.map(f32::to_bits)); + let open = operations.len(); + let mut op = Operation { + ids: [0, BEGIN_GROUP, weight_offset, 0], + effects: [begin, count, 0, 0], + constraints: [geometry_mask, 0, height_params[0], height_params[1]], + ..Operation::zeroed() + }; + op.balance[1] = background; + operations.push(op); + mask_layers.push((id, around, open as u32)); + procedural.anchors.draw_ranges.push(open as u32..open as u32 + 1); + group_depth += 1; + groups.depth = groups.depth.max(group_depth); + layers.push((StackWork::EndGroup(open), ContentsOffset::NONE)); + + // The group tests its geometry before entering. Children still apply their own masks + layers.extend(children.iter().rev().map(|&child| (StackWork::Layer(child, depth + 1, 0), children_around))); + continue; + } + + let mask_start = effects.len() as u32; + let mask_background = compile_mask(mask, around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut effects)?; + let shared_content = effects.len() as u32; + let mask_count = shared_content - mask_start; + let has_content_anchors = layer.content_effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor)); + if mask_background == 0.0 && mask_count == 0 && !has_content_anchors { + continue; + } + + let mut content_anchors = Vec::new(); + let mut visible_cut = 0u32; + let per_channel = layer.content_effects.iter().any(|effect| effect.visible && (content_depends_on_channel(effect) || blends_per_channel(effect))); + let mut templates = Vec::new(); + for effect in layer.content_effects.iter().filter(|e| e.visible) { + if matches!(effect.kind, EffectKind::Anchor) { + content_anchors.push((effect.id, visible_cut)); + continue; + } + + visible_cut += 1; + let first_input = procedural.input_sources.len(); + + // A filter laid on each channel apart is lowered once per channel of the set + let channel_ops = if blends_per_channel(effect) && !content_depends_on_channel(effect) { + let mut ops = BTreeMap::new(); + for &(channel, _) in &set.channels { + let op = channel_filter(effect, channel, &mut procedural).ok_or("A layer effect uses CPU compositing.")?; + ops.insert(channel, (procedural.preceding_stage.take(), op)); + } + Some(ops) + } else { + None + }; + let op = if content_depends_on_channel(effect) || channel_ops.is_some() { + None + } else { + Some(content_filter(effect, &mut procedural).ok_or("A layer effect uses CPU compositing.")?) + }; + stack::bind_input_tiles(effect, &mut procedural.input_sources[first_input..], &mut tile_patterns); + + // A lowering with a stage before its operation takes two operations, on every channel alike + let mut stage = procedural.preceding_stage.take(); + if channel_ops.as_ref().is_some_and(|ops| ops.values().any(|(channel_stage, _)| channel_stage.is_some())) { + stage = Some(Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() }); + } + visible_cut += u32::from(stage.is_some()); + if per_channel { + templates.push((effect, stage, op, channel_ops)); + } else if let Some(op) = op { + effects.extend(stage); + effects.push(op); + } + } + let fill = match &layer.kind { + LayerKind::Fill(fill) => Some(fill), + LayerKind::Paint => None, + _ => return Err("A group or another layer type uses CPU compositing."), + }; + let decal = fill.map(|fill| register_decal(fill, &mut procedural.materials)).transpose()?.flatten(); + + let height = layer.height_mask; + let height_params = if height.enabled && mask_count != 0 { + if !height.contrast.is_finite() || !height.offset.is_finite() { + return Err("A layer's height mask has invalid parameters."); + } + + [height.contrast.to_bits(), height.offset.to_bits()] + } else { + [0; 2] + }; + let first_op = operations.len(); + let mut height_op = 0; + for &(channel, _) in &set.channels { + if mask_background == 0.0 && mask_count == 0 { + break; + } + + let Some(blend) = layer.blend(channel) else { continue }; + if blend.mode == BlendMode::Disable || blend.opacity <= 0.0 { + continue; + } + + if !blend.opacity.is_finite() { + return Err("A layer has an invalid opacity."); + } + + let (painted, brush_value) = if fill.is_none() { + (sparse_channel(pixels, layer.id, channel)?, brush.as_ref().and_then(|brush| brush.value_for_layer(layer.id, channel))) + } else { + (None, None) + }; + let content_start = if per_channel { effects.len() as u32 } else { shared_content }; + let mut adds_coverage = false; + for (effect, shared_stage, shared_template, channel_ops) in &templates { + // A channel without a stage of its own keeps the placeholder, so an anchor's content cut holds on every channel + let (stage, template) = match channel_ops.as_ref().and_then(|ops| ops.get(&channel)) { + Some((channel_stage, op)) => (shared_stage.map(|placeholder| channel_stage.unwrap_or(placeholder)), Some(*op)), + None => (*shared_stage, *shared_template), + }; + effects.extend(stage); + let op = if let Some(op) = template { + op + } else if let Some(op) = + content_deposit(effect, (channel, around), pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns))? + { + adds_coverage = true; + op + } else { + Operation { ids: [0, NOOP_EFFECT_OPCODE, 0, 0], ..Operation::zeroed() } + }; + effects.push(op); + } + if fill.is_none() && painted.is_none() && brush_value.is_none() && !adds_coverage { + if per_channel { + effects.truncate(content_start as usize); + } + continue; + } + + let content_count = effects.len() as u32 - content_start; + let default = channel.default_value(); + let source = fill.and_then(|fill| fill.sources.get(&channel)); + let slot = channel_slot(channel); + + // Neutral fills can reset a channel only after its first contribution + if !non_default[slot as usize] + && painted.is_none() + && brush_value.is_none() + && content_count == 0 + && matches!(blend.mode, BlendMode::Normal | BlendMode::Passthrough | BlendMode::Replace) + && source.is_none_or(|source| matches!(source, Source::Uniform(value) if *value == default)) + { + continue; + } + + non_default[slot as usize] = true; + let mut op = if fill.is_none() { + content_paint(layer.id, channel, painted, brush_value, stencil_pigment, &mut paint) + } else { + fill.and_then(|fill| source_operation(source, &placed(around, &fill.projection), fill.sampling, default, channel.kind(), &mut procedural)) + .ok_or("A fill source or projection uses CPU compositing.")? + }; + if let Some(decal) = decal { + op.uv[0] = decal as f32; + } + bind_tile_source(&mut op, source, &mut tile_patterns); + op.ids[0] = slot; + op.low[3] = blend.opacity.min(1.0); + op.balance[1] = mask_background; + op.balance[2] = blend_code(blend.mode) as f32; + op.effects = [mask_start, mask_count, content_start, content_count]; + op.spatial[3] = u32::from(adds_coverage); + if height_params[0] != 0 && channel == Channel::Height { + height_op = operations.len() as u32 + 1; + } + operations.push(op); + } + + packages::order_layer_operations(&mut operations[first_op..]); + if height_op != 0 { + // The reorder can move the Height operation that the height mask reads + let height = operations[first_op..].iter().position(|op| op.ids[0] == channel_slot(Channel::Height)); + height_op = height.map_or(0, |index| (first_op + index) as u32 + 1); + } + for op in &mut operations[first_op..] { + op.constraints = [geometry_mask, height_op, height_params[0], height_params[1]]; + } + if first_op != operations.len() { + mask_layers.push((id, around, first_op as u32)); + } else if mask.as_ref().is_some_and(|mask| { + mask.effects.iter().any(|effect| effect.visible && (!effect.kind.anchors_read().is_empty() || matches!(effect.kind, EffectKind::Anchor))) + }) { + // A layer with no display channels can still publish anchors in its mask + mask_layers.push((id, around, first_op as u32)); + operations.push(Operation { + ids: [u32::MAX, ANCHOR_PUBLISH_MASK, 0, 0], + effects: [mask_start, mask_count, 0, 0], + balance: [0.0, mask_background, 0.0, 0.0], + constraints: [geometry_mask, 0, 0, 0], + ..Operation::zeroed() + }); + } + procedural.anchors.draw_ranges.push(first_op as u32..operations.len() as u32); + if !content_anchors.is_empty() { + let has_channels = + set.channels.iter().any(|&(channel, _)| layer.blend(channel).is_some_and(|blend| blend.mode != BlendMode::Disable && blend.opacity > 0.0)); + if !has_channels && mask.is_none_or(|mask| !mask.effects.iter().any(|effect| effect.visible && matches!(effect.kind, EffectKind::Anchor))) { + continue; + } + } + for (anchor, cut) in content_anchors { + let publication = procedural.anchors.publish(anchor, false); + operations.push(Operation { + ids: [u32::MAX, ANCHOR_PUBLISH_LAYER, publication, 0], + effects: [first_op as u32, cut, 0, 0], + ..Operation::zeroed() + }); + } + } + let mut display_outputs = display_bit(DisplayKind::BaseColor) | display_bit(DisplayKind::Orm); + for channel in Channel::ALL.into_iter().take(Channel::SHADED_COUNT) { + let slot = channel_slot(channel); + if operations.iter().any(|op| { + !groups::is_group(op) + && op.ids[0] == slot + && (op.ids[1] != 0 || op.low[..3] != channel.default_value() || op.effects[3] != 0 || op.balance[2] != 0.0) + }) { + display_outputs |= display_bit(DisplayKind::of_channel(channel)); + } + } + groups.finish(&operations); + let layer_count = operations.len() as u32; + if !operations.iter().any(|op| op.constraints[0] != 0) { + geometry.parts.clear(); + } + operations.extend(effects); + bind_input_sources(&mut operations, layer_count, &procedural.input_sources); + let mut filters = FilterPlan::compile(&mut operations, layer_count, &procedural); + bind_generator_sources(&mut operations, &procedural.generator_sources); + filters.bind_anchors(&mut operations); + let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; + + // A UV tile smaller than its block shades its height slopes at its own scale (Extra's alpha) + if layout.as_ref().is_some_and(|layout| layout.scaled) { + display_outputs |= display_bit(DisplayKind::Extra); + } + let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); + let (brush_alpha, brush_stencil) = brush.map_or((None, None), |brush| (Some(brush.alpha), brush.stencil)); + let needs_surface = brush_stencil.is_some() || needs_surface(&operations); + Ok(Self { + operations, + layer_count, + filters, + groups, + geometry, + paint: paint.images, + ramp_words: procedural.ramp_words, + curvature_sizes: procedural.curvature_sizes, + tile_patterns, + material_images: procedural.materials, + brush_alpha, + brush_stencil, + region, + coverage: None, + surface: None, + needs_surface, + baked: None, + id_bake: None, + display_outputs, + glossiness: set.has_channel(Channel::Glossiness), + mix_baked_ao: set.ao_mixing == texturecraft_core::AoMixing::Multiply, + mask_preview: false, + mask_layer: 0, + mask_layers, + image_words: procedural.image_words, + environment: LateEnvironment::new(procedural.environment_word, &project.display), + bake_rows: procedural.bake_rows, + udim, + udim_layout: layout, + }) + } + + /// Compose one layer's enabled mask into the standalone grayscale view. + pub fn try_compile_mask_preview( + project: &Project, + pixels: &PixelStore, + ts: usize, + owner: LayerId, + region: Option, + brush: Option, + ) -> Result { + let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; + packages::check_set(set, true)?; + + // The folders around the requested layer (an instance's own, as the CPU places it) re-place its mask fills + let requested = owner; + let owner = project.mask_owner(owner); + let around = project.contents_around(requested); + let mask = project.layers.get(&owner).and_then(|layer| layer.mask.as_ref()).filter(|mask| mask.enabled); + let mask = mask.ok_or("The layer has no enabled mask.")?; + + // A mask reading anchors or the layers needs the stack below it: the material program + let reads_below = |effect: &Effect| { + !effect.kind.anchors_read().is_empty() || effect.inputs.values().any(|source| source.reads_anchor(None)) || effect.kind.reads_stack() + }; + if mask.effects.iter().any(|effect| effect.visible && reads_below(effect)) { + // The material program draws the owner once per placement: show the draw where the requested layer sits + let mut program = Self::try_compile_with_brush(project, pixels, ts, region, brush)?; + let draw = program.mask_layers.iter().rev().find(|&&(id, offset, _)| (id == requested || id == owner) && offset == around); + program.mask_layer = draw.ok_or("The mask's GPU anchor stack is missing.")?.2; + program.mask_preview = true; + program.display_outputs = display_bit(DisplayKind::BaseColor); + return Ok(program); + } + + if let Some(brush) = &brush { + brush.validate(set.size())?; + } + let mut operations = vec![Operation::zeroed()]; + let mut paint = PaintInputs::default(); + let mut procedural = ProceduralInputs::new(set.resolution); + + // P8: a UV tile atlas's block, its tile scales and the set's own resolution + let layout = udim::UdimLayout::of(set); + udim::prepare(layout.as_ref(), &mut procedural); + let mut tile_patterns = TilePatterns::default(); + let background = compile_mask(Some(mask), around, pixels, brush.as_ref(), (&mut paint, &mut procedural, &mut tile_patterns), &mut operations)?; + operations[0].effects[1] = operations.len() as u32 - 1; + operations[0].balance[1] = background; + bind_input_sources(&mut operations, 1, &procedural.input_sources); + let mut filters = FilterPlan::compile(&mut operations, 1, &procedural); + bind_generator_sources(&mut operations, &procedural.generator_sources); + filters.bind_anchors(&mut operations); + let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; + let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); + let (brush_alpha, brush_stencil) = brush.map_or((None, None), |brush| (Some(brush.alpha), brush.stencil)); + let needs_surface = brush_stencil.is_some() || needs_surface(&operations); + Ok(Self { + operations, + layer_count: 1, + filters, + groups: GroupPlan::default(), + geometry: GeometryMasks::default(), + paint: paint.images, + ramp_words: procedural.ramp_words, + curvature_sizes: procedural.curvature_sizes, + tile_patterns, + material_images: procedural.materials, + brush_alpha, + brush_stencil, + region, + coverage: None, + surface: None, + needs_surface, + baked: None, + id_bake: None, + // Reuse the first four-byte display slot for linear grayscale + display_outputs: display_bit(DisplayKind::BaseColor), + glossiness: false, + mix_baked_ao: false, + mask_preview: true, + mask_layer: 0, + mask_layers: Vec::new(), + image_words: procedural.image_words, + environment: LateEnvironment::new(procedural.environment_word, &project.display), + bake_rows: procedural.bake_rows, + udim, + udim_layout: layout, + }) + } +} diff --git a/crates/render/src/gpu_composite/composite_region.rs b/crates/render/src/gpu_composite/composite_region.rs new file mode 100644 index 00000000..0b9189ac --- /dev/null +++ b/crates/render/src/gpu_composite/composite_region.rs @@ -0,0 +1,71 @@ +use super::TILE; + +/// Inclusive origin and exclusive end of a material update, in document texels. +#[derive(Clone, Copy, Debug)] +pub struct CompositeRegion { + pub(crate) min: [u32; 2], + pub(crate) max: [u32; 2], +} + +impl CompositeRegion { + pub fn from_tiles(tiles: impl IntoIterator) -> Option { + let last_tile = u32::MAX / TILE; + let mut tiles = tiles.into_iter().filter(|&(x, y)| x <= last_tile && y <= last_tile); + let (x, y) = tiles.next()?; + let mut first = [x, y]; + let mut last = first; + for (x, y) in tiles { + first = [first[0].min(x), first[1].min(y)]; + last = [last[0].max(x), last[1].max(y)]; + } + + Some(Self { min: first.map(|tile| tile * TILE), max: last.map(|tile| (tile * TILE).saturating_add(TILE)) }) + } + + pub(super) fn union(self, other: Self) -> Self { + Self { min: [self.min[0].min(other.min[0]), self.min[1].min(other.min[1])], max: [self.max[0].max(other.max[0]), self.max[1].max(other.max[1])] } + } + + pub fn expanded(self, texels: u32) -> Self { + Self { min: self.min.map(|x| x.saturating_sub(texels)), max: self.max.map(|x| x.saturating_add(texels)) } + } + + pub fn bounds(self) -> ([u32; 2], [u32; 2]) { + (self.min, self.max) + } + + pub(crate) fn viewport(self, shift: u32, size: (u32, u32)) -> Self { + let sample_step = 1 << shift; + let max = [self.max[0].div_ceil(sample_step).min(size.0), self.max[1].div_ceil(sample_step).min(size.1)]; + + Self { min: self.min.map(|origin| origin >> shift), max } + } +} + +#[cfg(test)] +mod tests { + use super::{CompositeRegion, TILE}; + + #[test] + fn a_downscaled_update_includes_samples_in_the_filter_halo() { + let region = CompositeRegion::from_tiles([(0, 0)]).unwrap().expanded(1); + let scale_shift = 1; + let edge_sample = TILE >> scale_shift; + + let (_, end) = region.viewport(scale_shift, (TILE, TILE)).bounds(); + + assert!(edge_sample < end[0] && edge_sample < end[1]); + assert!((end[0] << scale_shift) >= region.max[0]); + } + + #[test] + fn tile_bounds_preserve_representable_tiles_at_the_coordinate_limit() { + let last_column = u32::MAX / TILE; + let tiles = [(last_column + 1, 0), (last_column, 2), (last_column - 1, 1)]; + + let bounds = CompositeRegion::from_tiles(tiles).unwrap().bounds(); + + assert_eq!(bounds, ([(last_column - 1) * TILE, TILE], [u32::MAX, 3 * TILE])); + assert!(CompositeRegion::from_tiles([(0, last_column + 1)]).is_none()); + } +} diff --git a/crates/render/src/gpu_composite/curvature_cache.rs b/crates/render/src/gpu_composite/curvature_cache.rs new file mode 100644 index 00000000..62fc01b6 --- /dev/null +++ b/crates/render/src/gpu_composite/curvature_cache.rs @@ -0,0 +1,9 @@ +use super::{CurvatureDetail, CurvatureLevels, UvGBuffer, Weak}; + +pub(super) struct CurvatureCache { + pub(super) gbuf: Weak, + pub(super) map: Weak>, + pub(super) size: [u32; 2], + pub(super) needed: [bool; CurvatureDetail::BLURRED_SIZES], + pub(super) levels: CurvatureLevels, +} diff --git a/crates/render/src/gpu_composite/curvature_resources.rs b/crates/render/src/gpu_composite/curvature_resources.rs new file mode 100644 index 00000000..273f14dd --- /dev/null +++ b/crates/render/src/gpu_composite/curvature_resources.rs @@ -0,0 +1,7 @@ +use super::{BTreeMap, CurvatureCache, CurvatureGpu, CurvatureLevels}; + +pub(super) struct CurvatureResources { + pub(super) gpu: Option, + pub(super) empty: CurvatureLevels, + pub(super) cache: BTreeMap, +} diff --git a/crates/render/src/gpu_composite/filter_plan.rs b/crates/render/src/gpu_composite/filter_plan.rs new file mode 100644 index 00000000..c6d567e3 --- /dev/null +++ b/crates/render/src/gpu_composite/filter_plan.rs @@ -0,0 +1,574 @@ +use super::{ + ANCHOR_PUBLISH_LAYER, ANCHOR_PUBLISH_MASK, ANCHOR_SOURCE, AnchorInputs, BTreeMap, BTreeSet, Channel, ChannelKind, CompositeRegion, ContentProgress, + FIELD_WORDS, FIRST_EXTENDED_PATTERN, FIRST_GENERATOR, Filter, FilterStage, GENERATOR_STAGE, INPUT_COLOR, INPUT_LAYER, MASK_ANCHOR_STAGE, MASK_STAGE, + MATERIAL_ANCHOR_STAGE, MAX_WHOLE_SET_STAGES, NEIGHBOURHOOD_OPCODE, NO_FIELDS, NeighbourhoodFilter, OWN_VIEW, Operation, ProceduralInputs, WholePass, + WholeSet, channel_slot, effect_ranges, gpu_neighbourhood, layer_height, layer_run, own_material_base, packages, slot_kind, stack_reads, udim, +}; + +#[derive(Debug, Default)] +pub(super) struct FilterPlan { + pub(super) stages: Vec, + pub(super) reach: u32, + pub(super) anchor_slots: Vec, + /// The operation index of the first input source (`bind_input_sources`), while compiling + pub(super) input_base: u32, +} + +impl FilterPlan { + pub(super) fn compile(operations: &mut [Operation], layer_count: u32, inputs: &ProceduralInputs) -> Self { + let reads_stack = operations.iter().skip(layer_count as usize).any(|op| stack_reads(op) != [0; 2]); + if inputs.filters.is_empty() && inputs.generator_stages.is_empty() && inputs.anchors.reads.is_empty() && !reads_stack { + return Self::default(); + } + + let mut plan = Self { input_base: (operations.len() - inputs.input_sources.len()) as u32, ..Self::default() }; + let (layers, effects) = operations.split_at_mut(layer_count as usize); + let mut masks = BTreeMap::new(); + plan.anchor_slots.resize(inputs.anchors.reads.len(), 0); + let mut stack_reads = BTreeMap::new(); + let mut read_effects = BTreeSet::new(); + let mut prepared = BTreeSet::new(); + for index in 0..layers.len() { + let run = layer_run(&inputs.anchors.draw_ranges, index); + if layers[index].ids[1] != ANCHOR_PUBLISH_LAYER { + plan.bind_stack_reads(layers, effects, index, run.clone(), false, (&mut stack_reads, &mut read_effects)); + } + let layer = &mut layers[index]; + if layer.ids[1] == ANCHOR_PUBLISH_LAYER { + plan.add_anchor(layer.ids[2], index as u32, MATERIAL_ANCHOR_STAGE, &inputs.anchors, Some((layer.effects[0], layer.effects[1]))); + continue; + } + + let [mask, mask_count, _, _] = layer.effects; + + // Prepare layer content before a mask that reads it, then capture the masked material + if mask_count > 0 && !masks.contains_key(&mask) && effects.iter().skip(mask as usize).take(mask_count as usize).any(packages::mask_reads_own_layer) + { + let lit = own_material_base(layers, effects, run.clone()); + for own in run.clone() { + if lit == Some(own) { + plan.bind_stack_reads(layers, effects, own, run.clone(), false, (&mut stack_reads, &mut read_effects)); + } else { + plan.add_layer_content(layers, effects, own, run.clone(), inputs, (&mut prepared, &mut stack_reads, &mut read_effects)); + } + } + + // A mask comparing its lit Base Color, which has stages: two masks (M1, M2) + let base_stages = |base: usize| { + let [_, _, content, count] = layers[base].effects.map(|word| word as usize); + effects.iter().skip(content).take(count).any(|op| op.ids[1] == NEIGHBOURHOOD_OPCODE) + }; + let reads_base = |base: usize| { + effects + .iter() + .skip(mask as usize) + .take(mask_count as usize) + .any(|op| packages::mask_reads_own_layer(op) && op.effects[0] == base as u32 + 1) + }; + match lit.filter(|&base| base_stages(base) && reads_base(base)) { + Some(base) => { + let progress = (&mut prepared, &mut stack_reads, &mut read_effects); + let mask_base = plan.add_lit_mask_views(layers, effects, (index, base, run.clone()), (mask, mask_count), inputs, progress); + masks.insert(mask, mask_base); + } + None => { + plan.add_this_layer_reads(layers, effects, (mask, mask_count), lit, |_| true); + } + } + } + + // The mask stack's first slot plus one (0: no fields), read by `layer_mask` + let mask_base = if mask_count == 0 { + 0 + } else { + *masks.entry(mask).or_insert_with(|| { + let before = plan.stages.len(); + plan.add_stack(effects, (mask, mask_count), (index as u32, None), None, inputs); + if plan.stages.len() != before { before as u32 + 1 } else { 0 } + }) + }; + + // The layer's own material is captured after its mask and its other channels' stacks + plan.bind_stack_reads(layers, effects, index, run.clone(), true, (&mut stack_reads, &mut read_effects)); + plan.add_layer_content(layers, effects, index, run, inputs, (&mut prepared, &mut stack_reads, &mut read_effects)); + layers[index].spatial[2] = mask_base; + } + + // Parallel channels share a footprint while chained anchor reads extend it + if !inputs.anchors.reads.is_empty() { + let mut draw_reach = BTreeMap::<(u32, bool), u32>::new(); + for stage in &plan.stages { + let reach = draw_reach.entry((stage.layer, stage.preceding & MASK_STAGE != 0)).or_default(); + *reach = reach.saturating_add(stage.reach()); + } + let across_layers = inputs.anchors.draw_ranges.iter().fold(0u32, |reach, range| { + let layer = draw_reach.range((range.start, false)..(range.end, false)).map(|(_, reach)| *reach).max().unwrap_or(0); + reach.saturating_add(layer) + }); + plan.reach = plan.reach.max(across_layers); + } + + // A stack read's field holds every layer below it at the texel, filters included + if !stack_reads.is_empty() { + let total = plan.stages.iter().fold(0u32, |sum, stage| sum.saturating_add(stage.reach())); + plan.reach = plan.reach.max(total); + } + + // The pre-pass resumes no anchor reads, and the band uniform addresses a few outputs + let anchors = plan.stages.iter().any(FilterStage::anchors); + let mut entries = 0; + for stage in plan.stages.iter_mut().filter(|stage| stage.whole) { + // P8: a stage's level stages share its entry, their results right after its own + entries += usize::from(stage.level == 0); + stage.whole = !anchors && entries <= MAX_WHOLE_SET_STAGES; + } + plan + } + + /// The whole-set pre-pass, None when no stage is whole-set (every program before the + /// packages mark one). Each whole-set stage takes the lower stages of its stack along. + pub(super) fn whole_set(&self) -> Option { + let outputs: Vec = self.stages.iter().enumerate().filter(|(_, stage)| stage.whole).map(|(index, _)| index).collect(); + if outputs.is_empty() { + return None; + } + + let mut stacks = BTreeMap::<(u32, bool), (BTreeSet, Vec)>::new(); + for &output in &outputs { + let stack = self.stages[output].stack(); + let lower = (0..=output).filter(|&index| { + self.stages[index].stack() == stack && !self.stages[index].anchors() && self.stages[index].view == 0 && self.stages[index].mask_view == [0; 4] + }); + let (stages, own) = stacks.entry(stack).or_default(); + stages.extend(lower); + own.push(output); + } + let passes: Vec = stacks + .into_values() + .map(|(stages, outputs)| { + let stages: Vec = stages.into_iter().collect(); + let reach = stages.iter().fold(0u32, |sum, &index| sum.saturating_add(self.stages[index].reach())); + let topmost = stages.iter().rposition(|&index| self.stages[index].wrap); + let past_edges = topmost.map_or(0, |top| stages[..=top].iter().fold(0u32, |sum, &index| sum.saturating_add(self.stages[index].reach()))); + let blur_fields = stages + .iter() + .map(|&index| { + let stage = &self.stages[index]; + stage.filter.map_or(0, NeighbourhoodFilter::blur_fields).max(u32::from(stage.cell > 1)) + }) + .max() + .unwrap_or(0); + WholePass { stages, outputs, reach, past_edges, blur_fields } + }) + .collect(); + let mut stages: Vec = passes.iter().flat_map(|pass| pass.stages.iter().copied()).collect(); + stages.sort_unstable(); + let reach = passes.iter().map(|pass| pass.reach).max().unwrap_or(0); + let entries = outputs.iter().enumerate().filter(|&(_, &output)| self.stages[output].level == 0).map(|(index, _)| index).collect(); + Some(WholeSet { stages, outputs, entries, reach, passes }) + } + + /// The halo of a band: every stack's reach, without the stages the whole-set pre-pass + /// evaluates (their reach is the pre-pass's). The plan's reach without a pre-pass. + pub(super) fn band_reach(&self, whole: Option<&WholeSet>) -> u32 { + let Some(whole) = whole else { return self.reach }; + let mut stacks = BTreeMap::<(u32, bool), u32>::new(); + for (index, stage) in self.stages.iter().enumerate() { + let reach = stacks.entry(stage.stack()).or_default(); + if !whole.stages.contains(&index) { + *reach = reach.saturating_add(stage.reach()); + } + } + stacks.into_values().max().unwrap_or(0) + } + + /// Bind the stack reads of layer operation `index`'s mask and content effects: an effect + /// operation that sets `spatial[3]` to a channel slot plus one asks for the material of that + /// channel at the texel, accumulated over every layer below its layer (`effects[1]` 0) or + /// also over its layer's operations before Base Color (`effects[1]` 1, P6's material reads). + /// A stage captures it (a material-anchor capture without a cut), `spatial[3]` becomes that + /// stage's slot plus one (`stack_at` in WGSL), and `effects[0]` the layer's own operation of + /// that channel plus one (0: none; `this_layer_content` in WGSL). P3: Compare reading This + /// Layer and Layers Below; P6: lighting's material. + /// + /// A package effect (`packages::EXTENDED_EFFECTS`) may ask for a second channel in + /// `spatial[2]` the same way, read with `stack_at_second` (P6: Stylized lighting's Metallic + /// and Roughness, or Glossiness and Specular). It is bound like the first, up to the same + /// operation, and shares a stage with any read of the same channel there; it gets no + /// `this_layer_content`. + /// + /// With `own_material` false it binds the reads of operation `index`'s own effects that stop + /// below the layer (`effects[1]` 0). With it true, at the layer's Base Color operation, it + /// binds every read of the layer's material (each channel operation's copy), so the capture + /// follows the layer's mask and the stacks of its other channels; a layer without a Base + /// Color operation has nothing for them to read, and they read nothing. + #[allow(clippy::too_many_arguments)] + pub(super) fn bind_stack_reads( + &mut self, + layers: &[Operation], + effects: &mut [Operation], + index: usize, + run: std::ops::Range, + own_material: bool, + (stages, done): (&mut BTreeMap<(u32, Channel), u32>, &mut BTreeSet), + ) { + let base_color = (run.start..run.end).find(|&own| layers[own].ids[0] == channel_slot(Channel::BaseColor)); + let reads: BTreeSet = if own_material { + if base_color.is_some_and(|base| base != index) { + return; + } + + // A set: operations sharing a content range list its effects once each + run.clone() + .flat_map(|own| effect_ranges(&layers[own])) + .filter(|&effect| effects.get(effect).is_some_and(|op| stack_reads(op) != [0; 2] && op.effects[1] == 1)) + .collect() + } else { + effect_ranges(&layers[index]).filter(|&effect| effects.get(effect).is_some_and(|op| stack_reads(op) != [0; 2] && op.effects[1] != 1)).collect() + }; + for effect in reads { + if !done.insert(effect) { + continue; + } + + let op = &mut effects[effect]; + let until = if op.effects[1] == 1 { base_color } else { Some(run.start) }; + let Some(until) = until else { + op.spatial[3] = 0; + if packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { + op.spatial[2] = 0; + } + continue; + }; + + let [first_read, second_read] = stack_reads(op); + let mut bind = |read: u32| { + let slot = read.checked_sub(1)?; + let channel = Channel::ALL.into_iter().find(|&channel| channel_slot(channel) == slot)?; + let stage = *stages.entry((until as u32, channel)).or_insert_with(|| { + self.stages.push(FilterStage { + layer: until as u32, + preceding: MATERIAL_ANCHOR_STAGE, + filter: None, + cell: 1, + anchor: Some((channel, u32::MAX, 0)), + input: 0, + input_kind: 0, + input2: 0, + wrap: false, + whole: false, + view: 0, + mask_view: [0; 4], + level: 0, + }); + self.stages.len() as u32 + }); + Some((slot, stage)) + }; + + // Keep the default channels visible to a mask reading its own layer + if op.effects[1] == 1 && packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { + op.effects[2] = first_read | (second_read << 16); + } + let first_stage = bind(first_read); + let second_stage = bind(second_read); + op.spatial[3] = first_stage.map_or(0, |(_, stage)| stage); + if packages::EXTENDED_EFFECTS.contains(&op.ids[1]) { + op.spatial[2] = second_stage.map_or(0, |(_, stage)| stage); + } + if let Some((slot, _)) = first_stage { + op.effects[0] = run.clone().find(|&own| layers[own].ids[0] == slot).map_or(0, |own| own as u32 + 1); + } + } + } + + /// The layer's own content as its mask reads it (This Layer, `this_layer_content` in WGSL): + /// one stage per read channel operation (`reads` picks which), prepared from its whole + /// content stack before the mask stack, its slot plus one in the reading effect's + /// `effects[2]`. The mask then reads a field instead of evaluating the content inline, which + /// keeps the content's code out of the mask's (the driver inlines every call site). + /// + /// The lit Base Color `lit`: the CPU evaluates the mask with no lit material (`Texel::lit` + /// is None while `node_mask` runs), so its own-material reads give the defaults there + /// (`OWN_VIEW`) past its last field. + #[allow(clippy::too_many_arguments)] + pub(super) fn add_this_layer_reads( + &mut self, + layers: &[Operation], + effects: &mut [Operation], + (mask, mask_count): (u32, u32), + lit: Option, + reads: impl Fn(u32) -> bool, + ) -> BTreeMap { + let mut views = BTreeMap::::new(); + for effect in mask as usize..(mask + mask_count) as usize { + let Some(op) = effects.get(effect).filter(|op| packages::mask_reads_own_layer(op)) else { continue }; + let Some(own) = op.effects[0].checked_sub(1).filter(|&own| reads(own)) else { continue }; + let slot = *views.entry(own).or_insert_with(|| self.add_this_layer(layers, own, if lit == Some(own as usize) { OWN_VIEW } else { 0 })); + effects[effect].effects[2] = slot; + } + views + } + + /// A This Layer stage of layer operation `own` viewed as `view`: its slot plus one. + pub(super) fn add_this_layer(&mut self, layers: &[Operation], own: u32, view: u32) -> u32 { + self.stages.push(FilterStage { + layer: own, + preceding: layers[own as usize].effects[3], + filter: None, + cell: 1, + anchor: None, + input: 0, + input_kind: 0, + input2: 0, + wrap: false, + whole: false, + view, + mask_view: [0; 4], + level: 0, + }); + self.stages.len() as u32 + } + + /// A mask that compares its lit Base Color `base` (This Layer) on a layer whose Base Color + /// has stages. The CPU (`fields_of`) builds the content fields first, Base Color last; the + /// material its lighting reads lies under a first mask M1, whose This Layer reads the Base + /// Color with no fields (its stages as identity, `Filter::point`) and no lit material. Then + /// it builds the mask field M2, whose This Layer resumes from the finished Base Color + /// field; the composite uses M2. So: the other This Layer stages, the Base Color's view V1 + /// (`OWN_VIEW | NO_FIELDS`), M1 (a copy of the mask stack), the material's capture, the Base + /// Color's stack, its view V2 (`OWN_VIEW`), and M2, the layer's mask stack. M1's stages and + /// the capture read M1 and V1 in M2's and V2's place (`mask_view`). Returns M2's base plus one. + #[allow(clippy::too_many_arguments)] + pub(super) fn add_lit_mask_views( + &mut self, + layers: &mut [Operation], + effects: &mut [Operation], + (index, base, run): (usize, usize, std::ops::Range), + (mask, mask_count): (u32, u32), + inputs: &ProceduralInputs, + (prepared, stages, done): ContentProgress, + ) -> u32 { + self.add_this_layer_reads(layers, effects, (mask, mask_count), None, |own| own as usize != base); + let first_view = self.add_this_layer(layers, base as u32, OWN_VIEW | NO_FIELDS); + let first_mask = self.stages.len(); + self.add_stack(effects, (mask, mask_count), (index as u32, None), None, inputs); + let first_end = self.stages.len(); + self.bind_stack_reads(layers, effects, base, run.clone(), true, (stages, done)); + let capture_end = self.stages.len(); + self.add_layer_content(layers, effects, base, run, inputs, (prepared, stages, done)); + let views = self.add_this_layer_reads(layers, effects, (mask, mask_count), Some(base), |own| own as usize == base); + let view = views.get(&(base as u32)).copied(); + let mask_base = self.stages.len(); + let copy: Vec = self.stages[first_mask..first_end].to_vec(); + self.stages.extend(copy); + let mask_view = [mask_base as u32 + 1, first_mask as u32 + 1, first_view, view.unwrap_or(0)]; + for stage in &mut self.stages[first_mask..capture_end] { + stage.mask_view = mask_view; + stage.whole = false; + } + if first_end == first_mask { 0 } else { mask_base as u32 + 1 } + } + + /// The stack reads and the content stack of layer operation `index`, once: its first stage + /// and whether it has any in the layer's `spatial[0..2]`. A Normal operation whose stack has a + /// Height To Normal stage reads its layer's own Height operation (`INPUT_LAYER`), whose stack + /// goes first so the Normal stage's prepare pass reads prepared Height fields. + #[allow(clippy::too_many_arguments)] + pub(super) fn add_layer_content( + &mut self, + layers: &mut [Operation], + effects: &mut [Operation], + index: usize, + run: std::ops::Range, + inputs: &ProceduralInputs, + (prepared, stages, done): ContentProgress, + ) { + if !prepared.insert(index) { + return; + } + + let height = layer_height(layers, effects, index, run.clone(), inputs); + if let Some(height) = height.filter(|&height| height != index) { + self.add_layer_content(layers, effects, height, run.clone(), inputs, (prepared, stages, done)); + } + self.bind_stack_reads(layers, effects, index, run, false, (stages, done)); + let [_, _, content, content_count] = layers[index].effects; + let first = self.stages.len(); + self.add_stack(effects, (content, content_count), (index as u32, height.map(|height| height as u32)), Some(slot_kind(layers[index].ids[0])), inputs); + layers[index].spatial[..2].copy_from_slice(&[first as u32, u32::from(first != self.stages.len())]); + } + + pub(super) fn add_anchor(&mut self, publication: u32, layer: u32, preceding: u32, inputs: &AnchorInputs, material: Option<(u32, u32)>) { + for (read, &(producer, channel)) in inputs.reads.iter().enumerate().filter(|(_, (producer, _))| *producer == publication) { + debug_assert_eq!(producer, publication); + self.anchor_slots[read] = self.stages.len() as u32 + 1; + self.stages.push(FilterStage { + layer, + preceding, + filter: None, + cell: 1, + anchor: material.map(|(first, cut)| (channel, first, cut)), + input: 0, + input_kind: 0, + input2: 0, + wrap: false, + whole: false, + view: 0, + mask_view: [0; 4], + level: 0, + }); + } + } + + pub(super) fn bind_anchors(&self, operations: &mut [Operation]) { + for operation in operations.iter_mut().filter(|op| op.ids[1] == ANCHOR_SOURCE && op.ids[2] != 0) { + operation.ids[2] = self.anchor_slots[operation.ids[2] as usize - 1]; + } + } + + #[allow(clippy::too_many_arguments)] + /// The stages of one effect stack: a mask's when `channel` is None, else the content of a + /// channel of that kind (the stage context the packages' stages read). + /// `height` is the layer's own Height operation a Height To Normal stage reads (`layer_height`). + pub(super) fn add_stack( + &mut self, + effects: &mut [Operation], + (start, count): (u32, u32), + (layer, height): (u32, Option), + channel: Option, + inputs: &ProceduralInputs, + ) { + let mask = channel.is_none(); + let first = self.stages.len(); + let mut reach: u32 = 0; + for (preceding, effect) in effects.iter_mut().skip(start as usize).take(count as usize).enumerate() { + if mask && effect.ids[1] == ANCHOR_PUBLISH_MASK { + self.add_anchor(effect.ids[2], layer, preceding as u32 | MASK_STAGE | MASK_ANCHOR_STAGE, &inputs.anchors, None); + continue; + } + + if (FIRST_GENERATOR..FIRST_EXTENDED_PATTERN).contains(&effect.ids[1]) && effect.spatial[1] != 0 { + let generator = effect.spatial[1] as usize - 1; + let (filter, cell) = inputs.generator_stages[generator]; + + // Mask field offsets are relative to the first stage of the mask stack + effect.spatial[1] = (self.stages.len() - first) as u32 + 1; + reach = reach.saturating_add(filter.map_or(0, NeighbourhoodFilter::reach)); + if cell > 1 { + reach = reach.saturating_add(cell * 2); + } + + // P8: the generator at each further UV tile scale follows its base stage + let levels = inputs.generator_levels.get(generator).map_or(&[][..], Vec::as_slice); + for (level, &(filter, cell)) in std::iter::once(&(filter, cell)).chain(levels).enumerate() { + self.stages.push(FilterStage { + layer, + preceding: preceding as u32 | MASK_STAGE | GENERATOR_STAGE, + filter, + cell, + anchor: None, + input: 0, + input_kind: 0, + input2: 0, + wrap: false, + whole: false, + view: 0, + mask_view: [0; 4], + level: level as u32, + }); + } + continue; + } + + if effect.ids[1] != NEIGHBOURHOOD_OPCODE { + continue; + } + + let (effect_filter, opacity) = &inputs.filters[effect.ids[2] as usize]; + let Some(filter) = NeighbourhoodFilter::new(effect_filter, inputs.resolution, inputs.longest_side, *opacity, channel) else { continue }; + + // P8: the same filter at each further UV tile scale, each a stage after this one + let level_filters = udim::level_filters(effect_filter, filter, (*opacity, channel), inputs); + let slot = self.stages.len(); + let whole = filter.whole_set(inputs.resolution); + effect.spatial[0] = (slot - first) as u32; + let preceding = preceding as u32 | if mask { MASK_STAGE } else { 0 }; + + // Height To Normal on a normal channel samples the layer's own height + let (input, input_kind) = match height.filter(|_| matches!(inputs.filters[effect.ids[2] as usize].0, Filter::HeightToNormal(_))) { + Some(height) => (height + 1, INPUT_LAYER), + None => { + let input = effect.effects[3]; + let color = input != 0 && inputs.color_inputs.contains(&input.saturating_sub(self.input_base)); + (input, if color { INPUT_COLOR } else { 0 }) + } + }; + + // The pre-pass carries the lower stages of the stage's own stack only, not the Height's + let whole = whole && input_kind != INPUT_LAYER; + + // P4: Blur and Bevel with Wrap read the set periodically past its edges + let wrap = gpu_neighbourhood::box_family::wraps(filter); + let input2 = effect.effects[2]; + for (level, filter) in std::iter::once(filter).chain(level_filters).map(Some).enumerate() { + self.stages.push(FilterStage { + layer, + preceding, + filter, + cell: 1, + anchor: None, + input, + input_kind, + input2, + wrap, + whole, + view: 0, + mask_view: [0; 4], + level: level as u32, + }); + } + reach = reach.saturating_add(filter.reach()); + } + self.reach = self.reach.max(reach); + } + + /// The update `region` grown by the stages' reach on a set of `size`; None (a full update) + /// when a wrapping stage's reach crosses the set's edge, as an edit there changes the + /// opposite edge too + pub(super) fn expand(&self, region: Option, (width, height): (u32, u32)) -> Option { + let region = region?; + let crosses = |min: u32, max: u32, side: u32| min < self.reach || max.saturating_add(self.reach) > side; + if self.wraps() && (crosses(region.min[0], region.max[0], width) || crosses(region.min[1], region.max[1], height)) { + return None; + } + + Some(region.expanded(self.reach)) + } + + pub(super) fn words(&self, area: u64, field_words: u32) -> u64 { + if self.stages.is_empty() { 0 } else { (self.stages.len() as u64 + 3) * u64::from(field_words) * area } + } + + /// Whether a stage wraps: the fields then extend by the halo past the set's edges, with an + /// origin below zero, and the prepare pass fills the wrapping stages periodically there. + pub(super) fn wraps(&self) -> bool { + self.stages.iter().any(|stage| stage.wrap) + } + + /// Words per field texel: four premultiplied components and the UV coverage, plus a sixth + /// word when a stage carries an input ([`FilterStage::input`]), or three when one reads its + /// input as colour. One stride for every field of the program; the shaders read it from the + /// uniform, never from a literal. + pub(super) fn field_words(&self) -> u32 { + if self.stages.iter().any(|stage| stage.input2 != 0) { + FIELD_WORDS + 6 + } else if self.stages.iter().any(|stage| stage.input_kind == INPUT_COLOR) { + FIELD_WORDS + 3 + } else if self.stages.iter().any(|stage| stage.input != 0) { + FIELD_WORDS + 1 + } else { + FIELD_WORDS + } + } +} diff --git a/crates/render/src/gpu_composite/filter_stage.rs b/crates/render/src/gpu_composite/filter_stage.rs new file mode 100644 index 00000000..59717e65 --- /dev/null +++ b/crates/render/src/gpu_composite/filter_stage.rs @@ -0,0 +1,65 @@ +use super::{Channel, FIELD_WORDS, MASK_ANCHOR_STAGE, MASK_STAGE, MATERIAL_ANCHOR_STAGE, NeighbourhoodFilter}; + +#[derive(Clone, Debug)] +pub(super) struct FilterStage { + pub(super) layer: u32, + pub(super) preceding: u32, + pub(super) filter: Option, + pub(super) cell: u32, + pub(super) anchor: Option<(Channel, u32, u32)>, + /// The operation (index plus one, 0: none) the prepare pass evaluates into the field's sixth + /// word: an image input's gray (P3) or the layer's own Height (P5, Height To Normal). + pub(super) input: u32, + /// How the prepare pass reads `input` ([`super::INPUT_LAYER`], [`super::INPUT_COLOR`]; 0: an input source's gray) + pub(super) input_kind: u32, + /// A second input source (operation index plus one, 0: none), read as colour into words + /// 8..11 (`input2_color_at` in neighbourhood.wgsl): an effect's `effects[2]` on a + /// neighbourhood operation (P5: Color Match's Input and Image Input both linked). + pub(super) input2: u32, + /// The prepare pass reads the set periodically outside it (P4: Blur and Bevel `wrap`), and + /// the fields of the program may start below zero ([`super::FilterPlan::wraps`]). + pub(super) wrap: bool, + /// Evaluated once per update by the whole-set pre-pass ([`super::FilterPlan::whole_set`]) instead + /// of in every band: a stage with a large reach, or one that needs the whole set. + pub(super) whole: bool, + /// How the prepare pass views the content (bits of its `field_layout.w`): [`super::OWN_VIEW`], the + /// layer's own material read as the channels' defaults (a mask's This Layer of a lit Base + /// Color), and [`super::NO_FIELDS`], every neighbourhood stage as identity. + pub(super) view: u32, + /// The prepare pass's `mask_view` (`FilterPlan::add_lit_mask_views`), zero for most stages + pub(super) mask_view: [u32; 4], + /// P8: 0 for a stage of its own; `n` for the stage of the base stage `n` slots before it at a + /// UV tile atlas's level `n` (a smaller tile scale), whose output the texels of that level's + /// blocks read instead (`udim_level_slot` in WGSL) + pub(super) level: u32, +} + +impl FilterStage { + pub(super) fn reach(&self) -> u32 { + // A level stage runs beside its base stage, which reaches at least as far + if self.level != 0 { + return 0; + } + + self.filter.map_or(0, NeighbourhoodFilter::reach).saturating_add(if self.cell > 1 { self.cell * 2 } else { 0 }) + } + + /// The stack the stage belongs to: its layer operation and whether it filters the mask. + pub(super) fn stack(&self) -> (u32, bool) { + (self.layer, self.preceding & MASK_STAGE != 0) + } + + pub(super) fn anchors(&self) -> bool { + self.anchor.is_some() || self.preceding & (MATERIAL_ANCHOR_STAGE | MASK_ANCHOR_STAGE) != 0 + } + + /// The kernels' `NeighbourhoodRegion::input` bits for `stage`: the fields carry input words + /// (1), the stage has an input of its own (2), the fields carry colour words 5..8 (4), the + /// stage has a second input in words 8..11 (8). + pub(super) fn input_bits(&self, field_words: u32) -> u32 { + u32::from(field_words > FIELD_WORDS) + | (u32::from(self.input != 0) << 1) + | (u32::from(field_words >= FIELD_WORDS + 3) << 2) + | (u32::from(self.input2 != 0) << 3) + } +} diff --git a/crates/render/src/gpu_composite/geometry_masks.rs b/crates/render/src/gpu_composite/geometry_masks.rs new file mode 100644 index 00000000..c9b35b39 --- /dev/null +++ b/crates/render/src/gpu_composite/geometry_masks.rs @@ -0,0 +1,71 @@ +use super::Mesh; + +#[derive(Debug, Default)] +pub(super) struct GeometryMasks { + pub(super) parts: Vec>, + pub(super) words: Vec, + pub(super) stride: usize, +} + +impl GeometryMasks { + /// Zero allows every part. A passthrough folder restricts every child to its own allowed parts. + pub(super) fn register(&mut self, inherited: u32, own: Option<&[String]>) -> u32 { + let Some(own) = own else { return inherited }; + let mut names = match inherited.checked_sub(1).and_then(|index| self.parts.get(index as usize)) { + Some(parent) => own.iter().filter(|name| parent.binary_search(name).is_ok()).cloned().collect(), + None => own.to_vec(), + }; + names.sort_unstable(); + names.dedup(); + if let Some(index) = self.parts.iter().position(|mask| *mask == names) { + return index as u32 + 1; + } + + self.parts.push(names); + self.parts.len() as u32 + } + + pub(super) fn resolve(&mut self, mesh: &Mesh) { + if self.parts.is_empty() { + return; + } + + let triangles = mesh.triangle_count(); + self.stride = triangles.div_ceil(32).max(1); + self.words.clear(); + self.words.resize(self.parts.len() * self.stride, u32::MAX); + let parts = &mesh.submeshes; + let ordered = parts.windows(2).all(|pair| pair[0].start.saturating_add(pair[0].count) <= pair[1].start); + for (names, row) in self.parts.iter().zip(self.words.chunks_exact_mut(self.stride)) { + if ordered { + for part in parts.iter().filter(|part| names.binary_search(&part.name).is_err()) { + let first = part.start.div_ceil(3) as usize; + let end = (part.start.saturating_add(part.count).div_ceil(3) as usize).min(triangles); + if first >= end { + continue; + } + + for (index, word) in row.iter_mut().enumerate().take(end.div_ceil(32)).skip(first / 32) { + let start_bit = first.saturating_sub(index * 32); + let end_bit = (end - index * 32).min(32); + *word &= !((u32::MAX << start_bit) & (u32::MAX >> (32 - end_bit))); + } + } + } else { + // Match the CPU's lookup even for overlapping or out-of-order submeshes + for triangle in 0..triangles { + let first = triangle as u32 * 3; + let holds = |index: usize| parts.get(index).is_some_and(|part| part.start <= first && first < part.start.saturating_add(part.count)); + let part = parts + .partition_point(|part| part.start <= first) + .checked_sub(1) + .filter(|index| holds(*index)) + .or_else(|| (0..parts.len()).find(|index| holds(*index))); + if part.and_then(|index| parts.get(index)).is_some_and(|part| names.binary_search(&part.name).is_err()) { + row[triangle / 32] &= !(1 << (triangle % 32)); + } + } + } + } + } +} diff --git a/crates/render/src/gpu_composite/gpu_compositor.rs b/crates/render/src/gpu_composite/gpu_compositor.rs new file mode 100644 index 00000000..28703a93 --- /dev/null +++ b/crates/render/src/gpu_composite/gpu_compositor.rs @@ -0,0 +1,1280 @@ +#[cfg(all(test, not(target_arch = "wasm32")))] +use super::PRE_PASS_CHUNK_WINDOWS; + +use super::{ + Arc, BAKE_ROW_MAPS, BTreeMap, BakeCache, BakedInputs, COLOR_SELECTION_OPCODE, CompositePaintWindow, CompositePipelines, CompositeProgram, CompositeRegion, + Cow, CurvatureCache, CurvatureGpu, CurvatureInput, CurvatureLevels, CurvatureResources, DECAL_PROJECTION, DeviceExt, DisplayKind, ENVIRONMENT_WORDS, + FIELD_WORDS, GPU_PIPELINES_PENDING, GpuStencil, IMAGE_SOURCE_OPCODE, INPUT2, IdBake, IdBakeCache, IndexedParallelIterator, IntoParallelIterator, + IntoParallelRefIterator, LOOKUP_WORDS, LateEnvironment, MAX_ID_BAKE_BYTES, MAX_ID_UPLOAD_BYTES, MAX_PAINT_WORDS, MAX_TILE_WORK_PER_SUBMISSION, Mesh, + NeighbourhoodFilter, NeighbourhoodGpu, NeighbourhoodRegion, Operation, ParallelIterator, ParallelSlice, ROWS, SEPARATE_MAPS, SurfaceCache, + TILE_GENERATOR_OPCODE, TileImageAtlas, UvGBuffer, Vec3, WORKGROUP, Weak, WholeSetPass, Zeroable, channel_slot, check_texel_work, chunk_paint, + composite_band_size, coverage_word, encode_baked_normal, field_bounds, input_texture, packages, paint_windows, pipelines, pre_pass_budget, + pre_pass_paint_words, scratch_limit, udim, validate_triangle_grid, write_input, write_separate_bakes, +}; + +pub(crate) struct GpuCompositor { + pub(super) pipelines: Arc>, + /// Compile new pipelines on worker threads (`set_asynchronous_compile`) + pub(super) asynchronous: bool, + pub(super) bindings: wgpu::BindGroupLayout, + pub(super) pipeline_layout: wgpu::PipelineLayout, + pub(super) filter_gpu: Option, + /// Take the neighbourhood kernels the tests on the shared device share + pub(super) shared_test_kernels: bool, + pub(super) lookup: wgpu::Buffer, + pub(super) uniform_coverage: wgpu::Buffer, + pub(super) coverage: Vec<(Weak, wgpu::Buffer)>, + pub(super) surfaces: Vec, + pub(super) baked: BTreeMap, + pub(super) id_bakes: BTreeMap, + pub(super) curvature: Option, + pub(super) default_surface: wgpu::TextureView, + pub(super) default_vertices: wgpu::Buffer, + pub(super) default_baked: wgpu::TextureView, + pub(super) default_id_bake: Option, + pub(super) default_brush_alpha: wgpu::TextureView, + pub(super) default_brush_stencil: GpuStencil, + pub(super) default_tile_images: wgpu::TextureView, + pub(super) tile_images: BTreeMap, + pub(super) paint_upload: Option, + /// The working buffer of the last update, reused while the next one fits it + pub(super) scratch: Option, + /// Bytes of the last update's working space and paint upload (tests report them) + pub(super) update_bytes: [u64; 2], +} + +impl GpuCompositor { + pub(crate) fn supports(device: &wgpu::Device) -> bool { + let limits = device.limits(); + limits.max_storage_buffers_per_shader_stage >= 6 + && limits.max_sampled_textures_per_shader_stage >= 5 + && limits.max_uniform_buffers_per_shader_stage >= 2 + && limits.max_bindings_per_bind_group >= 13 + && limits.max_compute_invocations_per_workgroup >= WORKGROUP * WORKGROUP + && limits.max_compute_workgroup_size_x >= WORKGROUP + && limits.max_compute_workgroup_size_y >= WORKGROUP + } + + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn new(device: &wgpu::Device) -> Self { + Self::new_with(device, false) + } + + /// `GpuCompositor::new`, taking the pipelines and kernels the tests on the shared device + /// share when `shared` ([`crate::headless::Headless::for_tests`]) + pub(crate) fn new_with(device: &wgpu::Device, shared: bool) -> Self { + let binding = |binding, ty| wgpu::BindGroupLayoutEntry { binding, visibility: wgpu::ShaderStages::COMPUTE, ty, count: None }; + let buffer = |ty| wgpu::BindingType::Buffer { ty, has_dynamic_offset: false, min_binding_size: None }; + let uniform = buffer(wgpu::BufferBindingType::Uniform); + let read = buffer(wgpu::BufferBindingType::Storage { read_only: true }); + let write = buffer(wgpu::BufferBindingType::Storage { read_only: false }); + let texture = |sample_type, view_dimension| wgpu::BindingType::Texture { sample_type, view_dimension, multisampled: false }; + let uint = texture(wgpu::TextureSampleType::Uint, wgpu::TextureViewDimension::D2); + let array = texture(wgpu::TextureSampleType::Uint, wgpu::TextureViewDimension::D2Array); + let float = texture(wgpu::TextureSampleType::Float { filterable: false }, wgpu::TextureViewDimension::D2); + let limits = device.limits(); + let supports_curvature = limits.max_sampled_textures_per_shader_stage >= 6 + && limits.max_uniform_buffers_per_shader_stage >= 3 + && limits.max_bindings_per_bind_group >= 15 + && limits.max_storage_textures_per_shader_stage >= 1 + && limits.max_compute_workgroup_size_x >= 64; + let supports_id = limits.max_sampled_textures_per_shader_stage >= 6 + u32::from(supports_curvature) && limits.max_bindings_per_bind_group >= 16; + let mut entries = vec![ + binding(0, uniform), + binding(1, read), + binding(2, read), + binding(3, write), + binding(4, read), + binding(5, read), + binding(6, uint), + binding(7, read), + binding(8, uint), + binding(9, uint), + binding(10, array), + binding(11, float), + binding(12, uniform), + ]; + if supports_curvature { + entries.extend([binding(13, uint), binding(14, uniform)]); + } + if supports_id { + entries.push(binding(15, uint)); + } + let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("tc_gpu_composite_bindings"), entries: &entries }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_gpu_composite_layout"), + bind_group_layouts: &[Some(&bindings)], + immediate_size: 0, + }); + let values = texturecraft_texel::srgb_lut().map(u32::from); + let lookup = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_srgb"), + contents: bytemuck::cast_slice(&values), + usage: wgpu::BufferUsages::STORAGE, + }); + let uniform_coverage = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_uniform_coverage"), + contents: &[0; 4], + usage: wgpu::BufferUsages::STORAGE, + }); + let default_surface = input_texture(device, "tc_composite_empty_surface", (1, 1), 1, wgpu::TextureFormat::Rg32Uint).create_view(&Default::default()); + let default_vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_empty_vertices"), + contents: &[0; 32], + usage: wgpu::BufferUsages::STORAGE, + }); + let default_baked = input_texture(device, "tc_composite_empty_bakes", (1, 1), 1, wgpu::TextureFormat::Rgba32Uint).create_view(&Default::default()); + let default_brush_alpha = + input_texture(device, "tc_composite_empty_brush_alpha", (1, 1), 1, wgpu::TextureFormat::R16Uint).create_view(&Default::default()); + Self { + pipelines: pipelines::shared(shared, supports_curvature, supports_id), + shared_test_kernels: shared, + asynchronous: false, + bindings, + pipeline_layout, + filter_gpu: None, + lookup, + uniform_coverage, + coverage: Vec::new(), + surfaces: Vec::new(), + baked: BTreeMap::new(), + id_bakes: BTreeMap::new(), + curvature: supports_curvature.then(|| CurvatureResources { gpu: None, empty: CurvatureLevels::empty(device), cache: BTreeMap::new() }), + default_surface, + default_vertices, + default_baked, + default_id_bake: supports_id + .then(|| input_texture(device, "tc_composite_empty_id_bake", (1, 1), 1, wgpu::TextureFormat::Rgba32Uint).create_view(&Default::default())), + default_brush_alpha, + default_brush_stencil: GpuStencil::empty(device), + default_tile_images: TileImageAtlas::empty_view(device), + tile_images: BTreeMap::new(), + paint_upload: None, + scratch: None, + update_bytes: [0; 2], + } + } + + pub(super) fn surface_inputs( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + program: &CompositeProgram, + ) -> Result<(wgpu::TextureView, wgpu::Buffer), String> { + let Some((mesh, gbuf)) = &program.surface else { + if program.needs_surface || !program.geometry.parts.is_empty() { + return Err("Missing UV surface inputs for GPU layer composition".into()); + } + + return Ok((self.default_surface.clone(), self.default_vertices.clone())); + }; + + if program.needs_surface { + return self.uv_surface(device, queue, mesh, gbuf); + } + + validate_triangle_grid(gbuf)?; + + // A geometry-only mask needs triangle IDs but no barycentrics or surface vertices + self.release_unused_surfaces(); + let key = Arc::downgrade(gbuf); + if let Some(cache) = self.surfaces.iter().find(|cache| cache.gbuf.ptr_eq(&key)) { + return Ok((cache.view.clone(), self.default_vertices.clone())); + } + + let size = (gbuf.width, gbuf.height); + if size.0.max(size.1) > device.limits().max_texture_dimension_2d { + return Err("UV triangle data exceeds the GPU limits".into()); + } + + let texture = input_texture(device, "tc_composite_uv_triangles", size, 1, wgpu::TextureFormat::R32Uint); + for (band, triangles) in gbuf.tri.chunks((size.0 * ROWS) as usize).enumerate() { + write_input(queue, &texture, (size.0, triangles.len() as u32 / size.0), (band as u32 * ROWS, 0), triangles); + } + let view = texture.create_view(&Default::default()); + self.surfaces.push(SurfaceCache { gbuf: key, view: view.clone(), vertices: None }); + Ok((view, self.default_vertices.clone())) + } + + pub(crate) fn uv_surface( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + mesh: &Arc, + gbuf: &Arc, + ) -> Result<(wgpu::TextureView, wgpu::Buffer), String> { + validate_triangle_grid(gbuf)?; + if gbuf.bary.len() != gbuf.tri.len() { + return Err("The UV surface is missing barycentric data.".into()); + } + + self.release_unused_surfaces(); + let key = Arc::downgrade(gbuf); + if let Some((view, vertices)) = + self.surfaces.iter().find(|cache| cache.gbuf.ptr_eq(&key)).and_then(|cache| cache.vertices.as_ref().map(|vertices| (&cache.view, vertices))) + { + return Ok((view.clone(), vertices.clone())); + } + + let limits = device.limits(); + + // Two vec4 per vertex, then the tangents two per 32-byte element (`surface_tangent` in WGSL) + let vertex_bytes = (mesh.indices.len() as u64 + (mesh.indices.len() as u64).div_ceil(2)) * 32; + if gbuf.width.max(gbuf.height) > limits.max_texture_dimension_2d || vertex_bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err("UV surface data exceeds the GPU limits".into()); + } + + self.surfaces.retain(|cache| !cache.gbuf.ptr_eq(&key)); + let (lo, hi) = mesh.bounds(); + let center = (lo + hi) * 0.5; + let radius = ((hi - lo).length() * 0.5).max(1e-4); + let mut vertex_data = Vec::with_capacity(mesh.indices.len() + mesh.indices.len().div_ceil(2)); + vertex_data.extend(mesh.indices.iter().map(|&index| { + let index = index as usize; + let pos = (mesh.positions.get(index).copied().unwrap_or_default() - center) / radius; + let normal = mesh.normals.get(index).copied().unwrap_or(Vec3::Y); + let uv = mesh.uvs.get(index).copied().unwrap_or_default(); + [pos.extend(uv.x).to_array(), normal.extend(uv.y).to_array()] + })); + + // Pack two tangents per element to preserve the shared brush and stencil vertex stride + let tangent = |index: Option<&u32>| index.and_then(|&index| mesh.tangents.get(index as usize)).copied().unwrap_or_default().to_array(); + vertex_data.extend(mesh.indices.chunks(2).map(|pair| [tangent(pair.first()), tangent(pair.get(1))])); + let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_surface_vertices"), + contents: bytemuck::cast_slice(&vertex_data), + usage: wgpu::BufferUsages::STORAGE, + }); + drop(vertex_data); + + let texture = input_texture(device, "tc_composite_uv_surface", (gbuf.width, gbuf.height), 1, wgpu::TextureFormat::Rg32Uint); + let stride = (gbuf.width * ROWS) as usize; + let mut pixels = Vec::new(); + for (band, (tri, bary)) in gbuf.tri.chunks(stride).zip(gbuf.bary.chunks(stride)).enumerate() { + tri.par_iter() + .zip(bary) + .map(|(&tri, &[u, v])| { + let pack = |x: f32| u32::from(texturecraft_texel::to_u16(x)); + [tri, pack(u) | (pack(v) << 16)] + }) + .collect_into_vec(&mut pixels); + write_input(queue, &texture, (gbuf.width, tri.len() as u32 / gbuf.width), (band as u32 * ROWS, 0), &pixels); + } + let view = texture.create_view(&Default::default()); + self.surfaces.push(SurfaceCache { gbuf: key, view: view.clone(), vertices: Some(vertices.clone()) }); + Ok((view, vertices)) + } + + pub(crate) fn retain_texture_sets(&mut self, count: usize) { + self.release_unused_surfaces(); + self.baked.retain(|&ts, _| ts < count); + self.id_bakes.retain(|&ts, _| ts < count); + if let Some(curvature) = &mut self.curvature { + curvature.cache.retain(|&ts, _| ts < count); + } + self.tile_images.retain(|&ts, _| ts < count); + } + + pub(crate) fn release_unused_surfaces(&mut self) { + self.tile_images.retain(|_, atlas| atlas.is_live()); + self.surfaces.retain(|cache| cache.gbuf.strong_count() != 0); + self.coverage.retain(|(grid, _)| grid.strong_count() != 0); + self.id_bakes.retain(|_, cache| cache.data.strong_count() != 0); + if let Some(curvature) = &mut self.curvature { + curvature.cache.retain(|_, cache| cache.map.strong_count() != 0 && cache.gbuf.strong_count() != 0); + } + } + + pub(crate) fn clear_baked_inputs(&mut self) { + self.baked.clear(); + self.id_bakes.clear(); + if let Some(curvature) = &mut self.curvature { + curvature.cache.clear(); + } + } + + pub(crate) fn release_inputs(&mut self, ts: usize) { + self.baked.remove(&ts); + self.id_bakes.remove(&ts); + if let Some(curvature) = &mut self.curvature { + curvature.cache.remove(&ts); + } + self.tile_images.remove(&ts); + } + + pub(super) fn id_bake_input( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + ts: usize, + id_bake: Option<&IdBake>, + ) -> Result, String> { + let Some(id_bake) = id_bake else { + self.id_bakes.remove(&ts); + return Ok(self.default_id_bake.clone()); + }; + + if self.default_id_bake.is_none() { + return Err("Color selection exceeds the adapter's sampled-texture limit.".into()); + } + + let data = Arc::downgrade(&id_bake.data); + if let Some(cache) = self.id_bakes.get(&ts).filter(|cache| cache.size == id_bake.size && cache.data.ptr_eq(&data)) { + return Ok(Some(cache.view.clone())); + } + + let [width, height] = id_bake.size; + + // Pack four RGB words per texel so complete bake rows can upload directly + let packed_height = (u64::from(height) * 3).div_ceil(4) as u32; + let dimensions = device.limits().max_texture_dimension_2d; + if width.max(packed_height) > dimensions || u64::from(width) * u64::from(packed_height) * 16 > MAX_ID_BAKE_BYTES { + return Err("The ID map exceeds the adapter's GPU texture budget.".into()); + } + + self.id_bakes.remove(&ts); + let texture = input_texture(device, "tc_composite_id_bake", (width, packed_height), 1, wgpu::TextureFormat::Rgba32Uint); + let row_words = width as usize * 4; + let word_count = width as usize * height as usize * 3; + let mut tail_row = Vec::new(); + let mut pending = 0; + for (band, source) in id_bake.data[..word_count].chunks(row_words * ROWS as usize).enumerate() { + let rows = source.len() / row_words; + let top = band as u32 * ROWS; + let (full, tail) = source.split_at(rows * row_words); + if rows > 0 { + let full: &[[f32; 4]] = bytemuck::cast_slice(full); + write_input(queue, &texture, (width, rows as u32), (top, 0), full); + } + if !tail.is_empty() { + tail_row.extend_from_slice(tail); + tail_row.resize(row_words, 0.0); + let padded: &[[f32; 4]] = bytemuck::cast_slice(&tail_row); + write_input(queue, &texture, (width, 1), (top + rows as u32, 0), padded); + } + pending += std::mem::size_of_val(source); + if pending >= MAX_ID_UPLOAD_BYTES { + let submission = queue.submit([]); + #[cfg(not(target_arch = "wasm32"))] + device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None }).map_err(|error| error.to_string())?; + #[cfg(target_arch = "wasm32")] + let _ = submission; + pending = 0; + } + } + let view = texture.create_view(&Default::default()); + self.id_bakes.insert(ts, IdBakeCache { size: id_bake.size, data, view: view.clone() }); + Ok(Some(view)) + } + + pub(super) fn baked_input( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + ts: usize, + baked: Option<&BakedInputs>, + ) -> Result { + let Some(baked) = baked else { + self.baked.remove(&ts); + return Ok(self.default_baked.clone()); + }; + + let size = (baked.width, baked.height); + let refs: Vec<_> = baked.maps.iter().chain(&baked.rows).map(|map| map.as_ref().map(Arc::downgrade)).collect(); + if let Some(cache) = self.baked.get(&ts).filter(|cache| { + size == cache.size + && refs.len() == cache.maps.len() + && refs.iter().zip(&cache.maps).all(|(a, b)| match (a, b) { + (Some(a), Some(b)) => a.ptr_eq(b), + (None, None) => true, + _ => false, + }) + }) { + return Ok(cache.view.clone()); + } + + // Reserve separate rows for each map height before the header + let separate = baked.separate().then(|| baked.separate_layout()); + let rows = match separate { + Some((_, header)) => header.checked_add(SEPARATE_MAPS.div_ceil(size.0.max(1) as usize) as u32), + None => size.1.checked_mul(baked.blocks()), + } + .ok_or("Baked maps exceed the GPU texture dimensions")?; + if size.0.max(rows) > device.limits().max_texture_dimension_2d { + return Err("Baked maps exceed the GPU texture dimensions".into()); + } + + self.baked.remove(&ts); + + // Three full-precision scalars and one packed normal fit in one atlas texel + let texture = input_texture(device, "tc_composite_bakes", (size.0, rows), 1, wgpu::TextureFormat::Rgba32Uint); + if let Some(layout) = separate { + write_separate_bakes(queue, &texture, baked, layout); + let view = texture.create_view(&Default::default()); + self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone() }); + return Ok(view); + } + + let mut texels = Vec::new(); + let value = |map: usize, i: usize, fallback: f32| baked.maps[map].as_ref().and_then(|data| data.get(i).copied()).unwrap_or(fallback); + for top in (0..size.1).step_by(ROWS as usize) { + let end = (top + ROWS).min(size.1); + let indices = top as usize * size.0 as usize..end as usize * size.0 as usize; + indices + .into_par_iter() + .map(|i| { + let normal = if baked.maps[1].is_some() { + encode_baked_normal([value(1, i * 3, 0.5), value(1, i * 3 + 1, 0.5), value(1, i * 3 + 2, 1.0)]) + } else { + 0 + }; + [value(0, i, 1.0).to_bits(), value(2, i, 0.5).to_bits(), value(3, i, 1.0).to_bits(), normal] + }) + .collect_into_vec(&mut texels); + write_input(queue, &texture, (size.0, end - top), (top, 0), &texels); + } + if baked.blocks() > 1 { + // Height in x, the stored world normal in yzw; zeros where a map is not baked + let row = |map: usize, i: usize, component: usize| { + let components = BAKE_ROW_MAPS[map].components(); + baked.rows[map].as_ref().and_then(|data| data.get(i * components + component).copied()).unwrap_or(0.0).to_bits() + }; + for top in (0..size.1).step_by(ROWS as usize) { + let end = (top + ROWS).min(size.1); + let indices = top as usize * size.0 as usize..end as usize * size.0 as usize; + indices.into_par_iter().map(|i| [row(0, i, 0), row(1, i, 0), row(1, i, 1), row(1, i, 2)]).collect_into_vec(&mut texels); + write_input(queue, &texture, (size.0, end - top), (size.1 + top, 0), &texels); + } + } + let view = texture.create_view(&Default::default()); + self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone() }); + Ok(view) + } + + pub(super) fn coverage_buffer(&mut self, device: &wgpu::Device, map: Option<&Arc>) -> Result { + let Some(map) = map else { return Ok(self.uniform_coverage.clone()) }; + validate_triangle_grid(map)?; + let key = Arc::downgrade(map); + self.coverage.retain(|(cached, _)| cached.strong_count() != 0); + if let Some((_, buffer)) = self.coverage.iter().find(|(cached, _)| key.ptr_eq(cached)) { + return Ok(buffer.clone()); + } + + let width = map.width as usize; + let words_per_row = width.div_ceil(32); + let count = words_per_row * map.height as usize; + let limits = device.limits(); + if (count * 4) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err("UV padding data exceeds the adapter's storage-buffer limit".into()); + } + + // Each word packs 32 coverage samples. The same buffer serves every display resolution + let words: Vec = if width.is_multiple_of(32) { + map.tri.par_chunks(32).map(coverage_word).collect() + } else { + (0..count) + .into_par_iter() + .map(|i| { + let row = i / words_per_row * width; + let start = row + i % words_per_row * 32; + coverage_word(&map.tri[start..(start + 32).min(row + width)]) + }) + .collect() + }; + let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_coverage"), + contents: bytemuck::cast_slice(&words), + usage: wgpu::BufferUsages::STORAGE, + }); + self.coverage.push((key, buffer.clone())); + Ok(buffer) + } + + pub(super) fn curvature_inputs( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + ts: usize, + program: &CompositeProgram, + baked_view: &wgpu::TextureView, + ) -> Result, String> { + let needed = program.curvature_sizes; + let source = program.baked.as_ref().and_then(|baked| baked.maps[2].as_ref().map(|map| (baked, map))).filter(|_| needed.contains(&true)); + let Some((baked, map)) = source else { + return Ok(self.curvature.as_mut().map(|curvature| { + curvature.cache.remove(&ts); + curvature.empty.clone() + })); + }; + + let Some(curvature) = &self.curvature else { + return Err("Curvature detail sizes exceed the GPU adapter's binding or dispatch limits.".into()); + }; + + let (_, gbuf) = program.surface.as_ref().ok_or("Curvature detail is missing its UV coverage.")?; + let key = Arc::downgrade(gbuf); + let map = Arc::downgrade(map); + let size = [baked.width, baked.height]; + if let Some(cache) = curvature.cache.get(&ts).filter(|cache| cache.gbuf.ptr_eq(&key) && cache.map.ptr_eq(&map) && cache.size == size) + && needed.iter().zip(cache.needed).all(|(&required, present)| !required || present) + { + return Ok(Some(cache.levels.clone())); + } + + // Pad and coarsen each UV block independently, including partially covered blocks + let layout = program.udim_layout.as_ref(); + let block = layout.map_or(size, |layout| [size[0] / layout.grid.cols.max(1), size[1] / layout.grid.rows.max(1)]); + let scales = layout.filter(|layout| layout.scaled).map_or((0, &[][..]), |layout| (layout.block, layout.scales.as_slice())); + let partly_covered = gbuf.covered_count() != gbuf.tri.len() || !scales.1.is_empty(); + let coverage = partly_covered.then(|| self.coverage_buffer(device, Some(gbuf))).transpose()?; + let curvature = self.curvature.as_mut().ok_or("The GPU curvature adapter is unavailable.")?; + curvature.cache.remove(&ts); + let gpu = curvature.gpu.get_or_insert_with(|| CurvatureGpu::new(device)); + let working_size = [gbuf.width, gbuf.height]; + let levels = + gpu.build(device, queue, CurvatureInput { baked: baked_view, bake_size: size, coverage: coverage.as_ref(), working_size, needed, block, scales })?; + curvature.cache.insert(ts, CurvatureCache { gbuf: key, map, size, needed, levels: levels.clone() }); + Ok(Some(levels)) + } + + pub(super) fn tile_atlas( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + ts: usize, + program: &CompositeProgram, + ) -> Result, String> { + let gray: Vec<_> = program.tile_patterns.image_sources().collect(); + let color: Vec<_> = program.material_images.atlas_images().collect(); + let raw = program.material_images.raw_planes(); + if gray.is_empty() && color.is_empty() && raw.is_empty() { + self.tile_images.remove(&ts); + return Ok(None); + } + + if self.tile_images.get(&ts).is_none_or(|atlas| !atlas.matches(&gray, &color, raw)) { + self.tile_images.remove(&ts); + let atlas = TileImageAtlas::new(device, queue, &gray, &color, raw)?; + self.tile_images.insert(ts, atlas); + } + Ok(self.tile_images.get(&ts)) + } + + /// Compose bands into reusable GPU scratch space, then copy them into display textures. + /// Indexed/SRGB and floating-point maps use the same formats as the CPU uploader. + pub(crate) fn compose( + &mut self, + gpu: (&wgpu::Device, &wgpu::Queue), + program: &CompositeProgram, + target: (usize, (u32, u32), u32, Option), + textures: &[&wgpu::Texture], + submitted: &mut Option, + ) -> Result<(), String> { + let (device, queue) = gpu; + let (ts, source_size, shift, region) = target; + let base = textures.first().ok_or("The GPU output textures are missing.")?; + let extent = (base.width(), base.height()); + let region = region.map(|r| r.viewport(shift, extent)).unwrap_or(CompositeRegion { min: [0; 2], max: [extent.0, extent.1] }); + let width = region.max[0].saturating_sub(region.min[0]); + let height = region.max[1].saturating_sub(region.min[1]); + if width == 0 || height == 0 { + return Ok(()); + } + + let selection_work = if program.id_bake.is_some() { + program.operations.iter().filter(|op| op.ids[1] == COLOR_SELECTION_OPCODE).map(|op| u64::from(op.procedural[2])).sum() + } else { + 0 + }; + let pattern_work = program.tile_work_per_pixel()?; + check_texel_work(pattern_work)?; + let tile_work = pattern_work.saturating_add(program.groups.work_per_pixel()).saturating_add(selection_work); + let grouped = program.groups.depth != 0; + let radius = program.coverage.as_ref().map_or(0, |(_, radius)| *radius); + + // A band's halo leaves out the stages the whole-set pre-pass evaluates + let whole = program.filters.whole_set(); + let halo = radius.saturating_add(program.filters.band_reach(whole.as_ref())); + let limits = device.limits(); + let scratch_limit = scratch_limit(&limits); + let (mut band_width, mut band_rows) = composite_band_size(width, tile_work); + let filtered = !program.filters.stages.is_empty(); + if filtered { + if limits.max_compute_workgroup_size_x < 64 { + return Err("The GPU cannot run the neighbourhood filter workgroups.".into()); + } + + if tile_work == 0 { + band_rows = height.min(256); + } + let shared = self.shared_test_kernels; + self.filter_gpu.get_or_insert_with(|| NeighbourhoodGpu::for_device(device, shared)); + } + let (pipeline, prepare) = self.pipelines().get(device, &self.pipeline_layout, program, self.asynchronous)?.ok_or(GPU_PIPELINES_PENDING)?; + let coverage = self.coverage_buffer(device, program.coverage.as_ref().map(|(map, _)| map))?; + let (surface, vertices) = self.surface_inputs(device, queue, program)?; + let baked = self.baked_input(device, queue, ts, program.baked.as_ref())?; + let curvature = self.curvature_inputs(device, queue, ts, program, &baked)?; + let id_bake = self.id_bake_input(device, queue, ts, program.id_bake.as_ref())?; + let [id_width, id_height] = program.id_bake.as_ref().map_or([0; 2], |id| id.size); + let bake_words = program.baked.as_ref().map_or([0; 2], BakedInputs::uniform_words); + let mut words_per_pixel = 0; + let copies = DisplayKind::ALL.map(|kind| { + if !program.writes_display(kind) { + return None; + } + + let bytes_per_texel = kind.bytes_per_texel() as u32; + let offset = words_per_pixel; + words_per_pixel += u64::from(bytes_per_texel / 4); + Some((offset, bytes_per_texel)) + }); + + // A wrapping stage's fields extend past the set's edges (FilterPlan::wraps) + let wraps = program.filters.wraps(); + let field_area = |width: u32, rows: u32| { + let side = |pixels: u32, limit: u32| { + let side = (pixels << shift).saturating_add(halo.saturating_mul(2)); + if wraps { side } else { side.min(limit) } + }; + u64::from(side(width, source_size.0)) * u64::from(side(rows, source_size.1)) + }; + let band_area = |width: u32, rows: u32| u64::from(width.next_multiple_of(64) * rows); + let display_words = |width, rows| band_area(width, rows) * words_per_pixel; + let texel_words = program.filters.field_words(); + let group_start = |width, rows| display_words(width, rows) + program.filters.words(field_area(width, rows), texel_words); + let required = |width, rows| (group_start(width, rows) + program.groups.words(band_area(width, rows))) * 4; + let filter_work: u64 = + program.filters.stages.iter().map(|stage| stage.filter.map_or(1, NeighbourhoodFilter::work_per_texel) + if stage.cell > 1 { 6 } else { 0 }).sum(); + + // Reserve stripe scratch for the whole-set pre-pass before sizing the bands + let whole = whole.map(|whole| WholeSetPass::plan(whole, (region, shift), source_size, halo, wraps, texel_words, program.filters.stages.len())); + let whole_bytes = whole.as_ref().map_or(0, WholeSetPass::result_bytes); + if whole_bytes >= scratch_limit { + return Err("The whole-set filter results exceed the adapter's working memory limit.".into()); + } + + let scratch_limit = scratch_limit - whole_bytes; + let whole = whole.map(|whole| whole.with_stripes(scratch_limit)).transpose()?; + + // Use the CPU when stripes would compute separate Color Match averages + if let Some(whole) = &whole + && whole.stripe_rows < whole.region[3] - whole.region[1] + && whole + .stages + .stages + .iter() + .filter_map(|&stage| program.filters.stages.get(stage)?.filter) + .any(crate::gpu_neighbourhood::gather::reads_whole_set_mean) + { + return Err("Color Match's Average over a set that needs stripes uses CPU compositing.".into()); + } + + // A filtered band includes its source halo. Folder snapshots use only its output area + while required(band_width, band_rows) > scratch_limit { + if band_width == 1 && band_rows == 1 { + return Err("Composite inputs for one GPU texel exceed the adapter's working memory limit.".into()); + } + + if band_width >= band_rows { + band_width = band_width.div_ceil(2); + } else { + band_rows = band_rows.div_ceil(2); + } + } + let pitch = band_width.next_multiple_of(64); + + // A costly update submits its bands in parts of the submission budget + let update_work = (u64::from(width) * u64::from(height)).saturating_mul(tile_work); + let submit_budget = if grouped || filtered || band_width < width || band_rows < ROWS || update_work > MAX_TILE_WORK_PER_SUBMISSION { + MAX_TILE_WORK_PER_SUBMISSION + } else { + u64::MAX + }; + let area = pitch * band_rows; + let stride = u64::from(area) * 4; + let field_base = (display_words(band_width, band_rows)) as u32; + let group_base = group_start(band_width, band_rows) as u32; + + // The whole-set results follow the larger of the bands' and the pre-pass's working space + let working = whole.as_ref().map_or(0, WholeSetPass::stripe_bytes).max(required(band_width, band_rows)); + let whole_base = u32::try_from(working / 4).map_err(|_| "The GPU working memory exceeds 32-bit word addressing.")?; + + // Reuse cleared scratch only within four times the new working size + let size = working + whole_bytes; + let scratch = match &self.scratch { + Some(buffer) if buffer.size() >= size && buffer.size() / 4 <= size => { + let mut clear = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_composite_clear") }); + clear.clear_buffer(buffer, 0, Some(size)); + queue.submit([clear.finish()]); + buffer.clone() + } + _ => { + self.scratch = None; + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_composite_scratch"), + size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + self.scratch = Some(buffer.clone()); + buffer + } + }; + self.update_bytes = [size, 0]; + let atlas = self.tile_atlas(device, queue, ts, program)?; + let tile_images = atlas.map(|atlas| atlas.view.clone()); + let (operations, lookup) = + if program.tile_patterns.is_empty() && program.ramp_words.is_empty() && program.geometry.words.is_empty() && program.material_images.is_empty() { + (Cow::Borrowed(program.operations.as_slice()), self.lookup.clone()) + } else { + let mut words = texturecraft_texel::srgb_lut().map(u32::from).to_vec(); + words.extend(&program.ramp_words); + let geometry_start = words.len(); + words.extend(&program.geometry.words); + let offsets = program.tile_patterns.append_words(&mut words, atlas); + let mesh = program.surface.as_ref().map(|(mesh, _)| mesh.as_ref()); + let (images, decals) = program.material_images.append_words(&mut words, atlas, mesh); + + // Side-table words that name an image hold its record offset (`pack_image`) + for &(word, image) in &program.image_words { + let at = LOOKUP_WORDS as usize + word as usize; + words[at] = images.get(image as usize).copied().unwrap_or(u32::MAX); + } + + // The environment's diffuse light, late-bound (`reserve_environment`) + if let Some(LateEnvironment { word, words: Some(light), .. }) = &program.environment { + let at = LOOKUP_WORDS as usize + *word as usize; + words[at..at + ENVIRONMENT_WORDS].copy_from_slice(light); + } + let limits = device.limits(); + + // The operation stores the offset as an exactly represented float + if ((!offsets.is_empty() || !decals.is_empty()) && words.len() >= 1 << 24) + || (words.len() * 4) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) + { + return Err("Procedural settings exceed the GPU parameter buffer limit.".into()); + } + + let mut operations = program.operations.clone(); + for op in operations.iter_mut().filter(|op| op.constraints[0] != 0) { + let row = (op.constraints[0] - 1) as usize; + op.constraints[0] = + u32::try_from(geometry_start + row * program.geometry.stride).map_err(|_| "The GPU geometry mask offset is too large.")?; + } + for op in operations.iter_mut().filter(|op| op.ids[1] == TILE_GENERATOR_OPCODE) { + let index = op.high[3] as usize; + op.high[3] = *offsets.get(index).ok_or("A Tile Generator operation has no settings.")? as f32; + } + for op in &mut operations { + if op.ids[1] == IMAGE_SOURCE_OPCODE { + op.ids[2] = *images.get(op.ids[2] as usize).ok_or("An image source has no binding.")?; + } + + // Placed planars and warps (the first of P1's selectors) read their frame record + if op.procedural[3] == DECAL_PROJECTION || op.procedural[3] == packages::PROJECTION_SELECTORS.start { + op.uv[0] = *decals.get(op.uv[0] as usize).ok_or("A decal has no frame.")? as f32; + } + } + let lookup = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_tile_patterns"), + contents: bytemuck::cast_slice(&words), + usage: wgpu::BufferUsages::STORAGE, + }); + (Cow::Owned(operations), lookup) + }; + let tile_images = tile_images.as_ref().unwrap_or(&self.default_tile_images); + let brush_alpha = program.brush_alpha.as_ref().unwrap_or(&self.default_brush_alpha); + let brush_stencil = program.brush_stencil.as_ref().unwrap_or(&self.default_brush_stencil); + let empty_operation = Operation::zeroed(); + let limits = device.limits(); + if (operations.len() * size_of::()) as u64 > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err("The layer program exceeds the adapter's storage-buffer limit".into()); + } + + let ops = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_operations"), + contents: if operations.is_empty() { bytemuck::bytes_of(&empty_operation) } else { bytemuck::cast_slice(operations.as_ref()) }, + usage: wgpu::BufferUsages::STORAGE, + }); + let max_words = MAX_PAINT_WORDS.min((limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) / 4) as usize); + let windows = paint_windows(program, region, source_size, shift, halo, max_words)?; + + // The band uniform: the positional words, the field layout and the package vec4s + let band_values = + |(width, rows, top, left): (u32, u32, u32, u32), [paint_x, paint_y, paint_columns, paint_rows]: [u32; 4], field_rect: [u32; 4], field_base: u32| { + let mut values = [0; packages::UNIFORM_WORDS]; + values[..packages::FIELD_LAYOUT].copy_from_slice(&[ + width, + rows, + top, + area, + source_size.0, + source_size.1, + 1 << shift, + u32::from(program.glossiness), + program.layer_count, + pitch, + program.display_outputs, + left, + u32::from(program.coverage.is_some()), + source_size.0.div_ceil(32), + radius, + u32::from(program.needs_surface) + | (u32::from(program.baked.is_some()) << 1) + | (u32::from(program.brush_stencil.is_some()) << 2) + | (u32::from(!program.geometry.words.is_empty()) << 3) + | (u32::from(program.mix_baked_ao) << 4), + paint_x, + paint_y, + paint_columns, + paint_rows, + field_rect[0], + field_rect[1], + field_rect[2], + field_rect[3], + field_base, + group_base, + program.groups.words_per_level, + program.groups.channels, + 0, + 0, + field_rect[2], + field_rect[3], + id_width, + id_height, + bake_words[0], + bake_words[1], + 0, + 0, + 0, + program.mask_layer, + 0, + 0, + 0, + 0, + ]); + + // The prepare pass sets the third layout word to its input operation + values[packages::FIELD_LAYOUT..packages::FIELD_LAYOUT + 2].copy_from_slice(&[texel_words, u32::from(texel_words > FIELD_WORDS)]); + packages::write_band_uniform(program, &mut values); + values + }; + let make_bindings = |values: &[u32], paint: &wgpu::Buffer| { + let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_band"), + contents: bytemuck::cast_slice(values), + usage: wgpu::BufferUsages::UNIFORM, + }); + let mut entries = [ + wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: ops.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: lookup.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: scratch.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: paint.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 5, resource: coverage.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&surface) }, + wgpu::BindGroupEntry { binding: 7, resource: vertices.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(&baked) }, + wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(brush_alpha) }, + wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(tile_images) }, + wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(&brush_stencil.image) }, + wgpu::BindGroupEntry { binding: 12, resource: brush_stencil.uniforms.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 13, resource: wgpu::BindingResource::TextureView(curvature.as_ref().map_or(&baked, |levels| &levels.image)) }, + wgpu::BindGroupEntry { + binding: 14, + resource: curvature.as_ref().map_or_else(|| lookup.as_entire_binding(), |levels| levels.layout.as_entire_binding()), + }, + wgpu::BindGroupEntry { binding: 15, resource: wgpu::BindingResource::TextureView(id_bake.as_ref().unwrap_or(&baked)) }, + ]; + let mut count = if curvature.is_some() { 15 } else { 13 }; + if id_bake.is_some() { + entries.swap(count, 15); + count += 1; + } + device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_composite_band"), layout: &self.bindings, entries: &entries[..count] }) + }; + let mut packed = Vec::new(); + let mut pending_bytes = 0; + let mut last_submission = None; + let make_encoder = || device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_composite") }); + let submit = |encoder: wgpu::CommandEncoder, bounds: CompositeRegion, submitted: &mut Option| { + let submission = queue.submit([encoder.finish()]); + *submitted = Some(submitted.map_or(bounds, |region| region.union(bounds))); + submission + }; + + // Evaluate each whole-set stack once in shared stripe scratch before the bands read its results + if let (Some(whole), Some(prepare), Some(kernels)) = (&whole, &prepare, &self.filter_gpu) { + let [x0, y0, x1, y1] = whole.region; + let fields = program.filters.stages.len() as u32; + let paint_limit = (max_words * 4) as u64; + + // Pack and upload a paint window, after submitting what reads the previous one + let upload = |window: &CompositePaintWindow, + words: usize, + encoder: &mut wgpu::CommandEncoder, + (buffer, packed): (&mut Option, &mut Vec)| { + queue.submit([std::mem::replace(encoder, make_encoder()).finish()]); + window.pack(&program.paint, words, packed); + let bytes = (words * 4) as u64; + let paint = match buffer { + Some(paint) if paint.size() >= bytes => paint, + _ => buffer.insert(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_composite_paint"), + size: bytes.next_power_of_two().min(paint_limit), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })), + }; + queue.write_buffer(paint, 0, bytemuck::cast_slice(packed)); + }; + for top in (y0..y1).step_by(whole.stripe_rows as usize) { + let rows = whole.stripe_rows.min(y1 - top); + let mut encoder = make_encoder(); + + // Split the stripe by source chunk only when a shared paint window exceeds the budget + let (low, high) = whole.paint_window(source_size, top, rows); + let stripe_window = CompositePaintWindow::covering(low, high, [source_size.0, source_size.1], &program.paint); + let paint_words = pre_pass_paint_words(max_words); + let stripe_words = stripe_window.words(&program.paint, paint_words); + if let Some(words) = stripe_words { + upload(&stripe_window, words, &mut encoder, (&mut self.paint_upload, &mut packed)); + } + for pass in &whole.stages.passes { + let field_rect = whole.field_rect(pass, top, rows); + let set_bounds = field_bounds(field_rect, source_size); + let field_words = field_rect[2] * field_rect[3] * texel_words; + let offset = |slot: u32| pass.slot(slot, fields) * field_words; + let values = |paint_params: [u32; 4]| { + let mut values = band_values((0, 0, 0, 0), paint_params, field_rect, 0); + values[packages::WHOLE_COMPACT..packages::WHOLE_COMPACT + 4].copy_from_slice(&pass.compact(fields)); + values + }; + let (source_width, source_rows) = + if tile_work == 0 { (field_rect[2], field_rect[3]) } else { composite_band_size(field_rect[2], tile_work) }; + let mut work = 0u64; + for &output in &pass.stages { + let stage = &program.filters.stages[output]; + + // P8: a level stage runs only where a block of its tile scale lies, on its base stage's field + if !udim::runs_over(program.udim_layout.as_ref(), stage.level, field_rect, (source_size, wraps)) { + continue; + } + + let reuses_field = udim::reuses_base_field(&program.filters.stages, output); + let direct = stage.filter.is_none() && stage.cell == 1; + let slot = if direct { output as u32 } else { fields }; + let stage_values = |paint_params: [u32; 4]| { + let mut source = values(paint_params); + source[25..28].copy_from_slice(&[slot, stage.layer, stage.preceding]); + source[packages::FIELD_LAYOUT + 2] = stage.input; + source[packages::FIELD_LAYOUT + 3] = u32::from(wraps) | stage.input_kind | stage.view | if stage.input2 != 0 { INPUT2 } else { 0 }; + + // A second input source (operation plus one), the mask views + source[38] = stage.input2; + source[packages::MASK_VIEW..packages::MASK_VIEW + 4].copy_from_slice(&stage.mask_view); + source + }; + let source_rows_total = if reuses_field { 0 } else { field_rect[3] }; + let mut chunks: Vec<[u32; 4]> = (0..source_rows_total) + .step_by(source_rows as usize) + .flat_map(|y| { + (0..field_rect[2]) + .step_by(source_width as usize) + .map(move |x| [x, y, source_width.min(field_rect[2] - x), source_rows.min(field_rect[3] - y)]) + }) + .rev() + .collect(); + while let Some(chunk @ [x, y, columns, chunk_rows]) = chunks.pop() { + let paint_params = if stripe_words.is_some() { + stripe_window.params() + } else { + // The chunk's own paint, split in two while it does not fit + let (low, high) = chunk_paint(field_rect, chunk, source_size, wraps); + let window = CompositePaintWindow::covering(low, high, [source_size.0, source_size.1], &program.paint); + let Some(words) = window.words(&program.paint, paint_words) else { + if chunk_rows < 2 { + return Err("Paint inputs of the whole-set filter exceed the adapter's upload budget.".into()); + } + + let half = chunk_rows / 2; + chunks.extend([[x, y + half, columns, chunk_rows - half], [x, y, columns, half]]); + continue; + }; + + upload(&window, words, &mut encoder, (&mut self.paint_upload, &mut packed)); + #[cfg(all(test, not(target_arch = "wasm32")))] + PRE_PASS_CHUNK_WINDOWS.set(PRE_PASS_CHUNK_WINDOWS.get() + 1); + work = 0; + window.params() + }; + let work_here = u64::from(columns).saturating_mul(u64::from(chunk_rows)).saturating_mul(tile_work); + if work > 0 && work.saturating_add(work_here) > MAX_TILE_WORK_PER_SUBMISSION { + queue.submit([std::mem::replace(&mut encoder, make_encoder()).finish()]); + work = 0; + } + let mut source = stage_values(paint_params); + source[28..32].copy_from_slice(&chunk); + let paint = self.paint_upload.as_ref().ok_or("paint upload buffer is missing")?; + let source_bindings = make_bindings(&source, paint); + let mut compute = + encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_whole_set_source"), timestamp_writes: None }); + compute.set_pipeline(prepare); + compute.set_bind_group(0, &source_bindings, &[]); + compute.dispatch_workgroups(columns.div_ceil(WORKGROUP), chunk_rows.div_ceil(WORKGROUP), 1); + drop(compute); + work = work.saturating_add(work_here); + } + let region = NeighbourhoodRegion { + rect: field_rect, + original: offset(fields), + blur: pass.blur(fields, offset), + output: offset(output as u32), + field_words: texel_words, + input: stage.input_bits(texel_words), + wrap: stage.wrap, + bounds: set_bounds, + }; + + // Chunk row gathers to stay within the submission budget + queue.submit([std::mem::replace(&mut encoder, make_encoder()).finish()]); + work = 0; + if reuses_field && direct { + let field = (field_rect[2], field_rect[3]); + kernels.encode_copy( + device, + &mut encoder, + &scratch, + (region.original, field.0, [0; 2]), + (region.output, field.0, 0), + [field.0, field.1], + texel_words, + ); + } + let _budget = kernels.budget(queue, stage.filter.map_or(1, NeighbourhoodFilter::work_per_texel), pre_pass_budget()); + if stage.cell > 1 { + let target = if stage.filter.is_some() { region.original } else { region.output }; + kernels.encode_cells(device, &mut encoder, &scratch, NeighbourhoodRegion { output: target, ..region }, stage.cell); + } + if let Some(filter) = stage.filter { + kernels.encode(device, &mut encoder, &scratch, region, filter); + } + } + + // The stripe's rows of the pass's outputs, from their fields into the results + let from = [(x0 as i32 - field_rect[0] as i32) as u32, (top as i32 - field_rect[1] as i32) as u32]; + for &output in &pass.outputs { + let index = whole.stages.outputs.iter().position(|&own| own == output).ok_or("A whole-set output has no result.")?; + let result = whole.result_base(whole_base, index); + kernels.encode_copy( + device, + &mut encoder, + &scratch, + (offset(output as u32), field_rect[2], from), + (result, x1 - x0, top - y0), + [x1 - x0, rows], + texel_words, + ); + } + queue.submit([std::mem::replace(&mut encoder, make_encoder()).finish()]); + } + } + } + for (chunk, window, words) in windows { + let bytes = (words * 4) as u64; + window.pack(&program.paint, words, &mut packed); + let [paint_x, paint_y, paint_columns, paint_rows] = window.params(); + if pending_bytes + bytes > (max_words * 4) as u64 { + device.poll(wgpu::PollType::Wait { submission_index: last_submission.take(), timeout: None }).map_err(|e| e.to_string())?; + pending_bytes = 0; + } + let upload_size = bytes.next_power_of_two().min((max_words * 4) as u64); + if self.paint_upload.as_ref().is_none_or(|buffer| buffer.size() < bytes) { + self.paint_upload = Some(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_composite_paint"), + size: upload_size, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + let paint = self.paint_upload.as_ref().ok_or("paint upload buffer is missing")?; + queue.write_buffer(paint, 0, bytemuck::cast_slice(&packed)); + let mut encoder = make_encoder(); + let mut work = 0u64; + let mut bounds: Option = None; + let bands = (chunk.min[1]..chunk.max[1]) + .step_by(band_rows as usize) + .flat_map(|top| (chunk.min[0]..chunk.max[0]).step_by(band_width as usize).map(move |left| (left, top))); + for (left, top) in bands { + let width = band_width.min(chunk.max[0] - left); + let rows = band_rows.min(chunk.max[1] - top); + let source_work = u64::from(width).saturating_mul(u64::from(rows)).saturating_mul(tile_work); + let band_work = source_work.saturating_add(field_area(width, rows).saturating_mul(filter_work)); + if let Some(written) = bounds.take_if(|_| work.saturating_add(band_work) > submit_budget) { + let previous = std::mem::replace(&mut encoder, make_encoder()); + submit(previous, written, submitted); + work = 0; + } + let field = CompositeRegion { min: [left << shift, top << shift], max: [(left + width) << shift, (top + rows) << shift] }.expanded(halo); + let mut field_rect = + [field.min[0], field.min[1], field.max[0].min(source_size.0) - field.min[0], field.max[1].min(source_size.1) - field.min[1]]; + if wraps { + // The whole halo on every side; the origin can lie below zero (i32 bits) + let start = |pixel: u32| (i64::from(pixel << shift) - i64::from(halo)) as i32 as u32; + field_rect = [start(left), start(top), (width << shift).saturating_add(halo * 2), (rows << shift).saturating_add(halo * 2)]; + } + + // Only wrapping stages may sample field-local texels across a set edge + let set_bounds = field_bounds(field_rect, source_size); + let mut values = band_values((width, rows, top, left), [paint_x, paint_y, paint_columns, paint_rows], field_rect, field_base); + if let Some(whole) = &whole { + whole.write_uniform(&mut values, whole_base); + } + let bindings = |values: &[u32]| make_bindings(values, paint); + if let (Some(prepare), Some(kernels)) = (&prepare, &self.filter_gpu) { + let fields = program.filters.stages.len() as u32; + let field_words = field_rect[2] * field_rect[3] * texel_words; + let offset = |slot| field_base + slot * field_words; + let (source_width, source_rows) = + if tile_work == 0 { (field_rect[2], field_rect[3]) } else { composite_band_size(field_rect[2], tile_work) }; + for (output, stage) in program.filters.stages.iter().enumerate() { + // The whole-set pre-pass evaluated this stage for the bands + if whole.as_ref().is_some_and(|whole| whole.stages.stages.contains(&output)) { + continue; + } + + // P8: a level stage runs only where a block of its tile scale lies, on its base stage's field + if !udim::runs_over(program.udim_layout.as_ref(), stage.level, field_rect, (source_size, wraps)) { + continue; + } + + let reuses_field = udim::reuses_base_field(&program.filters.stages, output); + let mut source = values; + let direct = stage.filter.is_none() && stage.cell == 1; + let slot = if direct { output as u32 } else { fields }; + source[25..28].copy_from_slice(&[slot, stage.layer, stage.preceding]); + source[packages::FIELD_LAYOUT + 2] = stage.input; + + // Periodic copies extend beyond the set while stage bounds preserve seams + source[packages::FIELD_LAYOUT + 3] = u32::from(wraps) | stage.input_kind | stage.view | if stage.input2 != 0 { INPUT2 } else { 0 }; + + // A second input source (operation plus one), the mask views + source[38] = stage.input2; + source[packages::MASK_VIEW..packages::MASK_VIEW + 4].copy_from_slice(&stage.mask_view); + if let Some((channel, first, cut)) = stage.anchor { + source[36..39].copy_from_slice(&[channel_slot(channel), first, cut]); + source[40..43].copy_from_slice(&channel.default_value().map(f32::to_bits)); + } + let source_chunks = if reuses_field { 0 } else { field_rect[3] }; + for y in (0..source_chunks).step_by(source_rows as usize) { + for x in (0..field_rect[2]).step_by(source_width as usize) { + let columns = source_width.min(field_rect[2] - x); + let rows = source_rows.min(field_rect[3] - y); + let work_here = u64::from(columns).saturating_mul(u64::from(rows)).saturating_mul(tile_work); + if work > 0 && work.saturating_add(work_here) > submit_budget { + let previous = std::mem::replace(&mut encoder, make_encoder()); + last_submission = Some(match bounds.take() { + Some(written) => submit(previous, written, submitted), + None => queue.submit([previous.finish()]), + }); + work = 0; + } + source[28..32].copy_from_slice(&[x, y, columns, rows]); + let source_bindings = bindings(&source); + let mut pass = + encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_spatial_source"), timestamp_writes: None }); + pass.set_pipeline(prepare); + pass.set_bind_group(0, &source_bindings, &[]); + pass.dispatch_workgroups(columns.div_ceil(WORKGROUP), rows.div_ceil(WORKGROUP), 1); + work = work.saturating_add(work_here); + } + } + let region = NeighbourhoodRegion { + rect: field_rect, + original: offset(fields), + blur: [offset(fields + 1), offset(fields + 2)], + output: offset(output as u32), + field_words: texel_words, + input: stage.input_bits(texel_words), + wrap: stage.wrap, + bounds: set_bounds, + }; + if reuses_field && direct { + let field = (field_rect[2], field_rect[3]); + kernels.encode_copy( + device, + &mut encoder, + &scratch, + (region.original, field.0, [0; 2]), + (region.output, field.0, 0), + [field.0, field.1], + texel_words, + ); + } + if stage.cell > 1 { + let target = if stage.filter.is_some() { region.original } else { region.output }; + kernels.encode_cells(device, &mut encoder, &scratch, NeighbourhoodRegion { output: target, ..region }, stage.cell); + } + if let Some(filter) = stage.filter { + kernels.encode(device, &mut encoder, &scratch, region, filter); + } + } + } + let bindings = bindings(&values); + { + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_composite"), timestamp_writes: None }); + pass.set_pipeline(&pipeline); + pass.set_bind_group(0, &bindings, &[]); + pass.dispatch_workgroups(width.div_ceil(WORKGROUP), rows.div_ceil(WORKGROUP), 1); + } + for (texture, copy) in textures.iter().copied().zip(copies) { + let Some((offset, bytes_per_texel)) = copy else { continue }; + encoder.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: &scratch, + layout: wgpu::TexelCopyBufferLayout { offset: stride * offset, bytes_per_row: Some(pitch * bytes_per_texel), rows_per_image: None }, + }, + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: left, y: top, z: 0 }, ..texture.as_image_copy() }, + wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 }, + ); + } + let band = CompositeRegion { min: [left, top], max: [left + width, top + rows] }; + bounds = Some(bounds.map_or(band, |region| region.union(band))); + work = work.saturating_add(band_work); + } + if let Some(written) = bounds { + last_submission = Some(submit(encoder, written, submitted)); + } + pending_bytes += bytes; + } + self.update_bytes[1] = self.paint_upload.as_ref().map_or(0, wgpu::Buffer::size); + Ok(()) + } + + /// Whether `program`'s pipelines are compiled; starts compiling them otherwise (on worker + /// threads when [`Self::set_asynchronous_compile`] is on). An error when their compile failed. + pub(crate) fn pipelines_ready(&mut self, device: &wgpu::Device, program: &CompositeProgram) -> Result { + Ok(self.pipelines().get(device, &self.pipeline_layout, program, self.asynchronous)?.is_some()) + } + + /// Start compiling `program`'s pipelines on worker threads without compositing. + pub(crate) fn prewarm(&mut self, device: &wgpu::Device, program: &CompositeProgram) { + self.pipelines().prewarm(device, &self.pipeline_layout, program); + } + + /// Compile new pipelines on worker threads (the app's viewport) or in place (tests, wasm). + pub(crate) fn set_asynchronous_compile(&mut self, asynchronous: bool) { + self.asynchronous = asynchronous && !cfg!(target_arch = "wasm32"); + } + + pub(super) fn pipelines(&self) -> std::sync::MutexGuard<'_, CompositePipelines> { + self.pipelines.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Bytes of the last update's working buffer and paint upload buffer. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn update_bytes(&self) -> [u64; 2] { + self.update_bytes + } +} diff --git a/crates/render/src/gpu_composite/id_bake.rs b/crates/render/src/gpu_composite/id_bake.rs new file mode 100644 index 00000000..3f34574d --- /dev/null +++ b/crates/render/src/gpu_composite/id_bake.rs @@ -0,0 +1,15 @@ +use super::{Arc, BakedMap, BakedMaps}; + +#[derive(Debug)] +pub(super) struct IdBake { + pub(super) size: [u32; 2], + pub(super) data: Arc>, +} + +impl IdBake { + pub(super) fn new(baked: &BakedMaps) -> Option { + let data = baked.maps.get(&BakedMap::Id)?; + let height = baked.height(BakedMap::Id); + (height > 0).then(|| Self { size: [baked.resolution.max(1), height], data: data.clone() }) + } +} diff --git a/crates/render/src/gpu_composite/id_bake_cache.rs b/crates/render/src/gpu_composite/id_bake_cache.rs new file mode 100644 index 00000000..96c87b62 --- /dev/null +++ b/crates/render/src/gpu_composite/id_bake_cache.rs @@ -0,0 +1,7 @@ +use super::Weak; + +pub(super) struct IdBakeCache { + pub(super) size: [u32; 2], + pub(super) data: Weak>, + pub(super) view: wgpu::TextureView, +} diff --git a/crates/render/src/gpu_composite/late_environment.rs b/crates/render/src/gpu_composite/late_environment.rs new file mode 100644 index 00000000..9dfb35c2 --- /dev/null +++ b/crates/render/src/gpu_composite/late_environment.rs @@ -0,0 +1,25 @@ +use super::{DisplaySettings, ENVIRONMENT_WORDS, EnvironmentSh}; + +/// A program's late-bound environment words: where they start in the side table, the display +/// settings of the compiled project (environment and rotation) and, once the images are known, +/// the words. +#[derive(Debug)] +pub(super) struct LateEnvironment { + pub(super) word: u32, + pub(super) display: DisplaySettings, + pub(super) words: Option<[u32; ENVIRONMENT_WORDS]>, +} + +impl LateEnvironment { + pub(super) fn new(word: Option, display: &DisplaySettings) -> Option { + word.map(|word| Self { word, display: display.clone(), words: None }) + } + + pub(super) fn set(&mut self, environment: &EnvironmentSh) { + let mut words = [0; ENVIRONMENT_WORDS]; + for (word, value) in words.iter_mut().zip(environment.coefficients().iter().flatten().chain([environment.rotation()].iter())) { + *word = value.to_bits(); + } + self.words = Some(words); + } +} diff --git a/crates/render/src/gpu_composite/live_brush.rs b/crates/render/src/gpu_composite/live_brush.rs new file mode 100644 index 00000000..021106c8 --- /dev/null +++ b/crates/render/src/gpu_composite/live_brush.rs @@ -0,0 +1,43 @@ +use super::{Channel, GpuStencil, LayerId, LiveBrushTarget}; + +/// The active stroke's GPU alpha, sampled in the corresponding paint layer or mask effect. +pub struct LiveBrush { + pub target: LiveBrushTarget, + pub opacity: f32, + /// The Eraser: the stroke scales the target's paint and coverage down. A layer target then + /// lists the channels the commit erases, with unused values. + pub erase: bool, + pub alpha: wgpu::TextureView, + /// Supplies opacity modulation and Base Color for a projection stroke. + pub stencil: Option, +} + +impl LiveBrush { + pub(super) fn validate(&self, size: (u32, u32)) -> Result<(), &'static str> { + let alpha = self.alpha.texture(); + if (alpha.width(), alpha.height()) != size || alpha.format() != wgpu::TextureFormat::R16Uint { + return Err("The live brush alpha does not match the texture set."); + } + + let valid = match &self.target { + LiveBrushTarget::Layer { values, .. } => values.values().flatten().all(|v| v.is_finite()), + LiveBrushTarget::Mask { value, .. } => value.is_finite(), + }; + if !valid || !self.opacity.is_finite() { + return Err("The live brush has invalid paint values."); + } + + Ok(()) + } + + /// The live paint of `channel` on paint layer or content paint effect `id`: its value, the + /// stroke opacity and whether it erases. + pub(super) fn value_for_layer(&self, id: LayerId, channel: Channel) -> Option<([f32; 3], f32, bool)> { + let LiveBrushTarget::Layer { layer, values } = &self.target else { return None }; + if *layer != id { + return None; + } + + values.get(&channel).map(|&value| (value, self.opacity.clamp(0.0, 1.0), self.erase)) + } +} diff --git a/crates/render/src/gpu_composite/live_brush_target.rs b/crates/render/src/gpu_composite/live_brush_target.rs new file mode 100644 index 00000000..adfd0042 --- /dev/null +++ b/crates/render/src/gpu_composite/live_brush_target.rs @@ -0,0 +1,14 @@ +use super::{BTreeMap, Channel, LayerId}; + +pub enum LiveBrushTarget { + Layer { + layer: LayerId, + values: BTreeMap, + }, + /// `image`: the image resource whose gray the stroke paints per texel instead of `value`. + Mask { + effect: LayerId, + value: f32, + image: Option, + }, +} diff --git a/crates/render/src/gpu_composite/operation.rs b/crates/render/src/gpu_composite/operation.rs new file mode 100644 index 00000000..727f6674 --- /dev/null +++ b/crates/render/src/gpu_composite/operation.rs @@ -0,0 +1,26 @@ +use super::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Debug, Pod, Zeroable)] +pub(super) struct Operation { + // Destination, source kind, noise seed, invert + pub(super) ids: [u32; 4], + // RGB low and layer weight + pub(super) low: [f32; 4], + pub(super) high: [f32; 4], + // UV rotation and scale, or the pigment source in W for live paint (1: brush, 2: stencil) + pub(super) projection: [f32; 4], + // UV offset XY, procedural scale and contrast, live-brush values and opacity, or curvature weights and mode in XY + pub(super) uv: [f32; 4], + pub(super) balance: [f32; 4], + // Offsets and counts of the mask and content effects + pub(super) effects: [u32; 4], + // Sampling resolution, color-ramp offset and count, projection selector + pub(super) procedural: [u32; 4], + // First content field, content has fields, mask has fields, content can add coverage + pub(super) spatial: [u32; 4], + // Geometry row and height operation precede the float-encoded mask contrast and offset + pub(super) constraints: [u32; 4], + // Package words encode the side-table offset and projection, filter and UV-tile flags + pub(super) ext: [u32; 4], +} diff --git a/crates/render/src/gpu_composite/paint_inputs.rs b/crates/render/src/gpu_composite/paint_inputs.rs new file mode 100644 index 00000000..133b5fad --- /dev/null +++ b/crates/render/src/gpu_composite/paint_inputs.rs @@ -0,0 +1,17 @@ +use super::{BTreeMap, Channel, LayerId, TileImage}; + +#[derive(Default)] +pub(super) struct PaintInputs { + pub(super) images: Vec, + pub(super) indices: BTreeMap<(LayerId, Option), u32>, +} + +impl PaintInputs { + pub(super) fn register(&mut self, id: LayerId, channel: Option, image: &TileImage) -> u32 { + *self.indices.entry((id, channel)).or_insert_with(|| { + let index = self.images.len() as u32; + self.images.push(image.clone()); + index + }) + } +} diff --git a/crates/render/src/gpu_composite/procedural_inputs.rs b/crates/render/src/gpu_composite/procedural_inputs.rs new file mode 100644 index 00000000..56d0b4b1 --- /dev/null +++ b/crates/render/src/gpu_composite/procedural_inputs.rs @@ -0,0 +1,201 @@ +use super::{ + AnchorInputs, BTreeSet, CurvatureDetail, CurvatureMode, ENVIRONMENT_WORDS, Filter, ImageUse, LOOKUP_WORDS, MaterialImages, NEIGHBOURHOOD_OPCODE, + NeighbourhoodFilter, Operation, Zeroable, +}; + +pub(super) struct ProceduralInputs { + /// Texels per side of a UV tile at the base stage's scale (the set's resolution, or a UV + /// tile atlas's block) + pub(super) resolution: u32, + /// The set's own resolution, the texture set size of `OutputResolution::output_size` + pub(super) texture_set: u32, + /// The working atlas's longest side, which caps filter radii + pub(super) longest_side: u32, + /// P8: a UV tile atlas's block side, where a whole-tile stage finds its tile + pub(super) block: u32, + /// P8: the tile resolutions of a UV tile atlas's further scales (`udim::UdimLayout::levels`), + /// each a neighbourhood stage of its own after the base stage + pub(super) levels: Vec, + /// P8: each generator stage's (filter, cell) at those further scales, by generator stage + pub(super) generator_levels: Vec, u32)>>, + pub(super) ramp_words: Vec, + pub(super) curvature_sizes: [bool; CurvatureDetail::BLURRED_SIZES], + pub(super) filters: Vec<(Filter, f32)>, + pub(super) materials: MaterialImages, + pub(super) generator_stages: Vec<(Option, u32)>, + pub(super) generator_sources: Vec, + pub(super) anchors: AnchorInputs, + /// A neighbourhood stage a package lowering asked to run right before the effect's own + /// operation ([`Self::precede_with_stage`]); the callers of `point_effect` push it first. + pub(super) preceding_stage: Option, + /// Source operations effects read as image inputs (`register_input`), appended after the + /// effects like the generators' sources. + pub(super) input_sources: Vec, + /// Side-table words that hold an image's record offset once the atlas is laid out + /// (`pack_image`): (word index in the side table, image index). + pub(super) image_words: Vec<(u32, u32)>, + /// The side-table word where the environment's diffuse light starts, filled at upload + /// (`reserve_environment`). + pub(super) environment_word: Option, + /// A lowering reads the Height and World Normal bake rows (`read_bake_rows`). + pub(super) bake_rows: bool, + /// The image inputs (`register_input` references) read as colour (`register_color_input`). + pub(super) color_inputs: BTreeSet, +} + +impl ProceduralInputs { + pub(super) fn new(resolution: u32) -> Self { + Self { + resolution, + texture_set: resolution, + longest_side: resolution, + block: resolution, + levels: Vec::new(), + generator_levels: Vec::new(), + ramp_words: Vec::new(), + curvature_sizes: [false; CurvatureDetail::BLURRED_SIZES], + filters: Vec::new(), + materials: MaterialImages::default(), + generator_stages: Vec::new(), + generator_sources: Vec::new(), + anchors: AnchorInputs::default(), + preceding_stage: None, + input_sources: Vec::new(), + image_words: Vec::new(), + environment_word: None, + bake_rows: false, + color_inputs: BTreeSet::new(), + } + } + + /// [`Self::register_input`] for an input read as colour: a neighbourhood stage's field then + /// carries its RGB in words 5..8 (`input_color_at` in neighbourhood.wgsl), and a point + /// operation reads it with `effect_input_color(effect, texel)`. P5: Color Match's inputs. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn register_color_input(&mut self, source: Operation) -> u32 { + let reference = self.register_input(source); + self.color_inputs.insert(reference); + reference + } + + /// Reserve the [`ENVIRONMENT_WORDS`] side-table words that hold the viewport environment's + /// diffuse light (`EnvironmentSh`): its nine RGB coefficients as f32 bits in `sh_basis` order + /// (coefficient `i`, component `k` at word `3 i + k`), then the environment rotation in + /// radians. The program keeps the project's display settings from compile and fills the words + /// when it learns the images (`CompositeProgram::set_tile_images`), so a turned or changed + /// environment needs no other lowering. Returns their absolute offset (like `pack_words`); a + /// second reservation returns the same words. P6: Baked Lighting Environment. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn reserve_environment(&mut self) -> Option { + if let Some(word) = self.environment_word { + return LOOKUP_WORDS.checked_add(word); + } + + let word = u32::try_from(self.ramp_words.len()).ok()?; + let offset = self.pack_words(&[0; ENVIRONMENT_WORDS])?; + self.environment_word = Some(word); + Some(offset) + } + + /// Ask for the bake rows after the built-in maps: the baked Height and World Normal at + /// `baked_block_at(pixel, 1u)` in WGSL (x the height, yzw the stored world normal, f32 bits), + /// present when `bake_has(BAKED_HEIGHT)` / `bake_has(BAKED_WORLD_NORMAL)`. The rows exist only + /// in programs that ask and only for the maps that are baked. P6: lighting's height slope and + /// detail normal. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn read_bake_rows(&mut self) { + self.bake_rows = true; + } + + /// Register `source` (a `source_operation`) as an effect's image input: the returned + /// reference goes in the effect operation's `effects[3]`. The program appends the source + /// after the effects and rebinds the reference to its operation index plus one, which a + /// neighbourhood stage then evaluates into its field's sixth word (`FilterStage::input`) and + /// a point operation reads with `effect_input(effect, texel)` in WGSL. The CPU reads inputs + /// with `Sampling::default()` (Bilinear HQ): build the source with P1's sampling. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn register_input(&mut self, source: Operation) -> u32 { + self.input_sources.push(source); + self.input_sources.len() as u32 + } + + /// A side-table word that will hold image `name`'s record offset (the atlas layout of + /// `MaterialImages`, `u32::MAX` while the image is missing): the returned offset goes where + /// the operation's shader reads it with `param_word`, and `image_texel_nearest` reads the + /// image there (P3: a Color Selection's ID map). + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn pack_image(&mut self, name: &str, usage: ImageUse) -> Option { + let image = self.materials.register_image(name, usage); + let word = u32::try_from(self.ramp_words.len()).ok()?; + let offset = self.pack_words(&[u32::MAX])?; + self.image_words.push((word, image)); + Some(offset) + } + + /// Lets a package lowering (in `packages::lower_filter`) run the neighbourhood stage of + /// `filter` right before the effect's own operation: one effect, two operations. This is the + /// seam of the Gradient's `input.blur` (P4 defines the stage, P2 the gradient that follows). + /// The point operation then reads the stage's output field in place of the content, so a + /// stage that must keep the original colour (for the opacity mix) passes its derived value in + /// a component or the sixth field word, as P4 defines it. None, and nothing queued, when the + /// GPU has no stage for `filter` or its size reaches nothing. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn precede_with_stage(&mut self, filter: &Filter, opacity: f32) -> Option<()> { + NeighbourhoodFilter::new(filter, self.resolution, self.longest_side, opacity, None)?; + let ids = [0, NEIGHBOURHOOD_OPCODE, u32::try_from(self.filters.len()).ok()?, 0]; + self.filters.push((filter.clone(), opacity)); + self.preceding_stage = Some(Operation { ids, low: [0.0, 0.0, 0.0, opacity.clamp(0.0, 1.0)], ..Operation::zeroed() }); + Some(()) + } + + pub(super) fn pack_rgb(&mut self, colors: &[[f32; 3]]) -> Option<[u32; 2]> { + if colors.iter().flatten().any(|value| !value.is_finite()) { + return None; + } + + let offset = LOOKUP_WORDS.checked_add(u32::try_from(self.ramp_words.len()).ok()?)?; + let count = u32::try_from(colors.len()).ok()?; + self.ramp_words.extend(colors.iter().flatten().map(|value| value.to_bits())); + Some([offset, count]) + } + + /// Append finite `values` to the parameter side table (the words after the sRGB lookup in + /// binding 2, shared with [`Self::pack_rgb`]) and return their absolute word offset for + /// `Operation::ext[0]`. The shader reads them with `param(op, i)`. None for a non-finite value. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn pack_params(&mut self, values: &[f32]) -> Option { + if values.iter().any(|value| !value.is_finite()) { + return None; + } + + let words: Vec = values.iter().map(|value| value.to_bits()).collect(); + self.pack_words(&words) + } + + /// [`Self::pack_params`] for raw words (counts, packed flags, offsets); read with `param_word(op, i)`. + #[allow(dead_code)] // Used by the GPU port packages + pub(super) fn pack_words(&mut self, words: &[u32]) -> Option { + let offset = LOOKUP_WORDS.checked_add(u32::try_from(self.ramp_words.len()).ok()?)?; + self.ramp_words.extend_from_slice(words); + Some(offset) + } + + pub(super) fn pack_curvature(&mut self, detail: &CurvatureDetail, derive_levels: bool) -> Option<[f32; 2]> { + let offset = LOOKUP_WORDS.checked_add(u32::try_from(self.ramp_words.len()).ok()?)?; + if offset >= 1 << 24 || detail.weights.iter().any(|weight| !weight.is_finite()) { + return None; + } + + self.ramp_words.extend(detail.weights.map(|weight| weight.clamp(0.0, 1.0).to_bits())); + for (size, needed) in self.curvature_sizes.iter_mut().zip(detail.blurred_sizes_in_use()) { + *size |= derive_levels && needed; + } + let mode = match detail.mode { + CurvatureMode::Edges => 1.0, + CurvatureMode::Cavities => 2.0, + CurvatureMode::Both => 3.0, + CurvatureMode::Raw => 4.0, + }; + Some([offset as f32, mode]) + } +} diff --git a/crates/render/src/gpu_composite/surface_cache.rs b/crates/render/src/gpu_composite/surface_cache.rs new file mode 100644 index 00000000..ef547f43 --- /dev/null +++ b/crates/render/src/gpu_composite/surface_cache.rs @@ -0,0 +1,7 @@ +use super::{UvGBuffer, Weak}; + +pub(super) struct SurfaceCache { + pub(super) gbuf: Weak, + pub(super) view: wgpu::TextureView, + pub(super) vertices: Option, +} diff --git a/crates/render/src/gpu_composite/whole_pass.rs b/crates/render/src/gpu_composite/whole_pass.rs new file mode 100644 index 00000000..065ba584 --- /dev/null +++ b/crates/render/src/gpu_composite/whole_pass.rs @@ -0,0 +1,51 @@ +/// The whole-set pre-pass of one stack: its stages (a contiguous run of slots), the outputs of +/// [`super::WholeSet::outputs`] among them, the reach of its fields, and how far past the set's edges +/// its fields reach in a wrapping program (the stages at and below its topmost wrapping stage; +/// a stage that does not wrap reads only the set, its own copy). +#[derive(Debug, PartialEq)] +pub(super) struct WholePass { + pub(super) stages: Vec, + pub(super) outputs: Vec, + pub(super) reach: u32, + pub(super) past_edges: u32, + /// The working fields its kernels use besides the original ([`super::NeighbourhoodFilter::blur_fields`]) + pub(super) blur_fields: u32, +} + +impl WholePass { + /// The compact slot table (`whole_compact` in composite.wgsl): the pass's stages take slots + /// 0.., the working fields the next three. Not active when its stages are not contiguous. + pub(super) fn compact(&self, fields: u32) -> [u32; 4] { + let (Some(&first), Some(&last)) = (self.stages.first(), self.stages.last()) else { return [0; 4] }; + if last + 1 - first != self.stages.len() { + return [0, 0, fields, 0]; + } + + [first as u32, self.stages.len() as u32, fields, 1] + } + + /// The slot `slot` takes in the pass's working space ([`Self::compact`]). + pub(super) fn slot(&self, slot: u32, fields: u32) -> u32 { + match self.compact(fields) { + [_, count, fields, 1] if slot >= fields => count + slot - fields, + [base, _, _, 1] => slot - base, + _ => slot, + } + } + + /// Field slots of the pass's working space: its stages, the original and the working fields + /// its kernels use + pub(super) fn slots(&self, fields: u32) -> u64 { + match self.compact(fields) { + [_, count, _, 1] => u64::from(count) + 1 + u64::from(self.blur_fields), + _ => u64::from(fields) + 3, + } + } + + /// The kernels' working fields: the ones the pass has, else the original (never read then) + pub(super) fn blur(&self, fields: u32, offset: impl Fn(u32) -> u32) -> [u32; 2] { + let compact = self.compact(fields)[3] == 1; + let field = |index: u32| if !compact || self.blur_fields > index { offset(fields + 1 + index) } else { offset(fields) }; + [field(0), field(1)] + } +} diff --git a/crates/render/src/gpu_composite/whole_set.rs b/crates/render/src/gpu_composite/whole_set.rs new file mode 100644 index 00000000..83c95b35 --- /dev/null +++ b/crates/render/src/gpu_composite/whole_set.rs @@ -0,0 +1,17 @@ +use super::WholePass; + +/// The whole-set pre-pass of a program: the stages it evaluates (the whole-set stages and the +/// lower stages of their stacks), the whole-set stages whose outputs the bands read, and the +/// reach of the pre-pass fields. +#[derive(Debug, PartialEq)] +pub(super) struct WholeSet { + pub(super) stages: Vec, + pub(super) outputs: Vec, + /// The outputs the band uniform names (indices into `outputs`): every output but a level + /// stage, whose results follow its base stage's (P8) + pub(super) entries: Vec, + /// The largest pass's reach + pub(super) reach: u32, + /// One pass per stack, run one after another in the same working space + pub(super) passes: Vec, +} diff --git a/crates/render/src/gpu_composite/whole_set_pass.rs b/crates/render/src/gpu_composite/whole_set_pass.rs new file mode 100644 index 00000000..de30048a --- /dev/null +++ b/crates/render/src/gpu_composite/whole_set_pass.rs @@ -0,0 +1,124 @@ +use super::{CompositeRegion, WholePass, WholeSet, packages}; + +/// The whole-set pre-pass of one update ([`super::FilterPlan::whole_set`]): the region of results the +/// bands read (source texels [x0, y0, x1, y1]: the update plus the bands' halo, a whole axis +/// where a wrapping program crosses the set's edge) and the stripes it is evaluated in. +pub(super) struct WholeSetPass { + pub(super) stages: WholeSet, + pub(super) region: [u32; 4], + pub(super) size: (u32, u32), + pub(super) wraps: bool, + pub(super) texel_words: u32, + /// The program's stage count: its first working field's slot + pub(super) fields: u32, + pub(super) stripe_rows: u32, +} + +impl WholeSetPass { + pub(super) fn plan( + stages: WholeSet, + (region, shift): (CompositeRegion, u32), + size: (u32, u32), + halo: u32, + wraps: bool, + texel_words: u32, + stage_count: usize, + ) -> Self { + let axis = |min: u32, max: u32, side: u32| { + let (low, high) = ((min << shift).saturating_sub(halo), (max << shift).saturating_add(halo)); + if wraps && ((min << shift) < halo || high > side) { [0, side] } else { [low, high.min(side)] } + }; + let [x0, x1] = axis(region.min[0], region.max[0], size.0); + let [y0, y1] = axis(region.min[1], region.max[1], size.1); + Self { region: [x0, y0, x1, y1], size, wraps, texel_words, fields: stage_count as u32, stripe_rows: (y1 - y0).max(1), stages } + } + + pub(super) fn result_words(&self) -> u64 { + let [x0, y0, x1, y1] = self.region; + u64::from(x1 - x0) * u64::from(y1 - y0) * u64::from(self.texel_words) + } + + pub(super) fn result_bytes(&self) -> u64 { + self.result_words() * self.stages.outputs.len() as u64 * 4 + } + + /// First word of output `index`'s results, after the working space ending at word `base`. + pub(super) fn result_base(&self, base: u32, index: usize) -> u32 { + (u64::from(base) + self.result_words() * index as u64) as u32 + } + + /// The field of `pass` for the stripe of `rows` from row `top`: the pass's reach on every + /// side, clamped to the set, or in a wrapping program to the set plus how far the pass's + /// fields reach past its edges (origin as i32 bits). + pub(super) fn field_rect(&self, pass: &WholePass, top: u32, rows: u32) -> [u32; 4] { + let [x0, _, x1, _] = self.region; + let (left, right) = self.span(pass, x0, x1, self.size.0); + let (upper, lower) = self.span(pass, top, top + rows, self.size.1); + [left as i32 as u32, upper as i32 as u32, (right - left) as u32, (lower - upper) as u32] + } + + /// `low..high` plus the pass's reach on both sides, clamped to the set (`side`) widened by + /// the pass's reach past the edges in a wrapping program (periodic copies there). + pub(super) fn span(&self, pass: &WholePass, low: u32, high: u32, side: u32) -> (i64, i64) { + let reach = i64::from(pass.reach); + let past = if self.wraps { i64::from(pass.past_edges) } else { 0 }; + ((i64::from(low) - reach).max(-past), (i64::from(high) + reach).min(i64::from(side) + past)) + } + + /// Bytes of the largest stripe's fields: the largest pass's slots over the stripe plus its + /// reach, as `field_rect` clamps it. + pub(super) fn stripe_bytes(&self) -> u64 { + let [x0, _, x1, _] = self.region; + self.stages + .passes + .iter() + .map(|pass| { + let (left, right) = self.span(pass, x0, x1, self.size.0); + let past = if self.wraps { u64::from(pass.past_edges) } else { 0 }; + let rows = (u64::from(self.stripe_rows) + 2 * u64::from(pass.reach)).min(u64::from(self.size.1) + 2 * past); + (right - left) as u64 * rows * pass.slots(self.fields) * u64::from(self.texel_words) * 4 + }) + .max() + .unwrap_or(0) + } + + /// The tallest stripes whose fields fit in `limit` bytes beside the results. + pub(super) fn with_stripes(mut self, limit: u64) -> Result { + while self.stripe_bytes() > limit { + if self.stripe_rows <= 1 { + return Err("A whole-set filter's stripe exceeds the adapter's working memory limit.".into()); + } + + self.stripe_rows = self.stripe_rows.div_ceil(2); + } + Ok(self) + } + + /// The paint the stripe of `rows` from `top` reads: the stripe plus the pre-pass reach, the + /// whole axis where a wrapping program crosses the set's edge. + pub(super) fn paint_window(&self, size: (u32, u32), top: u32, rows: u32) -> ([u32; 2], [u32; 2]) { + let reach = self.stages.reach; + let [x0, _, x1, _] = self.region; + let (y0, y1) = (top, top + rows); + let axis = |low: u32, high: u32, side: u32| { + if self.wraps && (low < reach || high.saturating_add(reach) > side) { + (0, side) + } else { + (low.saturating_sub(reach), high.saturating_add(reach).min(side)) + } + }; + let ((left, right), (upper, lower)) = (axis(x0, x1, size.0), axis(y0, y1, size.1)); + ([left, upper], [right, lower]) + } + + /// The band uniform's whole-set table: each output's slot plus one, its first word, the region. + pub(super) fn write_uniform(&self, values: &mut [u32; packages::UNIFORM_WORDS], base: u32) { + let table = &mut values[packages::WHOLE_SET..packages::WHOLE_SET + 12]; + for (entry, &index) in self.stages.entries.iter().enumerate() { + table[entry] = self.stages.outputs[index] as u32 + 1; + table[4 + entry] = self.result_base(base, index); + } + let [x0, y0, x1, y1] = self.region; + table[8..].copy_from_slice(&[x0, y0, x1 - x0, y1 - y0]); + } +} diff --git a/crates/render/src/gpu_composite_brush.rs b/crates/render/src/gpu_composite_brush.rs index cd5ff674..b0b83b56 100644 --- a/crates/render/src/gpu_composite_brush.rs +++ b/crates/render/src/gpu_composite_brush.rs @@ -63,7 +63,7 @@ pub(super) fn band_uniform(_program: &CompositeProgram) -> [u32; 4] { [0; 4] } -#[cfg(test)] +#[cfg(all(test, not(target_arch = "wasm32")))] mod tests { use super::super::oracle::headless; use super::super::*; @@ -195,7 +195,7 @@ mod tests { gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); for (kind, actual) in [DisplayKind::BaseColor, DisplayKind::Height].into_iter().zip(&full) { - let expected = tile_bytes(&cpu, &baked, kind, 0, 0); + let expected = tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0); assert_eq!(actual.len(), expected.len()); if kind == DisplayKind::Height { for (actual, expected) in actual.as_chunks::<2>().0.iter().zip(expected.as_chunks::<2>().0) { @@ -305,7 +305,7 @@ mod tests { program.region = Some(CompositeRegion { min: [16, 20], max: [40, 48] }); gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); - let expected = tile_bytes(&cpu, &baked, DisplayKind::BaseColor, 0, 0); + let expected = tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, 0, 0); assert_eq!(full.len(), expected.len()); assert!(full.iter().zip(&expected).all(|(a, b)| a.abs_diff(*b) <= 1), "the GPU paints another gray than the CPU"); assert_eq!(read(&gpu), full, "the partial update keeps the full result"); diff --git a/crates/render/src/gpu_composite_groups.rs b/crates/render/src/gpu_composite_groups.rs index 52100985..7704a57e 100644 --- a/crates/render/src/gpu_composite_groups.rs +++ b/crates/render/src/gpu_composite_groups.rs @@ -5,47 +5,13 @@ use super::{Operation, channel_slot}; pub(super) const BEGIN_GROUP: u32 = 200; pub(super) const END_GROUP: u32 = 201; -pub(super) enum StackWork { - Layer(LayerId, usize, u32), - EndGroup(usize), -} +#[path = "composite_group/group_plan.rs"] +mod group_plan; +#[path = "composite_group/stack_work.rs"] +mod stack_work; -#[derive(Debug, Default)] -pub(super) struct GroupPlan { - pub(super) depth: u32, - pub(super) channels: u32, - pub(super) words_per_level: u32, - markers: u64, -} - -impl GroupPlan { - pub(super) fn finish(&mut self, operations: &[Operation]) { - if self.depth == 0 { - return; - } - for op in operations { - if is_group(op) { - self.markers += 1; - } else if let Some(bit) = 1u32.checked_shl(op.ids[0]) { - self.channels |= bit; - } - } - // One word for the mask, then compact snapshots of the channels that can change. - self.words_per_level = 1 + Channel::ALL - .iter() - .filter(|&&channel| self.channels & (1 << channel_slot(channel)) != 0) - .map(|channel| channel.components() as u32) - .sum::(); - } - - pub(super) fn words(&self, pixels: u64) -> u64 { - pixels * u64::from(self.depth) * u64::from(self.words_per_level) - } - - pub(super) fn work_per_pixel(&self) -> u64 { - self.markers * u64::from(self.words_per_level) - } -} +pub(super) use group_plan::GroupPlan; +pub(super) use stack_work::StackWork; pub(super) fn is_group(op: &Operation) -> bool { matches!(op.ids[1], BEGIN_GROUP | END_GROUP) @@ -56,10 +22,12 @@ pub(super) fn children_publish_anchors(project: &Project, children: &[LayerId], if depth > texturecraft_core::project::MAX_DEPTH { return false; } + children.iter().any(|&id| { if !project.layers.get(&id).is_some_and(|layer| layer.visible) { return false; } + let Some(layer) = project.content_layer(id) else { return false }; let mask = project.layers.get(&project.mask_owner(id)).and_then(|owner| owner.mask.as_ref()).filter(|mask| mask.enabled); layer.content_effects.iter().chain(mask.into_iter().flat_map(|mask| &mask.effects)).any(|eff| eff.visible && matches!(eff.kind, EffectKind::Anchor)) diff --git a/crates/render/src/gpu_composite_lighting.rs b/crates/render/src/gpu_composite_lighting.rs index 15324f45..41c38e6e 100644 --- a/crates/render/src/gpu_composite_lighting.rs +++ b/crates/render/src/gpu_composite_lighting.rs @@ -48,6 +48,7 @@ fn lighting_content_effect(effect: Operation, content: vec4, channel: u32, let filtered = lighting_effect_color(effect, content.rgb, channel, texel.surface, texel.baked.x); return vec4(content.rgb + (filtered - content.rgb) * effect.low.w, content.a); } + fn lighting_mask_effect(effect: Operation, mask: f32, texel: LayerTexel) -> f32 { return lighting_scalar_filter(effect, mask); }"; /// Baked Lighting Stylized: sun, two lights and sky shading the base color with the layer's material @@ -199,6 +200,10 @@ pub(super) fn band_uniform(_program: &CompositeProgram) -> [u32; 4] { [0; 4] } +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "gpu_composite_lighting/pipeline_log.rs"] +mod pipeline_log; + #[cfg(all(test, not(target_arch = "wasm32")))] mod tests { use texturecraft_core::{ContentsOffset, EffectKind, Filter}; @@ -240,6 +245,7 @@ mod tests { use crate::gpu_composite::oracle::{OracleCase, Tolerance, assert_matches_cpu, headless}; const SIZE: u32 = TILE * 2; + // sRGB grays away from 30, 50 and 240 of 255 and from 60 and 70 percent, inverted too const GRAYS_SRGB: [f32; 5] = [0.05, 0.15, 0.3, 0.65, 0.99]; let validate = Filter::PbrValidate(PbrValidate::LIBRARY); @@ -250,6 +256,7 @@ mod tests { let Some(mut gpu) = headless() else { return }; let mesh = Arc::new(primitives::plane(1.0, 1)); let (baked, images) = (BakedMaps::default(), ImageStore::default()); + // Each effect: filter, opacity, blend, and whether it starts on Base Color only as the library adds it let build = |content: &[(Filter, f32, BlendMode, bool)]| { let mut project = Project::new("PBR Validate", "builtin:plane"); @@ -287,6 +294,7 @@ mod tests { let gray = to_u16(linear(GRAYS_SRGB[(y * GRAYS_SRGB.len() as u32 / SIZE) as usize])); pixels.layer_mut(owner, Channel::BaseColor, (SIZE, SIZE)).set(x, y, &[gray, gray, gray, u16::MAX]); pixels.layer_mut(below, Channel::Metallic, (SIZE, SIZE)).set(x, y, &[to_u16(if left { 1.0 } else { 0.0 }), u16::MAX]); + // The layer's own metal flips the metal below, 0.6 over it under the mask if y >= SIZE * 3 / 4 { pixels.layer_mut(owner, Channel::Metallic, (SIZE, SIZE)).set(x, y, &[to_u16(if left { 0.0 } else { 1.0 }), u16::MAX]); @@ -411,8 +419,8 @@ mod tests { }; let bakes = lit_bakes(true, true); assert_lit_matches(&mut gpu, &project(0.1), &bakes, (true, Tolerance::TRANSCENDENTAL), "a mask comparing its lit Base Color"); - // A steeper ramp turns float noise into a few steps (at most 0.1 % of the texels; at - // hardness 0.6 the sphere's pole holds 22 to 70 such texels, over 0.1 %) + + // A steeper ramp magnifies small float differences at the sphere poles let flips = (LIT_SIZE * LIT_SIZE / 1000) as usize; assert_lit_matches(&mut gpu, &project(0.4), &bakes, (true, Tolerance::TRANSCENDENTAL.with_flips(flips)), "a steep mask comparing its lit Base Color"); } @@ -666,6 +674,7 @@ mod tests { assert!(compile_effects(Some(effect(EffectKind::Filter(stylized_lighting(library.clone())))), None, ContentsOffset::NONE).0.is_ok()); let Some(mut gpu) = headless() else { return }; + // Every value of the shading is a product, a sum, a square root or a division let tolerance = Tolerance::POINT; let detailed = StylizedLighting { @@ -839,21 +848,8 @@ mod tests { use crate::gpu_composite::CompositeProgram; use crate::gpu_composite::oracle::headless; - // The pipelines' compile times (debug log lines of this crate) - struct PipelineLog; - impl log::Log for PipelineLog { - fn enabled(&self, metadata: &log::Metadata) -> bool { - metadata.level() <= log::Level::Debug && metadata.target().starts_with("texturecraft_render") - } + use super::pipeline_log::PipelineLog; - fn log(&self, record: &log::Record) { - if self.enabled(record.metadata()) { - println!("BENCH {}", record.args()); - } - } - - fn flush(&self) {} - } static PIPELINE_LOG: PipelineLog = PipelineLog; if log::set_logger(&PIPELINE_LOG).is_ok() { log::set_max_level(log::LevelFilter::Debug); @@ -870,9 +866,8 @@ mod tests { ambient_occlusion: 0.4, specular_occlusion: 0.8, }; - // Each variant's pipelines compile on its first frame: unlit, a content Blur (the prepare - // pass), an anchor read (a capture without lighting) with and without a content filter, - // each lighting kind, and all three + + // Exercise each distinct combination of prepare, capture and lighting pipelines let validate = Filter::PbrValidate(texturecraft_core::PbrValidate::LIBRARY); let stylized = stylized_lighting(StylizedLighting::library()); let filters: [(&str, Vec); 8] = [ @@ -885,6 +880,7 @@ mod tests { ("stylized", vec![stylized.clone()]), ("all three", vec![validate, environment, stylized]), ]; + // The material layer publishes an anchor whose Roughness the lit layer's fill reads let anchor_read = |project: &mut texturecraft_core::Project| { use texturecraft_core::{Channel, Effect, EffectKind, LayerKind, Source}; diff --git a/crates/render/src/gpu_composite_lighting/pipeline_log.rs b/crates/render/src/gpu_composite_lighting/pipeline_log.rs new file mode 100644 index 00000000..03df52ab --- /dev/null +++ b/crates/render/src/gpu_composite_lighting/pipeline_log.rs @@ -0,0 +1,16 @@ +// The pipelines' compile times (debug log lines of this crate) +pub(super) struct PipelineLog; + +impl log::Log for PipelineLog { + fn enabled(&self, metadata: &log::Metadata) -> bool { + metadata.level() <= log::Level::Debug && metadata.target().starts_with("texturecraft_render") + } + + fn log(&self, record: &log::Record) { + if self.enabled(record.metadata()) { + println!("BENCH {}", record.args()); + } + } + + fn flush(&self) {} +} diff --git a/crates/render/src/gpu_composite_oracle.rs b/crates/render/src/gpu_composite_oracle.rs index 36900c84..a157c31e 100644 --- a/crates/render/src/gpu_composite_oracle.rs +++ b/crates/render/src/gpu_composite_oracle.rs @@ -5,7 +5,7 @@ //! mask preview of one layer, and optionally a partial update against the full one. Tolerances //! follow plan section 6; never loosen them, investigate instead. [`compile_effects`] is the //! compile-only probe of the packages' `still_on_cpu` tables. -// Test support: failing loudly is the point, and the packages use the helpers as they port. +// Test support: failing loudly is the point, and the packages use the helpers as they port #![allow(clippy::unwrap_used, clippy::panic, dead_code)] use std::collections::BTreeMap; @@ -28,68 +28,18 @@ pub(crate) fn earlier_generator(kind: texturecraft_core::GeneratorKind) -> textu texturecraft_core::Generator { wear: None, section: None, light: None, controls: None, ..texturecraft_core::Generator::new(kind) } } -/// The GPU for an oracle test, or None without an adapter: the test then returns, as the other -/// GPU tests do. With `TC_CI_LAVAPIPE` set (CI promises an adapter) a missing one fails the test. +/// The GPU for an oracle test, with the same adapter requirement as the viewport tests. pub(crate) fn headless() -> Option { - match Headless::new() { - Ok(gpu) => Some(gpu), - Err(error) => { - assert!(std::env::var_os("TC_CI_LAVAPIPE").is_none(), "TC_CI_LAVAPIPE is set but the GPU is unavailable: {error}"); - None - } - } + Headless::for_required_tests() } -/// How far the GPU may differ from the CPU oracle (plan section 6). -#[derive(Clone, Copy, Debug)] -pub(crate) struct Tolerance { - /// Largest difference of an 8-bit component, and of the 8-bit mask preview. - pub(crate) lsb: u8, - /// Largest difference of a half-float component (Height, Normal maps). - pub(crate) f16: f32, - /// Normal map texels compare by the dot product of their directions instead, when set. - pub(crate) normal_dot: Option, - /// Texels allowed beyond the limits: only for hard decisions (thresholds, steps, cell - /// centres, nearest sampling, depth culling) on inputs chosen away from the boundary. - pub(crate) flips: usize, -} +#[path = "gpu_composite_oracle/oracle_case.rs"] +mod oracle_case; +#[path = "gpu_composite_oracle/tolerance.rs"] +mod tolerance; -impl Tolerance { - /// Point filters, sampling, projections and masks. - pub(crate) const POINT: Self = Self { lsb: 1, f16: 0.001, normal_dot: None, flips: 0 }; - /// Bilinear image sampling. - pub(crate) const BILINEAR: Self = Self { lsb: 2, f16: 0.003, normal_dot: None, flips: 0 }; - /// The box family and distance filters (the raw distances must match exactly, test them apart). - pub(crate) const NEIGHBOURHOOD: Self = Self { lsb: 2, f16: 0.003, normal_dot: None, flips: 0 }; - /// Gather, warp, Kuwahara, FXAA, OKLab and SH lighting (transcendentals); normals by direction. - pub(crate) const TRANSCENDENTAL: Self = Self { lsb: 2, f16: 0.003, normal_dot: Some(0.99), flips: 0 }; - - /// A hard decision: allow at most `flips` texels (keep it at or below 0.1 % of the texels). - pub(crate) const fn with_flips(self, flips: usize) -> Self { - Self { flips, ..self } - } -} - -/// One project to composite on both sides. -pub(crate) struct OracleCase<'a> { - pub(crate) project: &'a Project, - pub(crate) ts: usize, - pub(crate) pixels: &'a PixelStore, - pub(crate) baked: &'a BakedMaps, - pub(crate) images: &'a ImageStore, - pub(crate) mesh: &'a Arc, - /// Also compare this layer's mask preview with `mask_image_sized` at the mask view's extent. - pub(crate) mask_owner: Option, - /// Also recomposite only this region and require the full result (a filter's halo). - pub(crate) region: Option, -} - -impl<'a> OracleCase<'a> { - /// The material of texture set 0 with no bakes, images, mask comparison or region. - pub(crate) fn new(project: &'a Project, pixels: &'a PixelStore, baked: &'a BakedMaps, images: &'a ImageStore, mesh: &'a Arc) -> Self { - Self { project, ts: 0, pixels, baked, images, mesh, mask_owner: None, region: None } - } -} +pub(crate) use oracle_case::OracleCase; +pub(crate) use tolerance::Tolerance; /// Composite `case` on the CPU and the GPU and panic, naming `label`, where they differ beyond /// `tolerance`: every display map the GPU program writes, then the mask preview and the partial @@ -113,6 +63,7 @@ pub(crate) fn assert_matches_cpu(gpu: &mut Headless, case: &OracleCase, toleranc bounds: case.mesh.bounds(), }; let tiles: Vec<(u32, u32)> = (0..height / TILE).flat_map(|ty| (0..width / TILE).map(move |tx| (tx, ty))).collect(); + // A UV tile atlas's displays read the bakes and tile scales per block, as the session's do let mut oracle = Composite { block_scales: set.block_scales(), ..Composite::with_size(&channels, width, height) }; composite_tiles(&inputs, &mut oracle, &tiles); @@ -128,6 +79,7 @@ pub(crate) fn assert_matches_cpu(gpu: &mut Headless, case: &OracleCase, toleranc let read = |gpu: &Headless, kind: DisplayKind| { let texture = gpu.renderer.display_textures()[case.ts][kind as usize]; let (w, h, bytes) = Readback::blocking(&gpu.device, &gpu.queue, texture).unwrap_or_else(|| panic!("{label}: {kind:?} readback")); + // A neutral program displays one texel if (w, h) == (1, 1) { bytes.repeat((width * height) as usize) } else { bytes } }; @@ -136,7 +88,7 @@ pub(crate) fn assert_matches_cpu(gpu: &mut Headless, case: &OracleCase, toleranc let bytes = kind.bytes_per_texel(); let mut expected = vec![0; actual.len()]; for &(tx, ty) in &tiles { - let tile = tile_bytes(&oracle, case.baked, kind, tx, ty); + let tile = tile_bytes(&oracle, case.baked, texturecraft_core::AoMixing::Multiply, kind, tx, ty); for (y, row) in tile.chunks_exact(TILE as usize * bytes).enumerate() { let start = ((ty * TILE + y as u32) * width + tx * TILE) as usize * bytes; expected[start..start + row.len()].copy_from_slice(row); diff --git a/crates/render/src/gpu_composite_oracle/oracle_case.rs b/crates/render/src/gpu_composite_oracle/oracle_case.rs new file mode 100644 index 00000000..76d1be50 --- /dev/null +++ b/crates/render/src/gpu_composite_oracle/oracle_case.rs @@ -0,0 +1,22 @@ +use super::*; + +/// One project to composite on both sides. +pub(crate) struct OracleCase<'a> { + pub(crate) project: &'a Project, + pub(crate) ts: usize, + pub(crate) pixels: &'a PixelStore, + pub(crate) baked: &'a BakedMaps, + pub(crate) images: &'a ImageStore, + pub(crate) mesh: &'a Arc, + /// Also compare this layer's mask preview with `mask_image_sized` at the mask view's extent. + pub(crate) mask_owner: Option, + /// Also recomposite only this region and require the full result (a filter's halo). + pub(crate) region: Option, +} + +impl<'a> OracleCase<'a> { + /// The material of texture set 0 with no bakes, images, mask comparison or region. + pub(crate) fn new(project: &'a Project, pixels: &'a PixelStore, baked: &'a BakedMaps, images: &'a ImageStore, mesh: &'a Arc) -> Self { + Self { project, ts: 0, pixels, baked, images, mesh, mask_owner: None, region: None } + } +} diff --git a/crates/render/src/gpu_composite_oracle/tolerance.rs b/crates/render/src/gpu_composite_oracle/tolerance.rs new file mode 100644 index 00000000..c262be1a --- /dev/null +++ b/crates/render/src/gpu_composite_oracle/tolerance.rs @@ -0,0 +1,29 @@ +/// How far the GPU may differ from the CPU oracle (plan section 6). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Tolerance { + /// Largest difference of an 8-bit component, and of the 8-bit mask preview. + pub(crate) lsb: u8, + /// Largest difference of a half-float component (Height, Normal maps). + pub(crate) f16: f32, + /// Normal map texels compare by the dot product of their directions instead, when set. + pub(crate) normal_dot: Option, + /// Texels allowed beyond the limits: only for hard decisions (thresholds, steps, cell + /// centres, nearest sampling, depth culling) on inputs chosen away from the boundary. + pub(crate) flips: usize, +} + +impl Tolerance { + /// Point filters, sampling, projections and masks. + pub(crate) const POINT: Self = Self { lsb: 1, f16: 0.001, normal_dot: None, flips: 0 }; + /// Bilinear image sampling. + pub(crate) const BILINEAR: Self = Self { lsb: 2, f16: 0.003, normal_dot: None, flips: 0 }; + /// The box family and distance filters (the raw distances must match exactly, test them apart). + pub(crate) const NEIGHBOURHOOD: Self = Self { lsb: 2, f16: 0.003, normal_dot: None, flips: 0 }; + /// Gather, warp, Kuwahara, FXAA, OKLab and SH lighting (transcendentals); normals by direction. + pub(crate) const TRANSCENDENTAL: Self = Self { lsb: 2, f16: 0.003, normal_dot: Some(0.99), flips: 0 }; + + /// A hard decision: allow at most `flips` texels (keep it at or below 0.1 % of the texels). + pub(crate) const fn with_flips(self, flips: usize) -> Self { + Self { flips, ..self } + } +} diff --git a/crates/render/src/gpu_composite_packages.rs b/crates/render/src/gpu_composite_packages.rs index 64bd0986..5917e6af 100644 --- a/crates/render/src/gpu_composite_packages.rs +++ b/crates/render/src/gpu_composite_packages.rs @@ -85,6 +85,7 @@ pub(super) fn lower_filter(filter: &Filter, effect: &Effect, op: &mut Operation, inputs.precede_with_stage(&Filter::Blur { radius: 24.0, wrap: false }, 1.0)?; return Some((21, [0.0; 3])); } + #[cfg(all(test, not(target_arch = "wasm32")))] if let (Some(probe), Filter::Smoothstep { min, max }) = (PROBE_LOWERING.get(), filter) { match (probe, PROBE_SELECTOR.get()) { @@ -113,8 +114,8 @@ pub(super) fn lower_filter(filter: &Filter, effect: &Effect, op: &mut Operation, } return Some((probe, [0.0; 3])); } - // Test seam: Height To Normal and Color Match as the input probe stage, Color Match with - // colour inputs of its source and target colours (the second one in `effects[2]`) + + // Probe both color inputs to Color Match as well as the height input to Height To Normal #[cfg(all(test, not(target_arch = "wasm32")))] if crate::gpu_neighbourhood::INPUT_PROBE.get() && matches!(filter, Filter::HeightToNormal(_) | Filter::ColorMatch(_)) { if let Filter::ColorMatch(matching) = filter { @@ -126,6 +127,7 @@ pub(super) fn lower_filter(filter: &Filter, effect: &Effect, op: &mut Operation, inputs.filters.push((filter.clone(), effect.opacity)); return Some((super::NEIGHBOURHOOD_OPCODE, [0.0; 3])); } + let mut lowered = point::lower(filter, effect, op, inputs); if lowered.is_none() { lowered = lighting::lower(filter, effect, op, inputs); @@ -164,6 +166,7 @@ pub(super) fn needs_surface(op: &Operation) -> bool { if op.ids[1] == 191 && op.ext[0] != 0 { return true; } + lighting::needs_surface(op) } @@ -175,6 +178,7 @@ pub(super) fn mask_reads_own_layer(op: &Operation) -> bool { if op.ids[1] == 188 { return true; } + stack::reads_own_layer(op) } @@ -187,13 +191,25 @@ pub(super) fn order_layer_operations(operations: &mut [Operation]) { /// Whether the GPU program evaluates texture set `set` (P8: UDIM sets); `mask_preview` picks the message. pub(super) fn check_set(set: &TextureSet, mask_preview: bool) -> Result<(), &'static str> { + if set.resolution != set.height() { + return Err("Rectangular texture sets use CPU compositing."); + } + + if set.iter_formats().any(|(channel, format)| { + use texturecraft_core::ChannelFormat; + !channel.is_shaded() + || (channel.components() == 3 && format.is_grey()) + || matches!(format, ChannelFormat::L8 | ChannelFormat::Rgb8 | ChannelFormat::Srgb8) + }) { + return Err("These texture set channels or storage formats use CPU compositing."); + } + udim::check_set(set, mask_preview) } /// The band uniform's package vec4s. pub(super) fn write_band_uniform(program: &CompositeProgram, values: &mut [u32; UNIFORM_WORDS]) { - // P4 and P5 run in the neighbourhood shader with their own parameters; their vec4s stay zero - // unless P5 writes its own from the prepare loop in `compose`. + // Neighbourhood passes supply their own uniforms let slots = [ fill_projection::band_uniform(program), point::band_uniform(program), @@ -209,50 +225,16 @@ pub(super) fn write_band_uniform(program: &CompositeProgram, values: &mut [u32; } } -/// Which package WGSL files a program compiles in full; the others compile as stubs so that -/// Mesa does not inline unused code (gpu_composite_pipelines.rs). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] -pub(super) struct ShaderFlags { - projection: bool, - point: bool, - stack: bool, - lighting: bool, - brush: bool, - udim: bool, -} +#[path = "composite_package/shader_flags.rs"] +mod shader_flags; -impl ShaderFlags { - pub(super) fn of(program: &CompositeProgram) -> Self { - Self { - projection: fill_projection::uses_shader(program), - point: point::uses_shader(program), - stack: stack::uses_shader(program), - lighting: lighting::uses_shader(program), - brush: brush::uses_shader(program), - udim: udim::uses_shader(program), - } - } - - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(super) const ALL: Self = Self { projection: true, point: true, stack: true, lighting: true, brush: true, udim: true }; - #[cfg(all(test, not(target_arch = "wasm32")))] - const NONE: Self = Self { projection: false, point: false, stack: false, lighting: false, brush: false, udim: false }; - /// Each package's file in full, the others as stubs. - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(super) const EACH: [Self; 6] = [ - Self { projection: true, ..Self::NONE }, - Self { point: true, ..Self::NONE }, - Self { stack: true, ..Self::NONE }, - Self { lighting: true, ..Self::NONE }, - Self { brush: true, ..Self::NONE }, - Self { udim: true, ..Self::NONE }, - ]; -} +pub(super) use shader_flags::ShaderFlags; /// The packages' WGSL for the composite shader: this hub's dispatcher, then each package file /// or its stub. pub(super) fn shader_sources(flags: ShaderFlags) -> [&'static str; 8] { let pick = |full: bool, source: &'static str, stub: &'static str| if full { source } else { stub }; + // The hooks' test probes only in the tests: the driver compiles every function the shader holds let probes = if cfg!(test) { include_str!("shaders/composite_probes.wgsl") @@ -394,6 +376,7 @@ mod tests { let staged = compile(&[(Filter::Smoothstep { min: 0.0, max: 1.0 }, 0.77)]); super::STAGED_TEST_LOWERING.set(false); let separate = compile(&[(Filter::Blur { radius: 24.0, wrap: false }, 1.0), (Filter::Invert, 0.77)]); + // A content stage per channel operation and one for the shared mask; the preview has the mask stage assert!(staged[0].1 >= 2 && staged[1].1 == 1, "{:?}", (staged[0].1, staged[1].1)); assert_eq!(staged, separate); @@ -439,6 +422,7 @@ mod tests { assert!(x0 <= 0 && y0 <= 0 && x1 >= rect[2] as i32 && y1 >= rect[3] as i32, "{rect:?}"); assert_eq!([x1 - x0, y1 - y0], [128, 96], "the bounds are the set, {rect:?}"); } + // A wrapping program's field starts 30 texels before the set's corner let start = (-30i32) as u32; assert_eq!(super::super::field_bounds([start, start, 76, 76], size), [30, 30, 158, 126]); @@ -522,6 +506,7 @@ mod tests { images: &images, bounds: mesh.bounds(), }; + // The stages of the 160 blur wrap; the generator's blur and the 24 blur do not let wide = crate::gpu_neighbourhood::NeighbourhoodFilter::new(&Filter::Blur { radius: 160.0, wrap: false }, SIZE, SIZE, 1.0, None).unwrap().radius; let mark = |program: &mut CompositeProgram| { @@ -548,7 +533,7 @@ mod tests { gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); let full = read(&gpu); for &(tx, ty) in &tiles { - let expected = tile_bytes(&oracle, &baked, DisplayKind::BaseColor, tx, ty); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, tx, ty); for (y, row) in expected.as_chunks::<{ TILE as usize * 4 }>().0.iter().enumerate() { let start = ((ty * TILE + y as u32) * SIZE + tx * TILE) as usize * 4; for (x, (gpu, cpu)) in full[start..start + row.len()].as_chunks::<4>().0.iter().zip(row.as_chunks::<4>().0).enumerate() { @@ -662,7 +647,7 @@ mod tests { } let whole = program.filters.whole_set().expect("the Blur 160 stages run in the pre-pass"); assert!(whole.outputs.iter().all(|&output| program.filters.stages[output].filter.is_some_and(|filter| filter.radius == wide.radius))); - assert!(program.filters.band_reach() < program.filters.reach, "the bands no longer carry the pre-pass's reach"); + assert!(program.filters.band_reach(Some(&whole)) < program.filters.reach, "the bands no longer carry the pre-pass's reach"); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); program }; @@ -676,7 +661,7 @@ mod tests { gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &compile(None, false)).unwrap(); let full = read(&gpu); for &(tx, ty) in &tiles { - let expected = tile_bytes(&oracle, &baked, DisplayKind::BaseColor, tx, ty); + let expected = tile_bytes(&oracle, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, tx, ty); for (y, row) in expected.as_chunks::<{ TILE as usize * 4 }>().0.iter().enumerate() { let start = ((ty * TILE + y as u32) * SIZE + tx * TILE) as usize * 4; for (x, (gpu, cpu)) in full[start..start + row.len()].as_chunks::<4>().0.iter().zip(row.as_chunks::<4>().0).enumerate() { @@ -685,6 +670,7 @@ mod tests { } } } + // A partial update: the pre-pass covers only what the corner region's bands read gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &compile(Some(CompositeRegion { min: [0, 0], max: [16, 16] }), false)).unwrap(); assert!(read(&gpu).iter().zip(&full).all(|(a, b)| a.abs_diff(*b) <= 1), "wrap {wrap}: the corner region changed the result"); @@ -728,6 +714,7 @@ mod tests { project.texture_sets.push(TextureSet::new("Plane", 0, size)); let owner = project.alloc_id(); let mut layer = Layer::new(owner, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + // A Bevel-like reach: about 411 texels at 4K let blur = Filter::Blur { radius: 68.5, wrap: false }; layer.content_effects.push(Effect::new(project.alloc_id(), EffectKind::Filter(blur.clone()))); @@ -784,6 +771,7 @@ mod tests { project.texture_sets.push(TextureSet::new("Plane", 0, SIZE)); let owner = project.alloc_id(); let mut layer = Layer::new(owner, "Paint", LayerKind::Paint, &[Channel::BaseColor]); + // Three box passes of 683 texels: a reach of 2049, half the set layer.content_effects.push(Effect::new(project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 341.5, wrap: false }))); project.insert_layer(0, layer, None, false).unwrap(); @@ -821,6 +809,7 @@ mod tests { )]); let roughness = super::super::channel_slot(Channel::Roughness); let channels = [Channel::BaseColor, Channel::Roughness]; + // A lower fill of roughness 0.3, an upper white fill of roughness 0.8 masked by `mask` let build = |mask: EffectKind| { let mut project = Project::new("Probes", "builtin:plane"); @@ -918,6 +907,7 @@ mod tests { let Some(mut gpu) = headless() else { return }; const SIZE: u32 = 64; let channels = [Channel::BaseColor, Channel::Roughness, Channel::Metallic]; + // A lower fill of roughness 0.3 and metallic 0.6, an upper white fill masked by `mask` let project_with = |mask: EffectKind| { let mut project = Project::new("Probes", "builtin:plane"); @@ -941,6 +931,7 @@ mod tests { project.insert_layer(0, layer, None, false).unwrap(); (project, owner) }; + // The probe as the upper layer's mask, compiled for the mask preview or the material let compile_probe = |selector: u32, min: f32, max: f32, preview: bool| { let (project, owner) = project_with(EffectKind::Filter(Filter::Smoothstep { min, max })); @@ -990,8 +981,7 @@ mod tests { let plane = Arc::new(primitives::plane(1.0, 1)); let uniform = |gray: &[u8], expected: u8, what: &str| assert!(gray.iter().all(|&value| value.abs_diff(expected) <= 1), "{what}: {:?}", &gray[..4]); - // The second stack read: Metallic (0.6) besides Roughness, each in its own capture stage, - // as the material's mask against a mask of 0.6 + // Capture Metallic and Roughness independently for the mask comparison let roughness = super::super::channel_slot(Channel::Roughness); let metallic = super::super::channel_slot(Channel::Metallic); let mut program = compile_probe(5, roughness as f32, metallic as f32, false); @@ -1024,8 +1014,7 @@ mod tests { uniform(&mask_gray(&mut gpu, &program), to_gray(expected), "environment word"); } - // The bake rows: the Height (0.4) in the second block, the ambient occlusion (0.7) still - // where `baked_at` reads it, and 0.25 from the probe without a baked Height + // Exercise both bake row blocks and the fallback for missing height let texels = (SIZE * SIZE) as usize; let mut baked = BakedMaps { resolution: SIZE, ..Default::default() }; baked.maps.insert(BakedMap::AmbientOcclusion, Arc::new(vec![0.7; texels])); @@ -1162,6 +1151,7 @@ mod tests { let owner = project.alloc_id(); let sources = channels.map(|channel| (channel, Source::Uniform([0.4; 3]))); let mut layer = Layer::new(owner, "Surface", LayerKind::Fill(Fill { sources: sources.into(), ..Default::default() }), &channels); + // Three box passes of 188 texels at 4K: a reach of 564 layer.content_effects.push(effect(EffectKind::Filter(Filter::Blur { radius: 94.0, wrap: false }))); project.insert_layer(0, layer, None, false).unwrap(); @@ -1172,11 +1162,13 @@ mod tests { let whole = program.filters.whole_set().expect("the Blur runs in the pre-pass"); assert_eq!((whole.outputs.len(), whole.reach), (4, 564)); let full = super::super::CompositeRegion { min: [0, 0], max: [SIZE, SIZE] }; - let pass = super::super::WholeSetPass::plan(whole, (full, 0), (SIZE, SIZE), program.filters.band_reach(), false, 5, program.filters.stages.len()); + let reach = program.filters.band_reach(Some(&whole)); + let pass = super::super::WholeSetPass::plan(whole, (full, 0), (SIZE, SIZE), reach, false, 5, program.filters.stages.len()); let limit = 2047u64 << 20; let results = pass.result_bytes(); let pass = pass.with_stripes(limit - results).expect("the stripes fit beside the results"); assert!(pass.stripe_bytes() + results <= limit && pass.stripe_rows >= 1); + // Every stripe's field stays inside the set for stack in &pass.stages.passes { let rect = pass.field_rect(stack, 0, pass.stripe_rows); @@ -1193,6 +1185,7 @@ mod tests { assert!(block.end <= other.start || other.end <= block.start, "{block:?} overlaps {other:?}"); } } + // Group markers and the Tile Generator stay outside the effects for kind in [crate::gpu_tile_pattern::TILE_GENERATOR_OPCODE, super::super::BEGIN_GROUP, super::super::END_GROUP] { assert!(!EXTENDED_EFFECTS.contains(&kind), "{kind}"); diff --git a/crates/render/src/gpu_composite_pipelines.rs b/crates/render/src/gpu_composite_pipelines.rs deleted file mode 100644 index 16a6e021..00000000 --- a/crates/render/src/gpu_composite_pipelines.rs +++ /dev/null @@ -1,633 +0,0 @@ -use std::collections::BTreeMap; -use std::sync::{Arc, Mutex, PoisonError}; - -use super::packages::{self, ShaderFlags}; -use super::{ANCHOR_PUBLISH_LAYER, ANCHOR_SOURCE, COLOR_SELECTION_OPCODE, CompositeProgram, FIRST_EXTENDED_PATTERN, FIRST_GENERATOR, TILE_GENERATOR_OPCODE}; - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] -struct Features { - patterns: bool, - extended_patterns: bool, - tile_generator: bool, - authored_images: bool, - mask_preview: bool, - extended_blend_modes: bool, - generators: bool, - curvature: bool, - sampled_generator_inputs: bool, - spatial: bool, - mask_effects: bool, - content_effects: bool, - height_mask: bool, - anchors: bool, - material_anchors: bool, - color_selection: bool, - // The GPU port packages' WGSL files compiled in full (gpu_composite_packages.rs) - packages: ShaderFlags, -} - -impl Features { - fn of(program: &CompositeProgram) -> Self { - let mut features = Self { - authored_images: !program.material_images.is_empty(), - mask_preview: program.is_mask_preview(), - spatial: !program.filters.stages.is_empty(), - packages: ShaderFlags::of(program), - ..Self::default() - }; - features.material_anchors = program.filters.stages.iter().any(|stage| stage.anchor.is_some()); - // A capture stage (an anchor or a stack read) runs the prepare pass's anchor path - features.anchors |= features.material_anchors; - for op in program.operations.iter().take(program.layer_count as usize).filter(|op| op.ids[1] != ANCHOR_PUBLISH_LAYER) { - features.mask_effects |= op.effects[1] != 0; - features.content_effects |= op.effects[3] != 0; - features.height_mask |= op.constraints[2] != 0; - } - // Inspect the compiled operations, including sources referenced by - // generator overrides and fills in the mask preview. - for op in &program.operations { - let kind = op.ids[1]; - features.extended_blend_modes |= op.balance[2] > 8.0; - features.anchors |= kind == ANCHOR_SOURCE; - features.color_selection |= kind == COLOR_SELECTION_OPCODE; - features.patterns |= matches!(kind, 1..=9 | 11..=13 | FIRST_EXTENDED_PATTERN..=TILE_GENERATOR_OPCODE); - features.extended_patterns |= (FIRST_EXTENDED_PATTERN..TILE_GENERATOR_OPCODE).contains(&kind); - features.tile_generator |= kind == TILE_GENERATOR_OPCODE; - if (FIRST_GENERATOR..FIRST_EXTENDED_PATTERN).contains(&kind) { - features.generators = true; - features.curvature |= op.uv[1] != 0.0; - if let Some(source) = op.effects[3].checked_sub(1).and_then(|index| program.operations.get(index as usize)) { - features.sampled_generator_inputs |= source.ids[1] != 0; - } - } - } - features - } - - fn source(self, supports_curvature: bool, supports_id: bool) -> String { - fn include(enabled: bool, full: &'static str, stub: &'static str) -> &'static str { - if enabled { full } else { stub } - } - - // Naga substitutes overrides on GL, but still emits the inactive - // function bodies. Omit those helpers so Mesa does not inline them - // before its dead-code pass. - [ - "override enable_authored_images: bool = false;\n override enable_generators: bool = false;\n override enable_curvature_detail: bool = false;\n override enable_spatial_fields: bool = false;\n override enable_anchor_reads: bool = false;", - include_str!("shaders/noise.wgsl"), - // Keep the gradient fallback when the program has no extended patterns. - include( - self.extended_patterns, - include_str!("shaders/procedural_extra.wgsl"), - "fn extended_pattern(kind: u32, p: vec3, seed: u32) -> f32 { return fract(p.x); }", - ), - include( - self.tile_generator, - include_str!("shaders/tile_generator.wgsl"), - "fn tile_generator(offset: u32, uv: vec2) -> f32 { return 0.0; }", - ), - include( - self.patterns, - include_str!("shaders/composite_patterns.wgsl"), - "fn procedural_value(layer: Operation, uv: vec2, surface: Surface) -> vec3 { return layer.low.rgb; }", - ), - include( - self.authored_images, - include_str!("shaders/material_image.wgsl"), - "fn authored_image_value(layer: Operation, uv: vec2, surface: Surface) -> vec3 { return layer.low.rgb; }\n fn decal_fill_value(layer: Operation, uv: vec2, surface: Surface) -> vec4 { return vec4(layer.low.rgb, 1.0); }\n fn material_image_texel(image: u32, pixel: vec2, size: vec2) -> vec4 { return vec4(0.0); }\n const MISSING_IMAGE: u32 = 0xffffffffu;\n fn decode_image_sample(layer: Operation, rgb: vec3) -> vec3 { return rgb; }", - ), - include_str!("shaders/stencil_projection.wgsl"), - include( - self.curvature && supports_curvature, - include_str!("shaders/curvature_sample.wgsl"), - "fn curvature_level_at(pixel: vec2, level: u32) -> f32 { return 0.0; }", - ), - include( - self.curvature, - include_str!("shaders/composite_curvature_detail.wgsl"), - "fn generator_curvature(effect: Operation, pixel: vec2, finest: f32, mode: u32, micro: f32) -> f32 { return 0.0; }", - ), - include( - self.sampled_generator_inputs, - "fn generator_source_value(index: u32, texel: LayerTexel) -> f32 {\n return fill_value(layers[index], texel.uv, texel.surface).x;\n }", - "fn generator_source_value(index: u32, texel: LayerTexel) -> f32 { return layers[index].low.x; }", - ), - include( - self.generators, - include_str!("shaders/composite_generators.wgsl"), - "fn generator_ramp(effect: Operation, texel: LayerTexel) -> f32 { return 0.0; }\n fn finish_generator(effect: Operation, ramp: f32) -> f32 { return ramp; }", - ), - include( - self.spatial, - include_str!("shaders/composite_spatial.wgsl"), - "fn previous_field(start: u32, count: u32) -> u32 { return 0u; }\n fn filter_value(slot: u32, pixel: vec2) -> vec4 { return vec4(0.0); }\n var preceding_field: u32 = 0xffffffffu;\n fn preceding_stage_word(pixel: vec2) -> f32 { return 0.0; }", - ), - include( - self.color_selection && supports_id, - include_str!("shaders/id_sample.wgsl"), - "fn id_color_at(pixel: vec2) -> vec3 { return vec3(0.0); }", - ), - include( - self.mask_effects, - include_str!("shaders/composite_mask_effects.wgsl"), - "fn layer_mask(layer: Operation, texel: LayerTexel, count: u32) -> f32 { return layer.balance.y; }", - ), - include( - self.content_effects, - include_str!("shaders/composite_content_effects.wgsl"), - "fn layer_content(layer: Operation, texel: LayerTexel, count: u32) -> vec4 { - let content = base_content(layer, texel); - return select(vec4(0.0), content, content.a > 0.0); - }", - ), - include( - self.height_mask, - include_str!("shaders/composite_height_mask.wgsl"), - "fn mask_with_height(layer: Operation, texel: LayerTexel, mask: f32) -> f32 { return mask; }", - ), - include_str!("shaders/composite_groups.wgsl"), - include_str!("shaders/composite.wgsl"), - ] - .into_iter() - .map(str::to_string) - .chain(packages::shader_sources(self.packages).into_iter().map(str::to_string)) - .chain(std::iter::once(super::channel_defaults_wgsl())) - .collect::>() - .join("\n") - } - - fn constants(self, grouped: bool) -> [(&'static str, f64); 8] { - [ - ("enable_authored_images", f64::from(u8::from(self.authored_images))), - ("enable_generators", f64::from(u8::from(self.generators))), - ("enable_curvature_detail", f64::from(u8::from(self.curvature))), - ("enable_spatial_fields", f64::from(u8::from(self.spatial))), - ("enable_anchor_reads", f64::from(u8::from(self.anchors))), - ("composite_groups", f64::from(u8::from(grouped))), - ("composite_mask_preview", f64::from(u8::from(self.mask_preview))), - ("enable_extended_blend_modes", f64::from(u8::from(self.extended_blend_modes))), - ] - } -} - -/// A pipeline compiled, or compiling on a worker thread (`CompositePipelines::asynchronous`) -enum Slot { - Ready(wgpu::ComputePipeline), - // The web compiles in place: no worker threads there - #[cfg_attr(target_arch = "wasm32", allow(dead_code))] - Compiling(Arc>>>), - /// A worker's compile that failed (the device's error handler panicked on it): final - #[cfg_attr(target_arch = "wasm32", allow(dead_code))] - Failed(String), -} - -impl Slot { - /// The pipeline once compiled (None while it compiles), or why it never will be; `wait` - /// waits for a compile in flight (a caller that compiles in place, after a pre-warm started - /// one on a worker thread) - fn ready(&mut self, wait: bool) -> Result, String> { - if let Slot::Compiling(compiled) = self { - let result = loop { - if let Some(result) = compiled.lock().unwrap_or_else(PoisonError::into_inner).take() { - break result; - } - if !wait { - return Ok(None); - } - std::thread::sleep(std::time::Duration::from_millis(1)); - }; - *self = match result { - Ok(pipeline) => Slot::Ready(pipeline), - Err(error) => Slot::Failed(error), - }; - } - match self { - Slot::Ready(pipeline) => Ok(Some(pipeline.clone())), - Slot::Compiling(_) => Ok(None), - Slot::Failed(error) => Err(error.clone()), - } - } -} - -struct Variants { - module: wgpu::ShaderModule, - render: [Option; 2], - prepare: [Option; 2], -} - -pub(super) struct CompositePipelines { - supports_curvature: bool, - supports_id: bool, - variants: BTreeMap, -} - -/// The pipelines a compositor uses: its own, or when `shared` (a compositor on the device tests -/// share, [`crate::headless::Headless::for_tests`]) one set for every such compositor, so a test -/// does not compile the variants an earlier one compiled (llvmpipe keeps what it compiled until -/// the process ends, and compiling dominates its tests' time). -pub(super) fn shared(shared: bool, supports_curvature: bool, supports_id: bool) -> Arc> { - #[cfg(all(any(test, feature = "test-support"), not(target_arch = "wasm32")))] - if shared { - static SHARED: std::sync::OnceLock>> = std::sync::OnceLock::new(); - return SHARED.get_or_init(|| Arc::new(Mutex::new(CompositePipelines::new(supports_curvature, supports_id)))).clone(); - } - #[cfg(not(all(any(test, feature = "test-support"), not(target_arch = "wasm32"))))] - let _ = shared; - Arc::new(Mutex::new(CompositePipelines::new(supports_curvature, supports_id))) -} - -impl CompositePipelines { - pub(super) fn new(supports_curvature: bool, supports_id: bool) -> Self { - Self { supports_curvature, supports_id, variants: BTreeMap::new() } - } - - /// Start compiling `program`'s pipelines without waiting (`get` returns them once ready). - pub(super) fn prewarm(&mut self, device: &wgpu::Device, layout: &wgpu::PipelineLayout, program: &CompositeProgram) { - let _ = self.get(device, layout, program, !cfg!(target_arch = "wasm32")); - } - - /// The program's compose and prepare pipelines; None while one still compiles (new ones - /// compile on worker threads when `asynchronous`: the viewport keeps its last result), an - /// error when a worker's compile failed. - pub(super) fn get( - &mut self, - device: &wgpu::Device, - layout: &wgpu::PipelineLayout, - program: &CompositeProgram, - asynchronous: bool, - ) -> Result)>, String> { - let features = Features::of(program); - let supports_curvature = self.supports_curvature; - let supports_id = self.supports_id; - let variants = self.variants.entry(features).or_insert_with(|| Variants { - module: device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("tc_gpu_composite"), - source: wgpu::ShaderSource::Wgsl(features.source(supports_curvature, supports_id).into()), - }), - render: [None, None], - prepare: [None, None], - }); - let module = variants.module.clone(); - let pipeline = |entry: &'static str, label: &'static str, grouped: bool| { - let compile = { - let (device, layout, module) = (device.clone(), layout.clone(), module.clone()); - move || { - #[cfg(not(target_arch = "wasm32"))] - let started = std::time::Instant::now(); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(label), - layout: Some(&layout), - module: &module, - entry_point: Some(entry), - compilation_options: wgpu::PipelineCompilationOptions { constants: &features.constants(grouped), ..Default::default() }, - cache: None, - }); - #[cfg(not(target_arch = "wasm32"))] - log::debug!("GPU pipeline {label} compiled in {:.1} ms ({:?})", started.elapsed().as_secs_f64() * 1000.0, device.adapter_info().backend); - pipeline - } - }; - #[cfg(not(target_arch = "wasm32"))] - if asynchronous { - let compiled = Arc::new(Mutex::new(None)); - let sink = compiled.clone(); - std::thread::spawn(move || { - // A compile the device's error handler panics on still answers, so the slot - // never waits for it forever - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(compile)).map_err(|panic| { - let message = panic.downcast_ref::().cloned().or_else(|| panic.downcast_ref::<&str>().map(|text| text.to_string())); - format!("GPU pipeline {label} failed to compile: {}", message.unwrap_or_default()) - }); - *sink.lock().unwrap_or_else(PoisonError::into_inner) = Some(result); - }); - return Slot::Compiling(compiled); - } - Slot::Ready(compile()) - }; - let grouped = program.groups.depth != 0; - let render = variants.render[usize::from(grouped)].get_or_insert_with(|| pipeline("compose", "tc_gpu_composite", grouped)).ready(!asynchronous)?; - // Only material anchor capture needs to walk the group structure while preparing a source. - let grouped_capture = grouped && features.material_anchors; - let prepare = match features.spatial { - true => match variants.prepare[usize::from(grouped_capture)] - .get_or_insert_with(|| pipeline("prepare_filter", "tc_spatial_source", grouped_capture)) - .ready(!asynchronous)? - { - Some(prepare) => Some(prepare), - None => return Ok(None), - }, - false => None, - }; - Ok(render.map(|render| (render, prepare))) - } -} - -#[cfg(all(test, not(target_arch = "wasm32")))] -mod tests { - use super::{Features, ShaderFlags}; - use crate::gpu_composite::{GpuCompositor, oracle}; - use crate::gpu_neighbourhood::NeighbourhoodGpu; - - /// Every package stub, each package in full alone and all in full, each with and without - /// neighbourhood fields, plus a mask preview and a program using every other feature. - fn variants() -> Vec { - let mut packages = vec![ShaderFlags::default(), ShaderFlags::ALL]; - packages.extend(ShaderFlags::EACH); - let mut variants: Vec = packages - .into_iter() - .flat_map(|packages| [false, true].map(|spatial| Features { spatial, mask_effects: true, content_effects: true, packages, ..Features::default() })) - .collect(); - variants.push(Features { mask_preview: true, spatial: true, mask_effects: true, packages: ShaderFlags::ALL, ..Features::default() }); - variants.push(Features { - patterns: true, - extended_patterns: true, - tile_generator: true, - authored_images: true, - mask_preview: false, - extended_blend_modes: true, - generators: true, - curvature: true, - sampled_generator_inputs: true, - spatial: true, - mask_effects: true, - content_effects: true, - height_mask: true, - anchors: true, - material_anchors: true, - color_selection: true, - packages: ShaderFlags::ALL, - }); - variants - } - - fn entry_points(features: Features) -> Vec<&'static str> { - if features.spatial { vec!["compose", "prepare_filter"] } else { vec!["compose"] } - } - - #[allow(clippy::panic)] // A test helper: a shader that does not translate fails the test - /// Parse and validate `source`, then write GLSL (GLES 3.1 and desktop 4.3, the GL backends' - /// path) for every entry point with the override constants of both group variants. - fn naga_check(label: &str, source: &str, entries: &[&str], constants: &[Vec<(&'static str, f64)>]) { - let module = naga::front::wgsl::parse_str(source).unwrap_or_else(|error| panic!("{label}: {}", error.emit_to_string(source))); - let info = naga::valid::Validator::new( - naga::valid::ValidationFlags::all(), - naga::valid::Capabilities::default() | naga::valid::Capabilities::SHADER_FLOAT16_IN_FLOAT32, - ) - .validate(&module) - .unwrap_or_else(|error| panic!("{label}: {error:?}")); - for constants in constants { - let mut values = naga::back::PipelineConstants::default(); - values.extend(constants.iter().map(|&(name, value)| (name.to_owned(), value))); - for &entry in entries { - let (module, info) = naga::back::pipeline_constants::process_overrides(&module, &info, Some((naga::ShaderStage::Compute, entry)), &values) - .unwrap_or_else(|error| panic!("{label} {entry}: {error}")); - for version in [naga::back::glsl::Version::new_gles(310), naga::back::glsl::Version::Desktop(430)] { - let options = naga::back::glsl::Options { version, ..Default::default() }; - let pipeline = - naga::back::glsl::PipelineOptions { shader_stage: naga::ShaderStage::Compute, entry_point: entry.to_owned(), multiview: None }; - let mut glsl = String::new(); - naga::back::glsl::Writer::new(&mut glsl, &module, &info, &options, &pipeline, naga::proc::BoundsCheckPolicies::default()) - .and_then(|mut writer| writer.write()) - .unwrap_or_else(|error| panic!("{label} {entry} {version:?} {constants:?}: {error}")); - } - } - } - } - - /// Every package WGSL file and stub, in the composite and the neighbourhood shader, without - /// an adapter: so this never skips. - #[test] - fn package_shaders_validate_and_write_glsl_without_an_adapter() { - for features in variants() { - for (curvature, id) in [(false, false), (true, true)] { - let constants = [false, true].map(|grouped| features.constants(grouped).to_vec()); - naga_check(&format!("{features:?} curvature {curvature} id {id}"), &features.source(curvature, id), &entry_points(features), &constants); - } - } - naga_check("neighbourhood", &NeighbourhoodGpu::source(), &NeighbourhoodGpu::ENTRY_POINTS, &[Vec::new()]); - } - - /// With asynchronous compiles a new program first answers GPU_PIPELINES_PENDING, leaving the - /// set's textures as they are, then composites once its pipelines are ready; a pre-warmed - /// program composites at once. - #[test] - #[allow(clippy::unwrap_used)] // A test: a program that does not build fails it - fn new_pipelines_compile_on_worker_threads() { - use std::collections::BTreeMap; - - use texturecraft_compose::PixelStore; - use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Project, Source, TextureSet}; - - use crate::gpu_composite::{CompositeProgram, GPU_PIPELINES_PENDING}; - - // A device of its own: the tests share their pipelines per device - let Ok(mut gpu) = crate::headless::Headless::with_limits(crate::device_limits) else { return }; - let project = |radius: f32| { - let mut project = Project::new("Asynchronous", "builtin:plane"); - project.texture_sets.push(TextureSet::new("Plane", 0, 64)); - let id = project.alloc_id(); - let fill = Fill { sources: BTreeMap::from([(Channel::BaseColor, Source::Uniform([0.6, 0.3, 0.2]))]), ..Default::default() }; - let mut layer = Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor]); - layer.content_effects.push(Effect::new(project.alloc_id(), EffectKind::Filter(Filter::Blur { radius, wrap: false }))); - project.insert_layer(0, layer, None, false).unwrap(); - project - }; - let mesh = std::sync::Arc::new(texturecraft_geom::primitives::plane(1.0, 1)); - let gbuf = std::sync::Arc::new(texturecraft_geom::UvGBuffer::new(&mesh, 0, 64, 64)); - let program = |project: &Project| { - let mut program = CompositeProgram::compile(project, &PixelStore::default(), 0).unwrap(); - program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); - program - }; - gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((64, 64), 0)], 1); - gpu.renderer.set_asynchronous_compile(true); - let first = program(&project(8.0)); - assert_eq!(gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &first), Err(GPU_PIPELINES_PENDING.to_string())); - let started = std::time::Instant::now(); - loop { - match gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &first) { - Err(error) if error == GPU_PIPELINES_PENDING => { - assert!(started.elapsed() < std::time::Duration::from_secs(300), "the pipelines never finished"); - std::thread::yield_now(); - } - result => { - assert_eq!(result, Ok(())); - break; - } - } - } - // The same features again: ready at once - assert_eq!(gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program(&project(16.0))), Ok(())); - } - - /// Cold compile times of realistic programs' pipelines (run with the driver's shader cache - /// off, e.g. `__GL_SHADER_DISK_CACHE=0` on NVIDIA): a material of fills with Blur, Levels and - /// lighting under a generator mask, a mask comparing the layers below and this layer, and the - /// test variant with every package and feature. - #[test] - #[ignore = "a measurement: cold pipeline compiles"] - #[allow(clippy::unwrap_used)] // A measurement: a program that does not build fails it - fn bench_cold_pipeline_compile() { - use std::collections::BTreeMap; - - use texturecraft_compose::PixelStore; - use texturecraft_core::{ - Channel, CompareOp, CompareSource, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerKind, Levels, Mask, MaskBackground, Project, - Source, StylizedLighting, TextureSet, - }; - - use crate::gpu_composite::CompositeProgram; - - let Some(gpu) = oracle::headless() else { return }; - let channels = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Normal, Channel::Height]; - let fill = |values: [f32; 3]| Fill { - sources: channels.iter().map(|&channel| (channel, Source::Uniform(values))).collect::>(), - ..Default::default() - }; - let project = |content: Vec, mask: Vec| { - let mut project = Project::new("Compile", "builtin:plane"); - project.texture_sets.push(TextureSet::new("Plane", 0, 256)); - let below = project.alloc_id(); - project.insert_layer(0, Layer::new(below, "Below", LayerKind::Fill(fill([0.3; 3])), &channels), None, false).unwrap(); - let owner = project.alloc_id(); - let mut layer = Layer::new(owner, "Layer", LayerKind::Fill(fill([0.6; 3])), &channels); - for kind in content { - layer.content_effects.push(Effect::new(project.alloc_id(), kind)); - } - if !mask.is_empty() { - let mut layer_mask = Mask::new(MaskBackground::White); - for kind in mask { - layer_mask.effects.push(Effect::new(project.alloc_id(), kind)); - } - layer.mask = Some(layer_mask); - } - project.insert_layer(0, layer, None, false).unwrap(); - project - }; - let lighting = Filter::BakedLighting { - azimuth: 30.0, - elevation: 50.0, - light: 1.0, - ambient: 1.0, - occlusion: 0.4, - stylized: Some(Box::new(StylizedLighting::library())), - }; - let uv_tiles = |mut project: Project| { - let set = &mut project.texture_sets[0]; - set.uv_tiles = vec![1001, 1002, 1011, 1012]; - set.tile_resolutions.extend([(1002, 128), (1012, 64)]); - project - }; - let compare = |left| EffectKind::Compare { - op: CompareOp::GreaterThan, - value: 0.4, - tolerance: 0.1, - left, - right: CompareSource::Constant, - channel: Channel::Roughness, - hardness: 0.5, - }; - let cases = [ - ( - "material: Blur, Levels, lighting, generator mask", - project( - vec![ - EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }), - EffectKind::Levels(Levels::default()), - EffectKind::Filter(lighting.clone()), - ], - vec![EffectKind::Generator(crate::gpu_composite::oracle::earlier_generator(GeneratorKind::Dirt))], - ), - ), - ("mask comparing Layers Below and This Layer", project(Vec::new(), vec![compare(CompareSource::LayersBelow), compare(CompareSource::ThisLayer)])), - ("plain fill", project(Vec::new(), Vec::new())), - // P8: the same material on a UV tile atlas with three tile scales - ( - "UV tile atlas: Blur, Levels, lighting, generator mask", - uv_tiles(project( - vec![ - EffectKind::Filter(Filter::Blur { radius: 8.0, wrap: false }), - EffectKind::Levels(Levels::default()), - EffectKind::Filter(lighting.clone()), - ], - vec![EffectKind::Generator(crate::gpu_composite::oracle::earlier_generator(GeneratorKind::Dirt))], - )), - ), - ("UV tile atlas: plain fill", uv_tiles(project(Vec::new(), Vec::new()))), - ]; - let compositor = GpuCompositor::new(&gpu.device); - let (curvature, id) = { - let pipelines = compositor.pipelines(); - (pipelines.supports_curvature, pipelines.supports_id) - }; - let programs = - cases.map(|(label, project)| (label, Features::of(&CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap()))); - let everything = - variants().into_iter().filter(|features| features.mask_preview || (features.spatial && !features.generators)).map(|features| ("variant", features)); - for (label, features) in programs.into_iter().chain(everything) { - let module = gpu.device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("tc_bench"), - source: wgpu::ShaderSource::Wgsl(features.source(curvature, id).into()), - }); - for entry in entry_points(features) { - let started = std::time::Instant::now(); - let _pipeline = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(entry), - layout: Some(&compositor.pipeline_layout), - module: &module, - entry_point: Some(entry), - compilation_options: wgpu::PipelineCompilationOptions { constants: &features.constants(false), ..Default::default() }, - cache: None, - }); - let memory = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); - let peak = memory.lines().filter(|line| line.starts_with("VmHWM") || line.starts_with("VmRSS")).collect::>().join(" "); - eprintln!("COMPILE {label} {:?} preview {}, {entry}: {:?} {peak}", features.packages, features.mask_preview, started.elapsed()); - } - } - } - - /// The programs with every package in full and with every package as a stub as compute - /// pipelines on the adapter, as `CompositePipelines::get` creates them (both group variants), - /// and the neighbourhood pipelines. The variants with one package in full are checked by naga - /// above: on the adapter they only repeat these compiles. - #[test] - fn package_shaders_build_compute_pipelines_in_full_and_as_stubs() { - let Some(gpu) = oracle::headless() else { return }; - let compositor = GpuCompositor::new(&gpu.device); - let (curvature, id) = { - let pipelines = compositor.pipelines(); - (pipelines.supports_curvature, pipelines.supports_id) - }; - // Every package variant; the program with every other feature too is left to the naga - // check above: Mesa's GL compiler needs over 28 GB for it (llvmpipe, measured) - // The program with every other feature too stays with the naga check above: Mesa's GL - // compiler (llvmpipe) runs out of 28 GB on its prepare_filter pipeline, with the package - // files as stubs too (a property of the base features, not of the packages). - let one_package = |features: &Features| ShaderFlags::EACH.contains(&features.packages); - for features in variants().into_iter().filter(|features| !features.generators && !one_package(features)) { - let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); - let module = gpu.device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("tc_gpu_composite_packages"), - source: wgpu::ShaderSource::Wgsl(features.source(curvature, id).into()), - }); - for grouped in [false, true] { - for entry in entry_points(features) { - let _pipeline = gpu.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(entry), - layout: Some(&compositor.pipeline_layout), - module: &module, - entry_point: Some(entry), - compilation_options: wgpu::PipelineCompilationOptions { constants: &features.constants(grouped), ..Default::default() }, - cache: None, - }); - } - } - let error = pollster::block_on(scope.pop()); - assert!(error.is_none(), "{features:?} on {}: {error:?}", gpu.adapter_name); - } - let scope = gpu.device.push_error_scope(wgpu::ErrorFilter::Validation); - let _neighbourhood = NeighbourhoodGpu::new(&gpu.device); - let error = pollster::block_on(scope.pop()); - assert!(error.is_none(), "neighbourhood on {}: {error:?}", gpu.adapter_name); - } -} diff --git a/crates/render/src/gpu_composite_point.rs b/crates/render/src/gpu_composite_point.rs index b9854784..33eb6c5b 100644 --- a/crates/render/src/gpu_composite_point.rs +++ b/crates/render/src/gpu_composite_point.rs @@ -84,6 +84,7 @@ fn point_content_effect(effect: Operation, content: vec4, channel: u32, tex let filtered = point_effect_color(effect, content.rgb, channel, texel.surface, texel.baked.x); return vec4(content.rgb + (filtered - content.rgb) * effect.low.w, content.a); } + fn point_mask_effect(effect: Operation, mask: f32, texel: LayerTexel) -> f32 { return point_scalar_filter(effect, mask); }"; /// A filter as a P2 point operation: (opcode, three parameters), or None. @@ -405,6 +406,7 @@ mod tests { let hard = [Filter::HistogramScan { position: 0.45, contrast: 1.0, invert_position: true }]; assert_filters_match_cpu(&soft, Tolerance::POINT); + // Full contrast is a threshold; the painted values sit away from it assert_filters_match_cpu(&hard, Tolerance::POINT.with_flips(4)); } @@ -434,6 +436,7 @@ mod tests { let step = [Filter::Smoothstep { min: 0.55, max: 0.55 }]; assert_filters_match_cpu(&soft, Tolerance::POINT); + // Equal bounds are a step; the painted values sit away from it assert_filters_match_cpu(&step, Tolerance::POINT.with_flips(4)); } @@ -452,6 +455,7 @@ mod tests { let steps = [curve(CurvePreset::Stairs), Filter::GradientCurve { preset: CurvePreset::Round, invert: false, balance: 0.5, contrast: 1.0 }]; assert_filters_match_cpu(&filters, Tolerance::POINT); + // Stairs and full contrast are hard decisions; the painted values sit away from them assert_filters_match_cpu(&steps, Tolerance::POINT.with_flips(4)); } @@ -473,6 +477,7 @@ mod tests { fn grayscale_conversion_matches_the_cpu() { let library = GrayscaleConversion::LIBRARY; let mut conversions: Vec = ConversionMode::ALL.into_iter().map(|mode| GrayscaleConversion { mode, ..library }).collect(); + // Alpha weighs the content's coverage, and 1 in a mask conversions.push(GrayscaleConversion { weights: [0.2, 0.3, 0.1, 0.4], ..library }); conversions.push(GrayscaleConversion { invert: true, balance: 0.6, contrast: 0.3, ..library }); @@ -480,6 +485,7 @@ mod tests { let hard = [Filter::GrayscaleConversion(GrayscaleConversion { contrast: 1.0, mode: ConversionMode::Average, ..library })]; assert_filters_match_cpu(&filters, Tolerance::POINT); + // Full contrast is a step at mid gray; the painted values sit away from it assert_filters_match_cpu(&hard, Tolerance::POINT.with_flips(4)); } @@ -496,6 +502,7 @@ mod tests { debug: false, }; let luma = GradientInput::default(); + // The library default: black, mid gray and white placed at 0, 0.5 and 1 of ten colours, the average gray let mut library_colors = vec![[0.0; 3], [0.214; 3]]; library_colors.resize(10, [1.0; 3]); @@ -522,6 +529,7 @@ mod tests { ]; assert_filters_match_cpu(&filters, Tolerance::POINT); + // The jump and full contrast are hard decisions; the painted values sit away from them assert_filters_match_cpu(&hard, Tolerance::POINT.with_flips(4)); } @@ -565,6 +573,7 @@ mod tests { blurred(GradientInput { blur: 4.0, ..GradientInput::LIBRARY }, true), blurred(GradientInput { blur: 12.0, balance: 0.6, contrast: 0.3, invert: true, ..GradientInput::default() }, false), ]; + // A region inside the tile, so the blur's halo reaches past it let region = CompositeRegion { min: [21, 17], max: [43, 39] }; diff --git a/crates/render/src/gpu_composite_projection.rs b/crates/render/src/gpu_composite_projection.rs index 128edd31..9b03c622 100644 --- a/crates/render/src/gpu_composite_projection.rs +++ b/crates/render/src/gpu_composite_projection.rs @@ -178,6 +178,7 @@ pub(super) fn place_image(projection: &Projection, _sampling: Sampling, op: &mut op.procedural[3] = 1; op.balance[3] = sharpness.max(1.0); } + // Framed projections read everything from P1's side table Projection::Planar { placed: Some(_), .. } | Projection::Warp { .. } => {} Projection::Planar { scale, axis, offset, .. } => { @@ -838,6 +839,7 @@ mod tests { let nearest = Sampling { filtering: Filtering::Nearest, ..Sampling::SAVED_BEFORE }; let triplanar = Projection::Triplanar { scale: 0.7, sharpness: 3.0, offset: [0.1, -0.2, 0.05], uv: UvTransform::default(), projector: Projector::default() }; + // Off the mesh's poles, where a whole texel row would sit on the projection's pole let spherical = Projection::Spherical { scale: 1.2, uv: UvTransform::default(), offset: [0.3, 0.1, -0.2], projector: Projector::default() }; let cylindrical = @@ -1022,6 +1024,7 @@ mod tests { let default = Backface { on: true, ..Backface::default() }; let culled = |backface| Projector { backface, ..Projector::default() }; let turned = |backface| Projector { rotation: [10.0, -25.0, 15.0], crop: ShapeCrop::Cropped, backface, ..Projector::default() }; + // Each culling mode once, on planar and cylindrical projections, plain and turned inside a crop let cases = [ ("hard planar X", Projection::Planar { scale: 0.9, axis: 0, offset: [0.0; 3], uv, projector: culled(hard), placed: None }), @@ -1438,7 +1441,7 @@ mod tests { /// Compositing cost of P1's heaviest settings, and of a plain Bilinear HQ fill against the /// CPU evaluator that composited it before: - /// `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture --test-threads=1 bench_fill_sampling` + /// `cargo test -p texturecraft-render --release --lib -- --ignored --nocapture bench_fill_sampling` #[test] #[ignore] fn bench_fill_sampling() { @@ -1449,6 +1452,7 @@ mod tests { let radial = FillSymmetry { on: true, kind: SymmetryKind::Radial, axis: 1, count: 64, position: OFF_POLE, ..FillSymmetry::OFF }; let triplanar = Projection::Triplanar { scale: 2.5, sharpness: 4.0, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::default() }; let hq = Sampling { filtering: Filtering::BilinearHq, ..Sampling::SAVED_BEFORE }; + // Cropped small, no copy covers a texel alone, so every texel evaluates all 64 let cropped = Projector { crop: ShapeCrop::Cropped, ..Projector::default() }; let small = Projection::Planar { scale: 3.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: cropped, placed: None }; diff --git a/crates/render/src/gpu_composite_stack.rs b/crates/render/src/gpu_composite_stack.rs index 2c2394ff..34541d95 100644 --- a/crates/render/src/gpu_composite_stack.rs +++ b/crates/render/src/gpu_composite_stack.rs @@ -57,6 +57,7 @@ fn stack_content_effect(effect: Operation, content: vec4, channel: u32, tex let filtered = stack_effect_color(effect, content.rgb, channel, texel.surface, texel.baked.x); return vec4(content.rgb + (filtered - content.rgb) * effect.low.w, content.a); } + fn stack_mask_effect(effect: Operation, mask: f32, texel: LayerTexel) -> f32 { return stack_scalar_filter(effect, mask); } fn stage_input_value(op: Operation, texel: LayerTexel) -> f32 { return base_content(op, texel).x; } fn stack_soft_compare(op: Operation, mask: f32) -> f32 { return mask; } @@ -192,6 +193,7 @@ pub(super) fn attach_distance_map(effect: &Effect, op: &mut Operation, inputs: & /// tile settings, from the input of the effect's filter that reads a Tile Generator. pub(super) fn bind_input_tiles(effect: &Effect, sources: &mut [Operation], patterns: &mut TilePatterns) { let EffectKind::Filter(filter) = &effect.kind else { return }; + // Color Match registers its Input and its Image Input in this order: each with its own tiles if let Filter::ColorMatch(_) = filter { let (_, texel_inputs) = crate::gpu_neighbourhood::gather::bind_inputs(effect, filter); @@ -203,6 +205,7 @@ pub(super) fn bind_input_tiles(effect: &Effect, sources: &mut [Operation], patte } return; } + let Some(source) = ImageInput::of(filter).iter().map(|input| effect.input(input)).find(|source| matches!(source, Source::Procedural { .. })) else { return; }; @@ -233,6 +236,7 @@ pub(super) fn attach_gather_input(effect: &Effect, op: &mut Operation, inputs: & else { return Some(()); }; + if op.ids[1] != NEIGHBOURHOOD_OPCODE { return Some(()); } @@ -291,6 +295,7 @@ mod tests { let image = Source::Image { name: "Pattern".into(), normal_format: NormalFormat::default() }; image_input.inputs.insert(texturecraft_core::ImageInput::CUSTOM_INPUT.id.into(), image); assert!(compile_effects(Some(image_input.clone()), Some(image_input.clone()), ContentsOffset::NONE).0.is_ok()); + // No layer below: the image read is the path under test let (project, pixels, owner) = compare_stack_in(vec![image_input.clone()], (false, 0, false, vec![image_input], false)); let mut case = OracleCase::new(&project, &pixels, &baked, &images, &mesh); @@ -638,6 +643,7 @@ mod tests { cases.push(vec![compare(CompareOp::LesserThan, 0.7, BlendMode::Multiply, 0.8)]); cases.push(vec![compare(CompareOp::WithinTolerance, 0.7, BlendMode::Disable, 0.8)]); cases.push(vec![invert.clone(), compare(CompareOp::GreaterThan, 0.5, BlendMode::Screen, 0.9), invert.clone()]); + // The constant on the left: its authored order let mut constant_first = compare(CompareOp::LesserThan, 0.5, BlendMode::Normal, 1.0); if let EffectKind::Compare { left, right, .. } = &mut constant_first.kind { @@ -662,8 +668,7 @@ mod tests { let mesh = Arc::new(primitives::plane(1.0, 1)); let images = ImageStore::default(); - // ID colours on, at and just past the tolerance of the picked ones, and far from them; the - // hard selections read IDs clear of the tolerance, where one ulp cannot flip a whole cell + // Keep hard ID selections clear of the rounding boundary let picked = vec![[0.40101, 0.69217, 0.05289], [0.375; 3], [0.21875, 0.78125, 0.09375]]; let ids = |boundary: bool| { let [at, past, below] = @@ -959,6 +964,7 @@ mod tests { #[test] fn mask_comparisons_reading_layers_match_the_cpu() { let invert = effect(EffectKind::Filter(Filter::Invert)); + // Each side pair, channel kind and comparison once: they are parameters of one compare path let channels = [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal]; let mut cases: Vec> = SIDES diff --git a/crates/render/src/gpu_composite_udim.rs b/crates/render/src/gpu_composite_udim.rs index 60ac79a0..ce987330 100644 --- a/crates/render/src/gpu_composite_udim.rs +++ b/crates/render/src/gpu_composite_udim.rs @@ -119,6 +119,7 @@ pub(super) fn pattern_levels(pattern: &Procedural, inputs: &mut ProceduralInputs if pixels.iter().all(|&texels| Some(&texels) == pixels.first()) { return Some(0); } + inputs.pack_words(&pixels) } @@ -141,6 +142,7 @@ pub(super) fn runs_over(layout: Option<&UdimLayout>, level: u32, field_rect: [u3 if wraps && (outside_x || outside_y) { return true; } + if x0 >= x1 || y0 >= y1 { return false; } @@ -528,8 +530,8 @@ mod tests { let mirror = Filter::Mirror(Mirror { offset: [0.4, 0.5], ..Mirror::LIBRARY }); let transform = Filter::Transform(TileTransform { rotation: 30.0, offset: [0.1, -0.2], ..TileTransform::LIBRARY }); let repeating = WarpSource { mode: WarpSourceMode::PreviousInput, tiling: 2.0, ..WarpSource::LIBRARY }; - // Directional: Warp mode's slope is a finite difference across the stripes' hard edges, - // which llvmpipe turns at a few texels + + // Finite differences at hard stripe edges can change direction on software adapters let warp = Filter::SourceWarp(SourceWarp { intensity: 0.5, mode: WarpMode::Directional, angle: 30.0, source: repeating, ..SourceWarp::LIBRARY }); let cases = [ ("Mirror", vec![(mirror.clone(), 1.0, normal)]), @@ -640,11 +642,13 @@ mod tests { let ramp = |side: usize, height: usize, value: fn(f32, f32) -> f32| -> Arc> { Arc::new((0..side * height).map(|index| value((index % side) as f32 / side as f32, (index / side) as f32 / height as f32)).collect()) }; + // A width and heights whose texels the working texels never meet at an edge let mut baked = BakedMaps { resolution: 48, ..Default::default() }; baked.maps.insert(BakedMap::AmbientOcclusion, ramp(48, 47, |u, v| 0.3 + 0.6 * u * v)); baked.maps.insert(BakedMap::Curvature, ramp(48, 23, |u, _| 0.2 + 0.6 * u)); baked.maps.insert(BakedMap::Thickness, ramp(48, 13, |_, v| 0.25 + 0.5 * v)); + // Steps of the GPU's 10-bit baked normal (1 / 1022), so both sides read the same normal let normals: Vec = (0..48 * 7).flat_map(|index| [(511 + 2 * (index % 48)) as f32 / 1022.0, 562.0 / 1022.0, 1.0]).collect(); baked.maps.insert(BakedMap::Normal, Arc::new(normals)); @@ -760,6 +764,7 @@ mod tests { #[test] fn whole_set_filters_keep_the_pre_pass_on_atlases_of_many_scales() { let Some(mut gpu) = headless() else { return }; + // Up to sixteen results of 256 K texels fit a 128 MiB storage binding const LARGE: u32 = 256; let normal = BlendMode::Normal; @@ -867,7 +872,7 @@ mod tests { let mut expected = vec![0; actual.len()]; for &(tx, ty) in &tiles { - let tile = tile_bytes(&cpu, &baked, DisplayKind::BaseColor, tx, ty); + let tile = tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, DisplayKind::BaseColor, tx, ty); for (y, row) in tile.as_chunks::<{ TILE as usize * 4 }>().0.iter().enumerate() { let start = ((ty * TILE + y as u32) * SIDE + tx * TILE) as usize * 4; expected[start..start + row.len()].copy_from_slice(row); diff --git a/crates/render/src/gpu_composite_udim_layout.rs b/crates/render/src/gpu_composite_udim_layout.rs index 4581f400..58c93204 100644 --- a/crates/render/src/gpu_composite_udim_layout.rs +++ b/crates/render/src/gpu_composite_udim_layout.rs @@ -2,58 +2,7 @@ use texturecraft_core::{TextureSet, TileGrid}; -/// A UV-tiled set's atlas: its grid of blocks, each block's tile scale and the distinct scales -/// the neighbourhood stages run at, as the CPU's `Inputs::tile_res_at` and `filter_region` read -/// them. The working atlas is the set's size, so a block is `TextureSet::block_resolution` texels. -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct UdimLayout { - pub(crate) grid: TileGrid, - /// Texels per side of an atlas block (the CPU's `tile_res` and `BlockScales` block) - pub(crate) block: u32, - /// The set's own resolution, the texture set size of `OutputResolution::output_size` - pub(crate) texture_set: u32, - /// The atlas's longest side, which caps filter radii as the CPU's `filter_extent` does - pub(crate) longest_side: u32, - /// A tile has a resolution of its own, so `TextureSet::from_atlas` undoes its scale - pub(crate) scaled: bool, - /// Each block's tile scale, row by row (`TextureSet::block_scales`) - pub(crate) scales: Vec, - /// The distinct block scales, largest first: level 0 is the base stage's scale - pub(crate) levels: Vec, -} +#[path = "gpu_composite_udim_layout/udim_layout.rs"] +mod udim_layout; -impl UdimLayout { - /// The layout of `set`, None for a classic set. - pub(crate) fn of(set: &TextureSet) -> Option { - let grid = set.tile_grid()?; - let scales: Vec = (0..grid.rows).flat_map(|by| (0..grid.cols).map(move |bx| (bx, by))).map(|(bx, by)| set.tile_scale(grid.udim(bx, by))).collect(); - let mut levels = scales.clone(); - levels.sort_by(|a, b| b.total_cmp(a)); - levels.dedup(); - let (width, height) = set.size(); - Some(Self { - grid, - block: set.block_resolution(), - texture_set: set.resolution, - longest_side: width.max(height), - scaled: !set.tile_resolutions.is_empty(), - scales, - levels, - }) - } - - /// Texels per side of a UV tile filling `scale` of its block (`Inputs::tile_res_at`). - pub(crate) fn tile_resolution(&self, scale: f32) -> u32 { - ((self.block as f32 * scale).round() as u32).max(1) - } - - /// The tile resolution of every level, the base stage's first. - pub(crate) fn level_resolutions(&self) -> Vec { - self.levels.iter().map(|&scale| self.tile_resolution(scale)).collect() - } - - /// The level of each block, row by row. - pub(crate) fn block_levels(&self) -> Vec { - self.scales.iter().map(|scale| self.levels.iter().position(|level| level == scale).unwrap_or(0) as u32).collect() - } -} +pub(crate) use udim_layout::UdimLayout; diff --git a/crates/render/src/gpu_composite_udim_layout/udim_layout.rs b/crates/render/src/gpu_composite_udim_layout/udim_layout.rs new file mode 100644 index 00000000..499b5a7e --- /dev/null +++ b/crates/render/src/gpu_composite_udim_layout/udim_layout.rs @@ -0,0 +1,57 @@ +use super::{TextureSet, TileGrid}; + +/// A UV-tiled set's atlas: its grid of blocks, each block's tile scale and the distinct scales +/// the neighbourhood stages run at, as the CPU's `Inputs::tile_res_at` and `filter_region` read +/// them. The working atlas is the set's size, so a block is `TextureSet::block_resolution` texels. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct UdimLayout { + pub(crate) grid: TileGrid, + /// Texels per side of an atlas block (the CPU's `tile_res` and `BlockScales` block) + pub(crate) block: u32, + /// The set's own resolution, the texture set size of `OutputResolution::output_size` + pub(crate) texture_set: u32, + /// The atlas's longest side, which caps filter radii as the CPU's `filter_extent` does + pub(crate) longest_side: u32, + /// A tile has a resolution of its own, so `TextureSet::from_atlas` undoes its scale + pub(crate) scaled: bool, + /// Each block's tile scale, row by row (`TextureSet::block_scales`) + pub(crate) scales: Vec, + /// The distinct block scales, largest first: level 0 is the base stage's scale + pub(crate) levels: Vec, +} + +impl UdimLayout { + /// The layout of `set`, None for a classic set. + pub(crate) fn of(set: &TextureSet) -> Option { + let grid = set.tile_grid()?; + let scales: Vec = (0..grid.rows).flat_map(|by| (0..grid.cols).map(move |bx| (bx, by))).map(|(bx, by)| set.tile_scale(grid.udim(bx, by))).collect(); + let mut levels = scales.clone(); + levels.sort_by(|a, b| b.total_cmp(a)); + levels.dedup(); + let (width, height) = set.size(); + Some(Self { + grid, + block: set.block_resolution(), + texture_set: set.resolution, + longest_side: width.max(height), + scaled: !set.tile_resolutions.is_empty(), + scales, + levels, + }) + } + + /// Texels per side of a UV tile filling `scale` of its block (`Inputs::tile_res_at`). + pub(crate) fn tile_resolution(&self, scale: f32) -> u32 { + ((self.block as f32 * scale).round() as u32).max(1) + } + + /// The tile resolution of every level, the base stage's first. + pub(crate) fn level_resolutions(&self) -> Vec { + self.levels.iter().map(|&scale| self.tile_resolution(scale)).collect() + } + + /// The level of each block, row by row. + pub(crate) fn block_levels(&self) -> Vec { + self.scales.iter().map(|scale| self.levels.iter().position(|level| level == scale).unwrap_or(0) as u32).collect() + } +} diff --git a/crates/render/src/gpu_curvature.rs b/crates/render/src/gpu_curvature.rs index fa7807eb..b6299979 100644 --- a/crates/render/src/gpu_curvature.rs +++ b/crates/render/src/gpu_curvature.rs @@ -14,243 +14,19 @@ const LINE_WORKGROUP: u32 = 64; const TILE_WORKGROUP: u32 = 8; const BOX_PASSES: usize = 3; -pub(crate) struct CurvatureInput<'a> { - /// Existing packed bake texture: the curvature scalar is f32 bits in its second word. - pub(crate) baked: &'a wgpu::TextureView, - pub(crate) bake_size: [u32; 2], - /// One bit per working UV texel, each row starting on a new word. None means fully covered. - pub(crate) coverage: Option<&'a wgpu::Buffer>, - pub(crate) working_size: [u32; 2], - pub(crate) needed: [bool; SIZES], - /// The bake texels of one UV tile block (`bake_size` for a classic set) - pub(crate) block: [u32; 2], - /// A UV tile atlas's working block side and each block's tile scale, row by row, when a tile - /// is smaller than its block (empty otherwise: the bake then covers what the working texels do) - pub(crate) scales: (u32, &'a [f32]), -} +mod curvature_gpu; +mod curvature_input; +mod curvature_levels; +mod layout; +mod level; +mod params; -#[derive(Clone, Debug)] -pub(crate) struct CurvatureLevels { - pub(crate) image: wgpu::TextureView, - pub(crate) layout: wgpu::Buffer, -} - -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Layout { - levels: [[u32; 4]; SIZES], - bake_size: [u32; 4], -} - -impl CurvatureLevels { - fn new(device: &wgpu::Device, extent: [u32; 2], data: &Layout) -> Self { - Self { - image: texture(device, "tc_curvature_levels", extent), - layout: device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_curvature_layout"), - contents: bytemuck::bytes_of(data), - usage: wgpu::BufferUsages::UNIFORM, - }), - } - } - - pub(crate) fn empty(device: &wgpu::Device) -> Self { - Self::new(device, [1, 1], &Layout::zeroed()) - } -} - -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Params { - dimensions: [u32; 4], - mode: [u32; 4], - level: [u32; 4], - /// The bake block's width and height, the working block's side and the block columns (0 - /// without tile scales) - block: [u32; 4], -} - -pub(crate) struct CurvatureGpu { - layout: wgpu::BindGroupLayout, - empty: wgpu::Buffer, - scan_rows: wgpu::ComputePipeline, - scan_columns: wgpu::ComputePipeline, - pad: wgpu::ComputePipeline, - blur: wgpu::ComputePipeline, - coarsen: wgpu::ComputePipeline, -} - -impl CurvatureGpu { - pub(crate) fn new(device: &wgpu::Device) -> Self { - let uint_image = - wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }; - let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("tc_curvature_inputs"), - entries: &[ - entry(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }), - entry(1, uint_image), - entry( - 2, - wgpu::BindingType::StorageTexture { - access: wgpu::StorageTextureAccess::WriteOnly, - format: wgpu::TextureFormat::R32Uint, - view_dimension: wgpu::TextureViewDimension::D2, - }, - ), - storage(3, true), - entry(4, uint_image), - storage(5, true), - ], - }); - let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("tc_curvature_pipeline"), - bind_group_layouts: &[Some(&layout)], - immediate_size: 0, - }); - let module = device.create_shader_module(wgpu::include_wgsl!("shaders/curvature_sizes.wgsl")); - let pipeline = |name| { - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(name), - layout: Some(&pipeline_layout), - module: &module, - entry_point: Some(name), - compilation_options: Default::default(), - cache: None, - }) - }; - let empty = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_curvature_empty"), - contents: &[0; 4], - usage: wgpu::BufferUsages::STORAGE, - }); - Self { - layout, - empty, - scan_rows: pipeline("scan_rows"), - scan_columns: pipeline("scan_columns"), - pad: pipeline("pad_curvature"), - blur: pipeline("blur_curvature"), - coarsen: pipeline("coarsen_curvature"), - } - } - - pub(crate) fn build(&self, device: &wgpu::Device, queue: &wgpu::Queue, input: CurvatureInput<'_>) -> Result { - let [width, height] = input.bake_size; - let [working_width, working_height] = input.working_size; - let dimensions = [width, height, working_width, working_height]; - let limits = device.limits(); - if !input.needed.contains(&true) { - return Ok(CurvatureLevels::empty(device)); - } - if dimensions.contains(&0) || width.max(height) > limits.max_texture_dimension_2d { - return Err("Curvature bake dimensions do not fit the GPU.".into()); - } - let coverage_bytes = u64::from(working_width.div_ceil(32)) * u64::from(working_height) * 4; - if input.coverage.is_some_and(|coverage| coverage.size() < coverage_bytes) { - return Err("The curvature UV coverage does not match its working size.".into()); - } - let block = [input.block[0].clamp(1, width), input.block[1].clamp(1, height)]; - let columns = if input.scales.1.is_empty() { 0 } else { width.div_ceil(block[0]) }; - let block_words = [block[0], block[1], input.scales.0, columns]; - let (extent, layout, levels) = plan_atlas(input.bake_size, block, input.needed, limits.max_texture_dimension_2d) - .ok_or("Curvature detail sizes do not fit the GPU texture dimensions.")?; - crate::gpu_trace::scoped(device, "GPU curvature detail", || { - let result = CurvatureLevels::new(device, extent, &layout); - let first = texture(device, "tc_curvature_first", input.bake_size); - let second = texture(device, "tc_curvature_second", input.bake_size); - let third = input.coverage.map(|_| texture(device, "tc_curvature_padded_scratch", input.bake_size)); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_curvature") }); - let mut run = |pipeline: &wgpu::ComputePipeline, - (source, target): (&wgpu::TextureView, &wgpu::TextureView), - weights: &wgpu::Buffer, - mode: [u32; 4], - level: [u32; 4], - groups: [u32; 2]| { - let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_curvature_params"), - contents: bytemuck::bytes_of(&Params { dimensions, mode, level, block: block_words }), - usage: wgpu::BufferUsages::UNIFORM, - }); - let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_curvature_stage"), - layout: &self.layout, - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(source) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(target) }, - wgpu::BindGroupEntry { binding: 3, resource: input.coverage.unwrap_or(&self.empty).as_entire_binding() }, - wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(input.baked) }, - wgpu::BindGroupEntry { binding: 5, resource: weights.as_entire_binding() }, - ], - }); - let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(pipeline); - pass.set_bind_group(0, &bindings, &[]); - pass.dispatch_workgroups(groups[0], groups[1], 1); - }; - // The coverage scan reads each block's tile scale where the edge weights go later - let scales = (!input.scales.1.is_empty()).then(|| { - device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_curvature_block_scales"), - contents: bytemuck::cast_slice(input.scales.1), - usage: wgpu::BufferUsages::STORAGE, - }) - }); - let scales = scales.as_ref().unwrap_or(&self.empty); - let (original, ping_pong, encoding) = if let Some(third) = &third { - run(&self.scan_rows, (input.baked, &first), scales, [0; 4], [0; 4], [height.div_ceil(LINE_WORKGROUP), 1]); - run(&self.scan_columns, (&first, &second), &self.empty, [0; 4], [0; 4], [width.div_ceil(LINE_WORKGROUP), 1]); - run(&self.pad, (&second, &first), &self.empty, [0; 4], [0; 4], [width.div_ceil(TILE_WORKGROUP), height.div_ceil(TILE_WORKGROUP)]); - (&first, [&second, third], 1) - } else { - (input.baked, [&first, &second], 2) - }; - for level in levels { - let mut source = original; - for pass in 0..BOX_PASSES * 2 { - let vertical = pass >= BOX_PASSES; - let line_count = if vertical { width } else { height }; - let destination = ping_pong[pass % 2]; - run( - &self.blur, - (source, destination), - &self.empty, - [level.radius, 0, u32::from(vertical), if pass == 0 { encoding } else { 0 }], - [0; 4], - [line_count.div_ceil(LINE_WORKGROUP), 1], - ); - source = destination; - } - // Each block is blurred alone, so its edges lose support at its own sides - let block_weights = - |length: u32, side: u32| (0..length).step_by(side as usize).flat_map(move |start| inside_weights(side.min(length - start), level.radius)); - let weights: Vec<_> = block_weights(width, block[0]).chain(block_weights(height, block[1])).collect(); - let weights = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_curvature_edge_weights"), - contents: bytemuck::cast_slice(&weights), - usage: wgpu::BufferUsages::STORAGE, - }); - run( - &self.coarsen, - (source, &result.image), - &weights, - [0, level.step, 0, 0], - level.rect, - [level.rect[2].div_ceil(TILE_WORKGROUP), level.rect[3].div_ceil(TILE_WORKGROUP)], - ); - } - queue.submit([encoder.finish()]); - result - }) - } -} - -#[derive(Clone, Copy)] -struct Level { - radius: u32, - step: u32, - rect: [u32; 4], -} +pub(crate) use curvature_gpu::CurvatureGpu; +pub(crate) use curvature_input::CurvatureInput; +pub(crate) use curvature_levels::CurvatureLevels; +use layout::Layout; +use level::Level; +use params::Params; /// The levels' places in one atlas: each size's radius (texels at 2K, scaled to the block's /// width) and coarsening step (dividing the block, so no cell spans two UV tiles). @@ -265,6 +41,7 @@ fn plan_atlas(size: [u32; 2], block: [u32; 2], needed: [bool; SIZES], limit: u32 if initial_width > limit { return None; } + std::iter::successors(Some(initial_width), |&width| (width < limit).then_some(width.saturating_mul(2).min(limit))) .filter_map(|width| pack_levels((size, block), &radii, width, limit)) .min_by_key(|(extent, ..)| u64::from(extent[0]) * u64::from(extent[1])) @@ -281,6 +58,7 @@ fn pack_levels((size, block): ([u32; 2], [u32; 2]), radii: &[Option], row_w *slot = [previous.rect[0], previous.rect[1], previous.step, 0]; continue; } + let step = level_step(block, radius); let [width, height] = size.map(|edge| edge.div_ceil(step)); if x + width > row_width { @@ -291,6 +69,7 @@ fn pack_levels((size, block): ([u32; 2], [u32; 2]), radii: &[Option], row_w if y + height > limit { return None; } + *slot = [x, y, step, 0]; levels.push(Level { radius, step, rect: [x, y, width, height] }); x += width; @@ -308,8 +87,7 @@ fn level_step(block: [u32; 2], radius: u32) -> u32 { step } -// The box filter reads zero beyond the bake. These dimension-only parameters -// normalize its loss of support at the border without a second blurred image. +// Normalize the border support lost to zero padding without a second blurred image fn inside_weights(length: u32, radius: u32) -> impl Iterator { let length = length as usize; let radius = radius as usize; diff --git a/crates/render/src/gpu_curvature/curvature_gpu.rs b/crates/render/src/gpu_curvature/curvature_gpu.rs new file mode 100644 index 00000000..8174b2f9 --- /dev/null +++ b/crates/render/src/gpu_curvature/curvature_gpu.rs @@ -0,0 +1,183 @@ +use super::{ + BOX_PASSES, CurvatureInput, CurvatureLevels, DeviceExt, LINE_WORKGROUP, Params, TILE_WORKGROUP, entry, inside_weights, plan_atlas, storage, texture, +}; + +pub(crate) struct CurvatureGpu { + pub(super) layout: wgpu::BindGroupLayout, + pub(super) empty: wgpu::Buffer, + pub(super) scan_rows: wgpu::ComputePipeline, + pub(super) scan_columns: wgpu::ComputePipeline, + pub(super) pad: wgpu::ComputePipeline, + pub(super) blur: wgpu::ComputePipeline, + pub(super) coarsen: wgpu::ComputePipeline, +} + +impl CurvatureGpu { + pub(crate) fn new(device: &wgpu::Device) -> Self { + let uint_image = + wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Uint, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tc_curvature_inputs"), + entries: &[ + entry(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }), + entry(1, uint_image), + entry( + 2, + wgpu::BindingType::StorageTexture { + access: wgpu::StorageTextureAccess::WriteOnly, + format: wgpu::TextureFormat::R32Uint, + view_dimension: wgpu::TextureViewDimension::D2, + }, + ), + storage(3, true), + entry(4, uint_image), + storage(5, true), + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_curvature_pipeline"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::include_wgsl!("../shaders/curvature_sizes.wgsl")); + let pipeline = |name| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(name), + layout: Some(&pipeline_layout), + module: &module, + entry_point: Some(name), + compilation_options: Default::default(), + cache: None, + }) + }; + let empty = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_curvature_empty"), + contents: &[0; 4], + usage: wgpu::BufferUsages::STORAGE, + }); + Self { + layout, + empty, + scan_rows: pipeline("scan_rows"), + scan_columns: pipeline("scan_columns"), + pad: pipeline("pad_curvature"), + blur: pipeline("blur_curvature"), + coarsen: pipeline("coarsen_curvature"), + } + } + + pub(crate) fn build(&self, device: &wgpu::Device, queue: &wgpu::Queue, input: CurvatureInput<'_>) -> Result { + let [width, height] = input.bake_size; + let [working_width, working_height] = input.working_size; + let dimensions = [width, height, working_width, working_height]; + let limits = device.limits(); + if !input.needed.contains(&true) { + return Ok(CurvatureLevels::empty(device)); + } + + if dimensions.contains(&0) || width.max(height) > limits.max_texture_dimension_2d { + return Err("Curvature bake dimensions do not fit the GPU.".into()); + } + + let coverage_bytes = u64::from(working_width.div_ceil(32)) * u64::from(working_height) * 4; + if input.coverage.is_some_and(|coverage| coverage.size() < coverage_bytes) { + return Err("The curvature UV coverage does not match its working size.".into()); + } + + let block = [input.block[0].clamp(1, width), input.block[1].clamp(1, height)]; + let columns = if input.scales.1.is_empty() { 0 } else { width.div_ceil(block[0]) }; + let block_words = [block[0], block[1], input.scales.0, columns]; + let (extent, layout, levels) = plan_atlas(input.bake_size, block, input.needed, limits.max_texture_dimension_2d) + .ok_or("Curvature detail sizes do not fit the GPU texture dimensions.")?; + crate::gpu_trace::scoped(device, "GPU curvature detail", || { + let result = CurvatureLevels::new(device, extent, &layout); + let first = texture(device, "tc_curvature_first", input.bake_size); + let second = texture(device, "tc_curvature_second", input.bake_size); + let third = input.coverage.map(|_| texture(device, "tc_curvature_padded_scratch", input.bake_size)); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_curvature") }); + let mut run = |pipeline: &wgpu::ComputePipeline, + (source, target): (&wgpu::TextureView, &wgpu::TextureView), + weights: &wgpu::Buffer, + mode: [u32; 4], + level: [u32; 4], + groups: [u32; 2]| { + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_curvature_params"), + contents: bytemuck::bytes_of(&Params { dimensions, mode, level, block: block_words }), + usage: wgpu::BufferUsages::UNIFORM, + }); + let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_curvature_stage"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(source) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(target) }, + wgpu::BindGroupEntry { binding: 3, resource: input.coverage.unwrap_or(&self.empty).as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(input.baked) }, + wgpu::BindGroupEntry { binding: 5, resource: weights.as_entire_binding() }, + ], + }); + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bindings, &[]); + pass.dispatch_workgroups(groups[0], groups[1], 1); + }; + + // The coverage scan reads each block's tile scale where the edge weights go later + let scales = (!input.scales.1.is_empty()).then(|| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_curvature_block_scales"), + contents: bytemuck::cast_slice(input.scales.1), + usage: wgpu::BufferUsages::STORAGE, + }) + }); + let scales = scales.as_ref().unwrap_or(&self.empty); + let (original, ping_pong, encoding) = if let Some(third) = &third { + run(&self.scan_rows, (input.baked, &first), scales, [0; 4], [0; 4], [height.div_ceil(LINE_WORKGROUP), 1]); + run(&self.scan_columns, (&first, &second), &self.empty, [0; 4], [0; 4], [width.div_ceil(LINE_WORKGROUP), 1]); + run(&self.pad, (&second, &first), &self.empty, [0; 4], [0; 4], [width.div_ceil(TILE_WORKGROUP), height.div_ceil(TILE_WORKGROUP)]); + (&first, [&second, third], 1) + } else { + (input.baked, [&first, &second], 2) + }; + for level in levels { + let mut source = original; + for pass in 0..BOX_PASSES * 2 { + let vertical = pass >= BOX_PASSES; + let line_count = if vertical { width } else { height }; + let destination = ping_pong[pass % 2]; + run( + &self.blur, + (source, destination), + &self.empty, + [level.radius, 0, u32::from(vertical), if pass == 0 { encoding } else { 0 }], + [0; 4], + [line_count.div_ceil(LINE_WORKGROUP), 1], + ); + source = destination; + } + + // Each block is blurred alone, so its edges lose support at its own sides + let block_weights = + |length: u32, side: u32| (0..length).step_by(side as usize).flat_map(move |start| inside_weights(side.min(length - start), level.radius)); + let weights: Vec<_> = block_weights(width, block[0]).chain(block_weights(height, block[1])).collect(); + let weights = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_curvature_edge_weights"), + contents: bytemuck::cast_slice(&weights), + usage: wgpu::BufferUsages::STORAGE, + }); + run( + &self.coarsen, + (source, &result.image), + &weights, + [0, level.step, 0, 0], + level.rect, + [level.rect[2].div_ceil(TILE_WORKGROUP), level.rect[3].div_ceil(TILE_WORKGROUP)], + ); + } + queue.submit([encoder.finish()]); + result + }) + } +} diff --git a/crates/render/src/gpu_curvature/curvature_input.rs b/crates/render/src/gpu_curvature/curvature_input.rs new file mode 100644 index 00000000..11469449 --- /dev/null +++ b/crates/render/src/gpu_curvature/curvature_input.rs @@ -0,0 +1,16 @@ +use super::SIZES; + +pub(crate) struct CurvatureInput<'a> { + /// Existing packed bake texture: the curvature scalar is f32 bits in its second word. + pub(crate) baked: &'a wgpu::TextureView, + pub(crate) bake_size: [u32; 2], + /// One bit per working UV texel, each row starting on a new word. None means fully covered. + pub(crate) coverage: Option<&'a wgpu::Buffer>, + pub(crate) working_size: [u32; 2], + pub(crate) needed: [bool; SIZES], + /// The bake texels of one UV tile block (`bake_size` for a classic set) + pub(crate) block: [u32; 2], + /// A UV tile atlas's working block side and each block's tile scale, row by row, when a tile + /// is smaller than its block (empty otherwise: the bake then covers what the working texels do) + pub(crate) scales: (u32, &'a [f32]), +} diff --git a/crates/render/src/gpu_curvature/curvature_levels.rs b/crates/render/src/gpu_curvature/curvature_levels.rs new file mode 100644 index 00000000..2ac2040f --- /dev/null +++ b/crates/render/src/gpu_curvature/curvature_levels.rs @@ -0,0 +1,24 @@ +use super::{DeviceExt, Layout, Zeroable, texture}; + +#[derive(Clone, Debug)] +pub(crate) struct CurvatureLevels { + pub(crate) image: wgpu::TextureView, + pub(crate) layout: wgpu::Buffer, +} + +impl CurvatureLevels { + pub(super) fn new(device: &wgpu::Device, extent: [u32; 2], data: &Layout) -> Self { + Self { + image: texture(device, "tc_curvature_levels", extent), + layout: device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_curvature_layout"), + contents: bytemuck::bytes_of(data), + usage: wgpu::BufferUsages::UNIFORM, + }), + } + } + + pub(crate) fn empty(device: &wgpu::Device) -> Self { + Self::new(device, [1, 1], &Layout::zeroed()) + } +} diff --git a/crates/render/src/gpu_curvature/layout.rs b/crates/render/src/gpu_curvature/layout.rs new file mode 100644 index 00000000..f4628858 --- /dev/null +++ b/crates/render/src/gpu_curvature/layout.rs @@ -0,0 +1,8 @@ +use super::{Pod, SIZES, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Layout { + pub(super) levels: [[u32; 4]; SIZES], + pub(super) bake_size: [u32; 4], +} diff --git a/crates/render/src/gpu_curvature/level.rs b/crates/render/src/gpu_curvature/level.rs new file mode 100644 index 00000000..032b1f0e --- /dev/null +++ b/crates/render/src/gpu_curvature/level.rs @@ -0,0 +1,6 @@ +#[derive(Clone, Copy)] +pub(super) struct Level { + pub(super) radius: u32, + pub(super) step: u32, + pub(super) rect: [u32; 4], +} diff --git a/crates/render/src/gpu_curvature/params.rs b/crates/render/src/gpu_curvature/params.rs new file mode 100644 index 00000000..c899c8d5 --- /dev/null +++ b/crates/render/src/gpu_curvature/params.rs @@ -0,0 +1,12 @@ +use super::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Params { + pub(super) dimensions: [u32; 4], + pub(super) mode: [u32; 4], + pub(super) level: [u32; 4], + /// The bake block's width and height, the working block's side and the block columns (0 + /// without tile scales) + pub(super) block: [u32; 4], +} diff --git a/crates/render/src/gpu_depth_grid.rs b/crates/render/src/gpu_depth_grid.rs index 500c35d8..f810d096 100644 --- a/crates/render/src/gpu_depth_grid.rs +++ b/crates/render/src/gpu_depth_grid.rs @@ -31,55 +31,10 @@ type CachedViews = Vec<(ViewKey, Option)>; /// The last mesh's grids, so a recompiled program keeps its atlas planes static CACHE: Mutex<(Weak, CachedViews)> = Mutex::new((Weak::new(), Vec::new())); -/// One projector depth grid as the shader reads it: its plane (per cell, row by row from the -/// lower corner: the nearest surface's nearness and its slope across and up) and the numbers -/// `ProjectorDepth::cover` reads it with. -#[derive(Clone, Debug)] -pub(crate) struct DepthGrid { - pub(crate) plane: RawPlane, - origin: Vec2, - cell: Vec2, - side: u32, - unit: f32, - bias: f32, - max_slope_bias: f32, - fade: f32, -} +#[path = "gpu_depth_grid/depth_grid.rs"] +mod grid; -impl DepthGrid { - fn of(depth: &ProjectorDepth) -> Self { - let grid = depth.grid(); - let side = grid.grid_side as u32; - let texels: Vec = grid.front.iter().flatten().copied().collect(); - Self { - plane: RawPlane { size: [side * 3, side], texels: Arc::new(texels) }, - origin: grid.origin, - cell: grid.cell, - side, - unit: grid.nearness_unit, - bias: grid.bias, - max_slope_bias: grid.max_slope_bias, - fade: grid.fade, - } - } - - /// The grid's directory entry with its plane at atlas descriptor `plane` - /// (composite_projection.wgsl `p1_depth_cover`). - pub(crate) fn entry(&self, plane: u32) -> [u32; ENTRY_WORDS] { - [ - plane, - self.origin.x.to_bits(), - self.origin.y.to_bits(), - self.cell.x.to_bits(), - self.cell.y.to_bits(), - self.side, - self.unit.to_bits(), - self.bias.to_bits(), - self.max_slope_bias.to_bits(), - self.fade.to_bits(), - ] - } -} +pub(crate) use grid::DepthGrid; /// The directory entry of a copy without a grid: it culls nothing. pub(crate) fn missing_entry() -> [u32; ENTRY_WORDS] { @@ -139,6 +94,7 @@ fn build(mesh: &Mesh, (view, copies): ViewKey) -> Option { let Some((symmetry, center, radius)) = copies else { return ProjectorDepth::build(view, mesh).map(|depth| Arc::from([Some(DepthGrid::of(&depth))])); }; + let maps = ProjectorDepth::build_copies(view, mesh, &symmetry, center, radius); maps.iter().any(Option::is_some).then(|| maps.iter().map(|map| map.as_ref().map(DepthGrid::of)).collect()) } diff --git a/crates/render/src/gpu_depth_grid/depth_grid.rs b/crates/render/src/gpu_depth_grid/depth_grid.rs new file mode 100644 index 00000000..3519b4bb --- /dev/null +++ b/crates/render/src/gpu_depth_grid/depth_grid.rs @@ -0,0 +1,51 @@ +use super::{Arc, ENTRY_WORDS, ProjectorDepth, RawPlane, Vec2}; + +/// One projector depth grid as the shader reads it: its plane (per cell, row by row from the +/// lower corner: the nearest surface's nearness and its slope across and up) and the numbers +/// `ProjectorDepth::cover` reads it with. +#[derive(Clone, Debug)] +pub(crate) struct DepthGrid { + pub(crate) plane: RawPlane, + pub(super) origin: Vec2, + pub(super) cell: Vec2, + pub(super) side: u32, + pub(super) unit: f32, + pub(super) bias: f32, + pub(super) max_slope_bias: f32, + pub(super) fade: f32, +} + +impl DepthGrid { + pub(super) fn of(depth: &ProjectorDepth) -> Self { + let grid = depth.grid(); + let side = grid.grid_side as u32; + let texels: Vec = grid.front.iter().flatten().copied().collect(); + Self { + plane: RawPlane { size: [side * 3, side], texels: Arc::new(texels) }, + origin: grid.origin, + cell: grid.cell, + side, + unit: grid.nearness_unit, + bias: grid.bias, + max_slope_bias: grid.max_slope_bias, + fade: grid.fade, + } + } + + /// The grid's directory entry with its plane at atlas descriptor `plane` + /// (composite_projection.wgsl `p1_depth_cover`). + pub(crate) fn entry(&self, plane: u32) -> [u32; ENTRY_WORDS] { + [ + plane, + self.origin.x.to_bits(), + self.origin.y.to_bits(), + self.cell.x.to_bits(), + self.cell.y.to_bits(), + self.side, + self.unit.to_bits(), + self.bias.to_bits(), + self.max_slope_bias.to_bits(), + self.fade.to_bits(), + ] + } +} diff --git a/crates/render/src/gpu_image_source.rs b/crates/render/src/gpu_image_source.rs index 85e6aabb..3e9470ac 100644 --- a/crates/render/src/gpu_image_source.rs +++ b/crates/render/src/gpu_image_source.rs @@ -18,218 +18,13 @@ use depth_grid::{FillGrids, depth_grids, missing_entry}; pub(crate) const IMAGE_SOURCE_OPCODE: u32 = 14; pub(crate) const DECAL_PROJECTION: u32 = 9; -/// What a registered image is read for. The GPU port packages register images only through -/// [`MaterialImages::register_image`]; P1 owns this type and adds kinds (mip-mapped, nearest, …) -/// as variants here, keeping that signature. P3 (Color Selection ID maps, effect image inputs) -/// and P7 (the mask image a stroke paints) read plain texels with `Material`. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ImageUse { - /// The image's texels alone (Bilinear Sharp and Nearest reads). - Material, - /// The image and its halved levels as stored: Bilinear HQ of a scalar, normal or alpha read. - Mipmapped, - /// The image and its halved levels for a colour read: an sRGB image's levels are linear. - MipmappedColor, - /// The image and either chain of its halved levels: an alpha read, whose levels agree in both. - MipmappedAlpha, -} +mod decal_source; +mod image_use; +mod material_images; -#[derive(Debug, Default)] -pub(crate) struct MaterialImages { - /// Each registered image with what it is read for - names: Vec<(String, ImageUse)>, - images: Vec>>, - /// The atlas's colour images, each image and chain once (`set_images`), and each registered - /// image's entry among them - atlas: Vec<(Arc, AtlasMips)>, - entries: Vec>, - decals: Vec, - /// The composited mesh's centre and radius (`set_surface`): P1's band uniform turns positions - /// in mesh radii back into world positions with them - mesh_frame: Option<(Vec3, f32)>, - /// Depth-culled fills: projection, symmetry, and the side-table word their depth directory's - /// offset goes in - depths: Vec<(Projection, Option, u32)>, - /// Each depth-culled fill's grids over the mesh (`set_surface`), with each copy's raw plane - depth_grids: Vec>)>>, - raw_planes: Vec, -} - -#[derive(Debug, PartialEq)] -struct DecalSource { - frame: Decal, - alpha_images: Vec, -} - -impl MaterialImages { - pub(crate) fn register_image(&mut self, name: &str, usage: ImageUse) -> u32 { - if let Some(index) = self.names.iter().position(|(existing, existing_usage)| existing == name && *existing_usage == usage) { - return index as u32; - } - - let index = self.names.len() as u32; - self.names.push((name.to_owned(), usage)); - index - } - - /// A frame and the images whose alpha it reads, sampled with the fill's `sampling`: Bilinear - /// HQ reads the alpha's halved levels. - pub(crate) fn register_decal<'a>(&mut self, frame: Decal, sources: impl Iterator, sampling: Sampling) -> u32 { - let usage = if sampling.filtering == Filtering::BilinearHq { ImageUse::MipmappedAlpha } else { ImageUse::Material }; - let alpha_images = sources - .filter_map(|source| match source { - Source::Image { name, .. } => Some(self.register_image(name, usage)), - _ => None, - }) - .collect(); - let decal = DecalSource { frame, alpha_images }; - if let Some(index) = self.decals.iter().position(|existing| *existing == decal) { - return index as u32; - } - - let index = self.decals.len() as u32; - self.decals.push(decal); - index - } - - /// A depth-culled fill with `sampling`: its grids are built over the mesh in - /// [`Self::set_surface`], and side-table word `directory_word` gets its depth directory's - /// offset when the program uploads. - pub(crate) fn register_depth(&mut self, projection: &Projection, sampling: Sampling, directory_word: u32) { - self.depths.push((projection.clone(), sampling.symmetry.on.then_some(sampling.symmetry), directory_word)); - } - - pub(crate) fn is_empty(&self) -> bool { - self.names.is_empty() && self.decals.is_empty() && self.depths.is_empty() - } - - /// Resolve the registered images and lay out the atlas's colour images: each image once per - /// chain of halved levels its reads need (`ImageRes::mip_chain`, or `linear_mip_chain` for an - /// sRGB colour read). An alpha read takes any chain the image already has, and a read of the - /// image's own texels any entry at all. - pub(crate) fn set_images(&mut self, images: &ImageStore) { - self.images = self.names.iter().map(|(name, _)| images.get(name).cloned()).collect(); - self.atlas.clear(); - self.entries = vec![None; self.names.len()]; - - // The chains first, then the reads an existing entry may serve - for pass in 0..3 { - for (slot, ((_, usage), image)) in self.names.iter().zip(&self.images).enumerate() { - let Some(image) = image else { continue }; - let mips = match (pass, usage) { - (0, ImageUse::Mipmapped) => AtlasMips::Stored, - (0, ImageUse::MipmappedColor) => AtlasMips::LinearColor, - (1, ImageUse::MipmappedAlpha) => AtlasMips::Stored, - (2, ImageUse::Material) => AtlasMips::None, - _ => continue, - }; - - // An sRGB colour read needs the linear chain, which a stored image does not differ from - let mips = if mips == AtlasMips::LinearColor && !image.srgb { AtlasMips::Stored } else { mips }; - let serves = |entry: &(Arc, AtlasMips)| { - Arc::ptr_eq(&entry.0, image) - && match usage { - ImageUse::Material => true, - ImageUse::MipmappedAlpha => entry.1 != AtlasMips::None, - ImageUse::Mipmapped | ImageUse::MipmappedColor => entry.1 == mips, - } - }; - let entry = self.atlas.iter().position(serves).unwrap_or_else(|| { - self.atlas.push((image.clone(), mips)); - self.atlas.len() - 1 - }); - self.entries[slot] = Some(entry); - } - } - } - - /// The colour images for the atlas with the halved levels each holds (see [`Self::set_images`]). - pub(crate) fn atlas_images(&self) -> impl Iterator, AtlasMips)> { - self.atlas.iter().map(|(image, mips)| (image, *mips)) - } - - /// Exact-f32 planes for the atlas: the projector depth grids built in [`Self::set_surface`]. - pub(crate) fn raw_planes(&self) -> &[RawPlane] { - &self.raw_planes - } - - /// The mesh the program composites: its frame, and the depth grids of the depth-culled - /// fills, one raw plane per distinct grid. Called by `CompositeProgram::set_surface_inputs` - /// before the atlas reads [`Self::raw_planes`]. - pub(crate) fn set_surface(&mut self, mesh: &Arc) { - self.mesh_frame = Some(mesh_frame(mesh.bounds())); - let requests: Vec<_> = self.depths.iter().map(|(projection, symmetry, _)| (projection.clone(), *symmetry)).collect(); - let mut planes: Vec = Vec::new(); - let grids = depth_grids(mesh, &requests) - .into_iter() - .map(|grids| { - let grids = grids?; - let indices = grids - .iter() - .map(|grid| { - let grid = grid.as_ref()?; - let index = planes.iter().position(|plane| Arc::ptr_eq(&plane.texels, &grid.plane.texels)).unwrap_or_else(|| { - planes.push(grid.plane.clone()); - planes.len() - 1 - }); - Some(index) - }) - .collect(); - Some((grids, indices)) - }) - .collect(); - self.depth_grids = grids; - self.raw_planes = planes; - } - - /// The composited mesh's centre and radius, once [`Self::set_surface`] has run. - pub(crate) fn mesh_frame(&self) -> Option<(Vec3, f32)> { - self.mesh_frame - } - - pub(crate) fn append_words(&self, words: &mut Vec, atlas: Option<&TileImageAtlas>, mesh: Option<&Mesh>) -> (Vec, Vec) { - let entry_offsets: Vec = - atlas.map_or_else(Vec::new, |atlas| self.atlas.iter().enumerate().map(|(index, (image, _))| atlas.append_rgba(words, index, image.srgb)).collect()); - let image_offsets: Vec<_> = (0..self.names.len()) - .map(|slot| self.entries.get(slot).copied().flatten().and_then(|entry| entry_offsets.get(entry).copied()).unwrap_or(u32::MAX)) - .collect(); - let normalization = mesh.map(|mesh| { - let (lo, hi) = mesh.bounds(); - ((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(1e-4)) - }); - let decal_offsets = self - .decals - .iter() - .map(|decal| { - let offset = words.len() as u32; - let alpha = decal.alpha_images.iter().map(|&slot| image_offsets[slot as usize]).find(|&offset| offset != u32::MAX).unwrap_or(u32::MAX); - words.extend(normalization.map_or_else(|| unplaced_decal_words(alpha), |(center, radius)| decal_words(&decal.frame, alpha, center, radius))); - offset - }) - .collect(); - self.append_depth_directories(words, atlas); - (image_offsets, decal_offsets) - } - - /// Each depth-culled fill's directory (its copy count, then one entry per copy) after the - /// grids' plane descriptors, its offset written into the fill's side-table word. - fn append_depth_directories(&self, words: &mut Vec, atlas: Option<&TileImageAtlas>) { - let plane_offsets: Vec = atlas.map_or_else(Vec::new, |atlas| (0..self.raw_planes.len()).map(|index| atlas.append_raw(words, index)).collect()); - for ((_, _, directory_word), grids) in self.depths.iter().zip(&self.depth_grids) { - let Some((grids, indices)) = grids else { continue }; - - let directory = words.len() as u32; - words.push(grids.len() as u32); - for (grid, index) in grids.iter().zip(indices) { - let plane = index.and_then(|index| plane_offsets.get(index).copied()); - words.extend(grid.as_ref().zip(plane).map_or_else(missing_entry, |(grid, plane)| grid.entry(plane))); - } - if let Some(word) = words.get_mut(*directory_word as usize) { - *word = directory; - } - } - } -} +use decal_source::DecalSource; +pub(crate) use image_use::ImageUse; +pub(crate) use material_images::MaterialImages; /// The word of a decal's alpha image (`composite_projection.wgsl` reads it for P1's frames) const DECAL_ALPHA_WORD: usize = 11; @@ -246,7 +41,8 @@ fn decal_words(decal: &Decal, alpha: u32, center: Vec3, radius: f32) -> [u32; 16 let Some((origin, right, up, normal)) = decal_axes(decal) else { return unplaced_decal_words(alpha); }; - // The UV surface buffer already stores positions relative to this center and radius. + + // The UV surface buffer already stores positions relative to this center and radius let origin = (origin - center) / radius; let right = right * (radius / decal.size[0].max(1e-6)); let up = up * (radius / decal.size[1].max(1e-6)); diff --git a/crates/render/src/gpu_image_source/decal_source.rs b/crates/render/src/gpu_image_source/decal_source.rs new file mode 100644 index 00000000..cd8e7ca7 --- /dev/null +++ b/crates/render/src/gpu_image_source/decal_source.rs @@ -0,0 +1,7 @@ +use super::Decal; + +#[derive(Debug, PartialEq)] +pub(super) struct DecalSource { + pub(super) frame: Decal, + pub(super) alpha_images: Vec, +} diff --git a/crates/render/src/gpu_image_source/image_use.rs b/crates/render/src/gpu_image_source/image_use.rs new file mode 100644 index 00000000..c331fc38 --- /dev/null +++ b/crates/render/src/gpu_image_source/image_use.rs @@ -0,0 +1,15 @@ +/// What a registered image is read for. The GPU port packages register images only through +/// [`super::MaterialImages::register_image`]; P1 owns this type and adds kinds (mip-mapped, nearest, …) +/// as variants here, keeping that signature. P3 (Color Selection ID maps, effect image inputs) +/// and P7 (the mask image a stroke paints) read plain texels with `Material`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ImageUse { + /// The image's texels alone (Bilinear Sharp and Nearest reads). + Material, + /// The image and its halved levels as stored: Bilinear HQ of a scalar, normal or alpha read. + Mipmapped, + /// The image and its halved levels for a colour read: an sRGB image's levels are linear. + MipmappedColor, + /// The image and either chain of its halved levels: an alpha read, whose levels agree in both. + MipmappedAlpha, +} diff --git a/crates/render/src/gpu_image_source/material_images.rs b/crates/render/src/gpu_image_source/material_images.rs new file mode 100644 index 00000000..5c60556c --- /dev/null +++ b/crates/render/src/gpu_image_source/material_images.rs @@ -0,0 +1,195 @@ +use super::{ + Arc, AtlasMips, Decal, DecalSource, FillGrids, FillSymmetry, Filtering, ImageRes, ImageStore, ImageUse, Mesh, Projection, RawPlane, Sampling, Source, + TileImageAtlas, Vec3, decal_words, depth_grids, mesh_frame, missing_entry, unplaced_decal_words, +}; + +#[derive(Debug, Default)] +pub(crate) struct MaterialImages { + /// Each registered image with what it is read for + pub(super) names: Vec<(String, ImageUse)>, + pub(super) images: Vec>>, + /// The atlas's colour images, each image and chain once (`set_images`), and each registered + /// image's entry among them + pub(super) atlas: Vec<(Arc, AtlasMips)>, + pub(super) entries: Vec>, + pub(super) decals: Vec, + /// The composited mesh's centre and radius (`set_surface`): P1's band uniform turns positions + /// in mesh radii back into world positions with them + pub(super) mesh_frame: Option<(Vec3, f32)>, + /// Depth-culled fills: projection, symmetry, and the side-table word their depth directory's + /// offset goes in + pub(super) depths: Vec<(Projection, Option, u32)>, + /// Each depth-culled fill's grids over the mesh (`set_surface`), with each copy's raw plane + pub(super) depth_grids: Vec>)>>, + pub(super) raw_planes: Vec, +} + +impl MaterialImages { + pub(crate) fn register_image(&mut self, name: &str, usage: ImageUse) -> u32 { + if let Some(index) = self.names.iter().position(|(existing, existing_usage)| existing == name && *existing_usage == usage) { + return index as u32; + } + + let index = self.names.len() as u32; + self.names.push((name.to_owned(), usage)); + index + } + + /// A frame and the images whose alpha it reads, sampled with the fill's `sampling`: Bilinear + /// HQ reads the alpha's halved levels. + pub(crate) fn register_decal<'a>(&mut self, frame: Decal, sources: impl Iterator, sampling: Sampling) -> u32 { + let usage = if sampling.filtering == Filtering::BilinearHq { ImageUse::MipmappedAlpha } else { ImageUse::Material }; + let alpha_images = sources + .filter_map(|source| match source { + Source::Image { name, .. } => Some(self.register_image(name, usage)), + _ => None, + }) + .collect(); + let decal = DecalSource { frame, alpha_images }; + if let Some(index) = self.decals.iter().position(|existing| *existing == decal) { + return index as u32; + } + + let index = self.decals.len() as u32; + self.decals.push(decal); + index + } + + /// A depth-culled fill with `sampling`: its grids are built over the mesh in + /// [`Self::set_surface`], and side-table word `directory_word` gets its depth directory's + /// offset when the program uploads. + pub(crate) fn register_depth(&mut self, projection: &Projection, sampling: Sampling, directory_word: u32) { + self.depths.push((projection.clone(), sampling.symmetry.on.then_some(sampling.symmetry), directory_word)); + } + + pub(crate) fn is_empty(&self) -> bool { + self.names.is_empty() && self.decals.is_empty() && self.depths.is_empty() + } + + /// Resolve the registered images and lay out the atlas's colour images: each image once per + /// chain of halved levels its reads need (`ImageRes::mip_chain`, or `linear_mip_chain` for an + /// sRGB colour read). An alpha read takes any chain the image already has, and a read of the + /// image's own texels any entry at all. + pub(crate) fn set_images(&mut self, images: &ImageStore) { + self.images = self.names.iter().map(|(name, _)| images.get(name).cloned()).collect(); + self.atlas.clear(); + self.entries = vec![None; self.names.len()]; + + // The chains first, then the reads an existing entry may serve + for pass in 0..3 { + for (slot, ((_, usage), image)) in self.names.iter().zip(&self.images).enumerate() { + let Some(image) = image else { continue }; + let mips = match (pass, usage) { + (0, ImageUse::Mipmapped) => AtlasMips::Stored, + (0, ImageUse::MipmappedColor) => AtlasMips::LinearColor, + (1, ImageUse::MipmappedAlpha) => AtlasMips::Stored, + (2, ImageUse::Material) => AtlasMips::None, + _ => continue, + }; + + // An sRGB colour read needs the linear chain, which a stored image does not differ from + let mips = if mips == AtlasMips::LinearColor && !image.srgb { AtlasMips::Stored } else { mips }; + let serves = |entry: &(Arc, AtlasMips)| { + Arc::ptr_eq(&entry.0, image) + && match usage { + ImageUse::Material => true, + ImageUse::MipmappedAlpha => entry.1 != AtlasMips::None, + ImageUse::Mipmapped | ImageUse::MipmappedColor => entry.1 == mips, + } + }; + let entry = self.atlas.iter().position(serves).unwrap_or_else(|| { + self.atlas.push((image.clone(), mips)); + self.atlas.len() - 1 + }); + self.entries[slot] = Some(entry); + } + } + } + + /// The colour images for the atlas with the halved levels each holds (see [`Self::set_images`]). + pub(crate) fn atlas_images(&self) -> impl Iterator, AtlasMips)> { + self.atlas.iter().map(|(image, mips)| (image, *mips)) + } + + /// Exact-f32 planes for the atlas: the projector depth grids built in [`Self::set_surface`]. + pub(crate) fn raw_planes(&self) -> &[RawPlane] { + &self.raw_planes + } + + /// The mesh the program composites: its frame, and the depth grids of the depth-culled + /// fills, one raw plane per distinct grid. Called by `CompositeProgram::set_surface_inputs` + /// before the atlas reads [`Self::raw_planes`]. + pub(crate) fn set_surface(&mut self, mesh: &Arc) { + self.mesh_frame = Some(mesh_frame(mesh.bounds())); + let requests: Vec<_> = self.depths.iter().map(|(projection, symmetry, _)| (projection.clone(), *symmetry)).collect(); + let mut planes: Vec = Vec::new(); + let grids = depth_grids(mesh, &requests) + .into_iter() + .map(|grids| { + let grids = grids?; + let indices = grids + .iter() + .map(|grid| { + let grid = grid.as_ref()?; + let index = planes.iter().position(|plane| Arc::ptr_eq(&plane.texels, &grid.plane.texels)).unwrap_or_else(|| { + planes.push(grid.plane.clone()); + planes.len() - 1 + }); + Some(index) + }) + .collect(); + Some((grids, indices)) + }) + .collect(); + self.depth_grids = grids; + self.raw_planes = planes; + } + + /// The composited mesh's centre and radius, once [`Self::set_surface`] has run. + pub(crate) fn mesh_frame(&self) -> Option<(Vec3, f32)> { + self.mesh_frame + } + + pub(crate) fn append_words(&self, words: &mut Vec, atlas: Option<&TileImageAtlas>, mesh: Option<&Mesh>) -> (Vec, Vec) { + let entry_offsets: Vec = + atlas.map_or_else(Vec::new, |atlas| self.atlas.iter().enumerate().map(|(index, (image, _))| atlas.append_rgba(words, index, image.srgb)).collect()); + let image_offsets: Vec<_> = (0..self.names.len()) + .map(|slot| self.entries.get(slot).copied().flatten().and_then(|entry| entry_offsets.get(entry).copied()).unwrap_or(u32::MAX)) + .collect(); + let normalization = mesh.map(|mesh| { + let (lo, hi) = mesh.bounds(); + ((lo + hi) * 0.5, ((hi - lo).length() * 0.5).max(1e-4)) + }); + let decal_offsets = self + .decals + .iter() + .map(|decal| { + let offset = words.len() as u32; + let alpha = decal.alpha_images.iter().map(|&slot| image_offsets[slot as usize]).find(|&offset| offset != u32::MAX).unwrap_or(u32::MAX); + words.extend(normalization.map_or_else(|| unplaced_decal_words(alpha), |(center, radius)| decal_words(&decal.frame, alpha, center, radius))); + offset + }) + .collect(); + self.append_depth_directories(words, atlas); + (image_offsets, decal_offsets) + } + + /// Each depth-culled fill's directory (its copy count, then one entry per copy) after the + /// grids' plane descriptors, its offset written into the fill's side-table word. + pub(super) fn append_depth_directories(&self, words: &mut Vec, atlas: Option<&TileImageAtlas>) { + let plane_offsets: Vec = atlas.map_or_else(Vec::new, |atlas| (0..self.raw_planes.len()).map(|index| atlas.append_raw(words, index)).collect()); + for ((_, _, directory_word), grids) in self.depths.iter().zip(&self.depth_grids) { + let Some((grids, indices)) = grids else { continue }; + + let directory = words.len() as u32; + words.push(grids.len() as u32); + for (grid, index) in grids.iter().zip(indices) { + let plane = index.and_then(|index| plane_offsets.get(index).copied()); + words.extend(grid.as_ref().zip(plane).map_or_else(missing_entry, |(grid, plane)| grid.entry(plane))); + } + if let Some(word) = words.get_mut(*directory_word as usize) { + *word = directory; + } + } + } +} diff --git a/crates/render/src/gpu_neighbourhood.rs b/crates/render/src/gpu_neighbourhood.rs index 5d2d5538..13819dac 100644 --- a/crates/render/src/gpu_neighbourhood.rs +++ b/crates/render/src/gpu_neighbourhood.rs @@ -34,52 +34,23 @@ pub(crate) const GATHER_KINDS: Range = 32..48; /// P5: the whole-set filters (Color Match). pub(crate) const WHOLE_SET_KINDS: Range = 48..56; -/// The stage a filter runs as; the value is `mode.y` in neighbourhood.wgsl. 0-10 are built in, -/// the packages own the ranges above and define their kinds as constants in their own module. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) struct Kind(pub(crate) u32); +mod budget; +mod budget_guard; +mod kind; +mod neighbourhood_filter; +mod neighbourhood_gpu; +mod neighbourhood_region; +mod params; +mod stage_inputs; -impl Kind { - const BLUR: Self = Self(0); - const SHARPEN: Self = Self(1); - const HIGH_PASS: Self = Self(2); - const BEVEL: Self = Self(3); - const GLOW: Self = Self(4); - const DIRECTIONAL_BLUR: Self = Self(5); - const WARP: Self = Self(6); - const DIRECTIONAL_WARP: Self = Self(7); - const EDGE: Self = Self(8); - const SLOPE_BLUR: Self = Self(9); - const MOSAIC: Self = Self(10); - /// Test probe of the stage inputs: the input's colour (`input_color_at`) at the texel. - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) const INPUT_PROBE: Self = Self(15); - - fn box_family(self) -> bool { - BOX_KINDS.contains(&self.0) || DISTANCE_KINDS.contains(&self.0) - } - - fn gather(self) -> bool { - GATHER_KINDS.contains(&self.0) || WHOLE_SET_KINDS.contains(&self.0) - } -} - -#[derive(Clone, Copy, Debug)] -pub(crate) struct NeighbourhoodFilter { - pub(crate) kind: Kind, - pub(crate) radius: u32, - pub(crate) opacity: f32, - pub(crate) amount: f32, - pub(crate) frequency: f32, - pub(crate) middle: f32, - pub(crate) direction: [f32; 2], - pub(crate) seed: u32, - /// The packages' words: `params.field_layout.zw` and `params.extra` in WGSL. - pub(crate) words: [u32; 2], - pub(crate) extra: [f32; 8], - /// What the stage filters ([`stage_context`]): `params.stage.x` in WGSL (`stage_context()`). - pub(crate) context: u32, -} +use budget::Budget; +pub(crate) use budget_guard::BudgetGuard; +pub(crate) use kind::Kind; +pub(crate) use neighbourhood_filter::NeighbourhoodFilter; +pub(crate) use neighbourhood_gpu::NeighbourhoodGpu; +pub(crate) use neighbourhood_region::NeighbourhoodRegion; +use params::Params; +pub(crate) use stage_inputs::StageInputs; #[cfg(all(test, not(target_arch = "wasm32")))] thread_local! { @@ -106,72 +77,10 @@ pub(crate) fn stage_context(channel: Option) -> u32 { } } -/// What a package's stage constructor gets: the CPU evaluator's working resolution, the longest -/// side, the effect's opacity and what the stage filters: `channel` is the content channel's -/// kind, None for a mask (and for the callers that only ask whether a stage exists). -#[allow(dead_code)] // Read by the GPU port packages -#[derive(Clone, Copy, Debug)] -pub(crate) struct StageInputs { - pub(crate) resolution: u32, - pub(crate) longest_side: u32, - pub(crate) opacity: f32, - pub(crate) channel: Option, -} - -#[allow(dead_code)] // Used by the GPU port packages -impl StageInputs { - /// Whether the stage filters a signed channel (Height): its high-pass middle is 0. - pub(crate) fn signed(self) -> bool { - self.channel == Some(ChannelKind::Signed) - } - - /// Source texels for a size given at 2048 texels, at least half a texel, as the CPU scales it. - pub(crate) fn texels_at_2k(self, at_2k: f32) -> f32 { - (at_2k * (self.resolution.max(1) as f32 / 2048.0)).max(0.5) - } - - /// A stage of `kind` reaching `texels` (rounded, 1 to the longest side) with neutral settings. - pub(crate) fn filter(self, kind: Kind, texels: f32) -> NeighbourhoodFilter { - NeighbourhoodFilter { - kind, - radius: texels.round().clamp(1.0, self.longest_side.max(1) as f32) as u32, - opacity: self.opacity.clamp(0.0, 1.0), - amount: 0.0, - frequency: 0.0, - middle: if self.signed() { 0.0 } else { 0.5 }, - direction: [0.0; 2], - seed: 0, - words: [0; 2], - extra: [0.0; 8], - context: stage_context(self.channel), - } - } -} - -/// A work budget the kernels run under (`NeighbourhoodGpu::budget`) -struct Budget { - queue: wgpu::Queue, - /// The apply and box pipelines' addresses: only their dispatches read their first row or - /// line from `stage.z` - apply: usize, - box_blur: usize, - work_per_texel: u64, - limit: u64, -} - thread_local! { static BUDGET: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } -/// Ends the work budget of `NeighbourhoodGpu::budget` when dropped (also on an early return). -pub(crate) struct BudgetGuard; - -impl Drop for BudgetGuard { - fn drop(&mut self) { - BUDGET.set(None); - } -} - #[cfg(all(test, not(target_arch = "wasm32")))] thread_local! { /// Test seam: Height To Normal and Color Match become the input probe stage @@ -204,449 +113,6 @@ fn supports_built_in(filter: &Filter) -> bool { ) } -impl NeighbourhoodFilter { - /// The source-pixel parameters used by the CPU evaluator at the same working resolution. - /// A nonpositive radius for an optional effect leaves the incoming field unchanged. - /// `channel` is what the stage filters (None: a mask, or a caller that only asks whether a - /// stage exists). None for a filter no stage evaluates. The packages' `new` may also build a - /// stage for a filter their `supports` rejects: one a lowering queues with - /// `ProceduralInputs::precede_with_stage` (the Gradient's pre-blur), which never becomes an - /// effect's own stage. - pub(crate) fn new(filter: &Filter, resolution: u32, longest_side: u32, opacity: f32, channel: Option) -> Option { - let signed = channel == Some(ChannelKind::Signed); - #[cfg(all(test, not(target_arch = "wasm32")))] - if INPUT_PROBE.get() && matches!(filter, Filter::HeightToNormal(_) | Filter::ColorMatch(_)) { - let stage = StageInputs { resolution, longest_side, opacity, channel }; - return Some(stage.filter(Kind::INPUT_PROBE, 1.0)); - } - if !supports_built_in(filter) { - let stage = StageInputs { resolution, longest_side, opacity, channel }; - return box_family::new(filter, stage).or_else(|| gather::new(filter, stage)); - } - let scale = resolution.max(1) as f32 / 2048.0; - let radius = |at_2k: f32| (at_2k * scale).max(0.5); - let mut out = Self { - kind: Kind::BLUR, - radius: 1, - opacity: opacity.clamp(0.0, 1.0), - amount: 0.0, - frequency: 0.0, - middle: if signed { 0.0 } else { 0.5 }, - direction: [0.0; 2], - seed: 0, - words: [0; 2], - extra: [0.0; 8], - context: stage_context(channel), - }; - let direction = |degrees: f32| { - let (sin, cos) = degrees.to_radians().sin_cos(); - [cos, -sin] - }; - let noise_frequency = |scale: f32| (if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 }) / resolution.max(1) as f32; - // A size over its intensity divider (a divider of 0 counts as 1), as the CPU reads it - let divided = |size: f32, divider: u16| size / f32::from(divider.max(1)); - - let (kind, texels) = match *filter { - Filter::Blur { radius: r, .. } if r > 0.0 => (Kind::BLUR, radius(r)), - Filter::Sharpen { amount } => { - out.amount = amount; - (Kind::SHARPEN, (1.5 * scale).max(0.75)) - } - Filter::HighPass { radius: r, .. } => (Kind::HIGH_PASS, radius(r)), - Filter::Bevel { width, .. } => (Kind::BEVEL, radius(width * 0.5)), - Filter::Glow { radius: r, amount } => { - out.amount = amount; - (Kind::GLOW, radius(r)) - } - Filter::DirectionalBlur { radius: r, angle } if r > 0.0 => { - out.direction = direction(angle); - (Kind::DIRECTIONAL_BLUR, radius(r)) - } - Filter::Warp { intensity, scale, seed, divider } if intensity > 0.0 => { - out.frequency = noise_frequency(scale); - out.seed = seed; - (Kind::WARP, radius(divided(intensity, divider))) - } - Filter::DirectionalWarp { intensity, angle, scale, seed, divider } if intensity > 0.0 => { - out.frequency = noise_frequency(scale); - out.direction = direction(angle); - out.seed = seed; - (Kind::DIRECTIONAL_WARP, radius(divided(intensity, divider))) - } - Filter::EdgeDetect { width } => (Kind::EDGE, radius(width)), - Filter::SlopeBlur { radius: r, scale, seed, divider } if r > 0.0 => { - out.frequency = noise_frequency(scale); - out.seed = seed; - (Kind::SLOPE_BLUR, radius(divided(r, divider))) - } - Filter::Mosaic { size, .. } => (Kind::MOSAIC, radius(size)), - _ => return None, - }; - out.kind = kind; - out.radius = texels.round().clamp(1.0, longest_side.max(1) as f32) as u32; - Some(out) - } - - /// Whether the stage runs in the whole-set pre-pass (once per update over the region the - /// bands read, in stripes) instead of in every band: a package's stage with a large reach - /// (P4: Bevel, Drop Shadow) or one that needs the whole set (P5: Color Match, Mirror, - /// Transform). `resolution` is the set's working resolution. - pub(crate) fn whole_set(self, resolution: u32) -> bool { - #[cfg(all(test, not(target_arch = "wasm32")))] - if WHOLE_SET_TEST_REACH.get().is_some_and(|reach| self.reach() >= reach) { - return true; - } - if self.kind.box_family() { - return box_family::whole_set(self, resolution); - } - if self.kind.gather() { - return gather::whole_set(self, resolution); - } - false - } - - /// Source texels the stage reads around an output texel. - pub(crate) fn reach(self) -> u32 { - if self.kind.box_family() { - return box_family::reach(self); - } - if self.kind.gather() { - return gather::reach(self); - } - if self.uses_box() { self.radius.saturating_mul(BOX_PASSES as u32) } else { self.radius.saturating_add(1) } - } - - /// The working fields its passes use besides the original and the output - /// (`NeighbourhoodRegion::blur`): two for the box passes and P4's kinds, P5's own count - /// (`gather::blur_fields`), none for a built-in gather. The whole-set pre-pass gives a stage - /// only these. - pub(crate) fn blur_fields(self) -> u32 { - if self.kind.gather() { - return gather::blur_fields(self); - } - if self.kind.box_family() { - return box_family::blur_fields(self); - } - if self.uses_box() { 2 } else { 0 } - } - - /// Whether the stage runs the three box passes before its apply pass (`uses_box_kind` in - /// neighbourhood.wgsl must agree). - pub(crate) fn uses_box(self) -> bool { - if self.kind.box_family() { - return box_family::uses_box(self); - } - if self.kind.gather() { - return gather::uses_box(self); - } - matches!(self.kind, Kind::BLUR | Kind::SHARPEN | Kind::HIGH_PASS | Kind::BEVEL | Kind::GLOW) - } - - pub(crate) fn work_per_texel(self) -> u64 { - if self.kind.box_family() { - return box_family::work_per_texel(self); - } - if self.kind.gather() { - return gather::work_per_texel(self); - } - let samples = u64::from(self.radius.min(24)); - match self.kind { - Kind::DIRECTIONAL_BLUR => 1 + 4 * (2 * samples + 1), - Kind::SLOPE_BLUR => 5 + 4 * (samples + 1), - Kind::EDGE => 17, - Kind::WARP | Kind::DIRECTIONAL_WARP => 9, - Kind::MOSAIC => 5, - _ => 8, - } - } -} - -/// Source-pixel region [left, top, width, height], with disjoint field offsets in u32 words. -#[derive(Clone, Copy)] -pub(crate) struct NeighbourhoodRegion { - pub(crate) rect: [u32; 4], - pub(crate) original: u32, - pub(crate) blur: [u32; 2], - pub(crate) output: u32, - /// Words per field texel ([`FIELD_WORDS`], or one more with the input word). - pub(crate) field_words: u32, - /// Bit 0: the original field carries input words; bit 1: this stage has an input of its own - /// (`stage_linked` in WGSL); bit 2: the fields carry the input's colour in words 5..8 - /// (`input_color_at`). - pub(crate) input: u32, - /// The stage wraps: it reads the field's periodic copies past the set's edges. - pub(crate) wrap: bool, - /// The set in field-local texels [x0, y0, x1, y1]: in a wrapping program the field holds - /// periodic copies of the set past its edges, and a stage that does not wrap never reads - /// across these bounds (`bounds` and the segment checks in neighbourhood.wgsl). Without a - /// wrapping stage the field lies inside the set and the bounds reach past it. - pub(crate) bounds: [i32; 4], -} - -impl NeighbourhoodRegion { - fn field_layout(self, words: [u32; 2]) -> [u32; 4] { - [self.field_words, self.input, words[0], words[1]] - } -} - -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Params { - rect: [u32; 4], - buffers: [u32; 4], - mode: [u32; 4], - weights: [f32; 4], - direction: [f32; 4], - field_layout: [u32; 4], - extra: [f32; 8], - stage: [u32; 4], - bounds: [i32; 4], -} - -#[derive(Clone)] -pub(crate) struct NeighbourhoodGpu { - box_blur: wgpu::ComputePipeline, - apply: wgpu::ComputePipeline, - cell_average: wgpu::ComputePipeline, - cell_interpolate: wgpu::ComputePipeline, - copy: wgpu::ComputePipeline, - // The packages' own passes (distance transforms, structure tensors, reductions) - box_family: box_family::Pipelines, - gather: gather::Pipelines, -} - -impl NeighbourhoodGpu { - /// [`NeighbourhoodGpu::new`], or when `shared` (on the device tests share, - /// [`crate::headless::Headless::for_tests`]) one set of kernels for all of them, compiled once. - pub(crate) fn for_device(device: &wgpu::Device, shared: bool) -> Self { - #[cfg(all(any(test, feature = "test-support"), not(target_arch = "wasm32")))] - if shared { - static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); - return SHARED.get_or_init(|| Self::new(device)).clone(); - } - #[cfg(not(all(any(test, feature = "test-support"), not(target_arch = "wasm32"))))] - let _ = shared; - Self::new(device) - } - - /// The neighbourhood shader with the packages' files. - pub(crate) fn source() -> String { - [include_str!("shaders/noise.wgsl"), include_str!("shaders/neighbourhood.wgsl"), box_family::WGSL, gather::WGSL].join("\n") - } - - /// The entry points of the built-in passes (the packages add theirs in their `Pipelines`). - #[cfg(all(test, not(target_arch = "wasm32")))] - pub(crate) const ENTRY_POINTS: [&str; 5] = ["box_blur", "apply_neighbourhood", "average_cells", "interpolate_cells", "copy_field"]; - - pub(crate) fn new(device: &wgpu::Device) -> Self { - let module = device - .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("tc_neighbourhood"), source: wgpu::ShaderSource::Wgsl(Self::source().into()) }); - let pipeline = |entry: &'static str| { - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some(entry), - layout: None, - module: &module, - entry_point: Some(entry), - compilation_options: Default::default(), - cache: None, - }) - }; - Self { - box_blur: pipeline("box_blur"), - apply: pipeline("apply_neighbourhood"), - cell_average: pipeline("average_cells"), - cell_interpolate: pipeline("interpolate_cells"), - copy: pipeline("copy_field"), - box_family: box_family::Pipelines::new(&pipeline), - gather: gather::Pipelines::new(&pipeline), - } - } - - pub(crate) fn encode_cells( - &self, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - scratch: &wgpu::Buffer, - region: NeighbourhoodRegion, - cell: u32, - ) { - let [left, top, width, height] = region.rect; - - // The field's origin is i32 bits and lies below zero in a program with a wrapping stage - let cells_across = |origin: u32, size: u32| { - let (origin, cell) = (i64::from(origin as i32), i64::from(cell.max(1))); - ((origin + i64::from(size) + cell - 1).div_euclid(cell) - origin.div_euclid(cell)) as u32 - }; - let cells = [cells_across(left, width), cells_across(top, height)]; - let params = Params { - rect: region.rect, - buffers: [region.original, region.blur[0], region.output, 0], - mode: [cell, 0, 0, 0], - field_layout: region.field_layout([0; 2]), - bounds: region.bounds, - ..Params::zeroed() - }; - Self::run(&self.cell_average, device, encoder, scratch, ¶ms, cells.map(|side| side.div_ceil(APPLY_WORKGROUP))); - Self::run(&self.cell_interpolate, device, encoder, scratch, ¶ms, [width.div_ceil(APPLY_WORKGROUP), height.div_ceil(APPLY_WORKGROUP)]); - } - - /// Copy `size` texels of the field at word `field` (`field_width` texels wide), from field - /// texel `from`, into rows `row..` of the whole-set result at word `result` (`result_width` - /// texels wide). - #[allow(clippy::too_many_arguments)] - pub(crate) fn encode_copy( - &self, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - scratch: &wgpu::Buffer, - (field, field_width, from): (u32, u32, [u32; 2]), - (result, result_width, row): (u32, u32, u32), - size: [u32; 2], - field_words: u32, - ) { - let params = Params { - rect: [from[0], from[1], field_width, 0], - buffers: [field, 0, result, 0], - mode: [result_width, size[0], size[1], row], - field_layout: [field_words, 0, 0, 0], - ..Params::zeroed() - }; - Self::run(&self.copy, device, encoder, scratch, ¶ms, [size[0].div_ceil(APPLY_WORKGROUP), size[1].div_ceil(APPLY_WORKGROUP)]); - } - - /// Run the kernels encoded until the guard drops under a work budget: an apply pass (the - /// gathers' heavy part) whose texels times `work_per_texel` exceed `limit` is dispatched in - /// row chunks, each submitted on its own (the whole-set pre-pass, whose fields span the set). - /// The packages' own passes run whole. - pub(crate) fn budget(&self, queue: &wgpu::Queue, work_per_texel: u64, limit: u64) -> BudgetGuard { - BUDGET.set(Some(Budget { - queue: queue.clone(), - apply: std::ptr::from_ref(&self.apply) as usize, - box_blur: std::ptr::from_ref(&self.box_blur) as usize, - work_per_texel, - limit, - })); - BudgetGuard - } - - fn run( - pipeline: &wgpu::ComputePipeline, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - scratch: &wgpu::Buffer, - params: &Params, - groups: [u32; 2], - ) { - // The apply pass splits by rows of workgroups, the box passes by lines (`stage.z` holds - // the first row or line of a chunk) - let address = std::ptr::from_ref(pipeline) as usize; - let budget = BUDGET.with_borrow(|budget| { - budget - .as_ref() - .filter(|budget| budget.apply == address || budget.box_blur == address) - .map(|budget| (budget.queue.clone(), budget.work_per_texel, budget.limit, budget.box_blur == address)) - }); - if let Some((queue, work_per_texel, limit, lines)) = budget { - let (axis, step, group_work) = if lines { - let length = if params.buffers[3] != 0 { params.rect[3] } else { params.rect[2] }; - (0, LINE_WORKGROUP, u64::from(LINE_WORKGROUP) * u64::from(length)) - } else { - (1, APPLY_WORKGROUP, u64::from(groups[0]) * u64::from(APPLY_WORKGROUP * APPLY_WORKGROUP)) - }; - let per_chunk = (limit / (group_work * work_per_texel.max(1)).max(1)).clamp(1, u64::from(groups[axis].max(1))) as u32; - if per_chunk < groups[axis] { - let mut first = 0; - while first < groups[axis] { - let count = per_chunk.min(groups[axis] - first); - let mut chunk = *params; - chunk.stage[2] = first * step; - let mut split = groups; - split[axis] = count; - Self::dispatch(pipeline, device, encoder, scratch, &chunk, split); - first += count; - let finished = - std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_neighbourhood") })); - queue.submit([finished.finish()]); - } - return; - } - } - Self::dispatch(pipeline, device, encoder, scratch, params, groups); - } - - fn dispatch( - pipeline: &wgpu::ComputePipeline, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - scratch: &wgpu::Buffer, - params: &Params, - groups: [u32; 2], - ) { - let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_neighbourhood_params"), - contents: bytemuck::bytes_of(params), - usage: wgpu::BufferUsages::UNIFORM, - }); - let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_neighbourhood_inputs"), - layout: &pipeline.get_bind_group_layout(0), - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: scratch.as_entire_binding() }, - ], - }); - let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(pipeline); - pass.set_bind_group(0, &bindings, &[]); - pass.dispatch_workgroups(groups[0], groups[1], 1); - } - - pub(crate) fn encode( - &self, - device: &wgpu::Device, - encoder: &mut wgpu::CommandEncoder, - scratch: &wgpu::Buffer, - region: NeighbourhoodRegion, - filter: NeighbourhoodFilter, - ) { - let [_, _, width, height] = region.rect; - if width == 0 || height == 0 { - return; - } - // A package encodes its kinds itself when they need passes of their own - if (filter.kind.box_family() && box_family::encode((self, &self.box_family), device, encoder, scratch, region, filter)) - || (filter.kind.gather() && gather::encode((self, &self.gather), device, encoder, scratch, region, filter)) - { - return; - } - let mut run = |pipeline: &wgpu::ComputePipeline, buffers: [u32; 4], first_box: bool, groups: [u32; 2]| { - let params = Params { - rect: region.rect, - buffers, - mode: [filter.radius, filter.kind.0, filter.seed, u32::from(first_box)], - weights: [filter.opacity, filter.amount, filter.frequency, filter.middle], - direction: [filter.direction[0], filter.direction[1], 0.0, 0.0], - field_layout: region.field_layout(filter.words), - extra: filter.extra, - stage: [filter.context, u32::from(region.wrap), 0, 0], - bounds: region.bounds, - }; - Self::run(pipeline, device, encoder, scratch, ¶ms, groups); - }; - let mut source = region.original; - if filter.uses_box() { - for step in 0..2 * BOX_PASSES { - let vertical = step >= BOX_PASSES; - let line_count = if vertical { width } else { height }; - let target = region.blur[step % 2]; - run(&self.box_blur, [region.original, source, target, u32::from(vertical)], step == 0, [line_count.div_ceil(LINE_WORKGROUP), 1]); - source = target; - } - } - run(&self.apply, [region.original, source, region.output, 0], false, [width.div_ceil(APPLY_WORKGROUP), height.div_ceil(APPLY_WORKGROUP)]); - } -} - #[cfg(all(test, not(target_arch = "wasm32")))] mod tests { use std::sync::Arc; @@ -733,6 +199,7 @@ mod tests { let (project, pixels, owner) = striped(&stack); WHOLE_SET_TEST_REACH.set(Some(whole_reach)); PRE_PASS_TEST_BUDGET.set(budget); + // The whole set's paint (2 × 2 tiles of three images) does not fit, a tile row does let windows = label.starts_with("paint"); PRE_PASS_TEST_PAINT_WORDS.set(windows.then_some(40_000)); @@ -773,6 +240,7 @@ mod tests { project.texture_sets.push(TextureSet::new("Plane", 0, side)); let set = &mut project.texture_sets[0]; set.channels = channels.iter().map(|&channel| (channel, texturecraft_core::ChannelFormat::default_for(channel))).collect(); + // A full material below, the painted layer with Base Color, Roughness and Height let base = project.alloc_id(); project.insert_layer(0, Layer::new(base, "Material", LayerKind::Fill(texturecraft_core::Fill::default()), &channels), None, false).unwrap(); @@ -931,8 +399,8 @@ mod tests { ("Slope Blur", Filter::SlopeBlur { radius: 2.0, scale: 2.0, seed: 4, divider: 1 }), ("Pixelate", Filter::Mosaic { size: 24.0, alpha: true }), ]; - // Slope Blur's direction is nearly along an axis at a few texels, so its reads land just - // below a stripe's edge: the case of a sample's floor and weights that must agree + + // Near an axis, sample weights and floor must agree on the stripe edge for (label, filter) in cases { let (project, pixels, owner) = striped(&[filter, wrap.clone()]); let mut case = OracleCase::new(&project, &pixels, &baked, &images, &mesh); diff --git a/crates/render/src/gpu_neighbourhood/budget.rs b/crates/render/src/gpu_neighbourhood/budget.rs new file mode 100644 index 00000000..4e4e10dc --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/budget.rs @@ -0,0 +1,10 @@ +/// A work budget the kernels run under (`NeighbourhoodGpu::budget`) +pub(super) struct Budget { + pub(super) queue: wgpu::Queue, + /// The apply and box pipelines' addresses: only their dispatches read their first row or + /// line from `stage.z` + pub(super) apply: usize, + pub(super) box_blur: usize, + pub(super) work_per_texel: u64, + pub(super) limit: u64, +} diff --git a/crates/render/src/gpu_neighbourhood/budget_guard.rs b/crates/render/src/gpu_neighbourhood/budget_guard.rs new file mode 100644 index 00000000..3bd5178f --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/budget_guard.rs @@ -0,0 +1,10 @@ +use super::BUDGET; + +/// Ends the work budget of `NeighbourhoodGpu::budget` when dropped (also on an early return). +pub(crate) struct BudgetGuard; + +impl Drop for BudgetGuard { + fn drop(&mut self) { + BUDGET.set(None); + } +} diff --git a/crates/render/src/gpu_neighbourhood/kind.rs b/crates/render/src/gpu_neighbourhood/kind.rs new file mode 100644 index 00000000..0768f21b --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/kind.rs @@ -0,0 +1,31 @@ +use super::{BOX_KINDS, DISTANCE_KINDS, GATHER_KINDS, WHOLE_SET_KINDS}; + +/// The stage a filter runs as; the value is `mode.y` in neighbourhood.wgsl. 0-10 are built in, +/// the packages own the ranges above and define their kinds as constants in their own module. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Kind(pub(crate) u32); + +impl Kind { + pub(super) const BLUR: Self = Self(0); + pub(super) const SHARPEN: Self = Self(1); + pub(super) const HIGH_PASS: Self = Self(2); + pub(super) const BEVEL: Self = Self(3); + pub(super) const GLOW: Self = Self(4); + pub(super) const DIRECTIONAL_BLUR: Self = Self(5); + pub(super) const WARP: Self = Self(6); + pub(super) const DIRECTIONAL_WARP: Self = Self(7); + pub(super) const EDGE: Self = Self(8); + pub(super) const SLOPE_BLUR: Self = Self(9); + pub(super) const MOSAIC: Self = Self(10); + /// Test probe of the stage inputs: the input's colour (`input_color_at`) at the texel. + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) const INPUT_PROBE: Self = Self(15); + + pub(super) fn box_family(self) -> bool { + BOX_KINDS.contains(&self.0) || DISTANCE_KINDS.contains(&self.0) + } + + pub(super) fn gather(self) -> bool { + GATHER_KINDS.contains(&self.0) || WHOLE_SET_KINDS.contains(&self.0) + } +} diff --git a/crates/render/src/gpu_neighbourhood/neighbourhood_filter.rs b/crates/render/src/gpu_neighbourhood/neighbourhood_filter.rs new file mode 100644 index 00000000..102ae6c4 --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/neighbourhood_filter.rs @@ -0,0 +1,192 @@ +#[cfg(all(test, not(target_arch = "wasm32")))] +use super::{INPUT_PROBE, WHOLE_SET_TEST_REACH}; + +use super::{BOX_PASSES, ChannelKind, Filter, Kind, StageInputs, box_family, gather, stage_context, supports_built_in}; + +#[derive(Clone, Copy, Debug)] +pub(crate) struct NeighbourhoodFilter { + pub(crate) kind: Kind, + pub(crate) radius: u32, + pub(crate) opacity: f32, + pub(crate) amount: f32, + pub(crate) frequency: f32, + pub(crate) middle: f32, + pub(crate) direction: [f32; 2], + pub(crate) seed: u32, + /// The packages' words: `params.field_layout.zw` and `params.extra` in WGSL. + pub(crate) words: [u32; 2], + pub(crate) extra: [f32; 8], + /// What the stage filters ([`stage_context`]): `params.stage.x` in WGSL (`stage_context()`). + pub(crate) context: u32, +} + +impl NeighbourhoodFilter { + /// The source-pixel parameters used by the CPU evaluator at the same working resolution. + /// A nonpositive radius for an optional effect leaves the incoming field unchanged. + /// `channel` is what the stage filters (None: a mask, or a caller that only asks whether a + /// stage exists). None for a filter no stage evaluates. The packages' `new` may also build a + /// stage for a filter their `supports` rejects: one a lowering queues with + /// `ProceduralInputs::precede_with_stage` (the Gradient's pre-blur), which never becomes an + /// effect's own stage. + pub(crate) fn new(filter: &Filter, resolution: u32, longest_side: u32, opacity: f32, channel: Option) -> Option { + let signed = channel == Some(ChannelKind::Signed); + #[cfg(all(test, not(target_arch = "wasm32")))] + if INPUT_PROBE.get() && matches!(filter, Filter::HeightToNormal(_) | Filter::ColorMatch(_)) { + let stage = StageInputs { resolution, longest_side, opacity, channel }; + return Some(stage.filter(Kind::INPUT_PROBE, 1.0)); + } + + if !supports_built_in(filter) { + let stage = StageInputs { resolution, longest_side, opacity, channel }; + return box_family::new(filter, stage).or_else(|| gather::new(filter, stage)); + } + + let scale = resolution.max(1) as f32 / 2048.0; + let radius = |at_2k: f32| (at_2k * scale).max(0.5); + let mut out = Self { + kind: Kind::BLUR, + radius: 1, + opacity: opacity.clamp(0.0, 1.0), + amount: 0.0, + frequency: 0.0, + middle: if signed { 0.0 } else { 0.5 }, + direction: [0.0; 2], + seed: 0, + words: [0; 2], + extra: [0.0; 8], + context: stage_context(channel), + }; + let direction = |degrees: f32| { + let (sin, cos) = degrees.to_radians().sin_cos(); + [cos, -sin] + }; + let noise_frequency = |scale: f32| (if scale.is_finite() { scale.clamp(0.01, 1000.0) } else { 1.0 }) / resolution.max(1) as f32; + + // A size over its intensity divider (a divider of 0 counts as 1), as the CPU reads it + let divided = |size: f32, divider: u16| size / f32::from(divider.max(1)); + + let (kind, texels) = match *filter { + Filter::Blur { radius: r, .. } if r > 0.0 => (Kind::BLUR, radius(r)), + Filter::Sharpen { amount } => { + out.amount = amount; + (Kind::SHARPEN, (1.5 * scale).max(0.75)) + } + Filter::HighPass { radius: r, .. } => (Kind::HIGH_PASS, radius(r)), + Filter::Bevel { width, .. } => (Kind::BEVEL, radius(width * 0.5)), + Filter::Glow { radius: r, amount } => { + out.amount = amount; + (Kind::GLOW, radius(r)) + } + Filter::DirectionalBlur { radius: r, angle } if r > 0.0 => { + out.direction = direction(angle); + (Kind::DIRECTIONAL_BLUR, radius(r)) + } + Filter::Warp { intensity, scale, seed, divider } if intensity > 0.0 => { + out.frequency = noise_frequency(scale); + out.seed = seed; + (Kind::WARP, radius(divided(intensity, divider))) + } + Filter::DirectionalWarp { intensity, angle, scale, seed, divider } if intensity > 0.0 => { + out.frequency = noise_frequency(scale); + out.direction = direction(angle); + out.seed = seed; + (Kind::DIRECTIONAL_WARP, radius(divided(intensity, divider))) + } + Filter::EdgeDetect { width } => (Kind::EDGE, radius(width)), + Filter::SlopeBlur { radius: r, scale, seed, divider } if r > 0.0 => { + out.frequency = noise_frequency(scale); + out.seed = seed; + (Kind::SLOPE_BLUR, radius(divided(r, divider))) + } + Filter::Mosaic { size, .. } => (Kind::MOSAIC, radius(size)), + _ => return None, + }; + out.kind = kind; + out.radius = texels.round().clamp(1.0, longest_side.max(1) as f32) as u32; + Some(out) + } + + /// Whether the stage runs in the whole-set pre-pass (once per update over the region the + /// bands read, in stripes) instead of in every band: a package's stage with a large reach + /// (P4: Bevel, Drop Shadow) or one that needs the whole set (P5: Color Match, Mirror, + /// Transform). `resolution` is the set's working resolution. + pub(crate) fn whole_set(self, resolution: u32) -> bool { + #[cfg(all(test, not(target_arch = "wasm32")))] + if WHOLE_SET_TEST_REACH.get().is_some_and(|reach| self.reach() >= reach) { + return true; + } + + if self.kind.box_family() { + return box_family::whole_set(self, resolution); + } + + if self.kind.gather() { + return gather::whole_set(self, resolution); + } + + false + } + + /// Source texels the stage reads around an output texel. + pub(crate) fn reach(self) -> u32 { + if self.kind.box_family() { + return box_family::reach(self); + } + + if self.kind.gather() { + return gather::reach(self); + } + + if self.uses_box() { self.radius.saturating_mul(BOX_PASSES as u32) } else { self.radius.saturating_add(1) } + } + + /// The working fields its passes use besides the original and the output + /// (`NeighbourhoodRegion::blur`): two for the box passes and P4's kinds, P5's own count + /// (`gather::blur_fields`), none for a built-in gather. The whole-set pre-pass gives a stage + /// only these. + pub(crate) fn blur_fields(self) -> u32 { + if self.kind.gather() { + return gather::blur_fields(self); + } + + if self.kind.box_family() { + return box_family::blur_fields(self); + } + + if self.uses_box() { 2 } else { 0 } + } + + /// Whether the stage runs the three box passes before its apply pass (`uses_box_kind` in + /// neighbourhood.wgsl must agree). + pub(crate) fn uses_box(self) -> bool { + if self.kind.box_family() { + return box_family::uses_box(self); + } + + if self.kind.gather() { + return gather::uses_box(self); + } + + matches!(self.kind, Kind::BLUR | Kind::SHARPEN | Kind::HIGH_PASS | Kind::BEVEL | Kind::GLOW) + } + + pub(crate) fn work_per_texel(self) -> u64 { + if self.kind.box_family() { + return box_family::work_per_texel(self); + } + + if self.kind.gather() { + return gather::work_per_texel(self); + } + + let samples = u64::from(self.radius.min(24)); + match self.kind { + Kind::DIRECTIONAL_BLUR => 1 + 4 * (2 * samples + 1), + Kind::SLOPE_BLUR => 5 + 4 * (samples + 1), + Kind::EDGE => 17, + Kind::WARP | Kind::DIRECTIONAL_WARP => 9, + Kind::MOSAIC => 5, + _ => 8, + } + } +} diff --git a/crates/render/src/gpu_neighbourhood/neighbourhood_gpu.rs b/crates/render/src/gpu_neighbourhood/neighbourhood_gpu.rs new file mode 100644 index 00000000..3ae8f9a5 --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/neighbourhood_gpu.rs @@ -0,0 +1,250 @@ +use super::{ + APPLY_WORKGROUP, BOX_PASSES, BUDGET, Budget, BudgetGuard, DeviceExt, LINE_WORKGROUP, NeighbourhoodFilter, NeighbourhoodRegion, Params, Zeroable, + box_family, gather, +}; + +#[derive(Clone)] +pub(crate) struct NeighbourhoodGpu { + pub(super) box_blur: wgpu::ComputePipeline, + pub(super) apply: wgpu::ComputePipeline, + pub(super) cell_average: wgpu::ComputePipeline, + pub(super) cell_interpolate: wgpu::ComputePipeline, + pub(super) copy: wgpu::ComputePipeline, + // The packages' own passes (distance transforms, structure tensors, reductions) + pub(super) box_family: box_family::Pipelines, + pub(super) gather: gather::Pipelines, +} + +impl NeighbourhoodGpu { + /// [`NeighbourhoodGpu::new`], or when `shared` (on the device tests share, + /// [`crate::headless::Headless::for_tests`]) one set of kernels for all of them, compiled once. + pub(crate) fn for_device(device: &wgpu::Device, shared: bool) -> Self { + #[cfg(all(any(test, feature = "test-support"), not(target_arch = "wasm32")))] + if shared { + static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); + return SHARED.get_or_init(|| Self::new(device)).clone(); + } + + #[cfg(not(all(any(test, feature = "test-support"), not(target_arch = "wasm32"))))] + let _ = shared; + Self::new(device) + } + + /// The neighbourhood shader with the packages' files. + pub(crate) fn source() -> String { + [include_str!("../shaders/noise.wgsl"), include_str!("../shaders/neighbourhood.wgsl"), box_family::WGSL, gather::WGSL].join("\n") + } + + /// The entry points of the built-in passes (the packages add theirs in their `Pipelines`). + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) const ENTRY_POINTS: [&str; 5] = ["box_blur", "apply_neighbourhood", "average_cells", "interpolate_cells", "copy_field"]; + + pub(crate) fn new(device: &wgpu::Device) -> Self { + let module = device + .create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("tc_neighbourhood"), source: wgpu::ShaderSource::Wgsl(Self::source().into()) }); + let pipeline = |entry: &'static str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(entry), + layout: None, + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + Self { + box_blur: pipeline("box_blur"), + apply: pipeline("apply_neighbourhood"), + cell_average: pipeline("average_cells"), + cell_interpolate: pipeline("interpolate_cells"), + copy: pipeline("copy_field"), + box_family: box_family::Pipelines::new(&pipeline), + gather: gather::Pipelines::new(&pipeline), + } + } + + pub(crate) fn encode_cells( + &self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + scratch: &wgpu::Buffer, + region: NeighbourhoodRegion, + cell: u32, + ) { + let [left, top, width, height] = region.rect; + + // The field's origin is i32 bits and lies below zero in a program with a wrapping stage + let cells_across = |origin: u32, size: u32| { + let (origin, cell) = (i64::from(origin as i32), i64::from(cell.max(1))); + ((origin + i64::from(size) + cell - 1).div_euclid(cell) - origin.div_euclid(cell)) as u32 + }; + let cells = [cells_across(left, width), cells_across(top, height)]; + let params = Params { + rect: region.rect, + buffers: [region.original, region.blur[0], region.output, 0], + mode: [cell, 0, 0, 0], + field_layout: region.field_layout([0; 2]), + bounds: region.bounds, + ..Params::zeroed() + }; + Self::run(&self.cell_average, device, encoder, scratch, ¶ms, cells.map(|side| side.div_ceil(APPLY_WORKGROUP))); + Self::run(&self.cell_interpolate, device, encoder, scratch, ¶ms, [width.div_ceil(APPLY_WORKGROUP), height.div_ceil(APPLY_WORKGROUP)]); + } + + /// Copy `size` texels of the field at word `field` (`field_width` texels wide), from field + /// texel `from`, into rows `row..` of the whole-set result at word `result` (`result_width` + /// texels wide). + #[allow(clippy::too_many_arguments)] + pub(crate) fn encode_copy( + &self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + scratch: &wgpu::Buffer, + (field, field_width, from): (u32, u32, [u32; 2]), + (result, result_width, row): (u32, u32, u32), + size: [u32; 2], + field_words: u32, + ) { + let params = Params { + rect: [from[0], from[1], field_width, 0], + buffers: [field, 0, result, 0], + mode: [result_width, size[0], size[1], row], + field_layout: [field_words, 0, 0, 0], + ..Params::zeroed() + }; + Self::run(&self.copy, device, encoder, scratch, ¶ms, [size[0].div_ceil(APPLY_WORKGROUP), size[1].div_ceil(APPLY_WORKGROUP)]); + } + + /// Run the kernels encoded until the guard drops under a work budget: an apply pass (the + /// gathers' heavy part) whose texels times `work_per_texel` exceed `limit` is dispatched in + /// row chunks, each submitted on its own (the whole-set pre-pass, whose fields span the set). + /// The packages' own passes run whole. + pub(crate) fn budget(&self, queue: &wgpu::Queue, work_per_texel: u64, limit: u64) -> BudgetGuard { + BUDGET.set(Some(Budget { + queue: queue.clone(), + apply: std::ptr::from_ref(&self.apply) as usize, + box_blur: std::ptr::from_ref(&self.box_blur) as usize, + work_per_texel, + limit, + })); + BudgetGuard + } + + pub(super) fn run( + pipeline: &wgpu::ComputePipeline, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + scratch: &wgpu::Buffer, + params: &Params, + groups: [u32; 2], + ) { + // The chunk origin selects rows for apply workgroups and lines for box passes + let address = std::ptr::from_ref(pipeline) as usize; + let budget = BUDGET.with_borrow(|budget| { + budget + .as_ref() + .filter(|budget| budget.apply == address || budget.box_blur == address) + .map(|budget| (budget.queue.clone(), budget.work_per_texel, budget.limit, budget.box_blur == address)) + }); + if let Some((queue, work_per_texel, limit, lines)) = budget { + let (axis, step, group_work) = if lines { + let length = if params.buffers[3] != 0 { params.rect[3] } else { params.rect[2] }; + (0, LINE_WORKGROUP, u64::from(LINE_WORKGROUP) * u64::from(length)) + } else { + (1, APPLY_WORKGROUP, u64::from(groups[0]) * u64::from(APPLY_WORKGROUP * APPLY_WORKGROUP)) + }; + let per_chunk = (limit / (group_work * work_per_texel.max(1)).max(1)).clamp(1, u64::from(groups[axis].max(1))) as u32; + if per_chunk < groups[axis] { + let mut first = 0; + while first < groups[axis] { + let count = per_chunk.min(groups[axis] - first); + let mut chunk = *params; + chunk.stage[2] = first * step; + let mut split = groups; + split[axis] = count; + Self::dispatch(pipeline, device, encoder, scratch, &chunk, split); + first += count; + let finished = + std::mem::replace(encoder, device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_neighbourhood") })); + queue.submit([finished.finish()]); + } + return; + } + } + Self::dispatch(pipeline, device, encoder, scratch, params, groups); + } + + pub(super) fn dispatch( + pipeline: &wgpu::ComputePipeline, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + scratch: &wgpu::Buffer, + params: &Params, + groups: [u32; 2], + ) { + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_neighbourhood_params"), + contents: bytemuck::bytes_of(params), + usage: wgpu::BufferUsages::UNIFORM, + }); + let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_neighbourhood_inputs"), + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: scratch.as_entire_binding() }, + ], + }); + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, &bindings, &[]); + pass.dispatch_workgroups(groups[0], groups[1], 1); + } + + pub(crate) fn encode( + &self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + scratch: &wgpu::Buffer, + region: NeighbourhoodRegion, + filter: NeighbourhoodFilter, + ) { + let [_, _, width, height] = region.rect; + if width == 0 || height == 0 { + return; + } + + // A package encodes its kinds itself when they need passes of their own + if (filter.kind.box_family() && box_family::encode((self, &self.box_family), device, encoder, scratch, region, filter)) + || (filter.kind.gather() && gather::encode((self, &self.gather), device, encoder, scratch, region, filter)) + { + return; + } + + let mut run = |pipeline: &wgpu::ComputePipeline, buffers: [u32; 4], first_box: bool, groups: [u32; 2]| { + let params = Params { + rect: region.rect, + buffers, + mode: [filter.radius, filter.kind.0, filter.seed, u32::from(first_box)], + weights: [filter.opacity, filter.amount, filter.frequency, filter.middle], + direction: [filter.direction[0], filter.direction[1], 0.0, 0.0], + field_layout: region.field_layout(filter.words), + extra: filter.extra, + stage: [filter.context, u32::from(region.wrap), 0, 0], + bounds: region.bounds, + }; + Self::run(pipeline, device, encoder, scratch, ¶ms, groups); + }; + let mut source = region.original; + if filter.uses_box() { + for step in 0..2 * BOX_PASSES { + let vertical = step >= BOX_PASSES; + let line_count = if vertical { width } else { height }; + let target = region.blur[step % 2]; + run(&self.box_blur, [region.original, source, target, u32::from(vertical)], step == 0, [line_count.div_ceil(LINE_WORKGROUP), 1]); + source = target; + } + } + run(&self.apply, [region.original, source, region.output, 0], false, [width.div_ceil(APPLY_WORKGROUP), height.div_ceil(APPLY_WORKGROUP)]); + } +} diff --git a/crates/render/src/gpu_neighbourhood/neighbourhood_region.rs b/crates/render/src/gpu_neighbourhood/neighbourhood_region.rs new file mode 100644 index 00000000..19b0066c --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/neighbourhood_region.rs @@ -0,0 +1,27 @@ +/// Source-pixel region [left, top, width, height], with disjoint field offsets in u32 words. +#[derive(Clone, Copy)] +pub(crate) struct NeighbourhoodRegion { + pub(crate) rect: [u32; 4], + pub(crate) original: u32, + pub(crate) blur: [u32; 2], + pub(crate) output: u32, + /// Words per field texel ([`super::FIELD_WORDS`], or one more with the input word). + pub(crate) field_words: u32, + /// Bit 0: the original field carries input words; bit 1: this stage has an input of its own + /// (`stage_linked` in WGSL); bit 2: the fields carry the input's colour in words 5..8 + /// (`input_color_at`). + pub(crate) input: u32, + /// The stage wraps: it reads the field's periodic copies past the set's edges. + pub(crate) wrap: bool, + /// The set in field-local texels [x0, y0, x1, y1]: in a wrapping program the field holds + /// periodic copies of the set past its edges, and a stage that does not wrap never reads + /// across these bounds (`bounds` and the segment checks in neighbourhood.wgsl). Without a + /// wrapping stage the field lies inside the set and the bounds reach past it. + pub(crate) bounds: [i32; 4], +} + +impl NeighbourhoodRegion { + pub(super) fn field_layout(self, words: [u32; 2]) -> [u32; 4] { + [self.field_words, self.input, words[0], words[1]] + } +} diff --git a/crates/render/src/gpu_neighbourhood/params.rs b/crates/render/src/gpu_neighbourhood/params.rs new file mode 100644 index 00000000..ccf04ff9 --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/params.rs @@ -0,0 +1,15 @@ +use super::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Params { + pub(super) rect: [u32; 4], + pub(super) buffers: [u32; 4], + pub(super) mode: [u32; 4], + pub(super) weights: [f32; 4], + pub(super) direction: [f32; 4], + pub(super) field_layout: [u32; 4], + pub(super) extra: [f32; 8], + pub(super) stage: [u32; 4], + pub(super) bounds: [i32; 4], +} diff --git a/crates/render/src/gpu_neighbourhood/stage_inputs.rs b/crates/render/src/gpu_neighbourhood/stage_inputs.rs new file mode 100644 index 00000000..28c7b86d --- /dev/null +++ b/crates/render/src/gpu_neighbourhood/stage_inputs.rs @@ -0,0 +1,43 @@ +use super::{ChannelKind, Kind, NeighbourhoodFilter, stage_context}; + +/// What a package's stage constructor gets: the CPU evaluator's working resolution, the longest +/// side, the effect's opacity and what the stage filters: `channel` is the content channel's +/// kind, None for a mask (and for the callers that only ask whether a stage exists). +#[allow(dead_code)] // Read by the GPU port packages +#[derive(Clone, Copy, Debug)] +pub(crate) struct StageInputs { + pub(crate) resolution: u32, + pub(crate) longest_side: u32, + pub(crate) opacity: f32, + pub(crate) channel: Option, +} + +#[allow(dead_code)] // Used by the GPU port packages +impl StageInputs { + /// Whether the stage filters a signed channel (Height): its high-pass middle is 0. + pub(crate) fn signed(self) -> bool { + self.channel == Some(ChannelKind::Signed) + } + + /// Source texels for a size given at 2048 texels, at least half a texel, as the CPU scales it. + pub(crate) fn texels_at_2k(self, at_2k: f32) -> f32 { + (at_2k * (self.resolution.max(1) as f32 / 2048.0)).max(0.5) + } + + /// A stage of `kind` reaching `texels` (rounded, 1 to the longest side) with neutral settings. + pub(crate) fn filter(self, kind: Kind, texels: f32) -> NeighbourhoodFilter { + NeighbourhoodFilter { + kind, + radius: texels.round().clamp(1.0, self.longest_side.max(1) as f32) as u32, + opacity: self.opacity.clamp(0.0, 1.0), + amount: 0.0, + frequency: 0.0, + middle: if self.signed() { 0.0 } else { 0.5 }, + direction: [0.0; 2], + seed: 0, + words: [0; 2], + extra: [0.0; 8], + context: stage_context(self.channel), + } + } +} diff --git a/crates/render/src/gpu_neighbourhood_box.rs b/crates/render/src/gpu_neighbourhood_box.rs index 4c9f7021..7fa71f23 100644 --- a/crates/render/src/gpu_neighbourhood_box.rs +++ b/crates/render/src/gpu_neighbourhood_box.rs @@ -112,29 +112,10 @@ const ROW_PASS_WORK: u64 = 4; /// Work per texel of the distance column pass (two envelopes, built and read back). const COLUMN_PASS_WORK: u64 = 8; -/// P4's own compute pipelines, created from the neighbourhood module. -#[derive(Clone)] -pub(super) struct Pipelines { - prepare: wgpu::ComputePipeline, - apply: wgpu::ComputePipeline, - distance_rows: wgpu::ComputePipeline, - distance_columns: wgpu::ComputePipeline, - distance_edges: wgpu::ComputePipeline, - directional_trail: wgpu::ComputePipeline, -} +#[path = "gpu_neighbourhood_box/pipelines.rs"] +mod pipelines; -impl Pipelines { - pub(super) fn new(pipeline: &dyn Fn(&'static str) -> wgpu::ComputePipeline) -> Self { - Self { - prepare: pipeline("box_family_prepare"), - apply: pipeline("box_family_apply"), - distance_rows: pipeline("distance_rows"), - distance_columns: pipeline("distance_columns"), - distance_edges: pipeline("distance_edges"), - directional_trail: pipeline("directional_trail"), - } - } -} +pub(super) use pipelines::Pipelines; /// Whether a P4 stage evaluates `filter` as the CPU does. /// The Gradient's input blur is no effect of its own: P2 queues [`new`]'s stage for it before the gradient. @@ -401,6 +382,7 @@ fn box_passes( let vertical = step >= BOX_PASSES; let line_count = if vertical { width } else { height }; let target = region.blur[step % 2]; + // The built-in box kernel reads no first line, so it runs whole run(box_blur, [first, source, target, u32::from(vertical)], radius, step == 0, [line_count.div_ceil(LINE_WORKGROUP), 1], (LINE_WORKGROUP, 0)); source = target; @@ -490,6 +472,7 @@ pub(super) fn encode( let blurred = box_passes(&mut run, &gpu.box_blur, region, original, filter.radius); run(&pipelines.apply, [original, blurred, output, 0], filter.radius, false, texel_groups, own); } + // Row distances in the first blur field, the envelopes' stacks in the second, the ramp in the output, then its smoothing DISTANCE_BEVEL | BEVEL_SMOOTH => { let [rows, stacks] = region.blur; @@ -507,6 +490,7 @@ pub(super) fn encode( run(&pipelines.directional_trail, [original, inside, output, 0], filter.radius, false, texel_groups, trail); run(&pipelines.apply, [original, output, output, 0], filter.radius, false, texel_groups, own); } + // Pixelate gathers and the wrapping filters run the built-in passes _ => return false, } @@ -653,6 +637,7 @@ mod tests { if !painted { continue; } + let (alpha, tone) = if across_edges { (if at_y < 64 { 1.0 } else { 0.65 }, if at_x < 64 { 0.8 } else { 0.4 }) } else { @@ -851,14 +836,17 @@ mod tests { }); encoder.copy_buffer_to_buffer(scratch, 0, &staging, 0, Some(scratch.size())); gpu.queue.submit([encoder.finish()]); + // The callback may run on another test's poll of the shared device: wait for it let (sender, receiver) = std::sync::mpsc::channel(); staging.slice(..).map_async(wgpu::MapMode::Read, move |result| drop(sender.send(result))); let _ = gpu.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }); + // A failed mapping reads no texels, which the tests' comparisons then report if !matches!(receiver.recv(), Ok(Ok(()))) { return Vec::new(); } + let Ok(bytes) = staging.slice(..).get_mapped_range() else { return Vec::new() }; bytemuck::cast_slice::(&bytes).as_chunks::<5>().0.to_vec() } @@ -923,6 +911,7 @@ mod tests { if original.1 <= 0.0 { continue; } + let value: Vec = output[..4].iter().map(|word| f32::from_bits(*word)).collect(); let average: Vec = blurred[..4].iter().map(|word| f32::from_bits(*word)).collect(); let gray = f32::from_bits(output[4]); @@ -935,6 +924,7 @@ mod tests { } continue; } + assert_eq!(value, original.0.to_vec(), "{label}: the original texel"); let expected = match channel { Some(ChannelKind::Color) => mode.gray(straight(&average)), @@ -1180,6 +1170,7 @@ mod tests { let smooth = Filter::BevelSmooth(BevelSmooth { distance: 0.2, ..BevelSmooth::LIBRARY }); let trail = Filter::DirectionalDistance(DirectionalDistance { angle: 30.0, ..DirectionalDistance::LIBRARY }); let normal = BlendMode::Normal; + // The checker's cell edges are a hard decision on both sides let tolerance = Tolerance::NEIGHBOURHOOD.with_flips((SIZE * SIZE / 1000) as usize); let cases = [ @@ -1305,11 +1296,13 @@ mod tests { } let mut program = CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); + // A halo too large for the adapter's working memory is reported, not timed if let Err(error) = gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program) { println!("{label} at {side}: GPU [{}] {error}", gpu.adapter_name); continue; } + let mut gpu_times: Vec = (0..5) .map(|_| { let start = Instant::now(); diff --git a/crates/render/src/gpu_neighbourhood_box/pipelines.rs b/crates/render/src/gpu_neighbourhood_box/pipelines.rs new file mode 100644 index 00000000..f96dcad8 --- /dev/null +++ b/crates/render/src/gpu_neighbourhood_box/pipelines.rs @@ -0,0 +1,23 @@ +/// P4's own compute pipelines, created from the neighbourhood module. +#[derive(Clone)] +pub(in super::super) struct Pipelines { + pub(super) prepare: wgpu::ComputePipeline, + pub(super) apply: wgpu::ComputePipeline, + pub(super) distance_rows: wgpu::ComputePipeline, + pub(super) distance_columns: wgpu::ComputePipeline, + pub(super) distance_edges: wgpu::ComputePipeline, + pub(super) directional_trail: wgpu::ComputePipeline, +} + +impl Pipelines { + pub(in super::super) fn new(pipeline: &dyn Fn(&'static str) -> wgpu::ComputePipeline) -> Self { + Self { + prepare: pipeline("box_family_prepare"), + apply: pipeline("box_family_apply"), + distance_rows: pipeline("distance_rows"), + distance_columns: pipeline("distance_columns"), + distance_edges: pipeline("distance_edges"), + directional_trail: pipeline("directional_trail"), + } + } +} diff --git a/crates/render/src/gpu_neighbourhood_gather.rs b/crates/render/src/gpu_neighbourhood_gather.rs index 2409f960..65ba3e31 100644 --- a/crates/render/src/gpu_neighbourhood_gather.rs +++ b/crates/render/src/gpu_neighbourhood_gather.rs @@ -151,25 +151,10 @@ const KUWAHARA_TENSOR_READS: u64 = 9 * 4; /// Work per Kuwahara ellipse read: the read and its sectors' weights. const KUWAHARA_SAMPLE_WORK: u64 = 3 * SAMPLE_WORK; -/// P5's own compute pipelines, created from the neighbourhood module. -#[derive(Clone)] -pub(super) struct Pipelines { - /// Anisotropic Kuwahara's structure tensor: each texel's ellipse frame. - kuwahara_frame: wgpu::ComputePipeline, - /// Color Match's mean: each row's sums, then the rows' total. - color_match_rows: wgpu::ComputePipeline, - color_match_total: wgpu::ComputePipeline, -} +#[path = "gpu_neighbourhood_gather/pipelines.rs"] +mod pipelines; -impl Pipelines { - pub(super) fn new(pipeline: &dyn Fn(&'static str) -> wgpu::ComputePipeline) -> Self { - Self { - kuwahara_frame: pipeline("gather_kuwahara_frame"), - color_match_rows: pipeline("gather_color_match_rows"), - color_match_total: pipeline("gather_color_match_total"), - } - } -} +pub(super) use pipelines::Pipelines; fn flag(on: bool, bit: u32) -> u32 { if on { bit } else { 0 } @@ -205,6 +190,7 @@ pub(super) fn new(filter: &Filter, stage: StageInputs) -> Option 0.0 => Some(kuwahara_stage(stage, kuwahara)), Filter::SourceWarp(warp) if warp.move_texels(stage.resolution) > 0.0 => Some(source_warp(stage, warp)), @@ -241,8 +227,7 @@ fn kuwahara_stage(stage: StageInputs, kuwahara: &AnisotropicKuwahara) -> Neighbo fn color_match_stage(stage: StageInputs, matcher: &ColorMatch) -> NeighbourhoodFilter { let average = matcher.source_mode == SourceColorMode::Average && stage.channel == Some(ChannelKind::Color); - // An image input not linked reads its default (filter_region in eval.rs); a linked one is - // read at the texel ([`bind_inputs`] laid the others in) + // Unlinked image inputs use the CPU filter default let source = match matcher.source_mode { SourceColorMode::Input => [ImageInput::SOURCE_INPUT.default; 3], SourceColorMode::Average | SourceColorMode::Parameter => matcher.source_color, @@ -580,6 +565,7 @@ pub(super) fn encode( dispatch_in_rows((device, &mut *encoder, scratch), &pipelines.kuwahara_frame, &frames, texel_groups, (APPLY_WORKGROUP, row_work)); NeighbourhoodGpu::run(&gpu.apply, device, encoder, scratch, ¶ms([original, frame, output, 0]), texel_groups); } + // Each row's sums in the first blur field, their total's mean in the second COLOR_MATCH if filter.words[0] & COLOR_MATCH_AVERAGE != 0 => { let [rows, mean] = region.blur; @@ -595,6 +581,7 @@ pub(super) fn encode( NeighbourhoodGpu::run(&pipelines.color_match_total, device, encoder, scratch, ¶ms([original, rows, mean, 0]), [1, 1]); NeighbourhoodGpu::run(&gpu.apply, device, encoder, scratch, ¶ms([original, mean, output, 0]), texel_groups); } + // The other kinds gather in the apply pass _ => return false, } @@ -901,6 +888,7 @@ mod tests { } else { (if at_x >= 63 { 1.0 } else { 0.65 }, if at_y <= 64 { 0.8 } else { 0.4 }) }; + // A diagonal stripe gives the edge searches slanted edges to follow let tone = if (at_x + 2 * at_y) % 37 < 5 { tone * 0.5 + 0.1 } else { tone }; let premultiplied = |value: f32| to_u16(value * alpha); diff --git a/crates/render/src/gpu_neighbourhood_gather/pipelines.rs b/crates/render/src/gpu_neighbourhood_gather/pipelines.rs new file mode 100644 index 00000000..31f178ee --- /dev/null +++ b/crates/render/src/gpu_neighbourhood_gather/pipelines.rs @@ -0,0 +1,19 @@ +/// P5's own compute pipelines, created from the neighbourhood module. +#[derive(Clone)] +pub(in super::super) struct Pipelines { + /// Anisotropic Kuwahara's structure tensor: each texel's ellipse frame. + pub(super) kuwahara_frame: wgpu::ComputePipeline, + /// Color Match's mean: each row's sums, then the rows' total. + pub(super) color_match_rows: wgpu::ComputePipeline, + pub(super) color_match_total: wgpu::ComputePipeline, +} + +impl Pipelines { + pub(in super::super) fn new(pipeline: &dyn Fn(&'static str) -> wgpu::ComputePipeline) -> Self { + Self { + kuwahara_frame: pipeline("gather_kuwahara_frame"), + color_match_rows: pipeline("gather_color_match_rows"), + color_match_total: pipeline("gather_color_match_total"), + } + } +} diff --git a/crates/render/src/gpu_quick_mask.rs b/crates/render/src/gpu_quick_mask.rs index f85843fd..f4d08662 100644 --- a/crates/render/src/gpu_quick_mask.rs +++ b/crates/render/src/gpu_quick_mask.rs @@ -4,123 +4,13 @@ use std::collections::BTreeMap; use texturecraft_texel::{TILE, TileImage}; use wgpu::util::DeviceExt; -pub enum QuickMaskAlpha { - Gpu(wgpu::TextureView), - Cpu(TileImage), -} +mod quick_mask_alpha; +mod quick_mask_gpu; +mod quick_mask_overlay; -pub struct QuickMaskOverlay { - pub mask: TileImage, - pub inverted: bool, - pub stroke: Option<(QuickMaskAlpha, f32, bool)>, -} - -pub(crate) struct QuickMaskGpu { - pub(crate) pipeline: wgpu::RenderPipeline, - empty: wgpu::TextureView, - coverage: BTreeMap, -} - -impl QuickMaskGpu { - pub(crate) fn new(device: &wgpu::Device) -> Self { - let texture_entry = |binding, sample_type| wgpu::BindGroupLayoutEntry { - binding, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, - count: None, - }; - let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: Some("tc_quick_mask"), - entries: &[ - texture_entry(0, wgpu::TextureSampleType::Float { filterable: false }), - texture_entry(1, wgpu::TextureSampleType::Uint), - texture_entry(2, wgpu::TextureSampleType::Uint), - wgpu::BindGroupLayoutEntry { - binding: 3, - visibility: wgpu::ShaderStages::FRAGMENT, - ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, - count: None, - }, - ], - }); - let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: Some("tc_quick_mask"), - bind_group_layouts: &[Some(&bindings)], - immediate_size: 0, - }); - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("tc_quick_mask"), - source: wgpu::ShaderSource::Wgsl(include_str!("shaders/quick_mask.wgsl").into()), - }); - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("tc_quick_mask"), - layout: Some(&layout), - vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, - fragment: Some(wgpu::FragmentState { - module: &module, - entry_point: Some("fs"), - compilation_options: Default::default(), - targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())], - }), - primitive: Default::default(), - depth_stencil: None, - multisample: Default::default(), - multiview_mask: None, - cache: None, - }); - Self { pipeline, empty: coverage_texture(device, 1).create_view(&Default::default()), coverage: BTreeMap::new() } - } - - pub(crate) fn clear_coverage(&mut self) { - self.coverage.clear(); - } - - pub(crate) fn retain_texture_sets(&mut self, count: usize) { - self.coverage.retain(|&ts, _| ts < count); - } - - pub(crate) fn bindings( - &mut self, - (device, queue): (&wgpu::Device, &wgpu::Queue), - ts: usize, - size: u32, - base: &wgpu::TextureView, - overlay: &QuickMaskOverlay, - ) -> wgpu::BindGroup { - let mask = &overlay.mask; - let committed = if mask.allocated_count() == 0 { - self.coverage.remove(&ts); - self.empty.clone() - } else { - if self.coverage.get(&ts).is_none_or(|(previous, _)| !previous.same_tiles(mask)) { - self.coverage.remove(&ts); - self.coverage.insert(ts, (mask.clone(), upload_coverage(device, queue, size, mask))); - } - self.coverage.get(&ts).map_or_else(|| self.empty.clone(), |(_, view)| view.clone()) - }; - let (stroke, opacity, erase) = match &overlay.stroke { - Some((QuickMaskAlpha::Gpu(view), opacity, erase)) => (view.clone(), *opacity, *erase), - Some((QuickMaskAlpha::Cpu(mask), opacity, erase)) => (upload_coverage(device, queue, size, mask), *opacity, *erase), - None => (self.empty.clone(), 0.0, false), - }; - let params = [size, u32::from(overlay.inverted), u32::from(erase), opacity.to_bits()]; - let uniforms = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_quick_mask_params"), - contents: bytemuck::cast_slice(¶ms), - usage: wgpu::BufferUsages::UNIFORM, - }); - device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_quick_mask"), - layout: &self.pipeline.get_bind_group_layout(0), - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(base) }, - wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&committed) }, - wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&stroke) }, - wgpu::BindGroupEntry { binding: 3, resource: uniforms.as_entire_binding() }, - ], - }) - } -} +pub use quick_mask_alpha::QuickMaskAlpha; +pub(crate) use quick_mask_gpu::QuickMaskGpu; +pub use quick_mask_overlay::QuickMaskOverlay; fn coverage_texture(device: &wgpu::Device, size: u32) -> wgpu::Texture { device.create_texture(&wgpu::TextureDescriptor { @@ -141,7 +31,8 @@ fn upload_coverage(device: &wgpu::Device, queue: &wgpu::Queue, size: u32, mask: let mut coverage = vec![0u16; (size * size) as usize]; for (tx, ty) in mask.allocated() { let Some(tile) = mask.tile(tx, ty) else { continue }; - // Only visit samples in allocated tiles. Their source position matches the CPU overlay. + + // Only visit samples in allocated tiles. Their source position matches the CPU overlay let first_x = (tx * TILE * size).div_ceil(width); let last_x = (((tx + 1) * TILE).min(width) * size).div_ceil(width); let first_y = (ty * TILE * size).div_ceil(height); diff --git a/crates/render/src/gpu_quick_mask/quick_mask_alpha.rs b/crates/render/src/gpu_quick_mask/quick_mask_alpha.rs new file mode 100644 index 00000000..0d7dc7d6 --- /dev/null +++ b/crates/render/src/gpu_quick_mask/quick_mask_alpha.rs @@ -0,0 +1,6 @@ +use super::TileImage; + +pub enum QuickMaskAlpha { + Gpu(wgpu::TextureView), + Cpu(TileImage), +} diff --git a/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs b/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs new file mode 100644 index 00000000..bcdb01f2 --- /dev/null +++ b/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs @@ -0,0 +1,108 @@ +use super::{BTreeMap, DeviceExt, QuickMaskAlpha, QuickMaskOverlay, TileImage, coverage_texture, upload_coverage}; + +pub(crate) struct QuickMaskGpu { + pub(crate) pipeline: wgpu::RenderPipeline, + pub(super) empty: wgpu::TextureView, + pub(super) coverage: BTreeMap, +} + +impl QuickMaskGpu { + pub(crate) fn new(device: &wgpu::Device) -> Self { + let texture_entry = |binding, sample_type| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { sample_type, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }, + count: None, + }; + let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tc_quick_mask"), + entries: &[ + texture_entry(0, wgpu::TextureSampleType::Float { filterable: false }), + texture_entry(1, wgpu::TextureSampleType::Uint), + texture_entry(2, wgpu::TextureSampleType::Uint), + wgpu::BindGroupLayoutEntry { + binding: 3, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_quick_mask"), + bind_group_layouts: &[Some(&bindings)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_quick_mask"), + source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/quick_mask.wgsl").into()), + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("tc_quick_mask"), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())], + }), + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + multiview_mask: None, + cache: None, + }); + Self { pipeline, empty: coverage_texture(device, 1).create_view(&Default::default()), coverage: BTreeMap::new() } + } + + pub(crate) fn clear_coverage(&mut self) { + self.coverage.clear(); + } + + pub(crate) fn retain_texture_sets(&mut self, count: usize) { + self.coverage.retain(|&ts, _| ts < count); + } + + pub(crate) fn bindings( + &mut self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + ts: usize, + size: u32, + base: &wgpu::TextureView, + overlay: &QuickMaskOverlay, + ) -> wgpu::BindGroup { + let mask = &overlay.mask; + let committed = if mask.allocated_count() == 0 { + self.coverage.remove(&ts); + self.empty.clone() + } else { + if self.coverage.get(&ts).is_none_or(|(previous, _)| !previous.same_tiles(mask)) { + self.coverage.remove(&ts); + self.coverage.insert(ts, (mask.clone(), upload_coverage(device, queue, size, mask))); + } + self.coverage.get(&ts).map_or_else(|| self.empty.clone(), |(_, view)| view.clone()) + }; + let (stroke, opacity, erase) = match &overlay.stroke { + Some((QuickMaskAlpha::Gpu(view), opacity, erase)) => (view.clone(), *opacity, *erase), + Some((QuickMaskAlpha::Cpu(mask), opacity, erase)) => (upload_coverage(device, queue, size, mask), *opacity, *erase), + None => (self.empty.clone(), 0.0, false), + }; + let params = [size, u32::from(overlay.inverted), u32::from(erase), opacity.to_bits()]; + let uniforms = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_quick_mask_params"), + contents: bytemuck::cast_slice(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_quick_mask"), + layout: &self.pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(base) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&committed) }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&stroke) }, + wgpu::BindGroupEntry { binding: 3, resource: uniforms.as_entire_binding() }, + ], + }) + } +} diff --git a/crates/render/src/gpu_quick_mask/quick_mask_overlay.rs b/crates/render/src/gpu_quick_mask/quick_mask_overlay.rs new file mode 100644 index 00000000..d5412b7b --- /dev/null +++ b/crates/render/src/gpu_quick_mask/quick_mask_overlay.rs @@ -0,0 +1,7 @@ +use super::{QuickMaskAlpha, TileImage}; + +pub struct QuickMaskOverlay { + pub mask: TileImage, + pub inverted: bool, + pub stroke: Option<(QuickMaskAlpha, f32, bool)>, +} diff --git a/crates/render/src/gpu_resize.rs b/crates/render/src/gpu_resize.rs index 4ae65498..776ad0d2 100644 --- a/crates/render/src/gpu_resize.rs +++ b/crates/render/src/gpu_resize.rs @@ -12,174 +12,9 @@ const INPUT_BYTES: u64 = 32 << 20; /// Keeps both center mapping and Q16 weight rounding within a WGSL u32. const MAX_INTEGER_RESIZE_SIDE: u32 = 32_768; -pub struct PaintResampler { - device: wgpu::Device, - queue: wgpu::Queue, - pipeline: wgpu::ComputePipeline, - input: Option, - result: Option, - readback: Option, -} +mod paint_resampler; -impl PaintResampler { - pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Result { - let pipeline = crate::gpu_trace::scoped(device, "paint resize shader", || { - let module = device.create_shader_module(wgpu::include_wgsl!("shaders/paint_resize.wgsl")); - device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("tc_paint_resize"), - layout: None, - module: &module, - entry_point: Some("resize"), - compilation_options: Default::default(), - cache: None, - }) - })?; - Ok(Self { device: device.clone(), queue: queue.clone(), pipeline, input: None, result: None, readback: None }) - } - - pub fn resize(&mut self, src: &TileImage, size: (u32, u32), empty: &[u16], cancelled: impl Fn() -> bool) -> Result { - if (src.width(), src.height()) == size { - return Ok(src.clone()); - } - let size = [size.0.max(1), size.1.max(1)]; - if src.width().max(src.height()).max(size[0]).max(size[1]) > MAX_INTEGER_RESIZE_SIDE { - return Err("Paint resize dimensions exceed the GPU integer resampling limit".into()); - } - let mut out = TileImage::new(size[0], size[1], src.comps()); - if src.allocated_count() == 0 { - return Ok(out); - } - if !matches!(src.comps(), 2 | 4) { - return Err("paint resize needs two or four components".into()); - } - - let limits = self.device.limits(); - let limit = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); - let tile_bytes = (TILE_AREA * src.comps() * 2) as u64; - let tiles_per_job = (limit.min(OUTPUT_BYTES) / tile_bytes).max(1) as u32; - let columns = out.tiles_x().min(tiles_per_job.isqrt().max(1)); - let rows = (tiles_per_job / columns).max(1); - let mut work = Vec::new(); - for y in (0..out.tiles_y()).step_by(rows as usize) { - for x in (0..out.tiles_x()).step_by(columns as usize) { - work.push(TileWindow { origin: [x, y], size: [columns.min(out.tiles_x() - x), rows.min(out.tiles_y() - y)] }); - } - } - let mut packed = Vec::new(); - while let Some(dest) = work.pop() { - if cancelled() { - return Err("Paint resize was cancelled".into()); - } - let (lo, hi) = source_footprint(src, size, dest); - if !src.has_allocated_texels(lo, hi) { - continue; - } - let source = TileWindow::covering(lo, hi, [src.width(), src.height()]); - if let Some(words) = source.words(std::slice::from_ref(src), (limit.min(INPUT_BYTES) / 4) as usize) { - source.pack(std::slice::from_ref(src), words, &mut packed); - self.resize_block(src, &mut out, source, dest, empty, &packed)?; - continue; - } - let axis = usize::from(dest.size[1] >= dest.size[0]); - let half = dest.size[axis] / 2; - if half == 0 { - return Err("source tiles for one resize block exceed the GPU upload budget".into()); - } - let (mut first, mut second) = (dest, dest); - first.size[axis] = half; - second.origin[axis] += half; - second.size[axis] -= half; - work.extend([second, first]); - } - Ok(out) - } - - fn resize_block( - &mut self, - src: &TileImage, - out: &mut TileImage, - source: TileWindow, - dest: TileWindow, - empty: &[u16], - packed: &[u32], - ) -> Result<(), String> { - let words_per_pixel = (src.comps() / 2) as u32; - let row_bytes = u64::from(dest.size[0] * dest.size[1]) * (TILE_AREA * src.comps() * 2) as u64; - let (device, queue) = (&self.device, &self.queue); - let submission = crate::gpu_trace::scoped(device, "GPU paint resize", || { - let input = - buffer(device, &mut self.input, "tc_resize_input", (packed.len() * 4) as u64, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST); - let result = buffer(device, &mut self.result, "tc_resize_result", row_bytes, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC); - let readback = buffer(device, &mut self.readback, "tc_resize_readback", row_bytes, wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST); - let cleared = |i: usize| u32::from(empty.get(i).copied().unwrap_or(0)); - let params = [ - src.width(), - src.height(), - out.width(), - out.height(), - source.origin[0], - source.origin[1], - source.size[0], - source.size[1], - dest.origin[0], - dest.origin[1], - dest.size[0], - dest.size[1], - words_per_pixel, - cleared(0) | (cleared(1) << 16), - cleared(2) | (cleared(3) << 16), - 0, - ]; - let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: Some("tc_resize_params"), - contents: bytemuck::cast_slice(¶ms), - usage: wgpu::BufferUsages::UNIFORM, - }); - queue.write_buffer(&input, 0, bytemuck::cast_slice(packed)); - let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_resize_inputs"), - layout: &self.pipeline.get_bind_group_layout(0), - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 2, resource: result.as_entire_binding() }, - ], - }); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_paint_resize") }); - { - let mut pass = encoder.begin_compute_pass(&Default::default()); - pass.set_pipeline(&self.pipeline); - pass.set_bind_group(0, &bindings, &[]); - pass.dispatch_workgroups(dest.size[0] * (TILE / 8), dest.size[1] * (TILE / 8), 1); - } - encoder.copy_buffer_to_buffer(&result, 0, &readback, 0, row_bytes); - (queue.submit([encoder.finish()]), readback) - })?; - let slice = submission.1.slice(..row_bytes); - let (sender, receiver) = std::sync::mpsc::channel(); - slice.map_async(wgpu::MapMode::Read, move |result| { - let _ = sender.send(result); - }); - device.poll(wgpu::PollType::Wait { submission_index: Some(submission.0), timeout: None }).map_err(|e| e.to_string())?; - receiver.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; - let mapped = (|| { - let data = slice.get_mapped_range().map_err(|e| e.to_string())?; - let samples = bytemuck::try_cast_slice::(&data).map_err(|e| e.to_string())?; - for (slot, tile_data) in samples.chunks_exact(TILE_AREA * src.comps()).enumerate() { - let x = dest.origin[0] + slot as u32 % dest.size[0]; - let y = dest.origin[1] + slot as u32 / dest.size[0]; - let tile = TileWindow { origin: [x, y], size: [1, 1] }; - let (lo, hi) = source_footprint(src, [out.width(), out.height()], tile); - if src.has_allocated_texels(lo, hi) { - out.set_tile(x, y, Some(Arc::new(tile_data.iter().copied().map(u16::from_le).collect()))); - } - } - Ok(()) - })(); - submission.1.unmap(); - mapped - } -} +pub use paint_resampler::PaintResampler; fn source_footprint(src: &TileImage, size: [u32; 2], dest: TileWindow) -> ([u32; 2], [u32; 2]) { src.resize_footprint(size, std::array::from_fn(|axis| dest.origin[axis]..dest.origin[axis] + dest.size[axis])) @@ -189,6 +24,7 @@ fn buffer(device: &wgpu::Device, slot: &mut Option, label: &str, s if let Some(buffer) = slot.as_ref().filter(|buffer| buffer.size() >= size) { return buffer.clone(); } + let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false }); *slot = Some(buffer.clone()); buffer diff --git a/crates/render/src/gpu_resize/paint_resampler.rs b/crates/render/src/gpu_resize/paint_resampler.rs new file mode 100644 index 00000000..1493e8c6 --- /dev/null +++ b/crates/render/src/gpu_resize/paint_resampler.rs @@ -0,0 +1,177 @@ +use super::{Arc, DeviceExt, INPUT_BYTES, MAX_INTEGER_RESIZE_SIDE, OUTPUT_BYTES, TILE, TILE_AREA, TileImage, TileWindow, buffer, source_footprint}; + +pub struct PaintResampler { + pub(super) device: wgpu::Device, + pub(super) queue: wgpu::Queue, + pub(super) pipeline: wgpu::ComputePipeline, + pub(super) input: Option, + pub(super) result: Option, + pub(super) readback: Option, +} + +impl PaintResampler { + pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Result { + let pipeline = crate::gpu_trace::scoped(device, "paint resize shader", || { + let module = device.create_shader_module(wgpu::include_wgsl!("../shaders/paint_resize.wgsl")); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("tc_paint_resize"), + layout: None, + module: &module, + entry_point: Some("resize"), + compilation_options: Default::default(), + cache: None, + }) + })?; + Ok(Self { device: device.clone(), queue: queue.clone(), pipeline, input: None, result: None, readback: None }) + } + + pub fn resize(&mut self, src: &TileImage, size: (u32, u32), empty: &[u16], cancelled: impl Fn() -> bool) -> Result { + if (src.width(), src.height()) == size { + return Ok(src.clone()); + } + + let size = [size.0.max(1), size.1.max(1)]; + if src.width().max(src.height()).max(size[0]).max(size[1]) > MAX_INTEGER_RESIZE_SIDE { + return Err("Paint resize dimensions exceed the GPU integer resampling limit".into()); + } + + let mut out = TileImage::new(size[0], size[1], src.comps()); + if src.allocated_count() == 0 { + return Ok(out); + } + + if !matches!(src.comps(), 2 | 4) { + return Err("paint resize needs two or four components".into()); + } + + let limits = self.device.limits(); + let limit = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); + let tile_bytes = (TILE_AREA * src.comps() * 2) as u64; + let tiles_per_job = (limit.min(OUTPUT_BYTES) / tile_bytes).max(1) as u32; + let columns = out.tiles_x().min(tiles_per_job.isqrt().max(1)); + let rows = (tiles_per_job / columns).max(1); + let mut work = Vec::new(); + for y in (0..out.tiles_y()).step_by(rows as usize) { + for x in (0..out.tiles_x()).step_by(columns as usize) { + work.push(TileWindow { origin: [x, y], size: [columns.min(out.tiles_x() - x), rows.min(out.tiles_y() - y)] }); + } + } + let mut packed = Vec::new(); + while let Some(dest) = work.pop() { + if cancelled() { + return Err("Paint resize was cancelled".into()); + } + + let (lo, hi) = source_footprint(src, size, dest); + if !src.has_allocated_texels(lo, hi) { + continue; + } + + let source = TileWindow::covering(lo, hi, [src.width(), src.height()]); + if let Some(words) = source.words(std::slice::from_ref(src), (limit.min(INPUT_BYTES) / 4) as usize) { + source.pack(std::slice::from_ref(src), words, &mut packed); + self.resize_block(src, &mut out, source, dest, empty, &packed)?; + continue; + } + + let axis = usize::from(dest.size[1] >= dest.size[0]); + let half = dest.size[axis] / 2; + if half == 0 { + return Err("source tiles for one resize block exceed the GPU upload budget".into()); + } + + let (mut first, mut second) = (dest, dest); + first.size[axis] = half; + second.origin[axis] += half; + second.size[axis] -= half; + work.extend([second, first]); + } + Ok(out) + } + + pub(super) fn resize_block( + &mut self, + src: &TileImage, + out: &mut TileImage, + source: TileWindow, + dest: TileWindow, + empty: &[u16], + packed: &[u32], + ) -> Result<(), String> { + let words_per_pixel = (src.comps() / 2) as u32; + let row_bytes = u64::from(dest.size[0] * dest.size[1]) * (TILE_AREA * src.comps() * 2) as u64; + let (device, queue) = (&self.device, &self.queue); + let submission = crate::gpu_trace::scoped(device, "GPU paint resize", || { + let input = + buffer(device, &mut self.input, "tc_resize_input", (packed.len() * 4) as u64, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST); + let result = buffer(device, &mut self.result, "tc_resize_result", row_bytes, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC); + let readback = buffer(device, &mut self.readback, "tc_resize_readback", row_bytes, wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST); + let cleared = |i: usize| u32::from(empty.get(i).copied().unwrap_or(0)); + let params = [ + src.width(), + src.height(), + out.width(), + out.height(), + source.origin[0], + source.origin[1], + source.size[0], + source.size[1], + dest.origin[0], + dest.origin[1], + dest.size[0], + dest.size[1], + words_per_pixel, + cleared(0) | (cleared(1) << 16), + cleared(2) | (cleared(3) << 16), + 0, + ]; + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_resize_params"), + contents: bytemuck::cast_slice(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + queue.write_buffer(&input, 0, bytemuck::cast_slice(packed)); + let bindings = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_resize_inputs"), + layout: &self.pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: input.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: result.as_entire_binding() }, + ], + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_paint_resize") }); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &bindings, &[]); + pass.dispatch_workgroups(dest.size[0] * (TILE / 8), dest.size[1] * (TILE / 8), 1); + } + encoder.copy_buffer_to_buffer(&result, 0, &readback, 0, row_bytes); + (queue.submit([encoder.finish()]), readback) + })?; + let slice = submission.1.slice(..row_bytes); + let (sender, receiver) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = sender.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(submission.0), timeout: None }).map_err(|e| e.to_string())?; + receiver.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + let mapped = (|| { + let data = slice.get_mapped_range().map_err(|e| e.to_string())?; + let samples = bytemuck::try_cast_slice::(&data).map_err(|e| e.to_string())?; + for (slot, tile_data) in samples.chunks_exact(TILE_AREA * src.comps()).enumerate() { + let x = dest.origin[0] + slot as u32 % dest.size[0]; + let y = dest.origin[1] + slot as u32 / dest.size[0]; + let tile = TileWindow { origin: [x, y], size: [1, 1] }; + let (lo, hi) = source_footprint(src, [out.width(), out.height()], tile); + if src.has_allocated_texels(lo, hi) { + out.set_tile(x, y, Some(Arc::new(tile_data.iter().copied().map(u16::from_le).collect()))); + } + } + Ok(()) + })(); + submission.1.unmap(); + mapped + } +} diff --git a/crates/render/src/gpu_stencil.rs b/crates/render/src/gpu_stencil.rs index 9c1c97ae..3f49cb11 100644 --- a/crates/render/src/gpu_stencil.rs +++ b/crates/render/src/gpu_stencil.rs @@ -7,15 +7,10 @@ use texturecraft_compose::{ImageRes, Stencil}; use texturecraft_geom::glam::{Mat4, Vec3}; use wgpu::util::DeviceExt; -#[repr(C)] -#[derive(Clone, Copy, Pod, Zeroable)] -struct Placement { - view_proj: [[f32; 4]; 4], - center_half: [f32; 4], - rotation_flags: [f32; 4], -} +mod placement; + +use placement::Placement; -/// GPU resources for an immutable projection image and its placement at stroke start. #[derive(Clone, Debug)] pub struct GpuStencil { pub(crate) image: wgpu::TextureView, @@ -41,8 +36,8 @@ impl GpuStencil { let (sin, cos) = (-stencil.rotation).sin_cos(); let [x, y] = stencil.center; let [w, h] = stencil.half; - // The surface buffer contains (world - center) / radius. Fold the inverse - // into the captured camera once, so each GPU sample can use that buffer. + + // Fold mesh normalization into the camera once per projection let world = Mat4::from_scale_rotation_translation(Vec3::splat(radius), texturecraft_geom::glam::Quat::IDENTITY, center); let placement = Placement { view_proj: (stencil.view_proj * world).to_cols_array_2d(), @@ -73,6 +68,7 @@ pub(crate) fn upload_image(device: &wgpu::Device, queue: &wgpu::Queue, image: &I if width == 0 || height == 0 || width.max(height) > limit { return Err("The projection image exceeds the adapter's texture layout limits.".into()); } + let texture = image_texture(device, width, height); for top in (0..height).step_by(64) { let rows = (height - top).min(64); @@ -82,7 +78,7 @@ pub(crate) fn upload_image(device: &wgpu::Device, queue: &wgpu::Queue, image: &I let rgba = if let Some(rgba) = image.rgba.get(first..end) { rgba } else { - // Missing texels have the same transparent value as ImageRes::sample. + // Missing texels have the same transparent value as ImageRes::sample let mut pixels = vec![[0.0; 4]; end - first]; if let Some(rest) = image.rgba.get(first..) { pixels[..rest.len()].copy_from_slice(rest); diff --git a/crates/render/src/gpu_stencil/placement.rs b/crates/render/src/gpu_stencil/placement.rs new file mode 100644 index 00000000..a074374b --- /dev/null +++ b/crates/render/src/gpu_stencil/placement.rs @@ -0,0 +1,9 @@ +use super::{Pod, Zeroable}; + +#[repr(C)] +#[derive(Clone, Copy, Pod, Zeroable)] +pub(super) struct Placement { + pub(super) view_proj: [[f32; 4]; 4], + pub(super) center_half: [f32; 4], + pub(super) rotation_flags: [f32; 4], +} diff --git a/crates/render/src/gpu_tile_pattern.rs b/crates/render/src/gpu_tile_pattern.rs index d256f723..51288a55 100644 --- a/crates/render/src/gpu_tile_pattern.rs +++ b/crates/render/src/gpu_tile_pattern.rs @@ -9,400 +9,45 @@ use texturecraft_core::{TileBlending, TileGenerator, TileShape}; pub(crate) const TILE_GENERATOR_OPCODE: u32 = 80; const NO_IMAGE: u32 = u32::MAX; -// Keep uploads banded even for an image that fills an entire atlas slice. + +// Keep uploads banded even for an image that fills an entire atlas slice const IMAGE_ROWS: usize = 64; -// Put a bound on packing overhead as well as authored pixels. + +// Put a bound on packing overhead as well as authored pixels const MAX_ATLAS_BYTES: u64 = 256 << 20; const MAX_COLOR_ATLAS_BYTES: u64 = 1 << 30; const MAX_PENDING_UPLOAD_BYTES: u64 = 64 << 20; -#[derive(Debug, Default)] -pub(crate) struct TilePatterns { - patterns: Vec, - images: BTreeMap>, -} +mod atlas_mips; +mod image_region; +mod raw_plane; +mod rgba_encoding; +mod rgba_level; +mod rgba_region; +mod tile_image_atlas; +mod tile_pattern; +mod tile_patterns; -#[derive(Debug)] -struct TilePattern { - settings: TileGenerator, - seed: u32, - layout: TileLayout, - work_per_sample: u64, -} - -impl TilePatterns { - pub(crate) fn register(&mut self, settings: TileGenerator, seed: u32) -> usize { - if let Some(index) = self.patterns.iter().position(|p| p.seed == seed && p.settings == settings) { - return index; - } - let layout = prepare_tile_layout(&settings, seed); - let work_per_sample = placement_work(&layout); - let index = self.patterns.len(); - self.patterns.push(TilePattern { settings, seed, layout, work_per_sample }); - index - } - - pub(crate) fn is_empty(&self) -> bool { - self.patterns.is_empty() - } - - pub(crate) fn work_per_sample(&self, index: usize) -> Option { - self.patterns.get(index).map(|pattern| pattern.work_per_sample) - } - - pub(crate) fn set_images(&mut self, images: &ImageStore) { - self.images = self - .patterns - .iter() - .flat_map(|pattern| { - let settings = &pattern.settings; - let count = if settings.shape == TileShape::Image { settings.inputs.len().min(TileGenerator::MAX_INPUTS) } else { 0 }; - settings.inputs[..count].iter().chain(settings.background_image.iter()) - }) - .filter_map(|name| images.get(name).map(|image| (name.clone(), image.clone()))) - .collect(); - } - - pub(crate) fn image_sources(&self) -> impl Iterator> { - self.images.values() - } - - /// Append image descriptors and prepared shapes to the compositor's packed parameter buffer. - /// All references are word offsets from its beginning, following the sRGB lookup. - pub(crate) fn append_words(&self, words: &mut Vec, atlas: Option<&TileImageAtlas>) -> Vec { - let mut images = BTreeMap::new(); - if let Some(atlas) = atlas { - for (name, region) in self.images.keys().zip(&atlas.regions) { - images.insert(name, words.len() as u32); - words.extend([region.origin[0], region.origin[1], region.origin[2], region.size[0], region.size[1]]); - } - } - let image = |name: &String| images.get(name).copied().unwrap_or(NO_IMAGE); - self.patterns - .iter() - .map(|pattern| { - let settings = &pattern.settings; - let layout = &pattern.layout; - let shift_offset = words.len() as u32; - words.extend(layout.line_shifts.iter().map(|x| x.to_bits())); - let placement_offset = words.len() as u32; - for placement in &layout.placements { - let Some(tile) = placement else { - words.extend([0; 11]); - continue; - }; - let input = tile.input.and_then(|index| settings.inputs.get(index)).map_or(NO_IMAGE, image); - let flags = tile.quarter_turns | (u32::from(tile.mirrors[0]) << 2) | (u32::from(tile.mirrors[1]) << 3); - words.extend([ - tile.center.x.to_bits(), - tile.center.y.to_bits(), - tile.size.x.to_bits(), - tile.size.y.to_bits(), - tile.radius.x.to_bits(), - tile.radius.y.to_bits(), - tile.rotation[0].to_bits(), - tile.rotation[1].to_bits(), - flags, - input, - tile.luminance.to_bits(), - ]); - } - - let angle = settings.shape_angle / 360.0 * std::f32::consts::TAU; - let (sin, cos) = angle.sin_cos(); - let low = (1.0 - 2.0 * settings.position).clamp(0.0, 1.0); - let high = (2.0 - 2.0 * settings.position).clamp(0.0, 1.0); - let middle = (low + high) * 0.5; - let half = (high - low) * 0.5 * (1.0 - settings.contrast); - let shape = TileShape::ALL.iter().position(|&shape| shape == settings.shape).unwrap_or_default() as u32; - let blending = match settings.blending { - TileBlending::Max => 0, - TileBlending::Add => 1, - TileBlending::AddSub => 2, - }; - let offset = words.len() as u32; - words.extend([ - layout.amount[0], - layout.amount[1], - layout.reach.x.to_bits(), - layout.reach.y.to_bits(), - u32::from(settings.vertical_offset), - shift_offset, - placement_offset, - shape, - settings.shape_resolution[0], - settings.shape_resolution[1], - settings.specific.to_bits(), - settings.shape_tiling, - (settings.shape_size[0] * settings.shape_scale).to_bits(), - (settings.shape_size[1] * settings.shape_scale).to_bits(), - sin.to_bits(), - cos.to_bits(), - u32::from(settings.shape_diagonal), - settings.background.to_bits(), - settings.background_image.as_ref().map_or(NO_IMAGE, image), - settings.color.to_bits(), - blending, - settings.opacity.to_bits(), - middle.to_bits(), - half.to_bits(), - settings.global_offset[0].to_bits(), - settings.global_offset[1].to_bits(), - ]); - offset - }) - .collect() - } -} +pub(crate) use atlas_mips::AtlasMips; +use image_region::ImageRegion; +pub(crate) use raw_plane::RawPlane; +use rgba_encoding::RgbaEncoding; +use rgba_level::RgbaLevel; +use rgba_region::RgbaRegion; +pub(crate) use tile_image_atlas::TileImageAtlas; +use tile_pattern::TilePattern; +pub(crate) use tile_patterns::TilePatterns; /// Upper bound on cell visits and periodic copies per sample in tile_generator.wgsl. fn placement_work(layout: &TileLayout) -> u64 { let cells = |reach: f32, count: u32| ((reach * 2.0).ceil() + 2.0).min(count as f32) as u64; - // The shader checks offsets −3 through 3 on each axis for a wrapped shape. + + // The shader checks offsets −3 through 3 on each axis for a wrapped shape let copies = |radius: f32| ((radius * 2.0).floor() + 1.0).clamp(1.0, 7.0) as u64; let wrapped_copies = layout.placements.iter().flatten().map(|tile| copies(tile.radius.x) * copies(tile.radius.y)).max().unwrap_or(1); cells(layout.reach.x, layout.amount[0]) * cells(layout.reach.y, layout.amount[1]) * wrapped_copies } -#[derive(Clone, Copy, Default)] -struct ImageRegion { - origin: [u32; 3], - size: [u32; 2], -} - -#[derive(Clone, Copy)] -enum RgbaEncoding { - Bytes = 1, - Shorts = 2, - Floats = 4, -} - -impl RgbaEncoding { - fn for_texels(rgba: &[[f32; 4]]) -> Self { - let exact = |v: f32, scale: f32| { - let integer = (v * scale).round(); - integer >= 0.0 && integer <= scale && (v == integer / scale || v == integer * (1.0 / scale)) - }; - if rgba.par_iter().all(|pixel| pixel.iter().all(|&v| exact(v, 255.0))) { - Self::Bytes - } else if rgba.par_iter().all(|pixel| pixel.iter().all(|&v| exact(v, 65535.0))) { - Self::Shorts - } else { - Self::Floats - } - } - - fn word(self, [r, g, b, a]: [f32; 4], lane: usize) -> u32 { - match self { - Self::Bytes => { - let byte = |v: f32| (v * 255.0).round() as u8; - u32::from_le_bytes([byte(r), byte(g), byte(b), byte(a)]) - } - Self::Shorts => { - let short = |v: f32| (v * 65535.0).round() as u32; - let [low, high] = if lane == 0 { [r, g] } else { [b, a] }; - short(low) | (short(high) << 16) - } - Self::Floats => [r, g, b, a][lane].to_bits(), - } - } -} - -struct RgbaRegion { - encoding: RgbaEncoding, - planes: Vec, - /// The halved levels held besides the image, level 1 first: size, encoding and planes each - levels: Vec, -} - -struct RgbaLevel { - size: [u32; 2], - encoding: RgbaEncoding, - planes: Vec, -} - -/// Which halved levels of a colour image the atlas holds besides the image. P1 (fill sampling) -/// chooses per image through `MaterialImages::atlas_images`; `None` uploads exactly what the -/// atlas held before. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub(crate) enum AtlasMips { - #[default] - None, - /// `ImageRes::mip_chain`: the levels as stored (Bilinear HQ of scalar and alpha reads). - Stored, - /// `ImageRes::linear_mip_chain`: RGB linear, alpha unchanged (an sRGB image's colour read). - LinearColor, -} - -/// One exact-f32 plane of the atlas (P1: a projector depth grid), row by row. The atlas keeps a -/// weak pointer to `texels`, so a plane rebuilt for every program rebuilds the atlas. -#[derive(Clone, Debug)] -pub(crate) struct RawPlane { - pub(crate) size: [u32; 2], - pub(crate) texels: Arc>, -} - -pub(crate) struct TileImageAtlas { - images: Vec>, - regions: Vec, - color: Vec, - color_mips: Vec, - raw: Vec<(Weak>, ImageRegion)>, - pub(crate) view: wgpu::TextureView, -} - -impl TileImageAtlas { - pub(crate) fn matches(&self, gray: &[&Arc], color: &[(&Arc, AtlasMips)], raw: &[RawPlane]) -> bool { - self.regions.len() == gray.len() - && self.color.len() == color.len() - && self.images.iter().zip(gray.iter().copied().chain(color.iter().map(|(image, _)| *image))).all(|(old, new)| old.ptr_eq(&Arc::downgrade(new))) - && self.color_mips.iter().eq(color.iter().map(|(_, mips)| mips)) - && self.raw.len() == raw.len() - && self.raw.iter().zip(raw).all(|((old, region), new)| old.ptr_eq(&Arc::downgrade(&new.texels)) && region.size == new.size) - } - - pub(crate) fn is_live(&self) -> bool { - self.images.iter().all(|image| image.strong_count() != 0) && self.raw.iter().all(|(texels, _)| texels.strong_count() != 0) - } - - pub(crate) fn empty_view(device: &wgpu::Device) -> wgpu::TextureView { - atlas_texture(device, 1, 1, 2).create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }) - } - - pub(crate) fn append_rgba(&self, words: &mut Vec, color_index: usize, srgb: bool) -> u32 { - let region = &self.color[color_index]; - let offset = words.len() as u32; - let [width, height] = region.planes[0].size; - // Bit 9: halved levels follow the planes; without levels the words are exactly as before - let flags = region.encoding as u32 | (u32::from(srgb) << 8) | (u32::from(!region.levels.is_empty()) << 9); - words.extend([width, height, flags]); - for plane in ®ion.planes { - words.extend(plane.origin); - } - - // The level count, each level's word offset (so a level is one read away), then per level its width, height, encoding and plane origins - if !region.levels.is_empty() { - words.push(region.levels.len() as u32); - let table = words.len(); - words.resize(table + region.levels.len(), 0); - for (index, level) in region.levels.iter().enumerate() { - words[table + index] = words.len() as u32; - words.extend([level.size[0], level.size[1], level.encoding as u32]); - for plane in &level.planes { - words.extend(plane.origin); - } - } - } - offset - } - - /// The words of raw plane `index`: width, height and its origin (x, y, layer), read as f32 bits. - pub(crate) fn append_raw(&self, words: &mut Vec, index: usize) -> u32 { - let offset = words.len() as u32; - let (_, region) = &self.raw[index]; - words.extend([region.size[0], region.size[1]]); - words.extend(region.origin); - offset - } - - /// Upload `gray` (one plane each), `color` (one to four planes each by encoding, plus the - /// chosen halved levels) and `raw` (one exact-f32 plane each) into one array texture. - pub(crate) fn new( - device: &wgpu::Device, - queue: &wgpu::Queue, - gray: &[&Arc], - color: &[(&Arc, AtlasMips)], - raw: &[RawPlane], - ) -> Result { - let limits = device.limits(); - let size = |image: &Arc| [image.width.max(1), image.height.max(1)]; - // Per colour image: the image, then each level, with its encoding - let color_parts: Vec> = color - .iter() - .map(|&(image, mips)| { - std::iter::once((image.rgba.as_slice(), size(image))) - .chain(levels_of(image, mips)) - .map(|(texels, size)| (texels, size, RgbaEncoding::for_texels(texels))) - .collect() - }) - .collect(); - let sizes: Vec<_> = gray - .iter() - .map(|image| size(image)) - .chain(color_parts.iter().flatten().flat_map(|&(_, size, encoding)| std::iter::repeat_n(size, encoding as usize))) - .chain(raw.iter().map(|plane| plane.size.map(|side| side.max(1)))) - .collect(); - let budget = if color.is_empty() && raw.is_empty() { MAX_ATLAS_BYTES } else { MAX_COLOR_ATLAS_BYTES }; - let (extent, regions) = - arrange_images(&sizes, limits.max_texture_dimension_2d, limits.max_texture_array_layers, device.adapter_info().backend, budget)?; - let texture = atlas_texture(device, extent[0], extent[1], extent[2]); - let mut pixels = Vec::new(); - let mut pending = 0; - let mut upload = |region: &ImageRegion, word: &dyn Fn(usize) -> u32| -> Result<(), String> { - let [width, height] = region.size; - for top in (0..height).step_by(IMAGE_ROWS) { - let rows = (height - top).min(IMAGE_ROWS as u32); - let first = top as usize * width as usize; - let n = rows as usize * width as usize; - pixels.clear(); - pixels.extend((first..first + n).map(word)); - queue.write_texture( - wgpu::TexelCopyTextureInfo { - origin: wgpu::Origin3d { x: region.origin[0], y: region.origin[1] + top, z: region.origin[2] }, - ..texture.as_image_copy() - }, - bytemuck::cast_slice(&pixels), - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 4), rows_per_image: None }, - wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 }, - ); - pending += u64::from(width) * u64::from(rows) * 4; - if pending >= MAX_PENDING_UPLOAD_BYTES { - let submission = queue.submit([]); - device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None }).map_err(|error| error.to_string())?; - pending = 0; - } - } - Ok(()) - }; - let (gray_regions, mut remaining) = regions.split_at(gray.len()); - for (image, region) in gray.iter().zip(gray_regions) { - upload(region, &|index| { - let sample = image.rgba.get(index).copied().unwrap_or_default(); - ((sample[0] + sample[1] + sample[2]) / 3.0).to_bits() - })?; - } - let mut color_layout = Vec::new(); - for parts in &color_parts { - let mut uploaded = Vec::new(); - for &(texels, size, encoding) in parts { - let (planes, rest) = remaining.split_at(encoding as usize); - remaining = rest; - for (lane, plane) in planes.iter().enumerate() { - upload(plane, &|index| encoding.word(texels.get(index).copied().unwrap_or_default(), lane))?; - } - uploaded.push(RgbaLevel { size, encoding, planes: planes.to_vec() }); - } - let mut uploaded = uploaded.into_iter(); - let Some(image) = uploaded.next() else { continue }; - color_layout.push(RgbaRegion { encoding: image.encoding, planes: image.planes, levels: uploaded.collect() }); - } - let mut raw_layout = Vec::new(); - for (plane, region) in raw.iter().zip(remaining) { - upload(region, &|index| plane.texels.get(index).copied().unwrap_or_default().to_bits())?; - raw_layout.push((Arc::downgrade(&plane.texels), *region)); - } - let view = texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); - Ok(Self { - images: gray.iter().copied().chain(color.iter().map(|(image, _)| *image)).map(Arc::downgrade).collect(), - regions: gray_regions.to_vec(), - color: color_layout, - color_mips: color.iter().map(|&(_, mips)| mips).collect(), - raw: raw_layout, - view, - }) - } -} - /// The texels, size and encoding of a colour image or one of its halved levels. type ColorPart<'a> = (&'a [[f32; 4]], [u32; 2], RgbaEncoding); @@ -424,6 +69,7 @@ fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backen if widest.max(tallest) > side_limit { return Err("An authored image exceeds the GPU texture dimension limit.".into()); } + let area: u64 = order.iter().map(|&(_, width, height)| u64::from(width) * u64::from(height)).sum(); let width = (area as f64).sqrt().ceil().min(f64::from(side_limit)) as u32; let width = width.max(widest); @@ -445,6 +91,7 @@ fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backen if layer >= layer_limit { return Err("The authored image atlas exceeds the GPU array limit.".into()); } + regions[index] = ImageRegion { origin: [x, y, layer], size: [w, h] }; x += w; row_height = row_height.max(h); @@ -452,8 +99,8 @@ fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backen used_h = used_h.max(y + row_height); } let mut layers = layer + 1; - // The GL backend derives the texture target from its extent. A view alone - // cannot turn a single-layer texture or a cube into a 2D array. + + // GL derives the array texture target from the allocated extent if backend == wgpu::Backend::Gl && (layers == 1 || (used_w == used_h && layers.is_multiple_of(6))) { layers += 1; if layers > layer_limit { @@ -465,6 +112,7 @@ fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backen if bytes > budget { return Err("The authored image atlas exceeds the GPU memory budget.".into()); } + Ok((extent, regions)) } diff --git a/crates/render/src/gpu_tile_pattern/atlas_mips.rs b/crates/render/src/gpu_tile_pattern/atlas_mips.rs new file mode 100644 index 00000000..0f79ca28 --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/atlas_mips.rs @@ -0,0 +1,12 @@ +/// Which halved levels of a colour image the atlas holds besides the image. P1 (fill sampling) +/// chooses per image through `MaterialImages::atlas_images`; `None` uploads exactly what the +/// atlas held before. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum AtlasMips { + #[default] + None, + /// `ImageRes::mip_chain`: the levels as stored (Bilinear HQ of scalar and alpha reads). + Stored, + /// `ImageRes::linear_mip_chain`: RGB linear, alpha unchanged (an sRGB image's colour read). + LinearColor, +} diff --git a/crates/render/src/gpu_tile_pattern/image_region.rs b/crates/render/src/gpu_tile_pattern/image_region.rs new file mode 100644 index 00000000..4085ac26 --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/image_region.rs @@ -0,0 +1,5 @@ +#[derive(Clone, Copy, Default)] +pub(super) struct ImageRegion { + pub(super) origin: [u32; 3], + pub(super) size: [u32; 2], +} diff --git a/crates/render/src/gpu_tile_pattern/raw_plane.rs b/crates/render/src/gpu_tile_pattern/raw_plane.rs new file mode 100644 index 00000000..2eb2ae09 --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/raw_plane.rs @@ -0,0 +1,9 @@ +use super::Arc; + +/// One exact-f32 plane of the atlas (P1: a projector depth grid), row by row. The atlas keeps a +/// weak pointer to `texels`, so a plane rebuilt for every program rebuilds the atlas. +#[derive(Clone, Debug)] +pub(crate) struct RawPlane { + pub(crate) size: [u32; 2], + pub(crate) texels: Arc>, +} diff --git a/crates/render/src/gpu_tile_pattern/rgba_encoding.rs b/crates/render/src/gpu_tile_pattern/rgba_encoding.rs new file mode 100644 index 00000000..7663542d --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/rgba_encoding.rs @@ -0,0 +1,39 @@ +use super::{IntoParallelRefIterator, ParallelIterator}; + +#[derive(Clone, Copy)] +pub(super) enum RgbaEncoding { + Bytes = 1, + Shorts = 2, + Floats = 4, +} + +impl RgbaEncoding { + pub(super) fn for_texels(rgba: &[[f32; 4]]) -> Self { + let exact = |v: f32, scale: f32| { + let integer = (v * scale).round(); + integer >= 0.0 && integer <= scale && (v == integer / scale || v == integer * (1.0 / scale)) + }; + if rgba.par_iter().all(|pixel| pixel.iter().all(|&v| exact(v, 255.0))) { + Self::Bytes + } else if rgba.par_iter().all(|pixel| pixel.iter().all(|&v| exact(v, 65535.0))) { + Self::Shorts + } else { + Self::Floats + } + } + + pub(super) fn word(self, [r, g, b, a]: [f32; 4], lane: usize) -> u32 { + match self { + Self::Bytes => { + let byte = |v: f32| (v * 255.0).round() as u8; + u32::from_le_bytes([byte(r), byte(g), byte(b), byte(a)]) + } + Self::Shorts => { + let short = |v: f32| (v * 65535.0).round() as u32; + let [low, high] = if lane == 0 { [r, g] } else { [b, a] }; + short(low) | (short(high) << 16) + } + Self::Floats => [r, g, b, a][lane].to_bits(), + } + } +} diff --git a/crates/render/src/gpu_tile_pattern/rgba_level.rs b/crates/render/src/gpu_tile_pattern/rgba_level.rs new file mode 100644 index 00000000..443141ab --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/rgba_level.rs @@ -0,0 +1,7 @@ +use super::{ImageRegion, RgbaEncoding}; + +pub(super) struct RgbaLevel { + pub(super) size: [u32; 2], + pub(super) encoding: RgbaEncoding, + pub(super) planes: Vec, +} diff --git a/crates/render/src/gpu_tile_pattern/rgba_region.rs b/crates/render/src/gpu_tile_pattern/rgba_region.rs new file mode 100644 index 00000000..886fb07c --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/rgba_region.rs @@ -0,0 +1,8 @@ +use super::{ImageRegion, RgbaEncoding, RgbaLevel}; + +pub(super) struct RgbaRegion { + pub(super) encoding: RgbaEncoding, + pub(super) planes: Vec, + /// The halved levels held besides the image, level 1 first: size, encoding and planes each + pub(super) levels: Vec, +} diff --git a/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs b/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs new file mode 100644 index 00000000..f5787627 --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs @@ -0,0 +1,167 @@ +use super::{ + Arc, AtlasMips, ColorPart, IMAGE_ROWS, ImageRegion, ImageRes, MAX_ATLAS_BYTES, MAX_COLOR_ATLAS_BYTES, MAX_PENDING_UPLOAD_BYTES, RawPlane, RgbaEncoding, + RgbaLevel, RgbaRegion, Weak, arrange_images, atlas_texture, levels_of, +}; + +pub(crate) struct TileImageAtlas { + pub(super) images: Vec>, + pub(super) regions: Vec, + pub(super) color: Vec, + pub(super) color_mips: Vec, + pub(super) raw: Vec<(Weak>, ImageRegion)>, + pub(crate) view: wgpu::TextureView, +} + +impl TileImageAtlas { + pub(crate) fn matches(&self, gray: &[&Arc], color: &[(&Arc, AtlasMips)], raw: &[RawPlane]) -> bool { + self.regions.len() == gray.len() + && self.color.len() == color.len() + && self.images.iter().zip(gray.iter().copied().chain(color.iter().map(|(image, _)| *image))).all(|(old, new)| old.ptr_eq(&Arc::downgrade(new))) + && self.color_mips.iter().eq(color.iter().map(|(_, mips)| mips)) + && self.raw.len() == raw.len() + && self.raw.iter().zip(raw).all(|((old, region), new)| old.ptr_eq(&Arc::downgrade(&new.texels)) && region.size == new.size) + } + + pub(crate) fn is_live(&self) -> bool { + self.images.iter().all(|image| image.strong_count() != 0) && self.raw.iter().all(|(texels, _)| texels.strong_count() != 0) + } + + pub(crate) fn empty_view(device: &wgpu::Device) -> wgpu::TextureView { + atlas_texture(device, 1, 1, 2).create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }) + } + + pub(crate) fn append_rgba(&self, words: &mut Vec, color_index: usize, srgb: bool) -> u32 { + let region = &self.color[color_index]; + let offset = words.len() as u32; + let [width, height] = region.planes[0].size; + + // Bit 9: halved levels follow the planes; without levels the words are exactly as before + let flags = region.encoding as u32 | (u32::from(srgb) << 8) | (u32::from(!region.levels.is_empty()) << 9); + words.extend([width, height, flags]); + for plane in ®ion.planes { + words.extend(plane.origin); + } + + // The level count, each level's word offset (so a level is one read away), then per level its width, height, encoding and plane origins + if !region.levels.is_empty() { + words.push(region.levels.len() as u32); + let table = words.len(); + words.resize(table + region.levels.len(), 0); + for (index, level) in region.levels.iter().enumerate() { + words[table + index] = words.len() as u32; + words.extend([level.size[0], level.size[1], level.encoding as u32]); + for plane in &level.planes { + words.extend(plane.origin); + } + } + } + offset + } + + /// The words of raw plane `index`: width, height and its origin (x, y, layer), read as f32 bits. + pub(crate) fn append_raw(&self, words: &mut Vec, index: usize) -> u32 { + let offset = words.len() as u32; + let (_, region) = &self.raw[index]; + words.extend([region.size[0], region.size[1]]); + words.extend(region.origin); + offset + } + + /// Upload `gray` (one plane each), `color` (one to four planes each by encoding, plus the + /// chosen halved levels) and `raw` (one exact-f32 plane each) into one array texture. + pub(crate) fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + gray: &[&Arc], + color: &[(&Arc, AtlasMips)], + raw: &[RawPlane], + ) -> Result { + let limits = device.limits(); + let size = |image: &Arc| [image.width.max(1), image.height.max(1)]; + + // Per colour image: the image, then each level, with its encoding + let color_parts: Vec> = color + .iter() + .map(|&(image, mips)| { + std::iter::once((image.rgba.as_slice(), size(image))) + .chain(levels_of(image, mips)) + .map(|(texels, size)| (texels, size, RgbaEncoding::for_texels(texels))) + .collect() + }) + .collect(); + let sizes: Vec<_> = gray + .iter() + .map(|image| size(image)) + .chain(color_parts.iter().flatten().flat_map(|&(_, size, encoding)| std::iter::repeat_n(size, encoding as usize))) + .chain(raw.iter().map(|plane| plane.size.map(|side| side.max(1)))) + .collect(); + let budget = if color.is_empty() && raw.is_empty() { MAX_ATLAS_BYTES } else { MAX_COLOR_ATLAS_BYTES }; + let (extent, regions) = + arrange_images(&sizes, limits.max_texture_dimension_2d, limits.max_texture_array_layers, device.adapter_info().backend, budget)?; + let texture = atlas_texture(device, extent[0], extent[1], extent[2]); + let mut pixels = Vec::new(); + let mut pending = 0; + let mut upload = |region: &ImageRegion, word: &dyn Fn(usize) -> u32| -> Result<(), String> { + let [width, height] = region.size; + for top in (0..height).step_by(IMAGE_ROWS) { + let rows = (height - top).min(IMAGE_ROWS as u32); + let first = top as usize * width as usize; + let n = rows as usize * width as usize; + pixels.clear(); + pixels.extend((first..first + n).map(word)); + queue.write_texture( + wgpu::TexelCopyTextureInfo { + origin: wgpu::Origin3d { x: region.origin[0], y: region.origin[1] + top, z: region.origin[2] }, + ..texture.as_image_copy() + }, + bytemuck::cast_slice(&pixels), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 4), rows_per_image: None }, + wgpu::Extent3d { width, height: rows, depth_or_array_layers: 1 }, + ); + pending += u64::from(width) * u64::from(rows) * 4; + if pending >= MAX_PENDING_UPLOAD_BYTES { + let submission = queue.submit([]); + device.poll(wgpu::PollType::Wait { submission_index: Some(submission), timeout: None }).map_err(|error| error.to_string())?; + pending = 0; + } + } + Ok(()) + }; + let (gray_regions, mut remaining) = regions.split_at(gray.len()); + for (image, region) in gray.iter().zip(gray_regions) { + upload(region, &|index| { + let sample = image.rgba.get(index).copied().unwrap_or_default(); + ((sample[0] + sample[1] + sample[2]) / 3.0).to_bits() + })?; + } + let mut color_layout = Vec::new(); + for parts in &color_parts { + let mut uploaded = Vec::new(); + for &(texels, size, encoding) in parts { + let (planes, rest) = remaining.split_at(encoding as usize); + remaining = rest; + for (lane, plane) in planes.iter().enumerate() { + upload(plane, &|index| encoding.word(texels.get(index).copied().unwrap_or_default(), lane))?; + } + uploaded.push(RgbaLevel { size, encoding, planes: planes.to_vec() }); + } + let mut uploaded = uploaded.into_iter(); + let Some(image) = uploaded.next() else { continue }; + color_layout.push(RgbaRegion { encoding: image.encoding, planes: image.planes, levels: uploaded.collect() }); + } + let mut raw_layout = Vec::new(); + for (plane, region) in raw.iter().zip(remaining) { + upload(region, &|index| plane.texels.get(index).copied().unwrap_or_default().to_bits())?; + raw_layout.push((Arc::downgrade(&plane.texels), *region)); + } + let view = texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); + Ok(Self { + images: gray.iter().copied().chain(color.iter().map(|(image, _)| *image)).map(Arc::downgrade).collect(), + regions: gray_regions.to_vec(), + color: color_layout, + color_mips: color.iter().map(|&(_, mips)| mips).collect(), + raw: raw_layout, + view, + }) + } +} diff --git a/crates/render/src/gpu_tile_pattern/tile_pattern.rs b/crates/render/src/gpu_tile_pattern/tile_pattern.rs new file mode 100644 index 00000000..4ce7a657 --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/tile_pattern.rs @@ -0,0 +1,9 @@ +use super::{TileGenerator, TileLayout}; + +#[derive(Debug)] +pub(super) struct TilePattern { + pub(super) settings: TileGenerator, + pub(super) seed: u32, + pub(super) layout: TileLayout, + pub(super) work_per_sample: u64, +} diff --git a/crates/render/src/gpu_tile_pattern/tile_patterns.rs b/crates/render/src/gpu_tile_pattern/tile_patterns.rs new file mode 100644 index 00000000..79fb2552 --- /dev/null +++ b/crates/render/src/gpu_tile_pattern/tile_patterns.rs @@ -0,0 +1,136 @@ +use super::{ + Arc, BTreeMap, ImageRes, ImageStore, NO_IMAGE, TileBlending, TileGenerator, TileImageAtlas, TilePattern, TileShape, placement_work, prepare_tile_layout, +}; + +#[derive(Debug, Default)] +pub(crate) struct TilePatterns { + pub(super) patterns: Vec, + pub(super) images: BTreeMap>, +} + +impl TilePatterns { + pub(crate) fn register(&mut self, settings: TileGenerator, seed: u32) -> usize { + if let Some(index) = self.patterns.iter().position(|p| p.seed == seed && p.settings == settings) { + return index; + } + + let layout = prepare_tile_layout(&settings, seed); + let work_per_sample = placement_work(&layout); + let index = self.patterns.len(); + self.patterns.push(TilePattern { settings, seed, layout, work_per_sample }); + index + } + + pub(crate) fn is_empty(&self) -> bool { + self.patterns.is_empty() + } + + pub(crate) fn work_per_sample(&self, index: usize) -> Option { + self.patterns.get(index).map(|pattern| pattern.work_per_sample) + } + + pub(crate) fn set_images(&mut self, images: &ImageStore) { + self.images = self + .patterns + .iter() + .flat_map(|pattern| { + let settings = &pattern.settings; + let count = if settings.shape == TileShape::Image { settings.inputs.len().min(TileGenerator::MAX_INPUTS) } else { 0 }; + settings.inputs[..count].iter().chain(settings.background_image.iter()) + }) + .filter_map(|name| images.get(name).map(|image| (name.clone(), image.clone()))) + .collect(); + } + + pub(crate) fn image_sources(&self) -> impl Iterator> { + self.images.values() + } + + /// Append image descriptors and prepared shapes to the compositor's packed parameter buffer. + /// All references are word offsets from its beginning, following the sRGB lookup. + pub(crate) fn append_words(&self, words: &mut Vec, atlas: Option<&TileImageAtlas>) -> Vec { + let mut images = BTreeMap::new(); + if let Some(atlas) = atlas { + for (name, region) in self.images.keys().zip(&atlas.regions) { + images.insert(name, words.len() as u32); + words.extend([region.origin[0], region.origin[1], region.origin[2], region.size[0], region.size[1]]); + } + } + let image = |name: &String| images.get(name).copied().unwrap_or(NO_IMAGE); + self.patterns + .iter() + .map(|pattern| { + let settings = &pattern.settings; + let layout = &pattern.layout; + let shift_offset = words.len() as u32; + words.extend(layout.line_shifts.iter().map(|x| x.to_bits())); + let placement_offset = words.len() as u32; + for placement in &layout.placements { + let Some(tile) = placement else { + words.extend([0; 11]); + continue; + }; + + let input = tile.input.and_then(|index| settings.inputs.get(index)).map_or(NO_IMAGE, image); + let flags = tile.quarter_turns | (u32::from(tile.mirrors[0]) << 2) | (u32::from(tile.mirrors[1]) << 3); + words.extend([ + tile.center.x.to_bits(), + tile.center.y.to_bits(), + tile.size.x.to_bits(), + tile.size.y.to_bits(), + tile.radius.x.to_bits(), + tile.radius.y.to_bits(), + tile.rotation[0].to_bits(), + tile.rotation[1].to_bits(), + flags, + input, + tile.luminance.to_bits(), + ]); + } + + let angle = settings.shape_angle / 360.0 * std::f32::consts::TAU; + let (sin, cos) = angle.sin_cos(); + let low = (1.0 - 2.0 * settings.position).clamp(0.0, 1.0); + let high = (2.0 - 2.0 * settings.position).clamp(0.0, 1.0); + let middle = (low + high) * 0.5; + let half = (high - low) * 0.5 * (1.0 - settings.contrast); + let shape = TileShape::ALL.iter().position(|&shape| shape == settings.shape).unwrap_or_default() as u32; + let blending = match settings.blending { + TileBlending::Max => 0, + TileBlending::Add => 1, + TileBlending::AddSub => 2, + }; + let offset = words.len() as u32; + words.extend([ + layout.amount[0], + layout.amount[1], + layout.reach.x.to_bits(), + layout.reach.y.to_bits(), + u32::from(settings.vertical_offset), + shift_offset, + placement_offset, + shape, + settings.shape_resolution[0], + settings.shape_resolution[1], + settings.specific.to_bits(), + settings.shape_tiling, + (settings.shape_size[0] * settings.shape_scale).to_bits(), + (settings.shape_size[1] * settings.shape_scale).to_bits(), + sin.to_bits(), + cos.to_bits(), + u32::from(settings.shape_diagonal), + settings.background.to_bits(), + settings.background_image.as_ref().map_or(NO_IMAGE, image), + settings.color.to_bits(), + blending, + settings.opacity.to_bits(), + middle.to_bits(), + half.to_bits(), + settings.global_offset[0].to_bits(), + settings.global_offset[1].to_bits(), + ]); + offset + }) + .collect() + } +} diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 75e9681c..ab182ff5 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,19 +858,46 @@ 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)> { - gpu_with(Headless::new()) + gpu_on(Headless::new()) } - fn gpu_with(headless: Result) -> Option<(Headless, GpuTracer)> { + /// 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; @@ -914,8 +974,7 @@ mod tests { /// Rejecting an oversized render preserves the image and lets tracing continue. #[test] fn failed_reset_retains_the_active_render() { - // The WebGPU default limits (128 MiB per binding) reject an 8192² accumulation - let Some((mut headless, mut tracer)) = gpu_with(Headless::with_limits(|_| wgpu::Limits::default())) 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(); @@ -992,6 +1051,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 @@ -1008,7 +1094,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(); @@ -1017,7 +1111,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 cfea764d..caef32d0 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -2,19 +2,87 @@ use crate::Renderer; +mod test_gpu_turn; +#[doc(hidden)] +pub use test_gpu_turn::TestGpuTurn; + pub struct Headless { pub device: wgpu::Device, pub queue: wgpu::Queue, pub renderer: Renderer, pub adapter_name: String, /// A test's turn on the GPU ([`Headless::for_tests`]), dropped after the device - _serial: Option, + _serial: Option, /// Whether this is the device the tests of the process share ([`Headless::for_tests`]), /// whose compiled pipelines they share too #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) shared_test_device: bool, } +/// 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. +#[cfg(test)] +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 with every limit it reports. Errors when no GPU /// (or software) adapter exists. @@ -37,7 +105,7 @@ impl Headless { /// compiling dominates their time, and llvmpipe keeps what it compiled until the process ends). /// A hardware adapter gives each test a device of its own, which its end destroys. pub fn for_tests() -> Result { - let turn = serial::Turn::take(); + let turn = TestGpuTurn::take(); #[cfg(all(any(test, feature = "test-support"), not(target_arch = "wasm32")))] if let Some((device, queue, adapter_name)) = shared_test_device()? { let mut renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); @@ -57,15 +125,14 @@ impl Headless { Ok(headless) } - /// [`Headless::for_tests`] for a test that must run on a GPU: None without an adapter on a - /// developer's machine, but a failure on CI (`CI` or `TC_CI_LAVAPIPE` set), which promises one, - /// so the test cannot pass there by skipping. + /// [`Headless::for_tests`] for an adapter-backed assertion. Set `TC_CI_LAVAPIPE` when the + /// test environment provides Lavapipe and a missing adapter should fail the test. pub fn for_required_tests() -> Option { match Self::for_tests() { Ok(gpu) => Some(gpu), Err(error) => { - let on_ci = std::env::var_os("CI").is_some() || std::env::var_os("TC_CI_LAVAPIPE").is_some(); - assert!(!on_ci, "CI promises a GPU adapter but none is available: {error}"); + assert!(std::env::var_os("TC_CI_LAVAPIPE").is_none(), "TC_CI_LAVAPIPE is set but the GPU is unavailable: {error}"); + eprintln!("skipping GPU assertions: {error}"); None } } @@ -73,16 +140,15 @@ impl Headless { /// [`Headless::new`] with the limits `limits` picks for the adapter (a test of a smaller GPU). pub fn with_limits(limits: impl FnOnce(&wgpu::Adapter) -> wgpu::Limits) -> Result { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); - let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).map_err(|e| format!("no GPU adapter: {e}"))?; + let adapter = adapter()?; let adapter_name = adapter.get_info().name; + // A device of the render crate's tests lives in a turn (`for_tests`) #[cfg(all(test, not(target_arch = "wasm32")))] - let serial = Some(serial::Turn::take()); + let serial = Some(TestGpuTurn::take()); #[cfg(not(all(test, not(target_arch = "wasm32"))))] let serial = None; - let descriptor = wgpu::DeviceDescriptor { required_limits: limits(&adapter), ..Default::default() }; - let (device, queue) = pollster::block_on(adapter.request_device(&descriptor)).map_err(|e| format!("no GPU device: {e}"))?; + let (device, queue) = device_with_limits(&adapter, limits(&adapter))?; let renderer = Renderer::new(&device, &queue, wgpu::TextureFormat::Rgba8Unorm); Ok(Headless { device, @@ -95,6 +161,18 @@ impl Headless { }) } + /// 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 { + Self::with_limits(|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); + limits + }) + } + /// Render a frame and read it back as RGBA8 (sRGB-encoded). pub fn render(&mut self, frame: &crate::Frame) -> Option<(u32, u32, Vec)> { let mut enc = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_headless") }); @@ -132,49 +210,6 @@ pub(crate) fn shares_test_device(info: &wgpu::AdapterInfo) -> bool { info.backend == wgpu::Backend::Gl || info.device_type == wgpu::DeviceType::Cpu } -/// Turns of tests on the GPU ([`Headless::for_tests`]). A thread already holding a turn (a test -/// with two devices) takes another at once. -#[doc(hidden)] -pub mod serial { - use std::cell::Cell; - use std::sync::{Condvar, Mutex, PoisonError}; - - static BUSY: Mutex = Mutex::new(false); - static FREED: Condvar = Condvar::new(); - thread_local! { - static HELD: Cell = const { Cell::new(0) }; - } - - /// One turn; the first one a thread takes waits for the device of another thread to go, and - /// the thread's last one to drop, in any order, lets the next thread's device in. - pub struct Turn(()); - - impl Turn { - pub fn take() -> Turn { - if HELD.get() == 0 { - let mut busy = BUSY.lock().unwrap_or_else(PoisonError::into_inner); - while *busy { - busy = FREED.wait(busy).unwrap_or_else(PoisonError::into_inner); - } - *busy = true; - } - HELD.set(HELD.get() + 1); - Turn(()) - } - } - - impl Drop for Turn { - fn drop(&mut self) { - let held = HELD.get().saturating_sub(1); - HELD.set(held); - if held == 0 { - *BUSY.lock().unwrap_or_else(PoisonError::into_inner) = false; - FREED.notify_all(); - } - } - } -} - #[cfg(test)] mod limits_tests { /// The device gets every limit the adapter reports (`device_limits`), so the compositor @@ -191,7 +226,7 @@ mod limits_tests { #[cfg(all(test, not(target_arch = "wasm32")))] mod tests { - use super::Headless; + use super::{Headless, Renderer, device, pick_adapter}; /// CI (Windows, and Linux through `cargo xtask ci`) promises lavapipe through Vulkan: no other /// adapter takes its place @@ -200,6 +235,7 @@ mod tests { if std::env::var_os("TC_CI_LAVAPIPE").is_none() { return; } + let gpu = Headless::new().expect("the CI Vulkan adapter must be available"); let adapter = gpu.device.adapter_info(); assert_eq!(adapter.backend, wgpu::Backend::Vulkan, "{adapter:?}"); @@ -208,4 +244,68 @@ mod tests { assert!(crate::gpu_composite::GpuCompositor::supports(&gpu.device), "{adapter:?}"); eprintln!("CI renderer adapter: {adapter:?}"); } + + /// 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/headless/test_gpu_turn.rs b/crates/render/src/headless/test_gpu_turn.rs new file mode 100644 index 00000000..e6c5c6d9 --- /dev/null +++ b/crates/render/src/headless/test_gpu_turn.rs @@ -0,0 +1,31 @@ +use std::sync::{Condvar, Mutex, PoisonError}; +use std::thread::{self, ThreadId}; + +static OWNER: Mutex> = Mutex::new(None); +static RELEASED: Condvar = Condvar::new(); + +/// Serializes GPU test devices to avoid overlapping device teardown and recording. +/// Allow nested acquisition by tests that need two devices. +pub struct TestGpuTurn(ThreadId); + +impl TestGpuTurn { + pub fn take() -> Self { + let thread = thread::current().id(); + let owner = OWNER.lock().unwrap_or_else(PoisonError::into_inner); + let mut owner = RELEASED.wait_while(owner, |owner| owner.is_some_and(|(id, _)| id != thread)).unwrap_or_else(PoisonError::into_inner); + owner.get_or_insert((thread, 0)).1 += 1; + Self(thread) + } +} + +impl Drop for TestGpuTurn { + fn drop(&mut self) { + let mut owner = OWNER.lock().unwrap_or_else(PoisonError::into_inner); + let Some((_, count)) = owner.as_mut().filter(|(id, _)| *id == self.0) else { return }; + *count -= 1; + if *count == 0 { + *owner = None; + RELEASED.notify_one(); + } + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f98760dc..4b19d916 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -59,10 +59,7 @@ pub use renderer::{ pub use set_highlight::SetHighlight; pub use wgpu; -/// The limits to request at device creation: everything the adapter reports. The compositor -/// sizes its bands and working buffers against the device's limits (and a later user-set -/// memory limit, `gpu_composite::user_memory_limit`), so it gets the adapter's full range; -/// software adapters keep their own reported values. +/// Request the adapter's full limits so the compositor can size bands and working buffers for the device. pub fn device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { adapter.limits() } diff --git a/crates/render/src/paint_window.rs b/crates/render/src/paint_window.rs index 9e3052b1..72a74b5e 100644 --- a/crates/render/src/paint_window.rs +++ b/crates/render/src/paint_window.rs @@ -2,132 +2,10 @@ use texturecraft_texel::{TILE, TILE_AREA, TileImage}; -#[derive(Clone, Copy)] -pub(crate) struct TileWindow { - pub origin: [u32; 2], - pub size: [u32; 2], -} +mod composite_paint_window; +mod tile_window; + +pub(crate) use composite_paint_window::CompositePaintWindow; +pub(crate) use tile_window::TileWindow; const COMPOSITE_IMAGE_WORDS: usize = 6; - -/// Per-image windows for compositing, where a linked source can have a different resolution. -pub(crate) enum CompositePaintWindow { - Uniform(TileWindow), - PerImage(Vec), -} - -impl CompositePaintWindow { - pub fn covering(min: [u32; 2], max: [u32; 2], size: [u32; 2], images: &[TileImage]) -> Self { - let common = TileWindow::covering(min, max, size); - if images.iter().all(|image| [image.width(), image.height()] == size) { - return Self::Uniform(common); - } - let windows = images - .iter() - .map(|image| { - let source = [image.width(), image.height()]; - if source == size { - return common; - } - // Include both bilinear neighbours of each output texel, even at tile edges. - let start = std::array::from_fn(|i| (u64::from(min[i]) * u64::from(source[i]) / u64::from(size[i])) as u32); - let end = std::array::from_fn(|i| (u64::from(max[i]) * u64::from(source[i])).div_ceil(u64::from(size[i])) as u32); - TileWindow::covering(start.map(|p| p.saturating_sub(1)), end.map(|p| p.saturating_add(2)), source) - }) - .collect(); - Self::PerImage(windows) - } - - pub fn params(&self) -> [u32; 4] { - match self { - Self::Uniform(window) => [window.origin[0], window.origin[1], window.size[0], window.size[1]], - Self::PerImage(_) => [u32::MAX, 0, 0, 0], - } - } - - pub fn words(&self, images: &[TileImage], limit: usize) -> Option { - let windows = match self { - Self::Uniform(window) => return window.words(images, limit), - Self::PerImage(windows) => windows, - }; - let mut words = images.len().max(1); - for (&window, image) in windows.iter().zip(images) { - words += COMPOSITE_IMAGE_WORDS; - words = window.image_words(image, words, limit)?; - } - (words <= limit).then_some(words) - } - - /// One offset per image, then the image size, tile window, tile offsets and packed pixels. - pub fn pack(&self, images: &[TileImage], words: usize, output: &mut Vec) { - let windows = match self { - Self::Uniform(window) => return window.pack(images, words, output), - Self::PerImage(windows) => windows, - }; - output.clear(); - output.reserve(words); - output.resize(images.len().max(1), 0); - for (i, (&window, image)) in windows.iter().zip(images).enumerate() { - output[i] = output.len() as u32; - output.extend([image.width(), image.height(), window.origin[0], window.origin[1], window.size[0], window.size[1]]); - window.pack_image(image, output); - } - } -} - -impl TileWindow { - pub fn covering(min: [u32; 2], max: [u32; 2], image_size: [u32; 2]) -> Self { - let origin = min.map(|p| p / TILE); - let end = [max[0].min(image_size[0]).div_ceil(TILE), max[1].min(image_size[1]).div_ceil(TILE)]; - Self { origin, size: [end[0].saturating_sub(origin[0]), end[1].saturating_sub(origin[1])] } - } - - pub fn words(self, images: &[TileImage], limit: usize) -> Option { - let mut words = images.len().max(1); - for image in images { - words = self.image_words(image, words, limit)?; - } - (words <= limit).then_some(words) - } - - fn image_words(self, image: &TileImage, mut words: usize, limit: usize) -> Option { - words += (self.size[0] * self.size[1]) as usize; - let per_tile = TILE_AREA * image.comps() / 2; - for y in self.origin[1]..self.origin[1] + self.size[1] { - let allocated = (self.origin[0]..self.origin[0] + self.size[0]).filter(|&x| image.is_allocated(x, y)).count(); - words += allocated * per_tile; - if words > limit { - return None; - } - } - (words <= limit).then_some(words) - } - - /// An offset per image, followed by each image's tile table and packed tile data. - pub fn pack(self, images: &[TileImage], words: usize, output: &mut Vec) { - output.clear(); - output.reserve(words); - output.resize(images.len().max(1), 0); - for (i, image) in images.iter().enumerate() { - output[i] = output.len() as u32; - self.pack_image(image, output); - } - } - - fn pack_image(self, image: &TileImage, output: &mut Vec) { - let table = output.len(); - output.resize(table + (self.size[0] * self.size[1]) as usize, 0); - for y in 0..self.size[1] { - for x in 0..self.size[0] { - let Some(tile) = image.tile(x + self.origin[0], y + self.origin[1]) else { continue }; - output[table + (y * self.size[0] + x) as usize] = output.len() as u32; - #[cfg(target_endian = "little")] - if let Ok(words) = bytemuck::try_cast_slice::(tile) { - output.extend_from_slice(words); - continue; - } - output.extend(tile.as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); - } - } - } -} diff --git a/crates/render/src/paint_window/composite_paint_window.rs b/crates/render/src/paint_window/composite_paint_window.rs new file mode 100644 index 00000000..9017e95e --- /dev/null +++ b/crates/render/src/paint_window/composite_paint_window.rs @@ -0,0 +1,68 @@ +use super::{COMPOSITE_IMAGE_WORDS, TileImage, TileWindow}; + +/// Per-image windows for compositing, where a linked source can have a different resolution. +pub(crate) enum CompositePaintWindow { + Uniform(TileWindow), + PerImage(Vec), +} + +impl CompositePaintWindow { + pub fn covering(min: [u32; 2], max: [u32; 2], size: [u32; 2], images: &[TileImage]) -> Self { + let common = TileWindow::covering(min, max, size); + if images.iter().all(|image| [image.width(), image.height()] == size) { + return Self::Uniform(common); + } + + let windows = images + .iter() + .map(|image| { + let source = [image.width(), image.height()]; + if source == size { + return common; + } + + // Include both bilinear neighbours of each output texel, even at tile edges + let start = std::array::from_fn(|i| (u64::from(min[i]) * u64::from(source[i]) / u64::from(size[i])) as u32); + let end = std::array::from_fn(|i| (u64::from(max[i]) * u64::from(source[i])).div_ceil(u64::from(size[i])) as u32); + TileWindow::covering(start.map(|p| p.saturating_sub(1)), end.map(|p| p.saturating_add(2)), source) + }) + .collect(); + Self::PerImage(windows) + } + + pub fn params(&self) -> [u32; 4] { + match self { + Self::Uniform(window) => [window.origin[0], window.origin[1], window.size[0], window.size[1]], + Self::PerImage(_) => [u32::MAX, 0, 0, 0], + } + } + + pub fn words(&self, images: &[TileImage], limit: usize) -> Option { + let windows = match self { + Self::Uniform(window) => return window.words(images, limit), + Self::PerImage(windows) => windows, + }; + let mut words = images.len().max(1); + for (&window, image) in windows.iter().zip(images) { + words += COMPOSITE_IMAGE_WORDS; + words = window.image_words(image, words, limit)?; + } + (words <= limit).then_some(words) + } + + /// One offset per image, then the image size, tile window, tile offsets and packed pixels. + pub fn pack(&self, images: &[TileImage], words: usize, output: &mut Vec) { + let windows = match self { + Self::Uniform(window) => return window.pack(images, words, output), + Self::PerImage(windows) => windows, + }; + output.clear(); + output.reserve(words); + output.resize(images.len().max(1), 0); + for (i, (&window, image)) in windows.iter().zip(images).enumerate() { + output[i] = output.len() as u32; + output.extend([image.width(), image.height(), window.origin[0], window.origin[1], window.size[0], window.size[1]]); + window.pack_image(image, output); + } + } +} diff --git a/crates/render/src/paint_window/tile_window.rs b/crates/render/src/paint_window/tile_window.rs new file mode 100644 index 00000000..dc0c6960 --- /dev/null +++ b/crates/render/src/paint_window/tile_window.rs @@ -0,0 +1,65 @@ +use super::{TILE, TILE_AREA, TileImage}; + +#[derive(Clone, Copy)] +pub(crate) struct TileWindow { + pub origin: [u32; 2], + pub size: [u32; 2], +} + +impl TileWindow { + pub fn covering(min: [u32; 2], max: [u32; 2], image_size: [u32; 2]) -> Self { + let origin = min.map(|p| p / TILE); + let end = [max[0].min(image_size[0]).div_ceil(TILE), max[1].min(image_size[1]).div_ceil(TILE)]; + Self { origin, size: [end[0].saturating_sub(origin[0]), end[1].saturating_sub(origin[1])] } + } + + pub fn words(self, images: &[TileImage], limit: usize) -> Option { + let mut words = images.len().max(1); + for image in images { + words = self.image_words(image, words, limit)?; + } + (words <= limit).then_some(words) + } + + pub(super) fn image_words(self, image: &TileImage, mut words: usize, limit: usize) -> Option { + words += (self.size[0] * self.size[1]) as usize; + let per_tile = TILE_AREA * image.comps() / 2; + for y in self.origin[1]..self.origin[1] + self.size[1] { + let allocated = (self.origin[0]..self.origin[0] + self.size[0]).filter(|&x| image.is_allocated(x, y)).count(); + words += allocated * per_tile; + if words > limit { + return None; + } + } + (words <= limit).then_some(words) + } + + /// An offset per image, followed by each image's tile table and packed tile data. + pub fn pack(self, images: &[TileImage], words: usize, output: &mut Vec) { + output.clear(); + output.reserve(words); + output.resize(images.len().max(1), 0); + for (i, image) in images.iter().enumerate() { + output[i] = output.len() as u32; + self.pack_image(image, output); + } + } + + pub(super) fn pack_image(self, image: &TileImage, output: &mut Vec) { + let table = output.len(); + output.resize(table + (self.size[0] * self.size[1]) as usize, 0); + for y in 0..self.size[1] { + for x in 0..self.size[0] { + let Some(tile) = image.tile(x + self.origin[0], y + self.origin[1]) else { continue }; + output[table + (y * self.size[0] + x) as usize] = output.len() as u32; + #[cfg(target_endian = "little")] + if let Ok(words) = bytemuck::try_cast_slice::(tile) { + output.extend_from_slice(words); + continue; + } + + output.extend(tile.as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); + } + } + } +} diff --git a/crates/render/src/readback.rs b/crates/render/src/readback.rs index a546cf63..1d93ec26 100644 --- a/crates/render/src/readback.rs +++ b/crates/render/src/readback.rs @@ -33,6 +33,7 @@ impl Readback { if format.block_dimensions() != (1, 1) || format.is_depth_stencil_format() { return None; } + let size = ((texture.width() >> level).max(1), (texture.height() >> level).max(1)); Some(Readback::encode(device, encoder, texture, level, size, format.block_copy_size(None)?)) } @@ -89,18 +90,26 @@ impl Readback { /// [`Readback::blocking`] for mip `level` (None also when `texture` has no such level). pub fn blocking_level(device: &wgpu::Device, queue: &wgpu::Queue, texture: &wgpu::Texture, level: u32) -> Option<(u32, u32, Vec)> { + // Browser mapping callbacks need the event loop to continue + if cfg!(target_arch = "wasm32") { + return None; + } + let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_read") }); let r = Readback::new_level(device, &mut enc, texture, level)?; let submitted = queue.submit([enc.finish()]); r.map(); + // Another thread polling the same device may run the map callback: wait until it ran loop { if device.poll(wgpu::PollType::Wait { submission_index: Some(submitted.clone()), timeout: None }).is_err() { return None; } + if let Some(pixels) = r.take() { return pixels; } + std::thread::yield_now(); } } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 1b276fdd..747a8f6e 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -113,6 +113,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). @@ -160,6 +161,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. @@ -253,6 +260,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, @@ -301,6 +309,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, @@ -417,6 +428,20 @@ fn mask_view_shift(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 }, @@ -424,11 +449,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()); @@ -436,6 +457,12 @@ impl Tex { } } +mod pending_display_seed; +mod seed_tile; + +use pending_display_seed::PendingDisplaySeed; +use seed_tile::SeedTile; + struct SetGpu { /// Texels across and down (a UV-tiled set's whole atlas). size: (u32, u32), @@ -467,20 +494,6 @@ struct PendingTex { answer: std::sync::Mutex>>, } -struct PendingDisplaySeed { - textures: Vec, - answer: std::sync::Mutex>>, - tiles: Vec, -} - -struct SeedTile { - kind: DisplayKind, - x: u32, - y: u32, - bytes: Vec, - shift: u32, -} - /// Replace the material's textures while leaving its aux view in place. fn install_display_seed(set: &mut SetGpu, textures: Vec, device: &wgpu::Device, layout: &wgpu::BindGroupLayout, sampler: &wgpu::Sampler) { for (i, texture) in textures.into_iter().enumerate() { @@ -685,7 +698,7 @@ pub struct Renderer { /// The compositor compiles new pipelines on worker threads (`set_asynchronous_compile`) asynchronous_compile: bool, /// The compositor takes the pipelines the tests on the shared device share - /// ([`Renderer::share_test_pipelines`]) + /// (`Renderer::share_test_pipelines`) shared_test_pipelines: bool, quick_mask: Option, #[cfg(not(target_arch = "wasm32"))] @@ -1301,7 +1314,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, @@ -1398,7 +1411,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(); @@ -1424,9 +1437,10 @@ impl Renderer { if self.mesh.as_ref().is_some_and(|m| m.id == id) { return; } + self.quick_mask = None; - // A replacement mesh may reuse the same display dimensions. Its textures must - // not be replaced by a late overview from the previous mesh. + + // A late overview from the previous mesh must never replace the current textures for set in &mut self.sets { set.pending_seed = None; set.pending.iter_mut().take(DisplayKind::ALL.len()).for_each(|slot| *slot = None); @@ -1637,6 +1651,7 @@ impl Renderer { if !GpuCompositor::supports(device) { return Err("adapter limits do not support the GPU brush".into()); } + let compile = (self.asynchronous_compile, self.shared_test_pipelines); let (compositor, brush, stroke) = crate::gpu_trace::scoped(device, "GPU brush startup", || { let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); @@ -1694,6 +1709,7 @@ impl Renderer { if !self.asynchronous_compile || cfg!(target_arch = "wasm32") || !GpuCompositor::supports(device) { return; } + let compile = (self.asynchronous_compile, self.shared_test_pipelines); self.compositor.get_or_insert_with(|| Self::new_compositor(device, compile)).prewarm(device, program); } @@ -1704,6 +1720,7 @@ impl Renderer { if !self.asynchronous_compile || cfg!(target_arch = "wasm32") || !GpuCompositor::supports(device) { return Ok(true); } + let compile = (true, self.shared_test_pipelines); self.compositor.get_or_insert_with(|| Self::new_compositor(device, compile)).pipelines_ready(device, program) } @@ -1715,9 +1732,11 @@ impl Renderer { if !program.is_neutral() && !self.composite_pipelines_ready(device, program)? { return Err(crate::gpu_composite::GPU_PIPELINES_PENDING.into()); } + if program.is_mask_preview() { return self.composite_mask_preview(device, queue, ts, program); } + let set = self.sets.get(ts).ok_or("texture set does not exist")?; if program.is_neutral() { self.release_composite_inputs(ts); @@ -1732,6 +1751,7 @@ impl Renderer { })?; let set = &mut self.sets[ts]; set.pending_seed = None; + // A replaced slot's earlier allocation failure no longer holds: later tiles may grow it for (i, texture) in textures.into_iter().enumerate() { set.tex[i] = texture; @@ -1743,14 +1763,13 @@ impl Renderer { self.content_rev += 1; return Ok(()); } + let size = display_dims(set.size, set.shift); if cfg!(target_arch = "wasm32") || !GpuCompositor::supports(device) { return Err("GPU composition is unavailable on this device or for this layout".into()); } - // A composed map whose texture has another extent (a seeded overview, a placeholder) gets a - // new texture: a regional update would leave it neutral outside the region, so it - // composes the whole set + // Recompose the whole set when a placeholder or overview texture needs replacement let resized = DisplayKind::ALL.iter().zip(&set.tex).any(|(&kind, old)| program.writes_display(kind) && (old.texture.width(), old.texture.height()) != size); let region = if resized { None } else { program.region }; @@ -1766,7 +1785,8 @@ impl Renderer { .map(|((&kind, neutral), old)| { let composed = program.writes_display(kind); let extent = if composed { size } else { (1, 1) }; - // At full extent 1×1, even an inactive map's old texel could be painted. + + // A 1×1 inactive map can still hold a painted texel if extent == (old.texture.width(), old.texture.height()) && (composed || size != (1, 1)) { in_place[kind as usize] = composed; old.clone() @@ -1825,15 +1845,18 @@ impl Renderer { if cfg!(target_arch = "wasm32") || !GpuCompositor::supports(device) { return Err("GPU mask preview is unavailable on this device".into()); } + let set = self.sets.get(ts).ok_or("texture set does not exist")?; let slot = DisplayKind::ALL.len(); let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; let shift = mask_view_shift(set.size); let (width, height) = mask_view_extent(set.size); + // The GPU reads every 2^shift-th texel: the CPU's nearest texel only when both sides divide if (width << shift, height << shift) != set.size { return Err("The mask preview layout uses CPU compositing.".into()); } + let reuse = (old.texture.width(), old.texture.height()) == (width, height); let region = if reuse { program.region } else { None }; let mut submitted = None; @@ -1877,7 +1900,7 @@ impl Renderer { Ok(()) } - // A later submission can fail after an earlier window wrote the bound texture. + // A later submission can fail after an earlier window wrote the bound texture fn invalidate_gpu_writes(&mut self, ts: usize, submitted: Option, slots: impl IntoIterator) { let Some(region) = submitted else { return }; let set = &mut self.sets[ts]; @@ -1901,12 +1924,13 @@ impl Renderer { if size.0 == 0 || size.1 == 0 || size.0.max(size.1) > 256 || size.0 > target.0 || size.1 > target.1 { return; } + if maps.is_empty() { - // A clear is a scene change, not an optional overview. Bind the same - // neutral placeholders used to initialise a set. + // Clearing the scene must bind neutral placeholders even without an overview self.replace_display_seed(device, queue, ts, None); return; } + for (kind, _) in maps { self.ensure_mip_pipeline(device, display_format(*kind)); } @@ -1940,13 +1964,14 @@ impl Renderer { fn replace_display_seed(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, textures: Option>>) { let Some(set) = self.sets.get_mut(ts) else { return }; let pending = match textures { - Some(Checked::Later(textures, answer)) => Some(PendingDisplaySeed { textures, answer: std::sync::Mutex::new(answer), tiles: Vec::new() }), + Some(Checked::Later(textures, answer)) => Some(PendingDisplaySeed { textures, answer: std::sync::Mutex::new(answer), tiles: Default::default() }), Some(Checked::Done(Ok(textures))) => { set.pending_seed = None; install_display_seed(set, textures, device, &self.set_bgl, &self.sampler); self.content_rev += 1; return; } + Some(Checked::Done(Err(_))) | None => None, }; let neutral = DisplayKind::ALL @@ -1990,22 +2015,34 @@ impl Renderer { if source_shift > shift { return; } + let source_side = TILE >> source_shift; let bytes_needed = (source_side * source_side * bytes_per_texel) as usize; if x >= set.size.0 || y >= set.size.1 || bytes.len() < bytes_needed { return; } + if let Some(seed) = &mut set.pending_seed { - // Detail uploads may start in the same frame as the overview. Replay them - // after acceptance so they overwrite only their own part of the overview. - seed.tiles.push(SeedTile { kind, x: tile_x, y: tile_y, bytes: bytes[..bytes_needed].to_vec(), shift: source_shift }); + // Only the latest detail for each target origin must survive the overview allocation + let tile = seed.tiles.entry((kind, x >> set.shift, y >> set.shift)).or_insert_with(|| SeedTile { + kind, + x: tile_x, + y: tile_y, + bytes: Vec::new(), + shift: source_shift, + }); + tile.x = tile_x; + tile.y = tile_y; + tile.shift = source_shift; + tile.bytes.clear(); + tile.bytes.extend_from_slice(&bytes[..bytes_needed]); return; } let display_size = display_dims(set.size, set.shift); let allocation_pending = set.pending.get(kind_index).is_some_and(Option::is_some); if !allocation_pending && (texture.texture.width() < display_size.0 || texture.texture.height() < display_size.1) { - // A neutral tile can still replace non-neutral pixels from the overview. + // A neutral tile can still replace non-neutral pixels from the overview let has_overview = texture.texture.width() > 1 || texture.texture.height() > 1; if set.failed.get(kind_index).copied().unwrap_or(true) || (!has_overview && bytes.chunks_exact(texel.len()).all(|px| px == texel.as_slice())) { return; @@ -2108,6 +2145,7 @@ impl Renderer { { return Err("The Quick Mask coverage does not match the texture set.".into()); } + let size = aux_size(set.size); let slot = DisplayKind::ALL.len(); let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; @@ -2154,8 +2192,7 @@ impl Renderer { return; } - // A pending allocation of another extent (a mesh map view still allocating when the mask - // view takes the slot) is retired: this upload sizes the slot anew + // Retire pending mesh-map allocations when a mask takes the slot at another extent let pending_extent = set.pending.get(aux_index).and_then(Option::as_ref).map(|p| (p.tex.texture.width(), p.tex.texture.height())); if pending_extent.is_some_and(|pending| pending != extent) { set.pending[aux_index] = None; @@ -2243,13 +2280,15 @@ impl Renderer { if matches!(verdict, Err(std::sync::mpsc::TryRecvError::Empty)) { return; } + let Some(seed) = set.pending_seed.take() else { return }; if matches!(verdict, Ok(None)) { install_display_seed(set, seed.textures, device, &self.set_bgl, &self.sampler); self.content_rev += 1; } - // On rejection, the seed is optional and the tiles still refine the neutral set. - for tile in seed.tiles { + + // Replay the details even when the overview is rejected + for tile in seed.tiles.into_values() { self.upload_display_tile(device, queue, ts, tile.kind, tile.x, tile.y, &tile.bytes, tile.shift); } } @@ -2683,9 +2722,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 }, @@ -2696,7 +2741,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), @@ -3221,6 +3267,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, &h.queue); @@ -3265,12 +3328,12 @@ mod tests { assert!(!h.renderer.awaiting_gpu()); } - fn pending_overview(h: &mut Headless) -> std::sync::mpsc::Sender> { + fn pending_overview(h: &mut Headless, texture_set: usize) -> std::sync::mpsc::Sender> { let maps = [(DisplayKind::BaseColor, [255, 0, 0, 255].repeat(64 * 64))]; - h.renderer.seed_display(&h.device, &h.queue, 0, (64, 64), &maps); - let textures = h.renderer.sets[0].tex[..DisplayKind::ALL.len()].to_vec(); + h.renderer.seed_display(&h.device, &h.queue, texture_set, (64, 64), &maps); + let textures = h.renderer.sets[texture_set].tex[..DisplayKind::ALL.len()].to_vec(); let (tx, rx) = std::sync::mpsc::channel(); - h.renderer.replace_display_seed(&h.device, &h.queue, 0, Some(Checked::Later(textures, rx))); + h.renderer.replace_display_seed(&h.device, &h.queue, texture_set, Some(Checked::Later(textures, rx))); tx } @@ -3285,7 +3348,7 @@ mod tests { fn late_overview_keeps_detail_tiles_over_the_coarse_background() { let Ok(mut h) = Headless::new() else { return }; h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0)], 1); - let tx = pending_overview(&mut h); + let tx = pending_overview(&mut h, 0); let kind = DisplayKind::BaseColor; let neutral = kind.default_texel(); let green = [0, 255, 0, 255]; @@ -3308,7 +3371,7 @@ mod tests { let Ok(mut h) = Headless::new() else { return }; let kind = DisplayKind::BaseColor; h.renderer.set_texture_sets(&h.device, &h.queue, &[((256, 256), 0)], 1); - let tx = pending_overview(&mut h); + let tx = pending_overview(&mut h, 0); let green = [0, 255, 0, 255]; h.renderer.upload_tile(&h.device, &h.queue, 0, kind, 1, 0, &green.repeat(64 * 64)); tx.send(Some("overview allocation rejected".into())).unwrap(); @@ -3323,10 +3386,11 @@ mod tests { let kind = DisplayKind::BaseColor; let layout = [((256, 256), 0)]; h.renderer.set_texture_sets(&h.device, &h.queue, &layout, 1); - let tx = pending_overview(&mut h); + let tx = pending_overview(&mut h, 0); h.renderer.upload_tile(&h.device, &h.queue, 0, kind, 1, 0, &[255, 0, 0, 255].repeat(64 * 64)); assert!(h.renderer.set_texture_sets(&h.device, &h.queue, &layout, 1).is_empty()); - // This is the explicit clear used before submitting details for the new view. + + // This is the explicit clear used before submitting details for the new view h.renderer.seed_display(&h.device, &h.queue, 0, (1, 1), &[]); assert!(tx.send(None).is_err(), "the old overview can no longer be accepted"); let green = [0, 255, 0, 255]; @@ -3336,6 +3400,46 @@ mod tests { assert_eq!(base_pixel(&h, 96, 32).as_slice(), kind.default_texel().as_slice()); } + #[test] + fn waiting_for_overviews_keeps_only_the_latest_upload_of_each_detail_tile() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + const SET_COUNT: usize = 2; + const UPDATE_COUNT: u8 = 16; + let kind = DisplayKind::BaseColor; + let extent = (4 * TILE, 4 * TILE); + let texels = (TILE * TILE) as usize; + let sets = [(extent, 0), (extent, 1)]; + gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &sets, SET_COUNT); + let [accept, reject] = std::array::from_fn(|set| pending_overview(&mut gpu, set)); + let detail = |round: u8, set: usize, x: u32| [round, set as u8 + 1, x as u8 + 1, 255]; + + for round in 1..=UPDATE_COUNT { + for set in 0..SET_COUNT { + for x in 0..2 { + let bytes = detail(round, set, x).repeat(texels); + gpu.renderer.upload_tile(&gpu.device, &gpu.queue, set, kind, x, 0, &bytes); + } + } + } + let queued_tiles: usize = gpu.renderer.sets.iter().map(|set| set.pending_seed.as_ref().unwrap().tiles.len()).sum(); + eprintln!("retained detail tiles: {queued_tiles}; payload bytes: {}", queued_tiles * texels * kind.bytes_per_texel()); + + accept.send(None).unwrap(); + reject.send(Some("overview allocation rejected".into())).unwrap(); + prepare(&mut gpu); + + assert!(!gpu.renderer.awaiting_gpu()); + let maps = gpu.renderer.display_textures(); + for (set, maps) in maps.iter().enumerate() { + let (_, _, bytes) = crate::readback::Readback::blocking_level(&gpu.device, &gpu.queue, maps[kind as usize], 0).unwrap(); + for x in 0..2 { + let index = (x * TILE) as usize * kind.bytes_per_texel(); + assert_eq!(bytes[index..index + 4], detail(UPDATE_COUNT, set, x), "the newest upload wins for each tile"); + } + } + assert_eq!(queued_tiles, SET_COUNT * 2, "each distinct tile needs only one queued upload"); + } + #[test] fn the_highlight_draws_only_the_highlighted_sets_edges() { let line_draws = [(0, 4, 0), (4, 6, 1), (10, 2, 2)]; @@ -3428,6 +3532,49 @@ mod tests { assert_eq!(headless.renderer.display_textures()[0][0].width(), 1); } + #[test] + fn a_regional_gpu_update_populates_the_whole_texture_when_replacing_an_overview() { + use crate::gpu_composite::CompositeRegion; + use crate::readback::Readback; + use std::collections::BTreeMap; + use texturecraft_compose::PixelStore; + use texturecraft_core::{Channel, Fill, Layer, LayerKind, Project, Source, TextureSet}; + + let Some(mut gpu) = Headless::for_required_tests() else { return }; + const DETAIL_SIDE: u32 = 2 * TILE; + const OVERVIEW_SIDE: u32 = TILE / 2; + let mut project = Project::new("Regional overview replacement", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, DETAIL_SIDE)); + let id = project.alloc_id(); + let sources = BTreeMap::from([(Channel::BaseColor, Source::Uniform([0.8, 0.2, 0.1]))]); + let fill = Layer::new(id, "Color", LayerKind::Fill(Fill { sources, ..Fill::default() }), &[Channel::BaseColor]); + project.insert_layer(0, fill, None, false).unwrap(); + let region = CompositeRegion { min: [0, 0], max: [TILE, TILE] }; + let mut program = CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, Some(region)).unwrap(); + let kind = DisplayKind::BaseColor; + let overview = [0, 0, 255, 255].repeat((OVERVIEW_SIDE * OVERVIEW_SIDE) as usize); + gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[((DETAIL_SIDE, DETAIL_SIDE), 0)], 1); + gpu.renderer.seed_display(&gpu.device, &gpu.queue, 0, (OVERVIEW_SIDE, OVERVIEW_SIDE), &[(kind, overview)]); + assert_eq!(base_width(&gpu), OVERVIEW_SIDE, "the regional update starts from an installed overview"); + + gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); + let read_detail = |gpu: &Headless| { + let texture = gpu.renderer.display_textures()[0][kind as usize]; + let (width, height, pixels) = Readback::blocking_level(&gpu.device, &gpu.queue, texture, 0).unwrap(); + assert_eq!((width, height), (DETAIL_SIDE, DETAIL_SIDE)); + pixels + }; + let regional = read_detail(&gpu); + + program.region = None; + gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); + let full = read_detail(&gpu); + let outside = ((DETAIL_SIDE * DETAIL_SIDE - 1) as usize) * kind.bytes_per_texel(); + assert_ne!(&full[outside..], kind.default_texel(), "the material reaches outside the requested region"); + assert_eq!(®ional[outside..], &full[outside..], "the replacement must populate the far corner"); + assert!(regional == full, "the replacement matches a full composite"); + } + #[test] fn a_neutral_detail_tile_replaces_only_its_part_of_the_material_overview() { let Ok(mut h) = Headless::new() else { return }; diff --git a/crates/render/src/renderer/pending_display_seed.rs b/crates/render/src/renderer/pending_display_seed.rs new file mode 100644 index 00000000..b7ed5af9 --- /dev/null +++ b/crates/render/src/renderer/pending_display_seed.rs @@ -0,0 +1,12 @@ +use std::collections::BTreeMap; + +use texturecraft_compose::DisplayKind; + +use super::{SeedTile, Tex}; + +pub(super) struct PendingDisplaySeed { + pub(super) textures: Vec, + pub(super) answer: std::sync::Mutex>>, + /// Latest detail upload for each display map and target origin + pub(super) tiles: BTreeMap<(DisplayKind, u32, u32), SeedTile>, +} diff --git a/crates/render/src/renderer/seed_tile.rs b/crates/render/src/renderer/seed_tile.rs new file mode 100644 index 00000000..a584f264 --- /dev/null +++ b/crates/render/src/renderer/seed_tile.rs @@ -0,0 +1,9 @@ +use texturecraft_compose::DisplayKind; + +pub(super) struct SeedTile { + pub(super) kind: DisplayKind, + pub(super) x: u32, + pub(super) y: u32, + pub(super) bytes: Vec, + pub(super) shift: u32, +} diff --git a/crates/render/src/shaders/brush.wgsl b/crates/render/src/shaders/brush.wgsl index 21953dcf..d1dcb92a 100644 --- a/crates/render/src/shaders/brush.wgsl +++ b/crates/render/src/shaders/brush.wgsl @@ -1,3 +1,6 @@ +// Match the CPU bound for a rotated square dab +const PLANAR_RADIUS_SCALE: f32 = 1.42; + struct Params { camera: mat4x4, eye: vec4, // world position, depth bias @@ -22,7 +25,8 @@ struct Dab { // The columns of StampSource::to_source to_source: array, 3>, } -// Corresponds to the BrushAlpha mapping in BrushPipeline::pipeline. + +// Corresponds to the BrushAlpha mapping in BrushPipeline::pipeline override alpha_kind: u32 = 0u; @group(0) @binding(0) var params: Params; @group(0) @binding(3) var uv_surface: texture_2d; @@ -40,12 +44,13 @@ fn unit(v: vec3, fallback: vec3) -> vec3 { return select(fallback, v / max(l, 1e-20), l > 1e-20); } -// Visible from the conservative near depth, and uncertain where the BVH must resolve it. +// Visible from the conservative near depth, and uncertain where the BVH must resolve it fn depth_test(point: vec3) -> vec2 { let clip = params.camera * vec4(point, 1.0); if clip.w <= 1e-6 || any(abs(clip.xy) > vec2(clip.w)) { return vec2(false); } + let uv = clip.xy / clip.w * vec2(0.5, -0.5) + 0.5; let size = vec2(textureDimensions(depth)); let pixel = min(vec2(uv * vec2(size)), size - 1); @@ -90,6 +95,7 @@ fn visible(point: vec3, geometric: vec3, direction: vec3, facing: if test.x { return reach <= 0.0 || depth_test(point).x || ray_visible(point, geometric, direction); } + return test.y && ray_visible(point, geometric, direction); } @@ -107,6 +113,7 @@ fn procedural_alpha(p: vec2, hardness: f32, seed: u32) -> f32 { let k = abs(cos(atan2(p.y, p.x) * 5.0 / 2.0)); return falloff(radius / (0.45 + 0.55 * k * k), hardness); } + default: {} } @@ -118,17 +125,21 @@ fn procedural_alpha(p: vec2, hardness: f32, seed: u32) -> f32 { let n = noise(vec3(p * 14.0, seed_position * 0.37), seed, false); return select(0.0, fall, n > 0.72); } + case 3u: { let n = fbm(vec3(p.x * 2.5 + seed_position * 0.13, p.y * 2.5, 0.5), 5u, seed, true); return fall * clamp((n - 0.42) * 5.0, 0.0, 1.0); } + case 4u: { return fall * fbm(vec3(p * 1.8, seed_position * 0.21), 4u, seed, false); } + case 6u: { let n = noise(vec3(p.x * 0.8, p.y * 18.0, seed_position * 0.7), seed, false); return fall * clamp((n - 0.35) * 3.0, 0.0, 1.0); } + default: { return fall; } } } @@ -180,6 +191,7 @@ fn copy_visible(dab: Dab, point: vec3, view: BrushView) -> bool { if test.x { return reach <= 0.0 || depth_test(allowed).x || ray_visible(allowed, view.geometric, view.direction); } + return test.y && ray_visible(allowed, view.geometric, view.direction); } @@ -216,8 +228,8 @@ fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { let b = vertices[v + 1u]; let c = vertices[v + 2u]; var interpolated = a.normal.xyz * weights.x + b.normal.xyz * weights.y + c.normal.xyz * weights.z; - // Packed barycentrics can leave a residual normal where the vertex normals cancel. - // Recover the full weights near cancellation before deciding whether a dab normal is needed. + + // Recover full barycentric weights near normal cancellation before using the dab normal let packed_error = 4.0 / 65535.0; if dot(interpolated, interpolated) <= packed_error * packed_error { let size = vec2(textureDimensions(uv_surface)); @@ -238,6 +250,7 @@ fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { has_normal = dot(normal, normal) > 0.0; if has_normal { view = brush_view(point, geometric, normal); + // Symmetry copies see the texel from their source's side back_facing = params.flags.y != 0u && view.facing <= 0.0; } @@ -251,11 +264,12 @@ fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { var dab_view = view; let symmetry_copy = !uv_mode && dab.source.w != 0.0; if uv_mode { - let reach = dab.center.w * 1.42; + let reach = dab.center.w * PLANAR_RADIUS_SCALE; let p = vec2(pixel); if any(p < floor(dab.center.xy - reach)) || any(p >= ceil(dab.center.xy + reach)) { continue; } + let d = (p + 0.5 - dab.center.xy) * vec2(1.0, -1.0) / dab.center.w; local = vec2(dot(d, dab.tangent.xy), dot(d, vec2(-dab.tangent.y, dab.tangent.x))); } else { @@ -264,6 +278,7 @@ fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { if dot(local, local) > 2.0 || abs(dot(offset, dab.normal.xyz)) > dab.center.w * dab.normal.w { continue; } + if has_normal && dot(normal, dab.normal.xyz) <= 0.0 { continue; } if symmetry_copy { dab_view = copy_view(dab, point, geometric, select(dab.normal.xyz, normal, has_normal)); @@ -288,6 +303,7 @@ fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { hidden = has_normal; continue; } + tested_visibility = has_normal; } let old = f32(coverage) / 65535.0; diff --git a/crates/render/src/shaders/composite.wgsl b/crates/render/src/shaders/composite.wgsl index d7c87fe2..77dae94d 100644 --- a/crates/render/src/shaders/composite.wgsl +++ b/crates/render/src/shaders/composite.wgsl @@ -1,4 +1,4 @@ -// UV fill compositor. Noise and color conversions follow texel/src/{noise,tile}.rs. +// UV fill compositor. Noise and color conversions follow texel/src/{noise,tile}.rs struct Operation { ids: vec4, low: vec4, @@ -8,56 +8,48 @@ struct Operation { balance: vec4, effects: vec4, procedural: vec4, - // Layer: first content field slot, content and mask field flags. Marker: - // relative content slot or absolute mask field slot. + // Layer fields carry content and mask flags + // Markers address relative content slots or absolute mask slots spatial: vec4, - // Geometry lookup offset, Height operation plus one, contrast and offset. + // Geometry lookup offset, Height operation plus one, contrast and offset constraints: vec4, - // GPU port packages: side-table offset (0: none, read with `param`), P1 projection flags, - // P2/P3/P6/P7 flag bytes, P8 word. Zero for every operation the packages do not emit. + // The optional side-table offset and package flags match the Rust Operation layout ext: vec4, } struct Params { - // Width, row count, top row, reserved texels per map. + // Width, row count, top row, reserved texels per map band: vec4, - // Source width, source height, display sampling step, output mode (roughness or glossiness). + // Source width, source height, display sampling step, output mode (roughness or glossiness) source: vec4, - // Layer count, scratch row pitch, DisplayKind output bits, left column. + // Layer count, scratch row pitch, DisplayKind output bits, left column program: vec4, coverage: vec4, - // Origin and size in tiles, or a sentinel in x for per-image windows. + // Origin and size in tiles, or a sentinel in x for per-image windows paint_window: vec4, - // Source origin and size of the neighborhood fields. + // Source origin and size of the neighborhood fields filter_region: vec4, - // Field word offset, destination slot, layer index, first excluded effect. - // The high bit of the last word selects the mask stack. + // The high effect-index bit selects the mask stack filter_stage: vec4, filter_chunk: vec4, - // Original ID bake dimensions, both zero when absent; bake rows per block (0: one block, the - // whole texture) and the second block's presence bits (bake_has). + // Zero dimensions mark an absent ID bake + // The second block uses the presence bits from bake_has id_bake: vec4, - // Channel, start of anchor owner's draws, content cut, mask preview draw. + // Channel, start of anchor owner's draws, content cut, mask preview draw anchor: vec4, anchor_default: vec4, - // Words per field texel (5, or 6 with the input word), input word present, the prepare - // pass's input operation plus one, the prepare pass's stage flags (bit 0: the stage wraps). - // The fields' origin, filter_region.xy, is i32 bits: it lies below zero with a wrapping stage. + // The field stride includes any optional input words + // Wrapping field origins use signed coordinates field_layout: vec4, - // One vec4 per GPU port package, P1 to P8, written by its `band_uniform` in Rust. + // One vec4 per GPU port package, P1 to P8, written by its `band_uniform` in Rust packages: array, 8>, - // The whole-set pre-pass's outputs the bands read instead of a band field: stage slot plus - // one (0: none), their first word in the scratch buffer, and the region they cover in source - // texels (origin as i32 bits, size). FilterPlan::whole_set in Rust. + // Whole-set slots encode the stage plus one, scratch offset and signed source region whole_slots: vec4, whole_bases: vec4, whole_rect: vec4, - // In a pre-pass with compact slots (WholePass::compact in Rust): its first stage slot, its - // stage count, the program's first working field, and 1 when active. Zero in the bands. + // Compact pre-passes reuse field slots starting at their first stage whole_compact: vec4, - // While preparing a lit Base Color's material and its first mask (FilterPlan:: - // add_lit_mask_views): the layer's mask base plus one, the first mask's base plus one, and - // the This Layer stages (plus one) of the first and of the layer's mask. Zero otherwise. + // Mask-view slots are one-based so zero can mark an inactive view mask_view: vec4, } @@ -72,8 +64,8 @@ struct SurfaceVertex { position: vec4, normal: vec4, } -// Three vertices per triangle (position and U, normal and V), then their tangents (xyz and the -// bitangent sign) two per element: GpuCompositor::uv_surface. + +// Surface vertices store position, UV and normal before the packed tangents @group(0) @binding(7) var surface_vertices: array; @group(0) @binding(8) var bake_maps: texture_2d; @group(0) @binding(9) var brush_alpha: texture_2d; @@ -84,6 +76,7 @@ struct SurfaceVertex { const NO_PAINT_IMAGE = 0xffffffffu; const PROJECTED_BRUSH: u32 = 4u; const GEOMETRY_MASKS: u32 = 8u; +const MIX_BAKED_AO: u32 = 16u; const IMAGE_SOURCE_OPCODE: u32 = 14u; const DECAL_PROJECTION: u32 = 9u; const UV_TILE_PROJECTION: u32 = 10u; @@ -94,21 +87,20 @@ struct Surface { position: vec3, normal: vec3, valid: bool, - // The MikkTSpace tangent (unit xyz) and the bitangent sign in w, as the CPU g-buffer's - // surface_at gives them: xyz interpolated and normalised, the sign of the triangle's first vertex. + // Interpolate and normalize tangent xyz but keep the first vertex's bitangent sign tangent: vec4, } const NO_SURFACE = Surface(vec3(0.0), vec3(0.0, 1.0, 0.0), false, vec4(1.0, 0.0, 0.0, 1.0)); -// The tangent of vertex `vertex` from the block after the vertices. +// The tangent of vertex `vertex` from the block after the vertices fn surface_tangent(vertex: u32) -> vec4 { let vertices = arrayLength(&surface_vertices) * 2u / 3u; let pair = surface_vertices[vertices + vertex / 2u]; return select(pair.position, pair.normal, (vertex & 1u) == 1u); } -// glam's Vec3::any_orthonormal_vector: the tangent the CPU takes where the interpolated one vanishes. +// glam's Vec3::any_orthonormal_vector: the tangent the CPU takes where the interpolated one vanishes fn any_orthonormal(n: vec3) -> vec3 { let sign = select(1.0, -1.0, (bitcast(n.z) >> 31u) == 1u); let a = -1.0 / (sign + n.z); @@ -126,15 +118,17 @@ fn surface_at(pixel: vec2) -> Surface { if (params.coverage.w & 1u) == 0u || any(pixel >= params.source.xy) { return NO_SURFACE; } + let hit = textureLoad(surface_uv, vec2(pixel), 0).xy; if hit.x == 0xffffffffu { return NO_SURFACE; } + let a = surface_vertices[hit.x * 3u]; let b = surface_vertices[hit.x * 3u + 1u]; let c = surface_vertices[hit.x * 3u + 2u]; - // Reconstruct the working position from the original UVs. Packed barycentrics can - // cross a hard procedural cell boundary at high frequencies. + + // Recover position from UVs to avoid crossing hard procedural boundaries let size = vec2(params.source.xy); let uv_a = vec2(a.position.w, a.normal.w) * size; let uv_b = vec2(b.position.w, b.normal.w) * size; @@ -156,8 +150,7 @@ fn surface_at(pixel: vec2) -> Surface { return Surface(position, unit, true, vec4(direction, select(1.0, -1.0, ta.w < 0.0))); } -// One row block of the bake texture: the whole texture, or params.id_bake.z rows when the -// program has the second block (BakedInputs::blocks in Rust). +// A zero block height selects the entire bake texture fn bake_block_size() -> vec2 { let size = textureDimensions(bake_maps); return vec2(size.x, select(params.id_bake.z, size.y, params.id_bake.z == 0u)); @@ -165,12 +158,13 @@ fn bake_block_size() -> vec2 { fn bake_pixel_at(pixel: vec2) -> vec2 { let size = bake_block_size(); + // P8: a UV tile smaller than its atlas block reads its own share of the bake (BlockScales::bake_uv) let uv = udim_bake_uv((vec2(pixel) + 0.5) / vec2(params.source.xy)).xy; return min(vec2(uv * vec2(size)), size - 1u); } -// The second bake row block's maps (ProceduralInputs::read_bake_rows): bits of params.id_bake.w. +// The second bake row block's maps (ProceduralInputs::read_bake_rows): bits of params.id_bake.w const BAKED_HEIGHT: u32 = 1u; const BAKED_WORLD_NORMAL: u32 = 2u; @@ -178,17 +172,18 @@ fn bake_has(maps: u32) -> bool { return (params.id_bake.w & maps) == maps; } -// Row block `block` at the texel: 0 the built-in maps (baked_at), 1 the baked Height in x and the -// stored World Normal in yzw (f32 bits; zeros where bake_has says a map is missing). +// The second block packs height and world normal as float bits fn baked_block_at(pixel: vec2, block: u32) -> vec4 { // P8: no bake where a smaller UV tile leaves its block empty if !udim_bake_valid(pixel) { return udim_absent_bake(block); } + // P8: maps of different heights in rows of their own (params.packages[7].y) if params.packages[7].y != 0u { return udim_separate_bake(pixel, block); } + let at = bake_pixel_at(pixel) + vec2(0u, block * bake_block_size().y); return textureLoad(bake_maps, vec2(at), 0); } @@ -217,7 +212,7 @@ fn gradient_color(op: Operation, t: f32) -> vec3 { } fn wrap_coordinate(coordinate: i32, period: i32) -> i32 { - // Use unsigned remainder so negative operands are consistent across shader backends. + // Use unsigned remainder so negative operands are consistent across shader backends let bits = bitcast(coordinate); let negative = coordinate < 0; let magnitude = select(bits, 0u - bits, negative); @@ -230,32 +225,32 @@ fn azimuth(y: f32, x: f32) -> f32 { return atan2(y, x) / 6.283185307 + 0.5; } -// acos within about one ulp of Rust's f32 acos (Cephes acosf). A backend's own acos can be far -// coarser (llvmpipe's is off by about 1e-5), which moves a nearest texel read across a texel edge +// Use accurate polar angles to keep nearest sampling on the same row as the CPU fn polar_angle(cosine: f32) -> f32 { let x = clamp(cosine, -1.0, 1.0); - if x > 0.5 { - return 2.0 * asin_small(sqrt(0.5 * (1.0 - x))); + if abs(x) <= 0.5 { + return 1.570796327 - asin_small(x); } - if x < -0.5 { - return 3.141592654 - 2.0 * asin_small(sqrt(0.5 * (1.0 + x))); - } - return 1.570796327 - asin_small(x); + + let acute = 2.0 * asin_small(sqrt(0.5 * (1.0 - abs(x)))); + return select(acute, 3.141592654 - acute, x < 0.0); } -// asin of |x| <= 0.5 (Cephes asinf's polynomial) +// Interpolate (asin(x) - x) / x³ at five Chebyshev nodes in x² over [0, 1/4] fn asin_small(x: f32) -> f32 { let z = x * x; - let p = (((4.2163199048e-2 * z + 2.4181311049e-2) * z + 4.5470025998e-2) * z + 7.4953002686e-2) * z + 1.6666752422e-1; - return p * z * x + x; + let correction = (((0.03808502356 * z + 0.026554542206) * z + 0.04500138007) * z + 0.074988550726) * z + 0.16666672415; + return correction * z * x + x; } + fn triplanar_weights(normal: vec3, sharpness: f32) -> vec3 { let axes = abs(normal); let strongest = max(axes.x, max(axes.y, axes.z)); if strongest <= 0.0 { return vec3(0.0); } - // Keep the strongest axis at one to preserve normalized blends at high sharpness. + + // Keep the strongest axis at one to preserve normalized blends at high sharpness let weights = pow(axes / strongest, vec3(sharpness)); return weights / (weights.x + weights.y + weights.z); } @@ -273,28 +268,35 @@ fn value(layer: Operation, uv: vec2, surface: Surface) -> vec3 { let t = select(lightness, lightness * 0.5 + 0.5, (layer.ids.w & 2u) != 0u); return gradient_color(layer, t); } + return select(color, vec3(luminance(color)), (layer.ids.w & 1u) != 0u); } + if layer.ids.y == 0u { return layer.low.rgb; } + if enable_authored_images && layer.ids.y == IMAGE_SOURCE_OPCODE { return authored_image_value(layer, uv, surface); } + return procedural_value(layer, uv, surface); } fn fill_value(layer: Operation, uv: vec2, surface: Surface) -> vec4 { // P8: a reduced pattern's texels per repeat follow the UV tile at the texel let placed = udim_placed(layer, uv); + // P1 (composite_projection.wgsl) evaluates fills that carry projection or sampling flags if placed.ext.y != 0u { return projection_fill_value(placed, uv, surface); } + if !enable_authored_images || placed.procedural.w != DECAL_PROJECTION { // P8: the mesh's own UV on a UV tile atlas, so projections repeat per tile return vec4(value(placed, udim_value_uv(placed, uv), surface), 1.0); } + return decal_fill_value(placed, uv, surface); } @@ -303,21 +305,25 @@ fn stored_sample(layer: Operation, table: u32, origin: vec2, size: vec2= size) { return empty; } + let local = pixel % 64u; let offset = paint[table + tile.y * size.x + tile.x]; if offset == 0u { return empty; } + let texel = offset + (local.y * 64u + local.x) * (layer.ids.w / 2u); let first = paint[texel]; if layer.ids.w == 4u { let second = paint[texel + 1u]; return vec4(vec4(first & 65535u, first >> 16u, second & 65535u, second >> 16u)); } + return vec4(vec3(f32(first & 65535u)), f32(first >> 16u)); } @@ -329,7 +335,9 @@ fn resampled_sample(layer: Operation, image: u32, pixel: vec2, empty: vec4< if all(texels == params.source.xy) { return stored_sample(layer, table, origin, window, pixel, empty); } + let pos = max((vec2(pixel) + 0.5) * vec2(texels) / vec2(params.source.xy) - 0.5, vec2(0.0)); + // The weights from the same floor as the texels (sample_field in neighbourhood.wgsl) let cell = floor(pos); let base = vec2(cell); @@ -346,7 +354,8 @@ fn resampled_sample(layer: Operation, image: u32, pixel: vec2, empty: vec4< fn stored_paint(layer: Operation, pixel: vec2) -> vec4 { let signed = layer.ids.x == 6u; - // An empty signed texel holds the rounded 16-bit encoding of signed zero. + + // An empty signed texel holds the rounded 16-bit encoding of signed zero let empty = vec4(vec3(select(0.0, 32768.0, signed)), 0.0); var raw = empty; if layer.ids.z != NO_PAINT_IMAGE { @@ -384,12 +393,11 @@ fn painted(layer: Operation, pixel: vec2, projected: ProjectedBrush) -> vec m = brush_coverage(pixel) * layer.uv.w; } if m > 0.0 && (layer.ext.z & BRUSH_OP_BITS) != 0u { - // P7 (composite_brush.wgsl) previews the live stroke modes it flags, at the texel's - // pixel and UV (a mask stroke's image value, MaskGray::at) + // Live mask strokes sample the mask image at the texel center let uv = (vec2(pixel) + 0.5) / vec2(params.source.xy); stored = live_brush_paint(layer, stored, m, projected, pixel, uv); } else if m > 0.0 { - // Match the paint commit's premultiplied over and 16-bit channel encoding. + // Match the paint commit's premultiplied over and 16-bit channel encoding let value = select(layer.uv.xxx, layer.uv.xyz, layer.ids.w == 4u); let pigment = select(value, projected.rgba.rgb, layer.projection.w == 2.0); let remaining = 1.0 - m; @@ -405,6 +413,7 @@ fn painted(layer: Operation, pixel: vec2, projected: ProjectedBrush) -> vec if stored.a == 0.0 { return vec4(0.0); } + return vec4(stored.rgb / stored.a, stored.a); } @@ -482,6 +491,7 @@ fn scalar_filter(op: Operation, x: f32) -> f32 { } return lerp(op.high.x, op.high.y, t); } + case 21u: { return 1.0 - x; } case 22u: { // Threshold: ids.z picks at or above, above, below, or at or below the level @@ -491,17 +501,20 @@ fn scalar_filter(op: Operation, x: f32) -> f32 { if op.ids.z == 3u { passes = x <= op.low.x; } return select(0.0, 1.0, passes); } + case 23u: { return clamp((x - 0.5) * (1.0 + clamp(op.low.x, -1.0, 1.0)) + 0.5 + op.low.y, 0.0, 1.0); } case 24u: { let steps = max(floor(clamp(op.low.x, 2.0, 64.0) + 0.5) - 1.0, 1.0); return floor(clamp(x, 0.0, 1.0) * steps + 0.5) / steps; } + case 25u: { return clamp(x, op.low.x, op.low.y); } case 26u: { if op.low.y >= 1.0 { return select(0.0, 1.0, x >= op.low.x); } let width = max(1.0 - clamp(op.low.y, 0.0, 1.0), 1e-3); return clamp((x - op.low.x) / width + 0.5, 0.0, 1.0); } + case 27u: { return clamp(op.low.y + (x - op.low.y) * op.low.x, 0.0, 1.0); } case 28u: { var t = clamp(x, 0.0, 1.0) + clamp(op.low.x, -1.0, 1.0); @@ -509,21 +522,25 @@ fn scalar_filter(op: Operation, x: f32) -> f32 { if t < 0.0 { t += 1.0; } return clamp(t, 0.0, 1.0); } + case 31u: { return shift_unit(clamp(x, 0.0, 1.0), op.low.z); } case 32u: { let shift = color_balance_shift(op, x); return filter_unit(x + (shift.x + shift.y + shift.z) / 3.0); } + case 33u: { if op.procedural.z > 0u { return luminance(gradient_color(op, x)); } return x; } + case 37u: { var passes = abs(x - op.low.x) <= op.low.y; if op.ids.z == 0u { passes = x < op.low.x; } if op.ids.z == 2u { passes = x > op.low.x; } return select(0.0, 1.0, passes); } + // Opcodes without a scalar form here, and the GPU port packages' opcodes default: { return extended_scalar_filter(op, x); } } @@ -533,6 +550,7 @@ fn effect_color(op: Operation, c: vec3, channel: u32, surface: Surface, bak if is_extended_effect(op.ids.y) { return extended_effect_color(op, c, channel, surface, baked_ao); } + if op.ids.y == 35u { if channel != 0u { return c; } let facing = max(0.0, dot(surface.normal, op.high.xyz)); @@ -541,9 +559,11 @@ fn effect_color(op: Operation, c: vec3, channel: u32, surface: Surface, bak let factor = select(1.0, max(0.0, light), abs(light) <= 3.402823466e38); return clamp(c * factor, vec3(0.0), vec3(1.0)); } + if channel == 7u || channel == 11u { return select(c, vec3(c.x, 1.0 - c.y, c.z), op.ids.y == 30u); } + if channel == 0u || (channel >= 8u && channel <= 10u) { if op.ids.y == 29u { return vec3(dot(c, vec3(0.3, 0.59, 0.11))); } if op.ids.y == 31u { return hsl_adjust(c, op.low.xyz); } @@ -551,16 +571,20 @@ fn effect_color(op: Operation, c: vec3, channel: u32, surface: Surface, bak let color = c + color_balance_shift(op, luminance(c)); return vec3(filter_unit(color.r), filter_unit(color.g), filter_unit(color.b)); } + if op.ids.y == 33u { if op.procedural.z > 0u { return gradient_color(op, luminance(c)); } return c; } + if op.ids.y == 34u { return replace_color(op, c); } return vec3(scalar_filter(op, c.r), scalar_filter(op, c.g), scalar_filter(op, c.b)); } + if channel == 6u { return vec3(scalar_filter(op, c.x * 0.5 + 0.5) * 2.0 - 1.0); } + return vec3(scalar_filter(op, c.x)); } @@ -580,8 +604,7 @@ fn overlay(a: f32, b: f32) -> f32 { return select(1.0 - 2.0 * (1.0 - a) * (1.0 - b), 2.0 * a * b, a < 0.5); } -// Most stacks only use the basic modes. Keep the other blend math out -// of those pipelines, where it would be inlined at every blend site. +// Keep uncommon blend math out of the inlined basic pipeline override enable_extended_blend_modes: bool = false; fn blend_scalar(mode: u32, a: f32, b: f32) -> f32 { @@ -614,6 +637,7 @@ fn blend_scalar(mode: u32, a: f32, b: f32) -> f32 { let d = select(sqrt(x), ((16.0 * x - 12.0) * x + 4.0) * x, x <= 0.25); return x + (2.0 * y - 1.0) * (d - x); } + case 20u: { return overlay(b, a); } case 21u: { return select(dodge(a, 2.0 * (b - 0.5)), burn(a, 2.0 * b), b < 0.5); } case 22u: { return select(max(a, 2.0 * b - 1.0), min(a, 2.0 * b), b < 0.5); } @@ -655,6 +679,7 @@ fn blend_rgb(mode: u32, a: vec3, b: vec3) -> vec3 { if width > 1e-6 { saturated = (a - lo) * (maximum(b) - minimum(b)) / width; } return with_luminance(saturated, luminance(a)); } + case 25u: { return with_luminance(b, luminance(a)); } case 26u: { let max_a = maximum(a); @@ -662,12 +687,14 @@ fn blend_rgb(mode: u32, a: vec3, b: vec3) -> vec3 { if max_a <= 1e-6 { return vec3(max_b); } return a * max_b / max_a; } + case 27u: { let p = a * 2.0 - 1.0; let q = b * 2.0 - 1.0; let n = vec3(p.xy + q.xy, p.z * q.z); return n / max(length(n), 1e-6) * 0.5 + 0.5; } + case 28u: { return rnm(a,b); } case 29u: { return rnm(b,a); } default: {} @@ -700,6 +727,7 @@ fn base_content(layer: Operation, texel: LayerTexel) -> vec4 { if layer.ids.y == 10u { return painted(layer, texel.pixel, texel.projected); } + return fill_value(layer, texel.uv, texel.surface); } @@ -733,15 +761,13 @@ fn writes_display(kind: u32) -> bool { } fn display_index(kind: u32, index: u32) -> u32 { - // Normal (2) and Height (3) use two words per pixel. The remaining display - // outputs use one. The Rust band layout omits all inactive outputs. + // Normal and Height need two words per texel while other active outputs need one let earlier = params.program.z & ((1u << kind) - 1u); let offset = countOneBits(earlier) + countOneBits(earlier & 12u); return offset * params.band.w + select(index, 2u * index, kind == 2u || kind == 3u); } -// Find a covered source within the padding radius. The CPU padding's breadth-first -// search breaks equal Chebyshev distances in row-major source order. +// Resolve equal padding distances in the CPU search's row-major order fn padded_source(pixel: vec2) -> vec2 { let pitch = params.coverage.y; let radius = params.coverage.z; @@ -766,6 +792,7 @@ fn padded_source(pixel: vec2) -> vec2 { if dy >= distance { continue; } + let index = row * pitch + start_word; var bits = uv_coverage[index] >> start_bit; if right / 32u != start_word { @@ -795,7 +822,7 @@ fn padded_source(pixel: vec2) -> vec2 { return best; } -// Keep mask preview evaluation out of the material pipeline. +// Keep mask preview evaluation out of the material pipeline override composite_mask_preview: bool = false; @compute @workgroup_size(8, 8) @@ -803,6 +830,7 @@ fn compose(@builtin(global_invocation_id) id: vec3) { if id.x >= params.band.x || id.y >= params.band.y { return; } + let display_pixel = vec2(id.x + params.program.w, id.y + params.band.z); let sample_pixel = display_pixel * params.source.z; var pixel = sample_pixel; @@ -822,7 +850,9 @@ fn compose(@builtin(global_invocation_id) id: vec3) { if (params.coverage.w & 2u) != 0u { let display_bake = baked_at(sample_pixel); let scalars = bitcast>(display_bake.xyz); - display_ao = scalars.x; + if (params.coverage.w & MIX_BAKED_AO) != 0u { + display_ao = scalars.x; + } baked_normal = display_bake.w; if covered { mask_bakes = scalars; @@ -835,10 +865,12 @@ fn compose(@builtin(global_invocation_id) id: vec3) { output[index] = 0xff000000u; return; } + var base = vec3(0.5); var normal = vec3(0.5, 0.5, 1.0); var scalars = array(1.0, 1.0, 0.5, 0.0, 0.5, 0.0); - // Grouped by the destination slots assigned by Rust. + + // Grouped by the destination slots assigned by Rust var lobe_colors = array, 4>(vec3(1.0), vec3(0.04), vec3(0.0), vec3(0.5, 0.5, 1.0)); var lobe_values = array(0.0, 0.5, 0.0, 0.0, 0.1, 0.0, 0.0, 0.0, 0.5); var last_mask = 0xffffffffu; @@ -848,8 +880,8 @@ fn compose(@builtin(global_invocation_id) id: vec3) { triangle = textureLoad(surface_uv, vec2(pixel), 0).x; } var group_depth = 0u; - // The mask preview runs the loop over its one layer, for its mask alone: every mask goes - // through the one layer_mask call below, which the driver inlines once + + // Share the mask call site to avoid inlining a separate copy for each mask var first = 0u; var end = params.program.x; if composite_mask_preview { @@ -869,7 +901,9 @@ fn compose(@builtin(global_invocation_id) id: vec3) { lobe_values = mixed.lobe_values; continue; } + if !group && (layer.ids.x == 0xffffffffu || !geometry_allows(layer.constraints.x, triangle)) && !composite_mask_preview { continue; } + // A folder's mask, or a layer's mask when its mask range changes if composite_mask_preview || group || (layer.effects.y != 0u && last_mask != layer.effects.x) { var mask = 0.0; @@ -883,15 +917,17 @@ fn compose(@builtin(global_invocation_id) id: vec3) { output[index] = (u32(mask * 255.0 + 0.5) * 0x00010101u) | 0xff000000u; return; } + if !group { last_mask = layer.effects.x; mask_value = mask; } else { if mask <= 0.0 { - // The instruction stores the first operation after its END_GROUP. + // The instruction stores the first operation after its END_GROUP i = layer.ids.w - 1u; continue; } + save_group_parent(group_depth, index, mask, MaterialValues(base, normal, scalars, lobe_colors, lobe_values)); group_depth += 1u; continue; diff --git a/crates/render/src/shaders/composite_brush.wgsl b/crates/render/src/shaders/composite_brush.wgsl index 2bbc8147..c5aee796 100644 --- a/crates/render/src/shaders/composite_brush.wgsl +++ b/crates/render/src/shaders/composite_brush.wgsl @@ -1,18 +1,15 @@ -// P7, brush and live stroke on the compositor side (gpu_composite_brush.rs). Owned by the P7 -// agent. Compiled into the composite shader when the program needs it, else replaced by the -// stub string in the Rust module (keep both signatures identical). +// Keep live-brush signatures in sync with the compositor stub -// The stored paint after the live stroke for a paint operation with P7 flags -// (Operation.ext.z & BRUSH_OP_BITS): m is the stroke's coverage times its opacity at the texel, -// stored the premultiplied stored paint, pixel and uv the texel's (uv at the texel centre, as -// MaskGray::at samples). painted() in composite.wgsl calls it. +// Apply coverage times opacity to the stored premultiplied paint fn live_brush_paint(layer: Operation, stored: vec4, m: f32, projected: ProjectedBrush, pixel: vec2, uv: vec2) -> vec4 { if (layer.ext.z & BRUSH_ERASE) != 0u { return erased_paint(layer, stored, m); } + if (layer.ext.z & BRUSH_MASK_IMAGE) != 0u { return gray_over(stored, m, mask_image_gray(param_word(layer, 0u), uv)); } + return stored; } diff --git a/crates/render/src/shaders/composite_content_effects.wgsl b/crates/render/src/shaders/composite_content_effects.wgsl index cc371367..c23661d2 100644 --- a/crates/render/src/shaders/composite_content_effects.wgsl +++ b/crates/render/src/shaders/composite_content_effects.wgsl @@ -23,8 +23,8 @@ fn layer_content(layer: Operation, texel: LayerTexel, count: u32) -> vec4 { skip = previous_field(start, count); } var content = vec4(0.0); - // The layer's own source (paint or fill) and its fill and paint effects go through one - // base_content call: the driver inlines each call site, and a fill can be large (P1) + + // Share the base-content call site to avoid duplicating the inlined fill var base = true; if skip != 0u { let field = layer.spatial.x + layers[start + skip - 1u].spatial.x; @@ -47,10 +47,12 @@ fn layer_content(layer: Operation, texel: LayerTexel, count: u32) -> vec4 { if !base && i >= count { break; } + var effect = layer; if !base { effect = layers[start + i]; } + // A package effect's image input through the same base_content call, before the effect let fetch = !base && !fetched && is_extended_effect(effect.ids.y) && effect.effects.w != 0u; if base || fetch || is_fill_opcode(effect.ids.y) { @@ -64,14 +66,17 @@ fn layer_content(layer: Operation, texel: LayerTexel, count: u32) -> vec4 { fetched = true; continue; } + if base { base = false; content = source; if content.a <= 0.0 && layer.spatial.w == 0u { return vec4(0.0); } + continue; } + content = content_over(content, source, effect, layer.ids.x); } else if is_extended_effect(effect.ids.y) { content = extended_content_effect(effect, content, layer.ids.x, texel); diff --git a/crates/render/src/shaders/composite_curvature_detail.wgsl b/crates/render/src/shaders/composite_curvature_detail.wgsl index 138c8151..ede51f6e 100644 --- a/crates/render/src/shaders/composite_curvature_detail.wgsl +++ b/crates/render/src/shaders/composite_curvature_detail.wgsl @@ -3,6 +3,7 @@ fn generator_curvature(effect: Operation, pixel: vec2, finest: f32, mode: u let offset = u32(effect.uv.x); var edges = 0.0; var cavities = 0.0; + // P8: no curvature where a smaller UV tile leaves its block empty, only the micro height let sizes = select(0u, 7u, udim_bake_valid(pixel)); for (var i = 0u; i < sizes; i++) { diff --git a/crates/render/src/shaders/composite_groups.wgsl b/crates/render/src/shaders/composite_groups.wgsl index ba177969..014e594a 100644 --- a/crates/render/src/shaders/composite_groups.wgsl +++ b/crates/render/src/shaders/composite_groups.wgsl @@ -1,5 +1,4 @@ -// Folder-local state uses spare space after the display and spatial filter -// outputs in the band buffer. The flat material pipeline specializes this off. +// Group snapshots follow display and filter outputs in the band buffer override composite_groups: bool = false; const BEGIN_GROUP: u32 = 200u; const END_GROUP: u32 = 201u; @@ -13,7 +12,7 @@ struct MaterialValues { } fn group_word(depth: u32, channel_word: u32, index: u32) -> u32 { - // Interleave adjacent pixels so a workgroup writes contiguous words. + // Interleave adjacent pixels so a workgroup writes contiguous words return params.filter_stage.y + (depth * params.filter_stage.z + channel_word) * params.band.w + index; } diff --git a/crates/render/src/shaders/composite_lighting.wgsl b/crates/render/src/shaders/composite_lighting.wgsl index 3255633f..b5c03c42 100644 --- a/crates/render/src/shaders/composite_lighting.wgsl +++ b/crates/render/src/shaders/composite_lighting.wgsl @@ -1,6 +1,4 @@ -// P6, lighting and material-reading effects (gpu_composite_lighting.rs). Owned by the P6 agent. -// Compiled into the composite shader when the program needs it, else replaced by the stub -// string in the Rust module (keep both signatures identical). +// Keep lighting entry points compatible with the unlit shader stub // Opcodes and flags as in gpu_composite_lighting.rs const LIGHTING_STYLIZED: u32 = 152u; @@ -49,6 +47,7 @@ fn lighting_content_effect(effect: Operation, content: vec4, channel: u32, if channel != 0u { return content; } + let kind = effect.ids.y; let material = stack_at(effect, texel.pixel); var lit = content.rgb; @@ -82,9 +81,7 @@ fn lighting_baked_height(pixel: vec2) -> f32 { return bitcast(baked_block_at(pixel, 1u).x); } -// The baked height's change per UV unit along U and V at `pixel`, as the CPU's height_slope, and -// 1 in z where there is one: within the texel's UV tile (P8: a UV tile atlas's block, or the -// part of it a smaller tile fills), where every height it reads is baked +// Height slopes stay within the baked part of the current UV tile fn lighting_height_slope(pixel: vec2) -> vec3 { let frame = udim_tile_frame(pixel); let last = min(frame.xy + max(frame.zw, vec2(1u)) - 1u, params.source.xy - 1u); @@ -108,6 +105,7 @@ fn lighting_height_slope(pixel: vec2) -> vec3 { // The baked world normal (the mesh's without one) tilted along the surface tangent by the baked height's slope times `relief`, as the CPU's detail_normal fn lighting_detail_normal(texel: LayerTexel, relief: f32) -> vec3 { var normal = texel.surface.normal; + // P8: no world normal where a smaller UV tile leaves its block empty if bake_has(BAKED_WORLD_NORMAL) && udim_bake_valid(texel.pixel) { let detail = bitcast>(baked_block_at(texel.pixel, 1u).yzw) * 2.0 - 1.0; @@ -124,6 +122,7 @@ fn lighting_detail_normal(texel: LayerTexel, relief: f32) -> vec3 { if slope.z == 0.0 || !lighting_finite(slope.x) || !lighting_finite(slope.y) { return normal; } + let tangent = texel.surface.tangent.xyz; let bitangent = cross(normal, tangent) * texel.surface.tangent.w; let tilted = normal - (tangent * slope.x + bitangent * slope.y) * LIGHTING_HEIGHT_RELIEF * relief; @@ -131,6 +130,7 @@ fn lighting_detail_normal(texel: LayerTexel, relief: f32) -> vec3 { if lighting_finite(reciprocal) && reciprocal > 0.0 { return tilted * reciprocal; } + return normal; } @@ -139,6 +139,7 @@ fn lighting_normal(effect: Operation, texel: LayerTexel) -> vec3 { if (effect.ids.z & LIGHTING_DETAIL_NORMAL) == 0u { return texel.surface.normal; } + return lighting_detail_normal(texel, effect.low.x); } @@ -174,6 +175,7 @@ fn lighting_fade_in(amount: f32, smoothness: f32) -> f32 { if smoothness <= LIGHTING_MIN_SMOOTHNESS { return select(0.0, 1.0, clamped > 0.0); } + return min(clamped / smoothness, 1.0); } @@ -184,6 +186,7 @@ fn lighting_ambient(effect: Operation, normal: vec3) -> vec3 { if up >= 0.0 { return lighting_mix3(horizon, lighting_param3(effect, LIGHTING_SKY_COLOR), up); } + return lighting_mix3(horizon, lighting_param3(effect, LIGHTING_GROUND_COLOR), -up); } @@ -208,6 +211,7 @@ fn lighting_normalize(v: vec3) -> vec3 { if magnitude > LIGHTING_MIN_LENGTH { return v / magnitude; } + return vec3(0.0, 1.0, 0.0); } @@ -301,6 +305,7 @@ const LIGHTING_EXPOSURE: u32 = 4u; const LIGHTING_DIFFUSE_OCCLUSION: u32 = 5u; const LIGHTING_SPECULAR_OCCLUSION: u32 = 6u; const LIGHTING_ENVIRONMENT_DIELECTRIC: u32 = 7u; + // The environment block: nine RGB coefficients, then the viewport's rotation (radians) const LIGHTING_SH_ROTATION: u32 = 27u; @@ -355,6 +360,7 @@ fn lighting_linear_to_srgb(v: f32) -> f32 { if x <= 0.0031308 { return x * 12.92; } + return 1.055 * pow(x, 1.0 / 2.4) - 0.055; } diff --git a/crates/render/src/shaders/composite_mask_effects.wgsl b/crates/render/src/shaders/composite_mask_effects.wgsl index ffdd30b5..2d4ad3d2 100644 --- a/crates/render/src/shaders/composite_mask_effects.wgsl +++ b/crates/render/src/shaders/composite_mask_effects.wgsl @@ -1,15 +1,13 @@ // Operation.ext.z flag of a soft comparison or colour selection (SOFT_MASK_EFFECT in gpu_composite_stack.rs) const SOFT_MASK_EFFECT: u32 = 0x00000100u; -// The fields of a mask stack sit at its first slot (Operation.spatial.z, plus one) and the -// stack's effects hold slots relative to it, so a layer can have a second copy of its mask -// stack: the lit Base Color's material reads the one at params.mask_view.y while preparing -// (FilterPlan::add_lit_mask_views). +// Relative mask slots allow a separate copy for lit base-color preparation fn mask_base(layer: Operation) -> u32 { if params.mask_view.x != 0u && layer.spatial.z == params.mask_view.x { mask_view_active = true; return params.mask_view.y; } + mask_view_active = false; return layer.spatial.z; } @@ -34,13 +32,16 @@ fn layer_mask(layer: Operation, texel: LayerTexel, count: u32) -> f32 { if i >= count { break; } + let e = layers[start + i]; + // A package effect's image input through the same base_content call, before the effect let fetch = !fetched && is_extended_effect(e.ids.y) && e.effects.w != 0u; var stay = false; if e.ids.y == 16u { continue; } + var weight = e.low.w; var result: f32; if fetch || is_fill_opcode(e.ids.y) { @@ -55,6 +56,7 @@ fn layer_mask(layer: Operation, texel: LayerTexel, count: u32) -> f32 { stay = true; continue; } + result = blend_scalar(u32(e.balance.z), mask, sampled.x); weight *= sampled.a; } else if enable_generators && e.ids.y >= 40u && e.ids.y < 48u { @@ -65,12 +67,13 @@ fn layer_mask(layer: Operation, texel: LayerTexel, count: u32) -> f32 { ramp = filter_value(base - 1u + e.spatial.y - 1u, texel.pixel).x; } if e.spatial.z != 0u { - // A generator's region is stored as mask values before later effects read it. + // A generator's region is stored as mask values before later effects read it mask = clamp(mask, 0.0, 1.0); result = blend_scalar(u32(e.balance.z), mask, finish_generator(e, ramp)); mask = clamp(lerp(mask, result, weight), 0.0, 1.0); continue; } + result = blend_scalar(u32(e.balance.z), mask, finish_generator(e, ramp)); } else if is_extended_effect(e.ids.y) { result = extended_mask_effect(e, mask, texel); diff --git a/crates/render/src/shaders/composite_packages.wgsl b/crates/render/src/shaders/composite_packages.wgsl index 6bb35ab2..5fb31845 100644 --- a/crates/render/src/shaders/composite_packages.wgsl +++ b/crates/render/src/shaders/composite_packages.wgsl @@ -1,6 +1,4 @@ -// Registration hub of the GPU port packages in the composite shader (gpu_composite_packages.rs). -// Frozen after Package 0: a package defines its functions in its own file (or stub) and never -// edits this one. The opcode blocks and flag bytes match the Rust constants there. +// Match package opcode blocks and flag bytes to the Rust registration table const FIRST_EXTENDED_EFFECT: u32 = 128u; const END_EXTENDED_EFFECT: u32 = 192u; @@ -10,14 +8,14 @@ const STACK_OPCODES_START: u32 = 144u; const STACK_OPCODES_END: u32 = 152u; const LIGHTING_OPCODES_START: u32 = 152u; const LIGHTING_OPCODES_END: u32 = 160u; + // Flag bytes of Operation.ext.z const POINT_OP_BITS: u32 = 0x000000ffu; const STACK_OP_BITS: u32 = 0x0000ff00u; const LIGHTING_OP_BITS: u32 = 0x00ff0000u; const BRUSH_OP_BITS: u32 = 0xff000000u; -// Fills, paint and patterns: below the built-in effects, and the extended patterns before the -// packages' effects. Generators (40..48) and effects are checked by their callers. +// The caller handles generators and effects separately from fills and patterns fn is_fill_opcode(kind: u32) -> bool { return kind < 20u || (kind >= 48u && kind < FIRST_EXTENDED_EFFECT); } @@ -26,107 +24,110 @@ fn is_extended_effect(kind: u32) -> bool { return kind >= FIRST_EXTENDED_EFFECT && kind < END_EXTENDED_EFFECT; } -// Parameter `index` of an operation from the side table (ProceduralInputs::pack_params). +// Parameter `index` of an operation from the side table (ProceduralInputs::pack_params) fn param(op: Operation, index: u32) -> f32 { return bitcast(srgb[op.ext.x + index]); } -// Raw word `index` of an operation from the side table (ProceduralInputs::pack_words). +// Raw word `index` of an operation from the side table (ProceduralInputs::pack_words) fn param_word(op: Operation, index: u32) -> u32 { return srgb[op.ext.x + index]; } -// scalar_filter's default branch: the packages' opcodes, and x for every other opcode. +// scalar_filter's default branch: the packages' opcodes, and x for every other opcode fn extended_scalar_filter(op: Operation, x: f32) -> f32 { let kind = op.ids.y; if kind >= POINT_OPCODES_START && kind < POINT_OPCODES_END { return point_scalar_filter(op, x); } + if kind >= STACK_OPCODES_START && kind < STACK_OPCODES_END { return stack_scalar_filter(op, x); } + if kind >= LIGHTING_OPCODES_START && kind < LIGHTING_OPCODES_END { return lighting_scalar_filter(op, x); } + return x; } -// A packages' content effect in the layer_content loop: the content (colour, coverage) after the -// effect, opacity (effect.low.w) applied. channel is the destination slot, texel the full texel -// (pixel, UV, surface, bakes) for effects that read more than the colour or change coverage. +// Content hooks return both color and coverage after applying opacity fn extended_content_effect(effect: Operation, content: vec4, channel: u32, texel: LayerTexel) -> vec4 { let kind = effect.ids.y; if kind >= POINT_OPCODES_START && kind < POINT_OPCODES_END { return point_content_effect(effect, content, channel, texel); } + if kind >= STACK_OPCODES_START && kind < STACK_OPCODES_END { return stack_content_effect(effect, content, channel, texel); } + if kind >= LIGHTING_OPCODES_START && kind < LIGHTING_OPCODES_END { return lighting_content_effect(effect, content, channel, texel); } + return content; } -// A packages' mask effect in the layer_mask loop: the effect's result for mask value mask, which -// the loop then mixes in by the effect's opacity (effect.low.w). +// The caller mixes each mask hook result by its opacity fn extended_mask_effect(effect: Operation, mask: f32, texel: LayerTexel) -> f32 { let kind = effect.ids.y; if kind >= PROBE_OPCODES_START && kind < END_EXTENDED_EFFECT { return probe_mask_effect(effect, texel); } + if kind >= POINT_OPCODES_START && kind < POINT_OPCODES_END { return point_mask_effect(effect, mask, texel); } + if kind >= STACK_OPCODES_START && kind < STACK_OPCODES_END { return stack_mask_effect(effect, mask, texel); } + if kind >= LIGHTING_OPCODES_START && kind < LIGHTING_OPCODES_END { return lighting_mask_effect(effect, mask, texel); } + return mask; } -// The channel's material at `pixel` that an effect's stack read asked for (Operation.spatial.w, -// bound by FilterPlan::bind_stack_reads): every layer below the effect's layer, or also its -// own operations before Base Color. Zero without a read. +// Stack reads select the material below the layer or its own earlier operations fn stack_at(effect: Operation, pixel: vec2) -> vec3 { if reading_own_layer && effect.effects.y == 1u { return channel_default((effect.effects.z & 0xffffu) - 1u); } + if effect.spatial.w == 0u { return vec3(0.0); } + return filter_value(effect.spatial.w - 1u, pixel).rgb; } -// The material of the second channel a package effect asked for (Operation.spatial.z, -// FilterPlan::bind_stack_reads): P6's Metallic and Roughness, or Glossiness and Specular. +// The second captured channel supports paired metallic or specular material reads fn stack_at_second(effect: Operation, pixel: vec2) -> vec3 { if reading_own_layer && effect.effects.y == 1u { return channel_default((effect.effects.z >> 16u) - 1u); } + if effect.spatial.z == 0u { return vec3(0.0); } + return filter_value(effect.spatial.z - 1u, pixel).rgb; } -// Set while the prepare pass evaluates the lit Base Color as its mask reads it (OWN_VIEW): the -// CPU evaluates a mask with no lit material (Texel::lit is None while node_mask runs), so the -// layer's own-material reads (Operation.effects.y 1) give the channels' defaults there -// (channel_default; their channel slots plus one in effects.z). +// An own-mask view reads channel defaults while the lit material is being prepared var reading_own_layer: bool = false; // Set by layer_mask while it evaluates the lit layer's first mask (params.mask_view) var mask_view_active: bool = false; -// The effect's layer's own content of the read channel, with its coverage in alpha: Compare's -// This Layer mixes it over stack_at. It reads the field of its This Layer stage (slot plus one in -// Operation.effects.z, FilterPlan::add_this_layer_reads), prepared from the whole content stack -// before the mask: no content code inline in the mask's. +// Prepare This Layer content before the mask to avoid inlining content in mask evaluation fn this_layer_content(effect: Operation, texel: LayerTexel) -> vec4 { var slot = effect.effects.z; + // The lit layer's first mask reads its Base Color without fields or material (mask_view) if mask_view_active && slot == params.mask_view.w { slot = params.mask_view.z; @@ -134,51 +135,50 @@ fn this_layer_content(effect: Operation, texel: LayerTexel) -> vec4 { if slot == 0u { return vec4(0.0); } + let field = filter_value(slot - 1u, texel.pixel); let coverage = clamp(field.a, 0.0, 1.0); return vec4(select(vec3(0.0), field.rgb / coverage, coverage > 1e-5), coverage); } -// A package effect's image input at the texel, read through layer_content's or layer_mask's one -// base_content call right before the effect (the driver inlines each call site) +// Share the base-content call site for an effect's image input var effect_input_cache: vec4 = vec4(0.0); -// The effect's image input at the texel (Operation.effects.w, ProceduralInputs::register_input), -// as P3's stage_input_value reads it: its base content's x. +// Scalar effects read the first component of the registered image input fn effect_input(effect: Operation, texel: LayerTexel) -> f32 { if effect.effects.w == 0u { return 0.0; } + return effect_input_cache.x; } -// The effect's image input as colour (ProceduralInputs::register_color_input). +// The effect's image input as colour (ProceduralInputs::register_color_input) fn effect_input_color(effect: Operation, texel: LayerTexel) -> vec3 { if effect.effects.w == 0u { return vec3(0.0); } + return effect_input_cache.rgb; } -// An image's stored texel under `uv`, wrapping, as ImageRes::sample_nearest reads it (an ID -// map's colours must not blend). `image` is the record offset ProceduralInputs::pack_image's -// side-table word holds (u32 max: missing). +// Sample stored ID colors without interpolation and wrap the UV fn image_texel_nearest(image: u32, uv: vec2) -> vec4 { if image == 0xffffffffu { return vec4(0.0); } + let size = vec2(i32(srgb[image]), i32(srgb[image + 1u])); let pixel = vec2(floor(uv * vec2(size))); return material_image_texel(image, pixel, size); } -// An image's stored texels under `uv` blended bilinearly without wrapping: past an edge it keeps -// the edge texels, as ImageRes::sample_filtered with BilinearSharp and UvWrap::None reads it -// (P7: the brush mask image, MaskGray::at). `image` as for image_texel_nearest. +// Brush mask images interpolate at the clamped edges fn image_texel_bilinear_clamped(image: u32, uv: vec2) -> vec4 { if image == 0xffffffffu { return vec4(0.0); } + let size = vec2(i32(srgb[image]), i32(srgb[image + 1u])); let at = uv * vec2(size) - 0.5; let corner = floor(at); @@ -191,25 +191,24 @@ fn image_texel_bilinear_clamped(image: u32, uv: vec2) -> vec4 { return mix(top, bottom, t.y); } -// Test probes of the hooks above: composite_probes.wgsl, compiled into the render crate's tests -// only (a stub elsewhere, shader_sources in gpu_composite_packages.rs). +// Only tests link the hook probes -// WGSL rejects recursion: a package function must not call anything that leads back to the hook -// that called it (scalar_filter, effect_color, layer_content and layer_mask reach the hooks above, -// fill_value reaches projection_fill_value, painted reaches live_brush_paint). +// WGSL forbids any indirect call back into the originating hook -// effect_color for the packages' opcodes (is_extended_effect). channel is the destination slot -// (channel_slot in Rust: 0 Base Color, 6 Height, 7 Normal, …). +// Extended color effects use the Rust channel-slot ordering fn extended_effect_color(op: Operation, c: vec3, channel: u32, surface: Surface, baked_ao: f32) -> vec3 { let kind = op.ids.y; if kind >= POINT_OPCODES_START && kind < POINT_OPCODES_END { return point_effect_color(op, c, channel, surface, baked_ao); } + if kind >= STACK_OPCODES_START && kind < STACK_OPCODES_END { return stack_effect_color(op, c, channel, surface, baked_ao); } + if kind >= LIGHTING_OPCODES_START && kind < LIGHTING_OPCODES_END { return lighting_effect_color(op, c, channel, surface, baked_ao); } + return c; } diff --git a/crates/render/src/shaders/composite_patterns.wgsl b/crates/render/src/shaders/composite_patterns.wgsl index b57715fb..d80f2b96 100644 --- a/crates/render/src/shaders/composite_patterns.wgsl +++ b/crates/render/src/shaders/composite_patterns.wgsl @@ -1,4 +1,4 @@ -// The nearest squared distance can be clipped to one when no feature ID is needed. +// The nearest squared distance can be clipped to one when no feature ID is needed fn cellular(p: vec3, seed: u32, details: bool) -> vec3 { let cell = vec3(floor(p)); let local = fract(p); @@ -59,12 +59,14 @@ fn pattern(kind: u32, p: vec3, seed: u32) -> f32 { let n = fbm(p, 6u, seed, true) * 0.7 + fbm(p * 3.7, 3u, seed ^ 0x55u, false) * 0.3; return clamp((n - 0.45) * 4.0 + 0.5, 0.0, 1.0); } + case 6u: { let n = noise(p * vec3(0.15, 6.0, 6.0), seed, true); let line = 1.0 - min(abs(n - 0.5) * 40.0, 1.0); let gate = noise(p * 0.8, seed ^ 0x99u, false); return line * clamp((gate - 0.45) * 4.0, 0.0, 1.0); } + case 7u: { let warp = fbm(p * vec3(0.18, 0.6, 1.0), 3u, seed, true); let t = fract((p.y + (warp - 0.5) * 0.9) * 5.0); @@ -73,25 +75,30 @@ fn pattern(kind: u32, p: vec3, seed: u32) -> f32 { let tone = fbm(p * vec3(0.6, 3.0, 1.0), 2u, seed ^ 0x71u, false); return clamp(ring * 0.6 + fiber * 0.25 + tone * 0.15, 0.0, 1.0); } + case 8u: { let turb = fbm(p, 5u, seed, true); let veins = pow(abs(sin((p.x + p.y * 0.5) * 2.5 + turb * 9.0)), 0.3); let cloud = fbm(p * 2.0, 3u, seed ^ 0x19u, false); return clamp(veins * 0.85 + cloud * 0.15, 0.0, 1.0); } + case 11u: { let first = cells(p, seed); let second = cells(p * 2.7 + 13.0, seed ^ 0x6bu); return min(smoothstep(0.08, 0.16, first), smoothstep(0.06, 0.12, second)); } + case 12u: { let first = cells(p * 2.0, seed ^ 0x45u); return smoothstep(0.55, 0.58, fbm(p, 5u, seed, true) + (first - 0.5) * 0.25); } + case 13u: { let fine = noise(p * vec3(37.0, 1.3, 1.0), seed ^ 0x2bu, false); return clamp(max(drip(p, p.x, 0, seed), drip(p, p.x + 0.37, 1, seed) * 0.8) * (0.6 + 0.4 * fine), 0.0, 1.0); } + default: { return extended_pattern(kind, p, seed); } } } @@ -100,6 +107,7 @@ fn raw_procedural(layer: Operation, p: vec3) -> f32 { if layer.ids.y == 80u { return tile_generator(u32(layer.high.w), p.xy); } + return pattern(layer.ids.y, p, layer.ids.z); } @@ -113,7 +121,8 @@ fn sample_procedural(layer: Operation, p: vec3) -> f32 { let offset = vec2(vec2(i % 2u, i / 2u)); let point = select(p.xy, (base + offset) / cells, reduced); let value = raw_procedural(layer, vec3(point, p.z)); - // Keeping the write at constant indices also lets FXC keep this loop rolled. + + // Keeping the write at constant indices also lets FXC keep this loop rolled switch i { case 0u: { values.x = value; } case 1u: { values.y = value; } @@ -174,5 +183,6 @@ fn procedural_value(layer: Operation, uv: vec2, surface: Surface) -> vec3 0u { return gradient_color(layer, t); } + return layer.low.rgb + (layer.high.rgb - layer.low.rgb) * t; } diff --git a/crates/render/src/shaders/composite_point.wgsl b/crates/render/src/shaders/composite_point.wgsl index 6f3ba489..0cb83e7f 100644 --- a/crates/render/src/shaders/composite_point.wgsl +++ b/crates/render/src/shaders/composite_point.wgsl @@ -1,6 +1,4 @@ -// P2, point filters and gradients (gpu_composite_point.rs). Owned by the P2 agent. -// Compiled into the composite shader when the program needs it, else replaced by the stub -// string in the Rust module (keep both signatures identical). +// Keep point filter signatures in sync with the unused-package stub // Opcodes of P2's block that the loop-level hooks test (the constants in gpu_composite_point.rs) const POINT_POSTERIZE_ALPHA: u32 = 129u; @@ -37,12 +35,15 @@ fn point_per_unit(op: Operation, c: vec3, channel: u32) -> vec3 { if channel == POINT_NORMAL_SLOT || channel == POINT_COAT_NORMAL_SLOT { return c; } + if point_is_color(channel) { return vec3(point_scalar_filter(op, c.r), point_scalar_filter(op, c.g), point_scalar_filter(op, c.b)); } + if channel == POINT_HEIGHT_SLOT { return vec3(point_scalar_filter(op, c.x * 0.5 + 0.5) * 2.0 - 1.0); } + return vec3(point_scalar_filter(op, c.x)); } @@ -137,6 +138,7 @@ fn point_curve(shape: u32, x: f32) -> f32 { case 7u: { y = peak; } case 8u: { y = peak * peak; } case 9u: { y = sin(POINT_PI * t); } + // Folded into -π..π, where GPU sines are accurate; |sin(2πt - π)| = |sin(2πt)| case 10u: { y = abs(sin(2.0 * POINT_PI * t - POINT_PI)); } default: { y = 1.0 - abs((2.0 * POINT_TRIANGULAR_TEETH * t) % 2.0 - 1.0); } @@ -166,12 +168,15 @@ fn point_conversion_channel(op: Operation, c: vec3, channel: u32, alpha: f3 if channel == POINT_NORMAL_SLOT || channel == POINT_COAT_NORMAL_SLOT { return c; } + if point_is_color(channel) { return vec3(point_conversion_gray(op, c, alpha)); } + if channel == POINT_HEIGHT_SLOT { return vec3(point_conversion_gray(op, vec3(c.x * 0.5 + 0.5), alpha) * 2.0 - 1.0); } + return vec3(point_conversion_gray(op, vec3(c.x), alpha)); } @@ -190,6 +195,7 @@ fn point_conversion_input(op: Operation, input: vec3, c: vec3, channel if channel == POINT_HEIGHT_SLOT { return vec3(gray * 2.0 - 1.0); } + return vec3(gray); } @@ -199,6 +205,7 @@ fn point_srgb_to_linear(v: f32) -> f32 { if x <= 0.04045 { return x / 12.92; } + return pow((x + 0.055) / 1.055, 2.4); } @@ -234,6 +241,7 @@ fn point_ramp(op: Operation, t: f32) -> vec3 { if (op.ext.z & POINT_GRADIENT_SRGB) == 0u { return color; } + return vec3(point_srgb_to_linear(color.x), point_srgb_to_linear(color.y), point_srgb_to_linear(color.z)); } @@ -242,6 +250,7 @@ fn point_gradient_position(op: Operation, x: f32) -> f32 { if (op.ext.z & POINT_GRADIENT_NEUTRAL_INPUT) != 0u { return x; } + return point_shape_gray(x, op.low.x, op.low.y, op.low.z > 0.5); } @@ -250,6 +259,7 @@ fn point_gradient_gray(op: Operation, gray: f32) -> f32 { if op.procedural.z == 0u { return gray; } + return point_luma(point_ramp(op, point_gradient_position(op, gray))); } @@ -259,15 +269,19 @@ fn point_blurred_gradient(op: Operation, c: vec3, channel: u32, gray: f32) if channel == POINT_NORMAL_SLOT || channel == POINT_COAT_NORMAL_SLOT { return c; } + if point_is_color(channel) { if op.procedural.z == 0u { return c; } + return point_ramp(op, point_gradient_position(op, gray)); } + if channel == POINT_HEIGHT_SLOT { return vec3(point_gradient_gray(op, gray * 0.5 + 0.5) * 2.0 - 1.0); } + return vec3(point_gradient_gray(op, gray)); } @@ -286,20 +300,24 @@ fn point_posterize(steps: f32, x: f32) -> f32 { return floor(filter_unit(x) * steps + 0.5) / steps; } -// A P2 opcode (128..144) on a scalar channel or a mask value. +// A P2 opcode (128..144) on a scalar channel or a mask value fn point_scalar_filter(op: Operation, x: f32) -> f32 { switch op.ids.y { // HSL Perceptive: grays and masks shift their lightness only, as opcode 31 case 128u: { return shift_unit(filter_unit(x), op.low.z); } + // Posterize with Apply to Alpha: the values as plain Posterize, low.x the steps case 129u: { return point_posterize(op.low.x, x); } + // Histogram Scan from the other end: low.x is 1 - position, low.y the contrast case 130u: { if op.low.y >= 1.0 { return select(0.0, 1.0, x >= op.low.x); } let width = max(1.0 - clamp(op.low.y, 0.0, 1.0), POINT_SCAN_MIN_WIDTH); return filter_unit((x - op.low.x) / width + 0.5); } + case 131u: { return filter_unit(point_correct(x, point_tone(op, x))); } + // Smoothstep: low.xy the bounds in order case 132u: { let span = op.low.y - op.low.x; @@ -307,46 +325,52 @@ fn point_scalar_filter(op: Operation, x: f32) -> f32 { let t = clamp((x - op.low.x) / span, 0.0, 1.0); return t * t * (3.0 - 2.0 * t); } + // Height Adjust: low.x 1 to invert, low.y the offset, low.z the multiplier case 133u: { let flipped = select(x, 1.0 - x, op.low.x > 0.5); return filter_unit((flipped - 0.5) * op.low.z + 0.5 + op.low.y); } + // Gradient Curve: low.xyz balance, contrast and 1 to invert, ids.z the shape case 134u: { return point_curve(op.ids.z, point_shape_gray(x, op.low.x, op.low.y, op.low.z > 0.5)); } + // Gradient Dynamic: high.x the colour's luminance case 135u: { return op.high.x; } + // Grayscale Conversion: a mask weighs alpha as 1 case 136u: { return point_conversion_gray(op, vec3(x), 1.0); } + // A gradient on a gray reads its ramp's luminance; a ramp without colours leaves the gray case 137u: { return point_gradient_gray(op, x); } default: { return x; } } } -// A P2 opcode on a content channel; channel is the destination slot (0 Base Color, 6 Height, -// 7 Normal, 8..10 colour lobes; channel_slot in Rust). +// Interpret the destination slot using the compositor's channel layout fn point_effect_color(op: Operation, c: vec3, channel: u32, surface: Surface, baked_ao: f32) -> vec3 { if point_is_color(channel) { switch op.ids.y { case 128u: { return point_perceptive_adjust(op, c); } case 131u: { return point_color_correct(op, c); } + // Gradient Dynamic: low.xyz the colour case 135u: { return op.low.xyz; } case 136u: { return vec3(point_conversion_gray(op, c, 1.0)); } + // A gradient on a colour: ids.z the gray it reads case 137u: { if op.procedural.z == 0u { return c; } return point_ramp(op, point_gradient_position(op, point_gray(op.ids.z, c, 1.0, vec4(0.0)))); } + default: {} } } return point_per_unit(op, c, channel); } -// A point opcode in the layer_content loop: the content after the effect, opacity applied. The -// default mixes point_effect_color by the opacity; take over for coverage or texel reads. +// Coverage-changing point effects need the full content record fn point_content_effect(effect: Operation, content: vec4, channel: u32, texel: LayerTexel) -> vec4 { var filtered: vec3; if effect.ids.y == POINT_GRAYSCALE_CONVERSION && effect.effects.w != 0u { @@ -360,6 +384,7 @@ fn point_content_effect(effect: Operation, content: vec4, channel: u32, tex if effect.procedural.z == 0u { return content; } + // Across each UV tile of a UV tile atlas too (P8: the mesh's own UV) let ramp = point_ramp(effect, fract(udim_mesh_uv(texel.uv).x)); filtered = select(vec3(point_luma(ramp)), ramp, point_is_color(channel)); @@ -376,19 +401,23 @@ fn point_content_effect(effect: Operation, content: vec4, channel: u32, tex return vec4(content.rgb + (filtered - content.rgb) * effect.low.w, coverage); } -// A point opcode in the layer_mask loop: the result the loop mixes in by the opacity. +// A point opcode in the layer_mask loop: the result the loop mixes in by the opacity fn point_mask_effect(effect: Operation, mask: f32, texel: LayerTexel) -> f32 { if effect.ids.y == POINT_GRAYSCALE_CONVERSION && effect.effects.w != 0u { return point_conversion_gray(effect, point_custom_input(effect, texel), 1.0); } + if point_is_gradient_debug(effect) { if effect.procedural.z == 0u { return mask; } + return point_luma(point_ramp(effect, fract(udim_mesh_uv(texel.uv).x))); } + if point_is_gradient_blurred(effect) { return point_gradient_gray(effect, preceding_stage_word(texel.pixel)); } + return point_scalar_filter(effect, mask); } diff --git a/crates/render/src/shaders/composite_probes.wgsl b/crates/render/src/shaders/composite_probes.wgsl index f9e1b745..84fb861c 100644 --- a/crates/render/src/shaders/composite_probes.wgsl +++ b/crates/render/src/shaders/composite_probes.wgsl @@ -1,4 +1,4 @@ -// Test probes of the hooks above (opcodes 188..192, emitted only by the render crate's tests). +// Test probes of the hooks above (opcodes 188..192, emitted only by the render crate's tests) const PROBE_OPCODES_START: u32 = 188u; fn probe_mask_effect(effect: Operation, texel: LayerTexel) -> f32 { switch effect.ids.y { @@ -9,16 +9,13 @@ fn probe_mask_effect(effect: Operation, texel: LayerTexel) -> f32 { if effect.ext.x != 0u { return probe_late_hooks(effect, texel); } + return effect_input(effect, texel); } } } -// Opcode 191 with a selector in its first side-table word probes the P0h hooks: 1..4 the surface -// tangent's x, y, z and sign as 0.5 + 0.5 v, 5 the second stack read, 6 environment word -// param_word(effect, 2u) of the block at param_word(effect, 1u), 7 the baked Height of the bake -// rows (0.25 without one), 8 the baked ambient occlusion where baked_at reads it, 9 the image -// "probe" read bilinearly without wrapping. +// Probe tangent, both stack reads, environment words, baked channels and clamped images fn probe_late_hooks(effect: Operation, texel: LayerTexel) -> f32 { let selector = param_word(effect, 0u); switch selector { @@ -31,8 +28,8 @@ fn probe_late_hooks(effect: Operation, texel: LayerTexel) -> f32 { if !bake_has(BAKED_HEIGHT) { return 0.25; } + return bitcast(baked_block_at(texel.pixel, 1u).x); } } } - diff --git a/crates/render/src/shaders/composite_projection.wgsl b/crates/render/src/shaders/composite_projection.wgsl index 14328a21..2c3952e4 100644 --- a/crates/render/src/shaders/composite_projection.wgsl +++ b/crates/render/src/shaders/composite_projection.wgsl @@ -62,31 +62,42 @@ const P1_KIND_WARP: u32 = 7u; const P1_MISSING: u32 = 0xffffffffu; const P1_ANCHOR_SOURCE: u32 = 15u; + // Operation.ids.w of an image read that returns the samples as stored (no decoding) const P1_RAW_KIND: u32 = 3u; + // An image descriptor's flag: its texels are sRGB encoded (gpu_tile_pattern.rs append_rgba) const P1_SRGB_IMAGE: u32 = 256u; const P1_LARGEST_FLOAT: f32 = 3.402823466e38; + // Floors at or beyond this reduce by the image's period before the integer conversion const P1_LARGEST_TEXEL_INDEX: f32 = 2147483520.0; + // Pattern tiles round and down a spherical projection, and round a cylindrical one (compose pattern.rs) const P1_SPHERE_PATTERN_TILES: vec2 = vec2(4.0, 2.0); const P1_CYLINDER_PATTERN_TILES: f32 = 4.0; + // Lighter triplanar planes than this cannot change a 0..1 pattern (compose pattern.rs TRIPLANAR_SKIP) const P1_TRIPLANAR_SKIP: f32 = 1.0 / 131072.0; const P1_FULL_TURN_DEGREES: f32 = 360.0; const P1_MIN_CYLINDER_ANGLE: f32 = 1.0; + // Where a frame's depth fade starts, as a share of its depth (compose pattern.rs DEPTH_FADE_START) const P1_DEPTH_FADE_START: f32 = 0.75; + // Nearer a cylinder's axis than this a texel counts as facing out (compose projector_cover.rs) const P1_MIN_AXIS_DISTANCE: f32 = 1e-6; const P1_FLOAT_EPSILON: f32 = 1.1920929e-7; + // A warp quad's twist this small against its area counts as parallel sides (compose warp.rs RELATIVE_PARALLEL) const P1_RELATIVE_PARALLEL: f32 = 1e-6; + // A neighbour farther than this share of the image away lies across a UV seam (compose eval.rs SEAM_JUMP_SHARE) const P1_SEAM_JUMP_SHARE: f32 = 0.25; + // Symmetry copies stop once they cover this much (compose eval.rs COVERED) const P1_COVERED: f32 = 0.9999; + // The word of a frame record's alpha image (gpu_image_source.rs decal_words) const P1_DECAL_ALPHA_WORD: u32 = 11u; @@ -275,8 +286,7 @@ fn p1_image_at(image: u32, uv: vec2, layer: Operation) -> vec4 { return full; } - // Blend the two levels round the footprint's level of detail, both through one - // p1_level_sample call (the driver inlines each call site) + // Use one inlined sampling site to blend adjacent mip levels let detail = min(log2(footprint), f32(p1_level_count(image))); let finer = u32(floor(detail)); let toward_coarser = detail - f32(finer); @@ -288,6 +298,7 @@ fn p1_image_at(image: u32, uv: vec2, layer: Operation) -> vec4 { if levels == 1u { return samples[0]; } + return samples[0] + (samples[1] - samples[0]) * toward_coarser; } @@ -381,6 +392,7 @@ fn p1_image_points(op: Operation, coords: P1Coords) -> P1Samples { ); return P1Samples(points, weights); } + case P1_KIND_PLANAR: { let point = p1_local(op, coords).pos * scale.x + offset; var plane = vec2(point.x, -point.y); @@ -391,11 +403,13 @@ fn p1_image_points(op: Operation, coords: P1Coords) -> P1Samples { } return p1_one(p1_place_uv(op, plane * 0.5 + vec2(0.5))); } + case P1_KIND_SPHERICAL: { return p1_one(p1_place_uv(op, p1_sphere(op, p1_local(op, coords).pos) * scale.x)); } case P1_KIND_CYLINDRICAL: { let around = p1_cylinder(op, p1_local(op, coords).pos); return p1_one(p1_place_uv(op, vec2(around.x, 0.5 - around.y * 0.5) * scale.x)); } + default: { return p1_one(p1_place_frame_uv(op, coords.uv)); } } } @@ -422,6 +436,7 @@ fn p1_pattern_points(op: Operation, coords: P1Coords) -> P1Samples { ); return P1Samples(points, select(weights, vec3(0.0), weights < vec3(skip))); } + case P1_KIND_PLANAR: { let point = p1_local(op, coords).pos * scale.x * pattern_scale + offset; var plane = vec2(point.x, point.y); @@ -432,14 +447,17 @@ fn p1_pattern_points(op: Operation, coords: P1Coords) -> P1Samples { } return p1_one(p1_place_uv(op, plane)); } + case P1_KIND_SPHERICAL: { let sphere = p1_sphere(op, p1_local(op, coords).pos); return p1_one(p1_place_uv(op, sphere * P1_SPHERE_PATTERN_TILES * scale.x * pattern_scale)); } + case P1_KIND_CYLINDRICAL: { let around = p1_cylinder(op, p1_local(op, coords).pos); return p1_one(p1_place_uv(op, vec2(around.x * P1_CYLINDER_PATTERN_TILES, around.y) * scale.x * pattern_scale)); } + default: { return p1_one(p1_place_frame_uv(op, coords.uv) * pattern_scale); } } } @@ -462,15 +480,17 @@ fn p1_read_image(op: Operation, image: u32, point: vec2, surface: Surface, read.ids.w = kind; read.procedural.w = P1_POINT_PROJECTION; read.projection = vec4(footprint, select(0.0, 1.0, linear), 0.0, 0.0); - // `authored_image_value` at a projected point alone: the other projections and the patterns - // would be inlined at every read + + // Isolate projected image reads from the other projection and pattern paths if image == MISSING_IMAGE { return vec3(0.5); } + let sampled = p1_image_at(image, point, read); if kind == P1_ALPHA_KIND { return vec3(sampled.a); } + return decode_image_sample(read, sampled.rgb); } @@ -509,8 +529,7 @@ fn p1_image_value(op: Operation, samples: P1Samples, surface: Surface, footprint } } -// A procedural source read at its pattern points: the pattern code weighs and shapes them -// (`value` of the returned operation) +// Let the pattern combine and weight its projected samples fn p1_procedural_planes(op: Operation, samples: P1Samples) -> Operation { var planes = op; planes.procedural.w = P1_PLANES_PROJECTION; @@ -823,8 +842,7 @@ fn p1_footprints(op: Operation, samples: P1Samples, uv: vec2, neighbours: P let source = vec2(params.source.xy); let kind = param_word(op, P1_KIND); if kind == P1_KIND_UV || kind == P1_KIND_UV_TILE { - // The current tile's affine mapping, even where a neighbour wraps or is uncovered - // P8: in a UV tile atlas, the mesh UV step of the texel's own tile + // Use the current tile's UV step across uncovered or wrapped neighbours let uv_step = udim_mesh_uv_step(vec2(uv * source)); var span = max(uv_step.x * size.x, uv_step.y * size.y); if kind == P1_KIND_UV { @@ -1012,6 +1030,7 @@ fn p1_copied(surface: Surface, copy: P1Copy) -> Surface { // The fill sampled once through `copy`: its value and its coverage (compose Texel::fill_texel) fn p1_fill_once(op: Operation, uv: vec2, surface: Surface, neighbours: P1Neighbours, copy: P1Copy) -> vec4 { let copied = p1_copied(surface, copy); + // P8: projections see the mesh's own UV on a UV tile atlas, so they repeat per tile let coords = P1Coords(udim_mesh_uv(uv), copied.position, copied.normal); let projected = p1_projected(op, coords, copied); @@ -1087,9 +1106,7 @@ fn p1_copy(op: Operation, index: u32, pivot: vec3) -> P1Copy { return copy; } -// Every copy of a symmetric fill laid over the others, the texel's own copy on top (compose Texel::symmetric_copies, in mesh radii) -// `symmetric` false: the fill once, as it is (one p1_fill_once call site for both: the driver -// inlines each call site) +// Overlay symmetry copies with the texel's own copy last fn p1_symmetric(op: Operation, uv: vec2, surface: Surface, neighbours: P1Neighbours, symmetric: bool) -> vec4 { var pivot = vec3(0.0); var axis = 0u; @@ -1119,6 +1136,7 @@ fn p1_symmetric(op: Operation, uv: vec2, surface: Surface, neighbours: P1Ne if !symmetric { return one; } + let weight = clamp(one.a, 0.0, 1.0) * (1.0 - cover); color += one.rgb * weight; cover += weight; diff --git a/crates/render/src/shaders/composite_spatial.wgsl b/crates/render/src/shaders/composite_spatial.wgsl index cd081e23..571d0081 100644 --- a/crates/render/src/shaders/composite_spatial.wgsl +++ b/crates/render/src/shaders/composite_spatial.wgsl @@ -1,8 +1,5 @@ -// Each scratch texel holds four float components followed by UV coverage, and a sixth word (the -// stage's input, FilterStage::input in Rust) when params.field_layout.y is set, or three words -// (the input's colour) when the stride is eight. -// A whole-set pre-pass keeps only its own stages and the working fields (whole_compact): a slot -// outside them has no field there (u32 max). +// Optional input words follow the four components and UV coverage +// Compact pre-passes expose only their own slots and working fields fn field_word(slot: u32, local: vec2) -> u32 { let size = params.filter_region.zw; var compact = slot; @@ -19,32 +16,29 @@ fn field_word(slot: u32, local: vec2) -> u32 { return params.filter_stage.x + (compact * size.x * size.y + local.y * size.x + local.x) * params.field_layout.x; } -// The fields' origin in source texels. It lies below zero when the program has a wrapping -// stage (FilterPlan::wraps in Rust), so read it signed. +// Read the field origin as signed when a wrapping halo extends below zero fn field_origin() -> vec2 { return bitcast>(params.filter_region.xy); } -// The field texel a periodic prepare pass writes (u32 max otherwise): there every field read -// (lower stages, anchors, generator ramps) takes the same copy of the set, not the pixel's -// position inside the set. +// All reads during periodic preparation must use the same copy of the set var periodic_local: vec2 = vec2(0xffffffffu); -// The texel of a field at source pixel `pixel`, or None (u32 max) outside the field. +// The texel of a field at source pixel `pixel`, or None (u32 max) outside the field fn field_local(pixel: vec2) -> vec2 { if periodic_local.x != 0xffffffffu { return periodic_local; } + let local = vec2(pixel) - field_origin(); if any(local < vec2(0)) || any(local >= vec2(params.filter_region.zw)) { return vec2(0xffffffffu); } + return vec2(local); } -// The first word of stage `slot` at source pixel `pixel`, or u32 max outside its field. A -// whole-set stage (whole_slots) reads the pre-pass result at the pixel, also in a periodic -// prepare pass; any other stage its band field. +// Whole-set stages read pre-pass results while local stages read the current band fn slot_word(stage_slot: u32, pixel: vec2) -> u32 { // P8: a texel of a smaller UV tile reads its tile scale's level stage let slot = udim_level_slot(stage_slot, pixel); @@ -55,6 +49,7 @@ fn slot_word(stage_slot: u32, pixel: vec2) -> u32 { if any(local < vec2(0)) || any(local >= vec2(params.whole_rect.zw)) { return 0xffffffffu; } + // P8: a level stage's result follows its base stage's let result = (slot - stage_slot) * params.whole_rect.z * params.whole_rect.w; return params.whole_bases[k] + (result + u32(local.y) * params.whole_rect.z + u32(local.x)) * params.field_layout.x; @@ -65,6 +60,7 @@ fn slot_word(stage_slot: u32, pixel: vec2) -> u32 { if local.x == 0xffffffffu { return 0xffffffffu; } + return field_word(slot, local); } @@ -73,27 +69,28 @@ fn filter_value(slot: u32, pixel: vec2) -> vec4 { if start == 0xffffffffu { return vec4(0.0); } + return bitcast>(vec4(output[start], output[start + 1u], output[start + 2u], output[start + 3u])); } -// The field the layer_content or layer_mask loop resumed from (its preceding stage), or none. +// The field the layer_content or layer_mask loop resumed from (its preceding stage), or none var preceding_field: u32 = 0xffffffffu; -// Word 4 of the preceding stage's output field at `pixel`: a stage's output keeps its coverage -// there, which no reader uses, so a stage can leave a second value in it (P4's pre-blur gray -// for P2's gradient after `precede_with_stage`). Zero outside the field or without a stage. +// A stage may reuse its unused output coverage word for pre-blur gray fn preceding_stage_word(pixel: vec2) -> f32 { if preceding_field == 0xffffffffu { return 0.0; } + let start = slot_word(preceding_field, pixel); if start == 0xffffffffu { return 0.0; } + return bitcast(output[start + 4u]); } -// The most recent prepared field already contains all the effects below it. +// The most recent prepared field already contains all the effects below it fn previous_field(start: u32, count: u32) -> u32 { for (var i = count; i > 0u; i--) { if layers[start + i - 1u].ids.y == SPATIAL_FILTER_OPCODE { @@ -103,8 +100,7 @@ fn previous_field(start: u32, count: u32) -> u32 { return 0u; } -// Bits of the prepare pass's params.field_layout.w besides bit 0 (the stage wraps): how it reads -// its input (FilterStage::input_kind in Rust) +// The prepare flags encode wrapping and input kind const INPUT_LAYER: u32 = 2u; const INPUT_COLOR: u32 = 4u; const OWN_VIEW: u32 = 8u; @@ -116,10 +112,10 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { if any(id.xy >= params.filter_chunk.zw) { return; } + let local = params.filter_chunk.xy + id.xy; - // A field can start below zero. In a wrapping program (field_layout.w bit 0) every stage's - // field holds periodic copies of the set there, and reads the lower fields at the same copy; - // otherwise the field lies inside the set. + + // Periodic copies must read lower stages in the same copy of the set let position = field_origin() + vec2(local); var pixel = vec2(max(position, vec2(0))); var covered = all(position >= vec2(0)) && all(pixel < params.source.xy); @@ -149,8 +145,8 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { let texel = LayerTexel(pixel, uv, surface, baked, projected); let layer = layers[params.filter_stage.z]; let count = params.filter_stage.w & 0x0fffffffu; - // Every mask and every content goes through one layer_mask and one layer_content call - // below, which the driver inlines once each (the call sites, not the paths, set the size) + + // Share mask and content call sites so each is inlined once let flags = params.filter_stage.w; let capture = enable_anchor_reads && (flags & 0x20000000u) != 0u; let anchor_mask = enable_anchor_reads && !capture && (flags & 0x10000000u) != 0u; @@ -164,9 +160,8 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { let source = layers[params.program.x + layer.effects.x + count]; prepared = vec4(generator_ramp(source, texel), 0.0, 0.0, 1.0); } - // One loop evaluates what the stage needs: a capture's layers below (their masks and - // contents blended as the anchor capture does), the stage's mask or its content, and a - // layer operation's content as its input (Height To Normal's own Height, INPUT_LAYER) + + // Use the same stack traversal for lower layers, capture and input reads let input_layer = params.field_layout.z != 0u && (params.field_layout.w & INPUT_LAYER) != 0u; var first = params.filter_stage.z; var end = first + select(1u, 0u, generator); @@ -194,10 +189,12 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { result = mix(parents[depth], result, weight); continue; } + if !(composite_groups && source.ids.y == BEGIN_GROUP) && source.ids.x != channel { continue; } } + // The mask: a capture's folders and layers (with their height masks), or the stage's var value = 1.0; if !input && (capture || mask) { @@ -212,16 +209,19 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { prepared = select(vec4(value, 0.0, 0.0, 1.0), vec4(vec3(value), 1.0), anchor_mask); continue; } + if composite_groups && source.ids.y == BEGIN_GROUP { parents[depth] = result; group_masks[depth] = value; depth += 1u; continue; } + if value <= 0.0 { continue; } } + // The content var source_count = count; if input { @@ -229,8 +229,7 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { } else if capture { source_count = select(source.effects.w, min(source.effects.w, params.anchor.z), i >= params.anchor.y); } else { - // A view of the layer for its mask (This Layer): its own material as the - // defaults (OWN_VIEW), its stages as identity (NO_FIELDS) + // A mask's own-layer view reads default material with identity stages reading_own_layer = (params.field_layout.w & OWN_VIEW) != 0u; if (params.field_layout.w & NO_FIELDS) != 0u { source.spatial.y = 0u; @@ -258,8 +257,8 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { if capture { prepared = vec4(result, 1.0); } - // The input sources: the first (unless a layer operation), and a second one (INPUT2, - // its colour); one base_content call (P3's stage_input_value is its base content's x) + + // Read both input sources through one base-content call site let second = (params.field_layout.w & INPUT2) != 0u; let sources = select(1u, 2u, second); for (var k = select(0u, 1u, params.field_layout.z == 0u || input_layer); k < sources; k++) { diff --git a/crates/render/src/shaders/composite_stack.wgsl b/crates/render/src/shaders/composite_stack.wgsl index f590a1b6..d6aff308 100644 --- a/crates/render/src/shaders/composite_stack.wgsl +++ b/crates/render/src/shaders/composite_stack.wgsl @@ -1,47 +1,46 @@ -// P3, stack plumbing and mask effects (gpu_composite_stack.rs). Owned by the P3 agent. -// Compiled into the composite shader when the program needs it, else replaced by the stub -// string in the Rust module (keep both signatures identical). +// Keep stack hook signatures compatible with the compositor stub -// A P3 opcode (144..152) on a scalar channel or a mask value. +// A P3 opcode (144..152) on a scalar channel or a mask value fn stack_scalar_filter(op: Operation, x: f32) -> f32 { return x; } -// A P3 opcode on a content channel; channel is the destination slot. +// A P3 opcode on a content channel; channel is the destination slot fn stack_effect_color(op: Operation, c: vec3, channel: u32, surface: Surface, baked_ao: f32) -> vec3 { return c; } -// The sixth word of a stage field (FilterStage::input): the input operation's value at the -// texel, written by prepare_filter in composite_spatial.wgsl. +// The prepare pass writes the optional input value in the sixth field word fn stage_input_value(op: Operation, texel: LayerTexel) -> f32 { return base_content(op, texel).x; } -// A stack opcode in the layer_content loop: the content after the effect, opacity applied. The -// default mixes stack_effect_color by the opacity; take over for coverage or texel reads. +// Handle coverage changes before applying the content effect's opacity fn stack_content_effect(effect: Operation, content: vec4, channel: u32, texel: LayerTexel) -> vec4 { let filtered = stack_effect_color(effect, content.rgb, channel, texel.surface, texel.baked.x); return vec4(content.rgb + (filtered - content.rgb) * effect.low.w, content.a); } -// A stack opcode in the layer_mask loop: the result the loop mixes in by the opacity. +// A stack opcode in the layer_mask loop: the result the loop mixes in by the opacity fn stack_mask_effect(effect: Operation, mask: f32, texel: LayerTexel) -> f32 { if effect.ids.y == STACK_LAYER_COMPARE { // A comparison blends its pass or fail into the mask like a fill return blend_scalar(u32(effect.balance.z), mask, stack_layer_compare(effect, mask, texel)); } + return stack_scalar_filter(effect, mask); } // A mask comparison reading layers (LAYER_COMPARE in gpu_composite_stack.rs) const STACK_LAYER_COMPARE: u32 = 144u; + // Side codes in ids.w, four bits each, left side first (the *_SIDE constants in Rust) const STACK_SIDE_BITS: u32 = 4u; const STACK_SIDE_MASK: u32 = 15u; const STACK_MASK_SIDE: u32 = 0u; const STACK_CONSTANT_SIDE: u32 = 1u; const STACK_THIS_LAYER_SIDE: u32 = 3u; + // The compared channel's kind in ids.w from bit 8 (the *_KIND constants in Rust) const STACK_KIND_SHIFT: u32 = 8u; const STACK_KIND_MASK: u32 = 255u; @@ -53,6 +52,7 @@ fn stack_compare_side(op: Operation, side: u32, mask: f32, texel: LayerTexel) -> if side == STACK_MASK_SIDE { return mask; } + if side == STACK_CONSTANT_SIDE { return op.low.x; } @@ -69,9 +69,11 @@ fn stack_compare_side(op: Operation, side: u32, mask: f32, texel: LayerTexel) -> if kind == STACK_SCALAR_KIND { return read.x; } + if kind == STACK_SIGNED_KIND { return read.x * 0.5 + 0.5; } + return luminance(read); } @@ -105,9 +107,11 @@ fn stack_soft_compare(op: Operation, mask: f32) -> f32 { if op.ids.z == 0u { return clamp((op.low.x - mask) / width, 0.0, 1.0); } + if op.ids.z == 2u { return clamp((mask - op.low.x) / width, 0.0, 1.0); } + return clamp(1.0 + (op.low.y - abs(mask - op.low.x)) / width, 0.0, 1.0); } @@ -153,5 +157,6 @@ fn stack_color_selection(effect: Operation, texel: LayerTexel) -> vec2 { if background < 0.0 { return vec2(output, amount); } + return vec2(background + (output - background) * amount, 1.0); } diff --git a/crates/render/src/shaders/composite_udim.wgsl b/crates/render/src/shaders/composite_udim.wgsl index 576b935e..10d5e4fd 100644 --- a/crates/render/src/shaders/composite_udim.wgsl +++ b/crates/render/src/shaders/composite_udim.wgsl @@ -1,10 +1,6 @@ -// P8, UDIM texture sets and baked layouts (gpu_composite_udim.rs). Owned by the P8 agent. -// Compiled into the composite shader when the program needs it. P8 defines its per-tile -// functions here; the stub string in the Rust module must declare the same signatures. +// Keep UV-tile entry points compatible with the classic-set stub -// A UV tile atlas's record in the side table (udim::bind in Rust), at params.packages[7].x (0 for -// a classic set): its grid, block side, flags and stage level table, then each block's scale (f32 -// bits) and level, row by row +// Each block's scale and level follows the grid and stage-level header const UDIM_COLS: u32 = 0u; const UDIM_ROWS: u32 = 1u; const UDIM_COL: u32 = 2u; @@ -13,11 +9,14 @@ const UDIM_BLOCK: u32 = 4u; const UDIM_FLAGS: u32 = 5u; const UDIM_SLOTS: u32 = 6u; const UDIM_SCALES: u32 = 7u; + // UDIM_FLAGS: a tile has a resolution of its own (TextureSet::from_atlas undoes its scale) const UDIM_SCALED: u32 = 1u; + // The anchor source opcode (ANCHOR_SOURCE in Rust): it reads its field at the texel const UDIM_ANCHOR_SOURCE: u32 = 15u; const UDIM_NONE: u32 = 0xffffffffu; + // The bake maps of separate heights (BakedInputs::separate in Rust): 4 built-in maps, then 2 row maps const UDIM_BUILT_IN_MAPS: u32 = 4u; const UDIM_ROW_MAPS: u32 = 2u; @@ -40,6 +39,7 @@ fn udim_block_index(pixel: vec2) -> u32 { if record == 0u || cell.x >= cols || cell.y >= srgb[record + UDIM_ROWS] { return UDIM_NONE; } + return cell.y * cols + cell.x; } @@ -49,6 +49,7 @@ fn udim_scale_at(pixel: vec2) -> f32 { if index == UDIM_NONE { return 1.0; } + return bitcast(srgb[udim_record() + UDIM_SCALES + index]); } @@ -58,6 +59,7 @@ fn udim_level_at(pixel: vec2) -> u32 { if index == UDIM_NONE { return 0u; } + let record = udim_record(); let blocks = srgb[record + UDIM_COLS] * srgb[record + UDIM_ROWS]; return srgb[record + UDIM_SCALES + blocks + index]; @@ -71,8 +73,7 @@ fn udim_grid_uv(uv: vec2) -> vec2 { return vec2(across, down); } -// The scale of the UV tile holding mesh UV `mesh` (TextureSet::tile_scale of udim_at): its -// block's, 1 outside the grid +// Use unit scale outside the UV grid fn udim_tile_scale(mesh: vec2) -> f32 { let record = udim_record(); let cols = srgb[record + UDIM_COLS]; @@ -80,16 +81,17 @@ fn udim_tile_scale(mesh: vec2) -> f32 { if any(cell < vec2(0)) || cell.x >= i32(cols) || cell.y >= i32(srgb[record + UDIM_ROWS]) { return 1.0; } + return bitcast(srgb[record + UDIM_SCALES + u32(cell.y) * cols + u32(cell.x)]); } -// The mesh's own UV at atlas UV `uv` (TextureSet::from_atlas): projections and patterns see it, -// so they repeat per UV tile (Texel::tile_uv) +// Use mesh UVs so projections and patterns repeat within each UV tile fn udim_mesh_uv(uv: vec2) -> vec2 { let record = udim_record(); if record == 0u { return uv; } + let mesh = udim_grid_uv(uv); if (srgb[record + UDIM_FLAGS] & UDIM_SCALED) == 0u { return mesh; @@ -99,12 +101,12 @@ fn udim_mesh_uv(uv: vec2) -> vec2 { return corner + (mesh - corner) / udim_tile_scale(mesh); } -// The UV a fill's value reads at atlas UV `uv`: the mesh's own, except for an anchor, which reads -// its field at the texel +// Anchors address the atlas field while other fills use mesh UVs fn udim_value_uv(layer: Operation, uv: vec2) -> vec2 { if layer.ids.y == UDIM_ANCHOR_SOURCE { return uv; } + return udim_mesh_uv(uv); } @@ -115,6 +117,7 @@ fn udim_mesh_uv_step(pixel: vec2) -> vec2 { if record == 0u { return atlas_step; } + let grid_step = atlas_step * vec2(f32(srgb[record + UDIM_COLS]), f32(srgb[record + UDIM_ROWS])); if (srgb[record + UDIM_FLAGS] & UDIM_SCALED) == 0u { return grid_step; @@ -125,50 +128,51 @@ fn udim_mesh_uv_step(pixel: vec2) -> vec2 { return grid_step / udim_tile_scale(udim_grid_uv(atlas_uv)); } -// A fill with its reduced pattern's texels per repeat at the UV tile of atlas UV `uv`: P8's -// ext.w is the side-table table of them per level (udim::pattern_levels in Rust) +// Select the reduced pattern resolution for this tile's level fn udim_placed(layer: Operation, uv: vec2) -> Operation { if layer.ext.w == 0u { return layer; } + var placed = layer; placed.procedural.x = srgb[layer.ext.w + udim_level_at(vec2(uv * vec2(params.source.xy)))]; return placed; } -// The stage slot a texel at `pixel` reads for stage `slot`: the level stage of its block's tile -// scale where level stages follow the stage (FilterStage::level in Rust) +// Read the stage variant matching this block's tile scale fn udim_level_slot(slot: u32, pixel: vec2) -> u32 { let record = udim_record(); if record == 0u { return slot; } + let table = srgb[record + UDIM_SLOTS]; if table == 0u || slot >= srgb[table] || srgb[table + 1u + slot] == 0u { return slot; } + return slot + udim_level_at(pixel); } -// The UV tile's origin and sides at `pixel` (x, y, width, height), where a height slope stays -// (Texel::height_slope): the whole set for a classic set +// Bound height slopes to the current tile or the entire classic set fn udim_tile_frame(pixel: vec2) -> vec4 { let record = udim_record(); if record == 0u { return vec4(0u, 0u, params.source.xy); } + let block = max(srgb[record + UDIM_BLOCK], 1u); let tile = max(u32(udim_round(f32(block) * udim_scale_at(pixel))), 1u); return vec4(pixel / block * block, tile, tile); } -// Working atlas UV to bake atlas UV, without the part of a block a smaller UV tile leaves empty -// (BlockScales::bake_uv): z is 0 where no bake lies +// Exclude the unfilled area of a reduced tile from its bake lookup fn udim_bake_uv(uv: vec2) -> vec3 { let record = udim_record(); if record == 0u || (srgb[record + UDIM_FLAGS] & UDIM_SCALED) == 0u { return vec3(uv, 1.0); } + let block = f32(max(srgb[record + UDIM_BLOCK], 1u)); let size = vec2(params.source.xy); let position = uv * size / block; @@ -177,6 +181,7 @@ fn udim_bake_uv(uv: vec2) -> vec3 { if any(local < vec2(0.0)) || any(local >= vec2(1.0)) { return vec3(uv, 0.0); } + return vec3((origin + local) * block / size, 1.0); } @@ -185,17 +190,16 @@ fn udim_bake_valid(pixel: vec2) -> bool { return udim_bake_uv((vec2(pixel) + 0.5) / vec2(params.source.xy)).z != 0.0; } -// Row block `block`'s texel where no bake lies: each map's value when it is not baked -// (GpuCompositor::baked_input in Rust) +// Missing map samples use the same defaults as the Rust bake uploader fn udim_absent_bake(block: u32) -> vec4 { if block == 1u { return vec4(0u); } + return vec4(bitcast(1.0), bitcast(0.5), bitcast(1.0), 0u); } -// Row block `block`'s texel at `pixel` when the baked maps have different heights: each map from -// the rows of its own height, found in the header row params.packages[7].y - 1 +// The atlas header locates rows for maps with different heights fn udim_separate_bake(pixel: vec2, block: u32) -> vec4 { let header = params.packages[7].y - 1u; let width = textureDimensions(bake_maps).x; @@ -208,9 +212,11 @@ fn udim_separate_bake(pixel: vec2, block: u32) -> vec4 { if entry.y == 0u { continue; } + let size = vec2(width, entry.y); let at = min(vec2(uv * vec2(size)), size - 1u) + vec2(0u, entry.x); let stored = textureLoad(bake_maps, vec2(at), 0); + // Each map keeps its component: AO x, Normal w, Curvature y, Thickness z; Height x, World Normal yzw switch index { case 0u, 4u: { texel.x = stored.x; } @@ -223,8 +229,7 @@ fn udim_separate_bake(pixel: vec2, block: u32) -> vec4 { return texel; } -// Extra's alpha at `pixel`: 32 × log2(1 / the UV tile's scale), which the viewport's height -// slopes read (encode_tile in compose's display.rs) +// Store logarithmic tile scale in Extra alpha for viewport height slopes fn udim_extra_scale(pixel: vec2) -> u32 { return u32(clamp(udim_round(-32.0 * log2(udim_scale_at(pixel))), 0.0, 255.0)); } diff --git a/crates/render/src/shaders/curvature_sample.wgsl b/crates/render/src/shaders/curvature_sample.wgsl index 1397b26b..eea41552 100644 --- a/crates/render/src/shaders/curvature_sample.wgsl +++ b/crates/render/src/shaders/curvature_sample.wgsl @@ -1,5 +1,4 @@ -// Coarsened curvature deviations sampled within their UV tile block of the bake (the whole bake -// of a classic set), as compose's CurvatureSizeLevel::sample interpolates. +// Interpolate curvature only within its bake block struct CurvatureLayout { levels: array, 6>, // Atlas origin, step (zero if absent), unused. bake_size: vec4, // Bake width and height, a UV tile block's width and height. diff --git a/crates/render/src/shaders/curvature_sizes.wgsl b/crates/render/src/shaders/curvature_sizes.wgsl index fbf1ab83..a884a9de 100644 --- a/crates/render/src/shaders/curvature_sizes.wgsl +++ b/crates/render/src/shaders/curvature_sizes.wgsl @@ -10,6 +10,7 @@ struct Params { @group(0) @binding(2) var destination_image: texture_storage_2d; @group(0) @binding(3) var coverage: array; @group(0) @binding(4) var bake: texture_2d; + // The coarsening's edge weights; in the coverage scan each block's tile scale @group(0) @binding(5) var edge_weights: array; @@ -21,8 +22,7 @@ fn working_covered(point: vec2) -> bool { return (bits & (1u << (point.x % 32u))) != 0u; } -// A bake texel of a UV tile atlas whose tiles have scales: covered when a covered working texel -// of its block reaches it through BlockScales::bake_uv, by its footprint (compose's covered_texels) +// Invert working-texel coverage separately within each scaled bake block fn scaled_bake_covered(point: vec2) -> bool { let bake_size = params.dimensions.xy; let working_size = params.dimensions.zw; @@ -60,8 +60,7 @@ fn bake_covered(point: vec2) -> bool { if params.block.w != 0u { return scaled_bake_covered(point); } if all(bake_size == working_size) { return working_covered(point); } - // Invert the working-texel footprints, then verify their original float - // bounds. The extra candidate on each end allows for roundoff at a bake edge. + // Verify candidates against their float footprints to tolerate boundary roundoff let scale = vec2(working_size) / vec2(bake_size); let first = vec2(max(floor(vec2(point) * scale) - 1.0, vec2(0.0))); let end = min(working_size, vec2(ceil(vec2(point + 1u) * scale)) + 1u); @@ -78,7 +77,7 @@ fn bake_covered(point: vec2) -> bool { return false; } -// Build the summed-area table of the projected coverage, one scan per line. +// Build the summed-area table of the projected coverage, one scan per line @compute @workgroup_size(64) fn scan_rows(@builtin(global_invocation_id) id: vec3) { let y = id.x; @@ -134,12 +133,14 @@ fn nearest(point: vec2) -> vec2 { var low = 1u; var high = 1u; let limit = max(size.x - origin.x, size.y - origin.y); - // Most uncovered texels are near an island. Find a tight upper bound first. + + // Most uncovered texels are near an island. Find a tight upper bound first while high < limit && !inside_radius(point, high) { low = high + 1u; high = min(high * 2u, limit); } - // The first square that contains a texel gives the exact Chebyshev distance. + + // The first square that contains a texel gives the exact Chebyshev distance while low < high { let mid = (low + high) / 2u; if inside_radius(point, mid) { @@ -150,7 +151,8 @@ fn nearest(point: vec2) -> vec2 { } let first = max(point - min(point, vec2(low)), origin); let last = min(point + low, size - 1u); - // Among those at the same distance, the CPU resolves ties in source row-major order. + + // Among those at the same distance, the CPU resolves ties in source row-major order low = first.y; high = last.y; while low < high { @@ -174,6 +176,7 @@ fn pad_curvature(@builtin(global_invocation_id) id: vec3) { let size = params.dimensions.xy; if any(id.xy >= size) { return; } var deviation = 0.0; + // A block without a covered texel has no source: it stays flat if covered_between(block_first(id.xy), block_last(id.xy)) { deviation = bitcast(textureLoad(bake, vec2(nearest(id.xy)), 0).y) - 0.5; @@ -184,8 +187,8 @@ fn pad_curvature(@builtin(global_invocation_id) id: vec3) { fn quantize_box(value: f32) -> f32 { let scaled = value * FIX; let lower = floor(scaled); - // Keep the half-unit comparison separate to avoid rounding twice at - // values whose fixed-point representation is already a whole float. + + // Compare the half unit separately to avoid rounding fixed-point values twice return (lower + select(0.0, 1.0, scaled - lower >= 0.5)) / FIX; } @@ -200,6 +203,7 @@ fn blur_sample(point: vec2) -> f32 { let finite = select(0.0, clamp(value, -1e6, 1e6), abs(value) <= 3.402823466e38); return sign(finite) * quantize_box(abs(finite)); } + return value; } @@ -209,8 +213,7 @@ fn add_compensated(total: vec2, value: f32) -> vec2 { return vec2(sum, (sum - total.x) - delta); } -// Three row passes and then three column passes, using one running sum per -// line rather than reading a whole window per output texel. +// Reuse a running sum for each of the three row and three column passes @compute @workgroup_size(64) fn blur_curvature(@builtin(global_invocation_id) id: vec3) { let vertical = params.mode.z != 0u; @@ -219,6 +222,7 @@ fn blur_curvature(@builtin(global_invocation_id) id: vec3) { if line >= size.y { return; } let radius = params.mode.x; let divisor = f32(radius * 2u + 1u); + // Each UV tile block of the line on its own, reading nothing past its ends let segment = max(select(params.block.x, params.block.y, vertical), 1u); for (var start = 0u; start < size.x; start += segment) { diff --git a/crates/render/src/shaders/id_sample.wgsl b/crates/render/src/shaders/id_sample.wgsl index 5af89c55..cc51c93e 100644 --- a/crates/render/src/shaders/id_sample.wgsl +++ b/crates/render/src/shaders/id_sample.wgsl @@ -4,9 +4,10 @@ fn id_word_group(group: u32, width: u32) -> vec4 { return textureLoad(id_bake, vec2(vec2(group % width, group / width)), 0); } -// The stored float bits are contiguous RGB, packed four words into each GPU texel. +// The stored float bits are contiguous RGB, packed four words into each GPU texel fn id_color_at(pixel: vec2) -> vec3 { let size = params.id_bake.xy; + // P8: a UV tile smaller than its atlas block reads its own share of the bake (BlockScales::bake_uv) let uv = udim_bake_uv((vec2(pixel) + 0.5) / vec2(params.source.xy)).xy; let sample_pixel = min(vec2(uv * vec2(size)), size - 1u); diff --git a/crates/render/src/shaders/material_image.wgsl b/crates/render/src/shaders/material_image.wgsl index 9b21c5dc..cc1d3b6c 100644 --- a/crates/render/src/shaders/material_image.wgsl +++ b/crates/render/src/shaders/material_image.wgsl @@ -1,5 +1,4 @@ -// Authored image and decal descriptors from gpu_image_source.rs. The R32Uint -// array also holds the Tile Generator's grayscale images. +// Authored images and grayscale tile patterns share the integer atlas const MISSING_IMAGE: u32 = 0xffffffffu; fn image_plane_at(plane: u32, pixel: vec2) -> u32 { @@ -20,13 +19,14 @@ fn material_image_texel(image: u32, pixel: vec2, size: vec2) -> vec4) -> vec4 { let size = vec2(i32(srgb[image]), i32(srgb[image + 1u])); let grid = uv * vec2(size) - 0.5; if !all(abs(grid) <= vec2(3.402823466e38)) { return vec4(0.0); } + let floor_grid = floor(grid); var base_grid = floor_grid; if any(abs(base_grid) >= vec2(2147483520.0)) { @@ -77,6 +77,7 @@ fn image_projection(layer: Operation, uv: vec2, surface: Surface) -> vec4, normal: vec3) -> vec4 { if facing <= 0.0 || !all(abs(vec2(x, y)) <= vec2(0.5)) || z > depth { return vec4(0.0); } + let flags = srgb[frame + 3u]; let uv = vec2(x + 0.5, 0.5 - y); let flipped = select(uv, 1.0 - uv, (vec2(flags) & vec2(2u, 4u)) != vec2(0u)); @@ -131,11 +133,13 @@ fn project_decal(frame: u32, surface: Surface) -> vec4 { if !surface.valid || (flags & 1u) == 0u { return vec4(0.0); } + let direct = decal_at(frame, surface.position, surface.normal); let axis = (flags >> 3u) & 3u; if axis == 0u { return direct; } + let mirror = vec3(1u, 2u, 3u) == vec3(axis); let plane = bitcast(srgb[frame + 7u]); let position = select(surface.position, 2.0 * plane - surface.position, mirror); @@ -145,6 +149,7 @@ fn project_decal(frame: u32, surface: Surface) -> vec4 { let flipped = select(reflected.xy, 1.0 - reflected.xy, (vec2(flags) & vec2(32u, 64u)) != vec2(0u)); return vec4(flipped, reflected.zw); } + return direct; } @@ -152,6 +157,7 @@ fn authored_image_value(layer: Operation, uv: vec2, surface: Surface) -> ve if layer.ids.z == MISSING_IMAGE { return vec3(0.5); } + let sampled = image_projection(layer, uv, surface); if layer.ids.w == P1_ALPHA_KIND { return vec3(sampled.a); @@ -166,6 +172,7 @@ fn decal_fill_value(layer: Operation, uv: vec2, surface: Surface) -> vec4, surface: Surface) -> 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/neighbourhood.wgsl b/crates/render/src/shaders/neighbourhood.wgsl index aed00555..9202a58b 100644 --- a/crates/render/src/shaders/neighbourhood.wgsl +++ b/crates/render/src/shaders/neighbourhood.wgsl @@ -1,21 +1,16 @@ -// Match the CPU neighbourhood filters in compose/src/eval.rs. Keep the -// material alpha separate from the geometric UV weight throughout the filter. +// Keep material alpha separate from geometric UV coverage struct Params { rect: vec4, // Absolute origin and extent in source texels. buffers: vec4, // Original, input, output word offsets, and vertical flag. mode: vec4, // Radius, filter kind, seed, and first box pass. weights: vec4, // Opacity, amount, noise frequency, and high-pass middle. direction: vec4, - // Words per field texel (5, or 6 with the input word), input word present, and two words of - // the GPU port packages (NeighbourhoodFilter::words). + // The field stride includes optional input words field_layout: vec4, extra: array, 2>, // The packages' parameters (NeighbourhoodFilter::extra). - // What the stage filters (stage_context), whether it wraps (bit 0), the first row of an apply - // dispatch split by rows (NeighbourhoodGpu::run), reserved. + // The apply origin selects the first row of this dispatch stage: vec4, - // The set in field-local texels [x0, y0, x1, y1] (NeighbourhoodRegion::bounds). In a wrapping - // program the field holds periodic copies past the set's edges; a stage that does not wrap - // never reads across these bounds, as the CPU's region stops at the set's edge. + // Clamp nonwrapping stages to the bounds of their own periodic copy bounds: vec4, } @@ -35,15 +30,13 @@ fn word_at(offset: u32, position: vec2) -> u32 { return offset + (position.y * params.rect.z + position.x) * params.field_layout.x; } -// The optional sixth word of an original-field texel (FilterStage::input in Rust): an input's -// gray or the layer's Height, zero when the program's fields have no input word. +// An absent sixth word supplies zero input fn input_at(position: vec2) -> f32 { if params.field_layout.y == 0u { return 0.0; } return bitcast(fields[word_at(params.buffers.x, position) + 5u]); } -// Whether this stage has an input of its own (a linked image input or the layer's Height), not -// only the program's input word (NeighbourhoodRegion::input bit 1). +// The stage can lack an input even when the shared fields have input words fn stage_linked() -> bool { return (params.field_layout.y & 2u) != 0u; } @@ -53,22 +46,21 @@ fn stage_has_second_input() -> bool { return (params.field_layout.y & 8u) != 0u; } -// The stage's second input's colour at an original-field texel (words 8..11), zero without one. +// The stage's second input's colour at an original-field texel (words 8..11), zero without one fn input2_color_at(position: vec2) -> vec3 { if !stage_has_second_input() { return vec3(0.0); } let i = word_at(params.buffers.x, position); return bitcast>(vec3(fields[i + 8u], fields[i + 9u], fields[i + 10u])); } -// The input's colour at an original-field texel: words 5..8 when the fields carry colour -// (NeighbourhoodRegion::input bit 2, ProceduralInputs::register_color_input), else its gray. +// Use color input words when present and replicate gray otherwise fn input_color_at(position: vec2) -> vec3 { if (params.field_layout.y & 4u) == 0u { return vec3(input_at(position)); } let i = word_at(params.buffers.x, position); return bitcast>(vec3(fields[i + 5u], fields[i + 6u], fields[i + 7u])); } -// What the stage filters (NeighbourhoodFilter::context): a mask, or content by channel kind. +// What the stage filters (NeighbourhoodFilter::context): a mask, or content by channel kind const STAGE_MASK: u32 = 0u; const STAGE_COLOR: u32 = 1u; const STAGE_SCALAR: u32 = 2u; @@ -83,13 +75,12 @@ fn stage_wraps() -> bool { return (params.stage.y & 1u) != 0u; } -// Which copy of the set a field-local texel lies in, per axis: -1 before, 0 in, 1 past the set. +// Which copy of the set a field-local texel lies in, per axis: -1 before, 0 in, 1 past the set fn copy_of(point: vec2) -> vec2 { return select(select(vec2(0), vec2(1), point >= params.bounds.zw), vec2(-1), point < params.bounds.xy); } -// How many set periods field-local `point` lies from the set, per axis (any distance: a wrapping -// field reaches as far as its stages do): `copy_of` past one period +// Count whole periods on each axis even when the halo spans multiple copies fn periodic_copy(point: vec2) -> vec2 { let period = max(params.bounds.zw - params.bounds.xy, vec2(1)); let offset = point - params.bounds.xy; @@ -97,30 +88,28 @@ fn periodic_copy(point: vec2) -> vec2 { return truncated - select(vec2(0), vec2(1), (offset < vec2(0)) & (truncated * period != offset)); } -// The texels [x0, y0, x1, y1) of the field a stage reads around field-local `point`: the whole -// field for a wrapping stage, else the copy of the set the point lies in (clipped to the field) +// Nonwrapping stages can read only the clipped bounds of this copy fn copy_segment(point: vec2) -> vec4 { let size = vec2(params.rect.zw); if stage_wraps() { return vec4(vec2(0), size); } + let copy = copy_of(point); let start = select(select(params.bounds.xy, params.bounds.zw, copy > vec2(0)), vec2(0), copy < vec2(0)); let end = select(select(params.bounds.zw, size, copy > vec2(0)), params.bounds.xy, copy < vec2(0)); return vec4(clamp(start, vec2(0), size), clamp(end, vec2(0), size)); } -// The copy of the set the texel being written lies in (apply_neighbourhood). +// The copy of the set the texel being written lies in (apply_neighbourhood) var output_copy: vec2 = vec2(0); -// The field's origin in source texels. It can lie below zero (a wrapping stage's field: the -// prepare pass then fills it periodically), so read it signed. +// Decode the origin as signed because a wrapping halo can extend below zero fn field_origin() -> vec2 { return bitcast>(params.rect.xy); } -// Kinds 16..32 are P4's (neighbourhood_box.wgsl), 32..56 P5's (neighbourhood_gather.wgsl). -// Whether a kind runs the box passes; NeighbourhoodFilter::uses_box in Rust must agree. +// Keep the box-pass classification in sync with NeighbourhoodFilter::uses_box fn uses_box_kind(kind: u32) -> bool { if kind <= 4u { return true; } if kind >= 16u && kind < 32u { return box_family_uses_box(kind); } @@ -169,8 +158,7 @@ struct BoxSum { covered: i32, } -// Compensated updates keep the sliding sum stable even where only tiny -// geometric support remains at the edge of an island. +// Compensate sliding sums where geometric support falls close to zero fn add_box_sample(acc: BoxSum, texel: Texel, weight: f32) -> BoxSum { let rgb = texel.value * weight - acc.correction.value; let coverage = texel.coverage * weight - acc.correction.coverage; @@ -180,8 +168,7 @@ fn add_box_sample(acc: BoxSum, texel: Texel, weight: f32) -> BoxSum { return BoxSum(sum, Texel((sum.value - acc.sum.value) - rgb, (sum.coverage - acc.sum.coverage) - coverage), nonzero, covered); } -// One running window per line segment [start, end). Its initial sum visits at most the length -// of the segment, and every subsequent pixel adds and removes at most one sample. +// Reuse the row segment's initial sum as its window advances fn box_segment(line: u32, vertical: bool, start: u32, end: u32) { let radius = params.mode.x; let reciprocal = 1.0 / f32(radius * 2u + 1u); @@ -192,8 +179,8 @@ fn box_segment(line: u32, vertical: bool, start: u32, end: u32) { } for (var index = start; index < end; index++) { let point = vec2(index, line); - // Preserve exact zeros outside the filter footprint. A residual in alpha - // would make sparse Replace blend an otherwise empty texel. + + // Exact zero coverage prevents sparse Replace from blending an empty texel let value = select(vec4(0.0), round_fixed(acc.sum.value * reciprocal * FIX) / FIX, acc.nonzero > vec4(0)); let coverage = select(0.0, round_fixed(vec4(max(acc.sum.coverage, 0.0) * reciprocal * FIX)).x / FIX, acc.covered > 0); write_at(params.buffers.z, select(point, point.yx, vertical), Texel(value, coverage)); @@ -209,12 +196,12 @@ fn box_segment(line: u32, vertical: bool, start: u32, end: u32) { } } -// A stage that does not wrap sums each copy of the set apart (the field lies inside the set -// unless the program wraps, so this is one segment then). +// Compute sums separately for each nonwrapping copy @compute @workgroup_size(64) fn box_blur(@builtin(global_invocation_id) id: vec3) { let vertical = params.buffers.w != 0u; let size = select(params.rect.zw, params.rect.wz, vertical); + // A dispatch split by lines (NeighbourhoodGpu::run under a work budget) starts at line stage.z let line = id.x + params.stage.z; if line >= size.y { return; } @@ -222,6 +209,7 @@ fn box_blur(@builtin(global_invocation_id) id: vec3) { box_segment(line, vertical, 0u, size.x); return; } + let length = i32(size.x); let first = u32(clamp(select(params.bounds.x, params.bounds.y, vertical), 0, length)); let last = u32(clamp(select(params.bounds.z, params.bounds.w, vertical), 0, length)); @@ -239,6 +227,7 @@ fn filtered_box(original: vec4, blurred: vec4) -> vec4 { let distance = abs(original.rgb); return vec4(side * min(distance, max(2.0 * blurred.rgb * side - distance, vec3(0.0))), original.a); } + case 4u: { return vec4(original.rgb + params.weights.y * blurred.rgb, original.a); } case 0u: { return blurred; } default: { @@ -252,19 +241,18 @@ fn filtered_box(original: vec4, blurred: vec4) -> vec4 { fn add_weighted(acc: Texel, point: vec2, weight: f32) -> Texel { if weight <= 0.0 || any(point < vec2(0)) || any(point >= vec2(params.rect.zw)) { return acc; } + // A stage that does not wrap reads nothing across the set's edges if !stage_wraps() && any(copy_of(point) != output_copy) { return acc; } let texel = original_at(vec2(point)); return Texel(acc.value + texel.value * weight, acc.coverage + texel.coverage * weight); } -// Bilinear samples use absolute texel positions so a cropped dispatch or a -// paint-window split does not shift filter effects. +// Use absolute coordinates so cropping or splitting a dispatch preserves the sample position fn sample_field(acc: Texel, point: vec2) -> Texel { if !all(abs(point) <= vec2(3.402823466e38)) { return acc; } - // The weights from the same floor as the texels: a compiler may fuse the point's multiply-add - // for one of floor and fract and round it for the other (llvmpipe does), which at a point just - // below an integer reads the next texel at full weight + + // Derive weights from the same floor used for lookup to avoid fused multiply-add disagreement let cell = floor(point); let base = vec2(cell) - field_origin(); let fraction = clamp(point - cell, vec2(0.0), vec2(1.0)); @@ -293,8 +281,8 @@ fn gathered(point: vec2, original: vec4) -> vec4 { let n = i32(clamp(params.mode.x, 1u, 24u)); let step = radius / f32(n); let seed = params.mode.z; - // The texel's home in the set: in a wrapping program a periodic copy past the set's edges - // takes its noise and cells there, as the CPU's wrapped read of the lower stage does + + // Generate periodic noise and cell coordinates in the texel's home period let shift = vec2(periodic_copy(vec2(point) - field_origin()) * (params.bounds.zw - params.bounds.xy)); let home = point - shift; var acc = EMPTY; @@ -321,6 +309,7 @@ fn gathered(point: vec2, original: vec4) -> vec4 { let gradient = min(sqrt(dx * dx + dy * dy), vec3(1.0)); return vec4(gradient * original.a, original.a); } + case 9u: { let d = vec2( height_noise(home, vec2(-0.01, 0.0), seed) - height_noise(home, vec2(0.01, 0.0), seed), @@ -331,11 +320,13 @@ fn gathered(point: vec2, original: vec4) -> vec4 { acc = sample_field(acc, point + direction * (f32(i) * step)); } } + // Test probe (INPUT_PROBE in Rust): the stage's input colours at the texel, summed case 15u: { let local = vec2(vec2(point) - field_origin()); return vec4((input_color_at(local) + input2_color_at(local)) * original.a, original.a); } + case 10u: { let center = (floor(home / radius) + 0.5) * radius - 0.5 + shift; acc = sample_field(acc, center); @@ -409,8 +400,7 @@ fn average_cells(@builtin(global_invocation_id) id: vec3) { write_at(params.buffers.y, id.xy, Texel(vec4(value, 0.0, 0.0, 1.0), select(0.0, 1.0, count != 0u))); } -// Cells clamp to those of the texel's copy of the set (`cells`: first and last), as the CPU clamps to its region's. -// Set sides are multiples of the generators' cells, so no cell straddles two copies +// Clamp generator cells to the current copy of the set fn cell_corner(point: vec2, weight: f32, cells: vec4) -> vec2 { let cell = vec2(clamp(point, cells.xy, cells.zw)); let sample = read_at(params.buffers.y, cell); @@ -424,6 +414,7 @@ fn interpolate_cells(@builtin(global_invocation_id) id: vec3) { var value = original.value.x; if original.coverage > 0.0 { let position = (vec2(field_origin() + vec2(id.xy)) + 0.5) / f32(params.mode.x) - 0.5 - vec2(first_cell()); + // The weights from the same floor as the cells (sample_field) let floored = floor(position); let cell = vec2(floored); @@ -444,10 +435,7 @@ fn interpolate_cells(@builtin(global_invocation_id) id: vec3) { write_at(params.buffers.z, id.xy, Texel(vec4(value, original.value.yzw), original.coverage)); } -// Copy a stage output out of a pre-pass field into the whole-set result (the composite's -// `whole_slots`): `mode.y` × `mode.z` texels from field texel `rect.xy` of the field at -// `buffers.x` (`rect.z` texels wide) to row `mode.w` of the result at `buffers.z` (`mode.x` -// texels wide), `field_layout.x` words each. +// Copy the compact stage field into its persistent whole-set output stripe @compute @workgroup_size(8, 8) fn copy_field(@builtin(global_invocation_id) id: vec3) { if id.x >= params.mode.y || id.y >= params.mode.z { return; } diff --git a/crates/render/src/shaders/neighbourhood_box.wgsl b/crates/render/src/shaders/neighbourhood_box.wgsl index b143fd6f..21496f12 100644 --- a/crates/render/src/shaders/neighbourhood_box.wgsl +++ b/crates/render/src/shaders/neighbourhood_box.wgsl @@ -1,17 +1,18 @@ -// P4, the box family and distance filters (gpu_neighbourhood_box.rs): kinds 16..24 (box) and -// 24..32 (distance). Owned by the P4 agent. Always part of the neighbourhood shader; extra -// passes (row and column distance transforms) get their own entry points here, created in -// box_family::Pipelines. Box sums use the 2^24 fixed point of box_blur, as the CPU's i64 sums. +// Box sums match the CPU's 24-bit fixed-point accumulation // Pixelate laid on each texel's own material alpha (box_family::PIXELATE_KEEPING_ALPHA) const PIXELATE_KEEPING_ALPHA: u32 = 16u; + // Blur and Bevel with Wrap over a field the prepare pass fills periodically const BOX_WRAPPED_BLUR: u32 = 17u; const BOX_WRAPPED_BEVEL: u32 = 18u; + // Highpass in an sRGB space or of the alpha const BOX_HIGHPASS: u32 = 19u; + // The Gradient's input blur for P2's gradient const BOX_PRE_BLUR: u32 = 20u; + // Glow and Drop Shadow const BOX_HALO: u32 = 21u; const BOX_OUTLINE: u32 = 22u; @@ -21,34 +22,43 @@ const BOX_DIRECTIONAL_DISTANCE: u32 = 26u; // Highpass in sRGB from ACEScg (params.field_layout.z; 0 is the working space, 1 sRGB from linear) const BOX_SPACE_SRGB_FROM_ACESCG: u32 = 2u; + // Below this alpha content has no straight colour (MIN_ALPHA in eval.rs) const BOX_MIN_ALPHA: f32 = 1e-5; + // Word 4 of a field texel: its coverage, the pre-blur's gray in a stage output, scratch in the distance passes const BOX_SECOND_WORD: u32 = 4u; + // Flags in params.field_layout.z const HALO_INNER: u32 = 1u; const HALO_PRECISE: u32 = 2u; + // The blurred value a precise halo is solid from const BOX_PRECISE_EDGE: f32 = 0.5; + // The largest finite f32 const BOX_LARGEST_FINITE: f32 = 3.402823466e38; + // Flags in params.field_layout.z const OUTLINE_FROM_BLACK: u32 = 1u; const OUTLINE_COVERS_INSIDE: u32 = 2u; const OUTLINE_COVERS_OUTSIDE: u32 = 4u; const OUTLINE_BAND_OFF: u32 = 8u; + // The shapes' blurred share at their edge const BOX_OUTLINE_EDGE_SHARE: f32 = 0.5; + // Flags in params.field_layout.z const DISTANCE_ANGULAR: u32 = 1u; const DISTANCE_INWARD: u32 = 2u; const DISTANCE_NON_UNIFORM: u32 = 4u; const SMOOTH_IN: u32 = 8u; const SMOOTH_IN_OUT: u32 = 16u; + // From a texel's centre to the edge between it and the nearest texel across const BOX_EDGE_OFFSET: f32 = 0.5; -// Whether a P4 kind runs the three box passes first (box_family::uses_box must agree). +// Whether a P4 kind runs the three box passes first (box_family::uses_box must agree) fn box_family_uses_box(kind: u32) -> bool { var uses = kind == BOX_WRAPPED_BLUR || kind == BOX_WRAPPED_BEVEL; uses = uses || kind == BOX_HIGHPASS; @@ -58,8 +68,7 @@ fn box_family_uses_box(kind: u32) -> bool { return uses; } -// A P4 kind after the box passes: the original and the box-blurred field, unpremultiplied -// by coverage like filtered_box. +// Unpremultiply original and blurred fields by their respective coverage fn box_family_filtered(original: vec4, blurred: vec4) -> vec4 { // Away from 0 by at most the value itself, as the built-in Bevel if params.mode.y == BOX_WRAPPED_BEVEL { @@ -67,19 +76,20 @@ fn box_family_filtered(original: vec4, blurred: vec4) -> vec4 { let distance = abs(original.rgb); return vec4(side * min(distance, max(2.0 * blurred.rgb * side - distance, vec3(0.0))), original.a); } + return blurred; } -// A P4 kind without the box passes, at absolute texel position point. +// A P4 kind without the box passes, at absolute texel position point fn box_family_gathered(point: vec2, original: vec4) -> vec4 { if params.mode.y == PIXELATE_KEEPING_ALPHA { return pixelate_keeping_alpha(point, original); } + return original; } -// The cell centre's sample with its colour laid on the texel's own alpha (keep_coverage in eval.rs) -// A mask's alpha is 1 wherever it is covered, so a mask pixelates as with Alpha on +// Keep the texel's own alpha when sampling a pixelated cell center fn pixelate_keeping_alpha(point: vec2, original: vec4) -> vec4 { let radius = f32(params.mode.x); let center = (floor(point / radius) + 0.5) * radius - 0.5; @@ -104,6 +114,7 @@ fn box_srgb_from_linear(value: f32) -> f32 { if v <= 0.0031308 { return v * 12.92; } + return 1.055 * pow(v, 1.0 / 2.4) - 0.055; } @@ -112,6 +123,7 @@ fn box_linear_from_srgb(value: f32) -> f32 { if v <= 0.04045 { return v / 12.92; } + return pow((v + 0.055) / 1.055, 2.4); } @@ -141,6 +153,7 @@ fn box_highpass_decode(rgb: vec3) -> vec3 { // REC709_TO_AP1 in highpass_space.rs return box_times_rows(vec3(0.61310, 0.33952, 0.04737), vec3(0.07019, 0.91635, 0.01345), vec3(0.02062, 0.10957, 0.86981), linear_rgb); } + return linear_rgb; } @@ -149,10 +162,12 @@ fn box_highpass_recode(value: vec4, encode: bool) -> vec4 { if box_flags() == 0u || value.w <= MIN_WEIGHT { return value; } + let straight = value.rgb / value.w; if encode { return vec4(box_highpass_encode(straight) * value.w, value.w); } + return vec4(box_highpass_decode(straight) * value.w, value.w); } @@ -198,20 +213,23 @@ fn box_gray_of(rgb: vec3) -> f32 { if mode == 0u { return (max(max(rgb.x, rgb.y), rgb.z) + min(min(rgb.x, rgb.y), rgb.z)) / 2.0; } + if mode == 1u { return box_lum(rgb); } + if mode == 2u { return (rgb.x + rgb.y + rgb.z) / 3.0; } + if mode == 3u { return max(max(rgb.x, rgb.y), rgb.z); } + return min(min(rgb.x, rgb.y), rgb.z); } -// The pre-blur's output (map_blurred in eval.rs): the original texel in words 0-3, the blurred gray in word 4 -// A normal map's gradient is the identity, so there the blur is mixed in here and word 4 stays 0 +// Preserve original color and pre-blur gray separately except for an identity normal gradient fn box_pre_blur_texel(point: vec2, original: Texel, blurred: Texel) { var average = original.value; if blurred.coverage > MIN_WEIGHT { @@ -286,9 +304,11 @@ fn box_shape_value(value: vec4) -> f32 { if box_is_mask() { return value.x; } + if value.w > BOX_MIN_ALPHA { return box_lum(value.rgb / value.w); } + return 0.0; } @@ -303,6 +323,7 @@ fn box_ramp_curve(along: f32, offset: f32, exponent: f32) -> f32 { if exponent == 1.0 || moved <= 0.0 { return moved; } + return pow(moved, exponent); } @@ -312,6 +333,7 @@ fn box_laid_on(value: vec4, after: f32) -> vec4 { if box_is_mask() { return vec4(value.x + (after - value.x) * opacity, value.yzw); } + let before = box_straight_color(value); return vec4((before + (vec3(after) - before) * opacity) * value.w, value.w); } @@ -338,10 +360,12 @@ fn box_outline_texel(original: Texel, blurred: Texel) -> vec4 { if (box_flags() & OUTLINE_FROM_BLACK) != 0u { return box_laid_on(value, band); } + let opacity = params.weights.x; if box_is_mask() { return vec4(value.x + (max(value.x, band) - value.x) * opacity, value.yzw); } + let before = box_straight_color(value); return vec4((before + (max(before, vec3(band)) - before) * opacity) * value.w, value.w); } @@ -361,6 +385,7 @@ fn box_bevel_texel(original: Texel, slope: f32) -> vec4 { } return vec4(value.x + (after - value.x) * opacity, value.yzw); } + let before = box_straight_color(value); var after = before; if inward && inside { @@ -379,6 +404,7 @@ fn box_family_apply(@builtin(global_invocation_id) id: vec3) { if any(point >= params.rect.zw) { return; } + let original = original_at(point); let filtered = read_at(params.buffers.y, point); let kind = params.mode.y; @@ -397,6 +423,7 @@ fn box_family_apply(@builtin(global_invocation_id) id: vec3) { box_pre_blur_texel(point, original, filtered); return; } + if kind == BOX_HALO { result = box_halo_texel(original.value, filtered); } @@ -430,6 +457,7 @@ fn box_family_prepare(@builtin(global_invocation_id) id: vec3) { if any(point >= params.rect.zw) { return; } + let kind = params.mode.y; var prepared = EMPTY; @@ -473,6 +501,7 @@ fn box_floor_div(value: i32, divisor: i32) -> i32 { if value % divisor != 0 && (value < 0) != (divisor < 0) { return quotient - 1; } + return quotient; } @@ -482,6 +511,7 @@ fn box_distance_far(angular: bool) -> f32 { if angular { return side; } + return side * side; } @@ -497,8 +527,7 @@ fn box_set_field_word(offset: u32, position: vec2, word: u32, value: u32) { fields[word_at(offset, position) + word] = value; } -// One invocation per row: the distance along it to the nearest texel inside (word 0) and outside (word 1) into buffers.z, the inside flag in word 4 -// A stage that does not wrap measures each copy of the set apart, as the CPU's region stops at the set's edges +// Record nearest inside and outside distances separately for each nonwrapping row segment @compute @workgroup_size(64) fn distance_rows(@builtin(global_invocation_id) id: vec3) { // A dispatch split by lines under a work budget starts at line stage.z @@ -506,6 +535,7 @@ fn distance_rows(@builtin(global_invocation_id) id: vec3) { if y >= params.rect.w { return; } + let width = i32(params.rect.z); var edges = array(0, clamp(params.bounds.x, 0, width), clamp(params.bounds.z, 0, width), width); for (var segment = 0; segment < 3; segment++) { @@ -577,6 +607,7 @@ fn box_envelope_value(place: i32, apex: i32, height: u32, angular: bool) -> u32 if angular { return max(across, height); } + return across * across + height; } @@ -587,14 +618,15 @@ fn box_envelope_separation(apex: i32, later: i32, height_apex: u32, height_later if height_apex <= height_later { return max(apex + i32(height_later), middle); } + return min(later - i32(height_apex), middle); } + let lifted = (later * later + i32(height_later)) - (apex * apex + i32(height_apex)); return box_floor_div(lifted, 2 * (later - apex)); } -// A column segment's lower envelope in exact integers (Meijster), where the CPU crosses the parabolas in f64 -// Rows [first, end) of column x: heights in word `side` of buffers.z, apexes and starts in buffers.y, the result in word side + 2 of buffers.z +// Construct the column's lower parabola envelope using exact integer intersections fn box_column_envelope(x: u32, side: u32, angular: bool, first: i32, end: i32) { let height = end - first; let heights = params.buffers.z; @@ -611,6 +643,7 @@ fn box_column_envelope(x: u32, side: u32, angular: bool, first: i32, end: i32) { if top < 0 { break; } + let apex = i32(box_field_word(stack, vec2(x, u32(first + top)), apex_word)); let start = i32(box_field_word(stack, vec2(x, u32(first + top)), start_word)); let height_apex = u32(box_field_float(heights, vec2(x, u32(first + apex)), side)); @@ -662,6 +695,7 @@ fn distance_columns(@builtin(global_invocation_id) id: vec3) { if x >= params.rect.z { return; } + let angular = (box_flags() & DISTANCE_ANGULAR) != 0u; let height = i32(params.rect.w); var edges = array(0, clamp(params.bounds.y, 0, height), clamp(params.bounds.w, 0, height), height); @@ -699,9 +733,11 @@ fn box_wide_shifted(value: u32, shift: u32) -> vec2 { if shift >= 32u { return vec2(value << (shift - 32u), 0u); } + if shift == 0u { return vec2(0u, value); } + return vec2(value >> (32u - shift), value << shift); } @@ -714,13 +750,13 @@ fn box_below_square(value: u32, odd: u32, exponent: i32) -> bool { return box_wide_less(box_wide_shifted(value, u32(-2 * exponent)), box_wide_product(odd, odd)); } -// The correctly rounded square root of an integer-valued f32 below 2^32, as the CPU's sqrt gives it (WGSL's may be off) -// A root of an integer never lies on a midpoint between two floats unless it is whole, so the midpoints decide +// Use adjacent midpoints to match the CPU's rounded integer square root fn box_exact_sqrt(squared: f32) -> f32 { let value = u32(squared); if value == 0u { return 0.0; } + var root = sqrt(squared); for (var attempt = 0; attempt < 4; attempt++) { let bits = bitcast(root); @@ -741,22 +777,22 @@ fn box_exact_sqrt(squared: f32) -> f32 { if !below_lower { break; } + root = bitcast(bits - 1u); } return root; } -// The Distance Map at the texel (the stage's input word, 0..1), else what the CPU reads without one: 1 on the mesh, 0 off it -// FilterStage::input is set for every Bevel Smooth and Directional Distance stage, so the word is this stage's whenever the fields carry it +// A missing distance map supplies full reach on covered texels fn box_distance_map(point: vec2) -> f32 { if params.field_layout.y != 0u { return clamp(input_at(point), 0.0, 1.0); } + return select(0.0, 1.0, original_at(point).coverage > 0.0); } -// The edge distance (word 1) and the ramp a distance filter makes of it (word 0) into buffers.z from the envelopes in buffers.y -// Coverage 1 everywhere, so the smoothing blurs every texel alike as the CPU's blur does; the reach in extra 1 +// Use uniform coverage for the distance ramp's smoothing blur @compute @workgroup_size(8, 8) fn distance_edges(@builtin(global_invocation_id) id: vec3) { // A dispatch split by rows under a work budget starts at row stage.z @@ -764,6 +800,7 @@ fn distance_edges(@builtin(global_invocation_id) id: vec3) { if any(point >= params.rect.zw) { return; } + let distances = params.buffers.y; let inside = box_field_word(distances, point, BOX_SECOND_WORD) != 0u; let flags = box_flags(); @@ -806,6 +843,7 @@ fn box_exact_product(first: f32, second: f32) -> f32 { if first == 0.0 || second == 0.0 { return 0.0; } + let first_bits = bitcast(first); let second_bits = bitcast(second); let sign = (first_bits ^ second_bits) & 0x80000000u; @@ -831,8 +869,7 @@ fn box_exact_product(first: f32, second: f32) -> f32 { return bitcast(sign | (u32(exponent) << 23u) | (mantissa & 0x7fffffu)); } -// Directional Distance: each texel walks back against the direction over the inside flags in buffers.y (trail_distances) -// The trail into word 0 of buffers.z, the step that found a shape (-1: none) into word 1; reach in extra 1, step length 2, 1 - contrast 3 +// Walk backward against the direction until the trail reaches a filled texel @compute @workgroup_size(8, 8) fn directional_trail(@builtin(global_invocation_id) id: vec3) { // A dispatch split by rows under a work budget starts at row stage.z @@ -840,6 +877,7 @@ fn directional_trail(@builtin(global_invocation_id) id: vec3) { if any(point >= params.rect.zw) { return; } + // The texel's copy of the set is the CPU's region let segment = copy_segment(vec2(point)); let size = segment.zw - segment.xy; @@ -861,18 +899,19 @@ fn directional_trail(@builtin(global_invocation_id) id: vec3) { if abs(offset.x) >= size.x || abs(offset.y) >= size.y { break; } + let source = vec2(point) + offset; if source.y < segment.y || source.y >= segment.w { break; } + if source.x >= segment.x && source.x < segment.z && box_field_float(params.buffers.y, vec2(source), 0u) != 0.0 { found = i32(sample); break; } } - // DirectionalDistance::value: no shape in reach leaves black - // The Distance Map shortens the texel's reach: a share of the full reach is a larger share of a shorter one, none where it is black + // A black distance map suppresses the trail entirely var trail = 0.0; if found >= 0 { var along = 0.0; diff --git a/crates/render/src/shaders/neighbourhood_gather.wgsl b/crates/render/src/shaders/neighbourhood_gather.wgsl index d47dcf0f..d2143a9a 100644 --- a/crates/render/src/shaders/neighbourhood_gather.wgsl +++ b/crates/render/src/shaders/neighbourhood_gather.wgsl @@ -1,7 +1,4 @@ -// P5, the gather and whole-set filters (gpu_neighbourhood_gather.rs): kinds 32..48 (gather) and -// 48..56 (whole set). Owned by the P5 agent. Always part of the neighbourhood shader; extra -// passes (structure tensor, reductions) get their own entry points here, created in -// gather::Pipelines. +// Create dedicated pipelines for gather reductions and structure tensors // The P5 kinds (gpu_neighbourhood_gather.rs) const GATHER_FXAA: u32 = 32u; @@ -18,6 +15,7 @@ const GATHER_FXAA_SEARCH: i32 = 8; const GATHER_FXAA_EDGE_MIN: f32 = 0.0312; const GATHER_FXAA_EDGE_RELATIVE: f32 = 0.125; const GATHER_FXAA_SUBPIXEL: f32 = 0.75; + // Flag bit of an FXAA stage's words[0]: Affect Alpha Channel const GATHER_FXAA_ALPHA: u32 = 1u; @@ -31,12 +29,14 @@ const GATHER_MIRROR_DEBUG: u32 = 16u; // Flag bits of a Color Match stage's words[0]: the source is the set's mean, and Custom Color Variation const GATHER_COLOR_MATCH_AVERAGE: u32 = 1u; const GATHER_COLOR_MATCH_CUSTOM_VARIATION: u32 = 2u; + // The source (Input) or the target (Image Input) read at the texel from a linked input const GATHER_COLOR_MATCH_SOURCE_INPUT: u32 = 4u; const GATHER_COLOR_MATCH_TARGET_INPUT: u32 = 8u; // Flag bit of a Height To Normal stage's words[0]: Overwrite Existing Normal const GATHER_HEIGHT_TO_NORMAL_OVERWRITE: u32 = 1u; + // The height of a Height To Normal stage without the layer's Height (eval.rs filter_region) const GATHER_FLAT_HEIGHT: f32 = 1.0; @@ -46,6 +46,7 @@ const GATHER_KUWAHARA_SECTORS: u32 = 8u; const GATHER_MIN_TENSOR: f32 = 1e-12; const GATHER_KUWAHARA_FALLOFF: f32 = 2.0; const GATHER_KUWAHARA_SPREAD_SCALE: f32 = 255.0; + // Flag bit of a Kuwahara stage's words[0]: Extract Direction Custom Input const GATHER_KUWAHARA_CUSTOM_INPUT: u32 = 1u; const GATHER_PI: f32 = 3.141592653589793; @@ -59,6 +60,7 @@ const GATHER_DIRECTION_COUNT_SHIFT: u32 = 4u; const GATHER_SOURCE_MODE_SHIFT: u32 = 8u; const GATHER_SOURCE_TILED: u32 = 1024u; const GATHER_READ_COUNT_SHIFT: u32 = 16u; + // A repeating source's seed word (gather::source_seed): its block's side below, its tile's above const GATHER_TILE_SIDE_SHIFT: u32 = 16u; const GATHER_BLOCK_SIDE_MASK: u32 = 0xffffu; @@ -71,17 +73,23 @@ const GATHER_SLOPE_BLENDING_BLUR: u32 = 0u; const GATHER_SLOPE_BLENDING_MAX: u32 = 2u; const GATHER_SOURCE_DEFAULT_NOISE: u32 = 0u; const GATHER_SOURCE_CUSTOM_NOISE: u32 = 2u; + // Mid gray moves nothing; noise is stretched from it (WarpSource in core) const GATHER_MID_GRAY: f32 = 0.5; const GATHER_NOISE_STRETCH: f32 = 1.5; + // Octaves of a warp's default noise (texel_noise in eval.rs) const GATHER_NOISE_OCTAVES: u32 = 3u; + // The source's slope (rise per UV tile) that moves a texel the whole way (SourceWarp::FULL_SLOPE) const GATHER_FULL_SLOPE: f32 = 4.0; + // A source rising less than this across a texel is flat (slope_texel.rs) const GATHER_FLAT_STEEPNESS: f32 = 1e-6; + // A content read covering less alpha than this has no colour (MIN_ALPHA in eval.rs) const GATHER_MIN_ALPHA: f32 = 1e-5; + // An unlinked image input's gray (ImageInput's default); linked inputs stay on the CPU const GATHER_INPUT_DEFAULT: f32 = 0.5; @@ -224,8 +232,7 @@ fn gather_finite_unit(value: f32) -> f32 { return select(0.0, clamp(value, 0.0, 1.0), gather_finite(value)); } -// The stage's input words at `home`, bilinear over the covered texels in the texel's copy, as -// (value, 1), or (0, 0) where none is covered (the input closure of gather in eval.rs) +// Interpolate covered samples within the texel's own copy and return their support fn gather_input_read(home: vec2, clamped: bool) -> vec2 { let point = home + gather_shift; if !all(abs(point) <= vec2(GATHER_LARGEST_FINITE)) { @@ -246,9 +253,11 @@ fn gather_input_read(home: vec2, clamped: bool) -> vec2 { if share <= 0.0 || any(texel < vec2(0)) || any(texel >= vec2(params.rect.zw)) { continue; } + if !stage_wraps() && any(copy_of(texel) != output_copy) { continue; } + if original_at(vec2(texel)).coverage <= 0.0 { continue; } @@ -261,6 +270,7 @@ fn gather_input_read(home: vec2, clamped: bool) -> vec2 { if weight > MIN_WEIGHT { return vec2(sum / weight, 1.0); } + return vec2(0.0); } @@ -269,9 +279,11 @@ fn gather_input(home: vec2) -> vec2 { if stage_linked() { return gather_input_read(home, true); } + if gather_read(home).coverage > MIN_WEIGHT { return vec2(GATHER_INPUT_DEFAULT, 1.0); } + return vec2(0.0); } @@ -280,9 +292,11 @@ fn gather_height(home: vec2) -> vec2 { if stage_linked() { return gather_input_read(home, false); } + if gather_read(home).coverage > MIN_WEIGHT { return vec2(GATHER_FLAT_HEIGHT, 1.0); } + return vec2(0.0); } @@ -371,8 +385,10 @@ fn gather_source_raw(texel: vec2, position: vec2) -> vec2 { let color = found.value.xyz / found.value.w; return vec2(0.3 * color.x + 0.59 * color.y + 0.11 * color.z, 1.0); } + return vec2(0.0); } + if found.coverage > MIN_WEIGHT { return vec2(found.value.x / found.coverage, 1.0); } @@ -493,6 +509,7 @@ fn gather_source_warp(home: vec2) -> Texel { } return gather_extreme_texel(extreme); } + var acc = EMPTY; for (var index = 0u; index < count; index++) { acc = gather_sample(acc, home + gather_direction(index) * moved); @@ -526,6 +543,7 @@ fn gather_source_slope_blur(home: vec2) -> Texel { } return acc; } + var extreme = GatherExtreme(vec4(0.0), false); for (var taken = 0u; taken <= reads; taken++) { extreme = gather_extreme_add(extreme, home + along * (f32(taken) * spacing), blending == GATHER_SLOPE_BLENDING_MAX); @@ -838,8 +856,7 @@ fn gather_color_match(point: vec2, original: vec4) -> vec4 { } var goal = params.extra[1].xyz; - // A linked Input or Image Input gives the texel its own source or target; with both, the - // Image Input is the second input + // With both links present, Image Input supplies the second input if stage_linked() { let local = vec2(vec2(point) - field_origin()); let linked = gather_color_reference(input_color_at(local), polar); @@ -910,6 +927,7 @@ fn gather_mirror(home: vec2, original: vec4) -> Texel { let axes = params.extra[0].xy; let line = params.extra[0].z; let side = params.extra[0].w; + // The tile at its atlas block's stride (a UV tile atlas's smaller tile fills part of it) let origin = gather_tile_origin(home, params.extra[1].x); let local = home - origin; @@ -948,6 +966,7 @@ fn gather_transform(home: vec2) -> Texel { let shift = params.extra[1].xy; let side = params.extra[1].z; let repeats = params.field_layout.z != 0u; + // The tile at its atlas block's stride (a UV tile atlas's smaller tile fills part of it) let origin = gather_tile_origin(home, params.extra[1].w); let local = home - origin; @@ -988,18 +1007,17 @@ fn gather_transform(home: vec2) -> Texel { return total; } -// Whether a P5 kind runs the three box passes first (gather::uses_box must agree). +// Whether a P5 kind runs the three box passes first (gather::uses_box must agree) fn gather_family_uses_box(kind: u32) -> bool { return false; } -// A P5 kind after the box passes. +// A P5 kind after the box passes fn gather_family_filtered(original: vec4, blurred: vec4) -> vec4 { return blurred; } -// A P5 kind at absolute texel position point: sample_field and normalized_or read the original -// field, input_at the sixth word. +// Gather in absolute coordinates and read stage input from the original field fn gather_family_gathered(point: vec2, original: vec4) -> vec4 { let kind = params.mode.y; if kind == GATHER_COLOR_MATCH { diff --git a/crates/render/src/shaders/noise.wgsl b/crates/render/src/shaders/noise.wgsl index 85138607..d40e85ab 100644 --- a/crates/render/src/shaders/noise.wgsl +++ b/crates/render/src/shaders/noise.wgsl @@ -1,4 +1,4 @@ -// Deterministic lattice noise shared with the CPU kernels in texel/src/noise.rs. +// Deterministic lattice noise shared with the CPU kernels in texel/src/noise.rs fn pcg3d(cell: vec3) -> vec3 { var v = cell * 1664525u + 1013904223u; @@ -31,6 +31,7 @@ fn corner(cell: vec3, seed: u32, offset: vec3, local: vec3, gradi if gradient { return dot(GRADIENTS[hash(cell + offset, seed * 0x85ebca6bu).y % 12u], local - vec3(offset)); } + return f32(hash(cell + offset, seed * 0x9e3779b9u).x) / 4294967296.0; } diff --git a/crates/render/src/shaders/paint_resize.wgsl b/crates/render/src/shaders/paint_resize.wgsl index 7819ae44..d6b1534d 100644 --- a/crates/render/src/shaders/paint_resize.wgsl +++ b/crates/render/src/shaders/paint_resize.wgsl @@ -1,9 +1,9 @@ struct Params { - // Source and destination dimensions, followed by source and output tile windows. + // Source and destination dimensions, followed by source and output tile windows sizes: vec4, source: vec4, dest: vec4, - // Packed words per texel and the empty texel as two packed words. + // Packed words per texel and the empty texel as two packed words format: vec4, } @@ -17,10 +17,12 @@ fn source_word(at: vec2, word: u32) -> u32 { if any(tile >= params.source.zw) { return params.format[word + 1u]; } + let addr = tiles[tiles[0] + tile.y * params.source.z + tile.x]; if addr == 0u { return params.format[word + 1u]; } + let local = pixel % 64u; return tiles[addr + (local.y * 64u + local.x) * params.format.x + word]; } @@ -32,8 +34,7 @@ fn channels(word: u32) -> vec2 { return vec2(word & LOW, word >> 16u); } -// Horizontal intermediates have 16 fractional bits. Split them into high/low words -// before the vertical blend and round once, as in TileImage::resampled_tile. +// Split the 16-bit horizontal fraction before rounding the vertical blend fn bilinear(a: vec2, b: vec2, c: vec2, d: vec2, w: vec2) -> vec2 { let top = a * (ONE - w.x) + b * w.x; let bottom = c * (ONE - w.x) + d * w.x; @@ -53,6 +54,7 @@ fn resize(@builtin(global_invocation_id) id: vec3) { for (var i = 0u; i < params.format.x; i++) { output[offset + i] = 0u; } return; } + let dest_size = params.sizes.zw; let denominator = 2u * dest_size; let center = max((2u * pixel + 1u) * params.sizes.xy, dest_size) - dest_size; diff --git a/crates/render/src/shaders/procedural_extra.wgsl b/crates/render/src/shaders/procedural_extra.wgsl index d5430f98..9e30af7f 100644 --- a/crates/render/src/shaders/procedural_extra.wgsl +++ b/crates/render/src/shaders/procedural_extra.wgsl @@ -1,5 +1,4 @@ -// Periodic geometry, organic, fabric and wood patterns. -// CPU formulas are in compose/src/{pattern,organic,fabric,timber}.rs. +// Keep periodic pattern math aligned with the CPU pattern evaluators const PATTERN_PI: f32 = 3.141592653589793; const PATTERN_TAU: f32 = 6.283185307179586; @@ -13,7 +12,7 @@ fn pattern_hash(cell: vec2, component: i32, seed: u32) -> f32 { } fn pattern_step(start: f32, end: f32, value: f32) -> f32 { - // The CPU's smoothstep also supports a descending interval. + // The CPU's smoothstep also supports a descending interval let t = clamp((value - start) / (end - start), 0.0, 1.0); return t * t * (3.0 - 2.0 * t); } @@ -52,7 +51,7 @@ fn lattice_fbm3(at: vec2, cells: vec3, weights: vec3, seed: u32) } fn round_pattern(p: vec2) -> vec2 { - // Rust round resolves half-integers away from zero. + // Rust round resolves half-integers away from zero return sign(p) * floor(abs(p) + 0.5); } @@ -79,6 +78,7 @@ fn wave_scales(uv: vec2) -> f32 { if abs(dy) > 0.5 { continue; } + let shift = select(0.0, 0.5, (circle_row & 1) == 1); let shifted = uv.x - shift; let dx = uv.x - (sign(shifted) * floor(abs(shifted) + 0.5) + shift); @@ -163,12 +163,13 @@ fn smooth_fur(uv: vec2, seed: u32) -> f32 { for (var column = -5; column <= 5; column++) { let root_cell = cell + vec2(column, row); let delta_center = point - (vec2(root_cell) + 0.5); - // A root moves by at most 0.35 on each axis. Discard unreachable roots - // before hashing their positions and tangents. + + // Reject roots beyond the maximum displacement before hashing their tangents let nearest_root = max(abs(delta_center) - 0.35, vec2(0.0)); if dot(nearest_root, nearest_root) > 16.0 { continue; } + let wrapped = wrap_cell(root_cell, vec2(6)); let salt = seed ^ 0x6du; let jitter = (vec2(pattern_hash(wrapped, 1, salt), pattern_hash(wrapped, 2, salt)) - 0.5) * 0.7; @@ -192,6 +193,7 @@ fn smooth_fur(uv: vec2, seed: u32) -> f32 { if along < 0.0 || along > 1.0 { continue; } + let radius = 1.55 * 0.5 * pow(1.0 - along, 0.65); let offset = length(vec2(local.x - arc_radius, local.y)) - abs(arc_radius); if radius <= 1e-6 || abs(offset) >= radius { @@ -349,6 +351,7 @@ fn flesh(uv: vec2, seed: u32) -> f32 { if decay == 0.0 { return clamp(healthy, 0.0, 1.0); } + let mottle = lattice_fbm2(warped, vec2(24, 48), vec2(0.5), seed ^ 0x77u); let point = warped * 14.0; let cell = vec2(floor(point)); @@ -361,6 +364,7 @@ fn flesh(uv: vec2, seed: u32) -> f32 { if pattern_hash(wrapped, 0, salt) > 0.55 { continue; } + let center = vec2(blister_cell) + vec2(pattern_hash(wrapped, 1, salt), pattern_hash(wrapped, 2, salt)); let radial = length(point - center) / (0.3 + 0.4 * pattern_hash(wrapped, 3, salt)); blister = max(blister, pattern_step(1.0, 0.0, radial)); @@ -413,6 +417,7 @@ fn knit(uv: vec2, seed: u32) -> f32 { if distance >= 0.21 { continue; } + let across = distance / 0.21; let twist = 0.5 + 0.5 * cos(PATTERN_TAU * (along * 2.5 + f32(side) * across * 0.3)); let leg = sqrt(1.0 - across * across) * (0.82 + 0.18 * twist) * yarn; @@ -536,6 +541,7 @@ fn knotty_wood(uv: vec2, seed: u32) -> f32 { if pattern_hash(wrapped, 0, salt) > 0.45 { continue; } + let jitter = vec2(pattern_hash(wrapped, 1, salt), pattern_hash(wrapped, 2, salt)) * 0.6; let center = vec2(knot) + 0.2 + jitter; let radius = 0.04 + 0.035 * pattern_hash(wrapped, 3, salt); @@ -544,6 +550,7 @@ fn knotty_wood(uv: vec2, seed: u32) -> f32 { if distance >= 2.2 { continue; } + if !with_noise { ring_noise = (lattice_noise(uv, vec2(24), seed ^ 0x66u) - 0.5) * 0.8; with_noise = true; @@ -582,6 +589,7 @@ fn extended_pattern(kind: u32, p: vec3, seed: u32) -> f32 { let cell = vec3(floor(p)); return select(0.0, 1.0, ((cell.x + cell.y + cell.z) & 1) == 0); } + case 49u: { return select(0.0, 1.0, fract(p.x) < 0.5); } case 50u: { let row = i32(floor(p.y * 2.0)); @@ -591,12 +599,14 @@ fn extended_pattern(kind: u32, p: vec3, seed: u32) -> f32 { let tone = cell_value(vec3(i32(floor(x)), row, 0), seed) * 0.6 + noise(p * 9.0, seed, false) * 0.4; return smoothstep(0.02, 0.045, d) * (0.85 + 0.15 * tone); } + case 51u: { let cell = vec2(floor(p.xy)); let local = fract(p.xy); let d = min(min(local.x, 1.0 - local.x), min(local.y, 1.0 - local.y)); return smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * cell_value(vec3(cell, 0), seed)); } + case 52u: { return woven(p, seed, false); } case 53u: { return woven(p, seed, true); } case 54u: { @@ -607,16 +617,19 @@ fn extended_pattern(kind: u32, p: vec3, seed: u32) -> f32 { let fine = noise(p * 7.0, seed ^ 0x13u, false); return clamp(crease * pebble * (0.85 + 0.15 * fine), 0.0, 1.0); } + case 55u: { let first = min(cells(p, seed) * 1.25, 1.0); let second = min(cells(p * 2.3 + 5.1, seed ^ 0x5au) * 1.25, 1.0); return clamp(first * first * 0.75 + second * second * 0.25, 0.0, 1.0); } + case 56u: { let a = noise(p * vec3(1.5, 60.0, 1.0), seed, false); let b = noise(p * vec3(0.4, 18.0, 1.0), seed ^ 0x77u, false); return clamp(a * 0.6 + b * 0.4, 0.0, 1.0); } + case 57u: { return cellular(p, seed, true).z; } case 58u: { let w = noise(p * 1.3, seed ^ 0x61u, true) - 0.5; @@ -628,6 +641,7 @@ fn extended_pattern(kind: u32, p: vec3, seed: u32) -> f32 { let smudge = clamp((fbm(p * 1.7, 4u, seed ^ 0x33u, false) - 0.55) * 3.0, 0.0, 1.0); return clamp(print * ridges * 0.9 + smudge * 0.4, 0.0, 1.0); } + case 60u: { return hexagon_tiles(uv, seed); } case 61u: { return wave_scales(uv); } case 62u: { return herringbone_planks(uv, seed); } diff --git a/crates/render/src/shaders/quick_mask.wgsl b/crates/render/src/shaders/quick_mask.wgsl index cd60f004..1968558b 100644 --- a/crates/render/src/shaders/quick_mask.wgsl +++ b/crates/render/src/shaders/quick_mask.wgsl @@ -19,8 +19,8 @@ fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { fn fs(@builtin(position) position: vec4) -> @location(0) vec4 { let p = vec2(position.xy); let source = textureLoad(material, vec2(p * textureDimensions(material) / params.size), 0).rgb; - // BaseColor was sampled from an sRGB texture. The original overlay tints the - // display-encoded color, before the aux view's ordinary decoding. + + // Tint in display-encoded color before the auxiliary view decodes it let srgb = select(1.055 * pow(source, vec3(1.0 / 2.4)) - 0.055, source * 12.92, source <= vec3(0.0031308)); var coverage = f32(textureLoad(mask, vec2(p * textureDimensions(mask) / params.size), 0).r) / 65535.0; if params.opacity > 0.0 { diff --git a/crates/render/src/shaders/stencil_projection.wgsl b/crates/render/src/shaders/stencil_projection.wgsl index 7505c632..89d958f4 100644 --- a/crates/render/src/shaders/stencil_projection.wgsl +++ b/crates/render/src/shaders/stencil_projection.wgsl @@ -1,4 +1,4 @@ -// Shared by live material compositing and projected stroke commit. +// Shared by live material compositing and projected stroke commit struct StencilProjection { view_proj: mat4x4, center_half: vec4, @@ -21,6 +21,7 @@ fn stencil_sample(image: texture_2d, placement: StencilProjection, position if clip.w <= 1e-6 { return vec4(0.0); } + let d = clip.xy / clip.w - placement.center_half.xy; let sn = placement.rotation_flags.x; let cs = placement.rotation_flags.y; @@ -28,15 +29,17 @@ fn stencil_sample(image: texture_2d, placement: StencilProjection, position if placement.rotation_flags.z == 0.0 && any(abs(local) > vec2(1.0)) { return vec4(0.0); } + let uv = local * vec2(0.5, -0.5) + 0.5; let size = textureDimensions(image); let grid = uv * vec2(size) - 0.5; if !all(abs(grid) <= vec2(3.402823466e38)) { return vec4(0.0); } + let floor_grid = floor(grid); - // The usual image positions fit in i32. Reduce huge tiled coordinates first - // so that the signed conversion and neighbouring texel remain in range. + + // Reduce huge tiled coordinates before converting them and their neighbours to signed texels var base_grid = floor_grid; if any(abs(base_grid) >= vec2(2147483520.0)) { base_grid = base_grid % vec2(size); @@ -54,6 +57,7 @@ fn stencil_sample(image: texture_2d, placement: StencilProjection, position if alpha == 0.0 { return vec4(0.0); } + var color = rgba.rgb; if placement.rotation_flags.w != 0.0 { let srgb = clamp(color, vec3(0.0), vec3(1.0)); diff --git a/crates/render/src/shaders/stencil_readback.wgsl b/crates/render/src/shaders/stencil_readback.wgsl index 032a4da3..b2f60bdc 100644 --- a/crates/render/src/shaders/stencil_readback.wgsl +++ b/crates/render/src/shaders/stencil_readback.wgsl @@ -17,7 +17,7 @@ fn projection_edge(a: vec2, b: vec2, p: vec2) -> f32 { return ab.x * ap.y - ab.y * ap.x; } -// One 64×64 document tile per dispatch layer, sampled only where the stroke has ink. +// One 64×64 document tile per dispatch layer, sampled only where the stroke has ink @compute @workgroup_size(8, 8) fn read_projection(@builtin(global_invocation_id) id: vec3) { let pixel = projection_tiles[id.z] + id.xy; @@ -27,15 +27,18 @@ fn read_projection(@builtin(global_invocation_id) id: vec3) { projected[index] = vec4(0.0); return; } + let hit = textureLoad(projection_uv, coords, 0).xy; if hit.x == 0xffffffffu { projected[index] = vec4(0.0); return; } + let a = projection_vertices[hit.x * 3u]; let b = projection_vertices[hit.x * 3u + 1u]; let c = projection_vertices[hit.x * 3u + 2u]; - // Match the live compositor's reconstruction from unquantized vertex UVs. + + // Match the live compositor's reconstruction from unquantized vertex UVs let size = vec2(textureDimensions(projection_uv)); let uv_a = vec2(a.position.w, a.normal.w) * size; let uv_b = vec2(b.position.w, b.normal.w) * size; diff --git a/crates/render/src/shaders/tile_generator.wgsl b/crates/render/src/shaders/tile_generator.wgsl index 81ae480e..0b413850 100644 --- a/crates/render/src/shaders/tile_generator.wgsl +++ b/crates/render/src/shaders/tile_generator.wgsl @@ -1,5 +1,4 @@ -// Tile Generator parameters and placements follow gpu_tile_pattern.rs in the packed -// compositor lookup buffer. Shapes, intersections and overlap blending run per texel. +// Read packed tile placements from the compositor's lookup buffer const TILE_NO_IMAGE = 0xffffffffu; const TILE_EPSILON = 0.000001; const TILE_PLACEMENT_WORDS = 11u; @@ -76,11 +75,13 @@ fn tile_analytic_shape(kind: u32, p: vec2, specific: f32) -> f32 { if specific <= TILE_EPSILON { return 1.0; } return tile_bevel((1.0 - abs(p.x)) / specific) * tile_bevel((1.0 - abs(p.y)) / specific); } + case 9u: { return (p.x + 1.0) * 0.5 * (1.0 - specific); } case 10u: { let cycles = 1.5 + 6.0 * specific; return clamp(1.0 - r * r, 0.0, 1.0) * (0.5 + 0.5 * cos(6.283185307179586 * cycles * p.x)); } + case 11u: { let width = 1.24 * (1.0 - specific); var cut = 1.0; @@ -88,22 +89,26 @@ fn tile_analytic_shape(kind: u32, p: vec2, specific: f32) -> f32 { if p.x > 0.0 && width <= TILE_EPSILON { cut = 0.0; } return tile_bell(r) * cut; } + case 12u: { let ridge = 1.0 - abs(p.x); return tile_bell(r) * ridge * ridge; } + case 13u: { if specific >= 1.0 { return 0.0; } let shifted = (p.x + 1.0) / (1.0 - specific) - 1.0; let ring = clamp(1.0 - r * r, 0.0, 1.0); return 6.75 * r * r * ring * ring * tile_bevel((1.0 - shifted) * 0.5); } + case 14u: { let radius = 0.2225; let half_length = specific * (1.0 - radius); let distance = length(vec2(max(abs(p.x) - half_length, 0.0), p.y)) / radius; return clamp(1.0 - distance * distance, 0.0, 1.0); } + case 15u: { return clamp(1.0 - r, 0.0, 1.0); } default: { return 0.0; } } @@ -130,6 +135,7 @@ fn tile_shape_sample(shape: TileShapeSettings, point: vec2, image: u32) -> if image == TILE_NO_IMAGE || any(abs(local) > vec2(1.0)) { return 0.0; } return tile_image_at(image, (local + 1.0) * 0.5); } + let grid = (local + 1.0) * 0.5 * shape.samples - 0.5; let base = floor(grid); let fraction = grid - base; @@ -146,7 +152,8 @@ fn tile_placement(shape: TileShapeSettings, offset: u32, point: vec2) -> f3 let size = tile_pair(offset + 2u); if any(size <= vec2(TILE_EPSILON)) { return 0.0; } let distance = point - tile_pair(offset); - // The CPU uses Rust's round-to-nearest with ties away from zero. + + // The CPU uses Rust's round-to-nearest with ties away from zero let delta = distance - sign(distance) * floor(abs(distance) + 0.5); let radius = tile_pair(offset + 4u); let first = vec2(max(ceil(-radius - delta), vec2(-3.0))); @@ -174,7 +181,7 @@ fn tile_placement(shape: TileShapeSettings, offset: u32, point: vec2) -> f3 return result * tile_float(offset + 10u); } -// First cell and number of cells to visit, counting each wrapped tile once. +// First cell and number of cells to visit, counting each wrapped tile once fn tile_near(position: f32, reach: f32, count: i32) -> vec2 { let first = floor(position - reach - 0.5); let last = ceil(position + reach - 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 e0e65b99..d7fa4088 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1,11 +1,8 @@ -use std::cell::RefCell; -use std::sync::{Mutex, MutexGuard, PoisonError}; - 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::headless::{Headless, TestGpuTurn}; use texturecraft_render::renderer::TAA_SAMPLES; use texturecraft_render::{BakeOverlay, BakeVisualization, CageGeometry, Frame, NeutralMaterial, Shade, ViewKind}; @@ -50,36 +47,34 @@ impl Img { /// The id `setup` uploads the material ball under const MESH_ID: u64 = 1; -/// Holds this test thread's turn until the thread ends, after the test dropped its device: the -/// NVIDIA driver can deadlock when one test destroys its device while another records commands -/// on its own. A thread that runs several tests (one test thread) keeps its turn. -fn take_turn() { - static TURN: Mutex<()> = Mutex::new(()); - thread_local! { - static HELD: RefCell>> = const { RefCell::new(None) }; - } - HELD.with(|held| { - if held.borrow().is_none() { - *held.borrow_mut() = Some(TURN.lock().unwrap_or_else(PoisonError::into_inner)); - } - }); +const TEST_TEXTURE_RESOLUTION: u32 = 256; + +fn headless_renderer() -> Option { + test_renderer(Headless::for_tests) +} + +fn test_renderer(create: impl FnOnce() -> Result) -> Option { + let Ok(headless) = create() else { + eprintln!("skipping: no GPU adapter"); + return None; + }; + + 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)> { - setup_with(Headless::new) + setup_with(Headless::for_tests) } -fn setup_with(headless: impl FnOnce() -> Result) -> Option<(Headless, Frame)> { - take_turn(); - let Ok(mut h) = headless() else { - eprintln!("skipping: no GPU adapter"); - return None; - }; - eprintln!("headless adapter: {:?}", h.device.adapter_info()); +fn setup_with(create: impl FnOnce() -> Result) -> Option<(Headless, Frame)> { + let mut h = test_renderer(create)?; 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); @@ -284,6 +279,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 }; @@ -619,6 +652,8 @@ fn bake_visualization_draws_the_high_poly_and_the_cage() { #[test] fn oversized_bake_high_poly_leaves_the_view_renderable() { + let _turn = TestGpuTurn::take(); + // The WebGPU default buffer limit (256 MiB) keeps the oversized mesh small enough to build let Some((mut headless, frame)) = setup_with(|| Headless::with_limits(|_| texturecraft_render::wgpu::Limits::default())) else { return }; @@ -763,10 +798,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); } } } @@ -1362,7 +1408,8 @@ fn prepacked_viewport_tiles_match_full_tiles_after_device_downscaling() { } let reference = render(&mut h, &uv, "full_tiles_downscaled"); assert_ne!(reference.px, neutral.px); - // Recreate the texture so missing writes cannot reuse the reference pixels. + + // Recreate the texture so missing writes cannot reuse the reference pixels h.renderer.set_texture_sets(&h.device, &h.queue, &[], 2); h.renderer.set_texture_sets(&h.device, &h.queue, &[((80, 96), 0)], 2); for y in 0..2 { diff --git a/crates/texel/src/tile.rs b/crates/texel/src/tile.rs index d337d99a..96dbfeed 100644 --- a/crates/texel/src/tile.rs +++ b/crates/texel/src/tile.rs @@ -62,6 +62,17 @@ impl TileImage { self.tile_index(tx, ty).and_then(|i| self.tiles.get(i)).and_then(Option::as_ref) } + /// Identity of the shared tile table: clones share it until one of them writes, so two images + /// with the same id hold one allocation (for memory accounting). + pub fn table_id(&self) -> usize { + Arc::as_ptr(&self.tiles) as usize + } + + /// Bytes of the tile table itself (one slot per tile position), not counting the tiles. + pub fn table_bytes(&self) -> usize { + self.tiles.len().saturating_mul(std::mem::size_of::>()) + } + /// Replace a tile wholesale (None frees it). pub fn set_tile(&mut self, tx: u32, ty: u32, data: Option) { let len = TILE_AREA * self.comps; @@ -354,10 +365,12 @@ impl TileImage { if (self.width, self.height) == (width.max(1), height.max(1)) { return self.clone(); } + let mut out = TileImage::new(width, height, self.comps); if self.allocated_count() == 0 { return out; } + for ty in 0..out.tiles_y { for tx in 0..out.tiles_x { if let Some(data) = self.resampled_tile(width, height, tx, ty, empty) { @@ -396,10 +409,12 @@ impl TileImage { if tx >= dw.div_ceil(TILE) || ty >= dh.div_ceil(TILE) { return None; } + let (start, end) = self.resize_footprint([dw, dh], [tx..tx + 1, ty..ty + 1]); if !self.has_allocated_texels(start, end) { return None; } + let mut absent = [0u16; 4]; for (value, default) in absent.iter_mut().zip(empty) { *value = *default; diff --git a/crates/ui-egui/build.rs b/crates/ui-egui/build.rs index 1e076445..274690a6 100644 --- a/crates/ui-egui/build.rs +++ b/crates/ui-egui/build.rs @@ -31,19 +31,7 @@ const LATIN: Faces = &[("Inter", "Regular"), ("Inter", "SemiBold")]; /// (family, style) pairs of a manifest. type Faces = &'static [(&'static str, &'static str)]; -/// Bytes each thread of this crate's test executables reserves for its stack when it asks for -/// none, on Windows (MSVC): Mesa's lavapipe, which the Windows CI gate renders with, runs the -/// composite shaders on its own threads, which get the executable's default of 1 MiB there and -/// overflow it on the larger programs (Linux gives them 8 MiB). As in texturecraft-render's -/// build script; this library crate links no other executable. -const THREAD_STACK_RESERVE: u32 = 8 * 1024 * 1024; - fn main() { - let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); - let target_env = std::env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(); - if target_os == "windows" && target_env == "msvc" { - println!("cargo::rustc-link-arg=/STACK:{THREAD_STACK_RESERVE}"); - } let catalogs = i18n_build::embed(); deflate_assets(); println!("cargo::rerun-if-env-changed=CRAFT_FONTS_DIR"); @@ -82,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}")); }; @@ -94,9 +82,9 @@ 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}"))?; diff --git a/crates/ui-egui/i18n_build.rs b/crates/ui-egui/i18n_build.rs index 1065757c..25de61b3 100644 --- a/crates/ui-egui/i18n_build.rs +++ b/crates/ui-egui/i18n_build.rs @@ -46,7 +46,7 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat Some(_) => String::from("static CRAFT_I18N_DEFLATED: &[(&str, &[u8], &[u8])] = &[\n"), None => String::from("pub static CRAFT_I18N: &craft_i18n::Embedded = &[\n"), }; - let close = |mut source: String| { + let finish_source = |mut source: String| { source.push_str("];\n"); source.push_str(if deflated_in.is_some() { INFLATE_FN @@ -55,11 +55,13 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat }); source }; + let Some(dir) = dir else { if required { return Err("CRAFT_I18N_REQUIRED=1 requires CRAFT_I18N_DIR".into()); } - return Ok((close(source), Vec::new())); + + return Ok((finish_source(source), Vec::new())); }; if !dir.is_absolute() { @@ -69,6 +71,7 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat 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())?; @@ -80,7 +83,8 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat 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()); @@ -104,9 +108,11 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat } None => format!("include_str!({name:?})"), }; + // The shared runtime needs static inputs for this short-lived build process Ok((include, Box::leak(text.into_boxed_str()))) }; + 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)?; @@ -116,6 +122,7 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat let _ = writeln!(source, " ({locale:?}, {shared}, {app}),"); count += 1; } + if required && count == 0 { return Err("no TextureCraft translation catalogs found".into()); } @@ -127,9 +134,9 @@ pub fn collect_into(dir: Option<&Path>, required: bool, deflated_in: Option<&Pat return Err(format!("invalid translation catalogs in {}: {}", locales.display(), problems.join("; "))); } + let mut characters: Vec<_> = characters.into_iter().collect(); characters.sort_unstable(); - characters.dedup(); - Ok((close(source), characters)) + Ok((finish_source(source), characters)) } /// Write the embedding for both desktop and wasm, reporting optional failures as warnings. 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_notice.rs b/crates/ui-egui/src/autosave_notice.rs new file mode 100644 index 00000000..5ca18157 --- /dev/null +++ b/crates/ui-egui/src/autosave_notice.rs @@ -0,0 +1,80 @@ +//! Tells the user when an autosave fails: the worker reports back, and one notice stays until a later +//! autosave works, so a missing backup is not mistaken for a saved one. + +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; + +use crate::TextureCraftApp; +use crate::i18n::trf; + +/// How one autosave ended. +struct Outcome { + path: PathBuf, + result: Result<(), String>, +} + +pub(crate) struct AutosaveNotice { + sender: Sender, + receiver: Receiver, + /// The failure the user was last told about; cleared by an autosave that works. + shown: Option, +} + +impl Default for AutosaveNotice { + fn default() -> Self { + let (sender, receiver) = channel(); + Self { sender, receiver, shown: None } + } +} + +/// Sends one autosave's result to the app, from any thread. +pub(crate) struct Reporter { + sender: Sender, + context: egui::Context, +} + +impl Reporter { + pub(crate) fn report(self, path: PathBuf, result: Result<(), String>) { + match &result { + Ok(()) => log::info!("autosaved {}", path.display()), + Err(error) => log::warn!("autosave to {} failed: {error}", path.display()), + } + + // A closed channel means the app is gone, so there is nobody left to tell + if self.sender.send(Outcome { path, result }).is_ok() { + self.context.request_repaint(); + } + } +} + +impl AutosaveNotice { + pub(crate) fn reporter(&self, context: &egui::Context) -> Reporter { + Reporter { sender: self.sender.clone(), context: context.clone() } + } +} + +/// Take in finished autosaves. A failure is announced once, however often it repeats. +pub(crate) fn poll(app: &mut TextureCraftApp) { + while let Ok(Outcome { path, result }) = app.autosave_notice.receiver.try_recv() { + let message = result.err().map(|error| trf("Autosave to {path} failed: {error}", &[("path", &path.display()), ("error", &error)])); + if message == app.autosave_notice.shown { + continue; + } + + if let Some(old) = app.autosave_notice.shown.take() { + app.toasts.retain(|toast| toast.text != old); + } + + if let Some(message) = &message { + app.session.log.error("Autosave", message.clone()); + app.toast_sticky(message.clone()); + + // The user's focus is elsewhere, so a screen reader hears the notice only as a live region + if let Some(toast) = app.toasts.last_mut() { + toast.announce = true; + } + } + + app.autosave_notice.shown = message; + } +} 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/dock.rs b/crates/ui-egui/src/dock.rs index 57c15011..30af76fb 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); } // --------------------------------------------------------------------------------------------- @@ -308,7 +215,7 @@ const SELECTED_LAYER_TINT: f32 = 0.3; const EYE_CHIP_INSET: f32 = 1.0; const EYE_CHIP_ROUNDING: f32 = 4.0; /// An effect thumbnail's corner rounding and border, the strike across a hidden effect's, and the line marking where a drag drops. -const THUMBNAIL_ROUNDING: f32 = 2.0; +pub(crate) const THUMBNAIL_ROUNDING: f32 = 2.0; const THUMBNAIL_BORDER_WIDTH: f32 = 1.0; const HIDDEN_STRIKE_WIDTH: f32 = 1.5; const DROP_LINE_WIDTH: f32 = 2.0; @@ -373,6 +280,8 @@ const EFFECT_ROW_SHADES: [f32; 2] = [0.2, 0.5]; /// Width of the blend mode and opacity pair at the right of an effect row (a gap between them), and of its opacity part. const EFFECT_BLEND_WIDTH: f32 = 82.0; const EFFECT_OPACITY_WIDTH: f32 = 36.0; +/// Width of the column at an effect row's right end holding its remove cross +const EFFECT_REMOVE_WIDTH: f32 = 17.0; /// Hover tint of alternating layer rows const ALTERNATE_LAYER_SHADE: f32 = 0.45; /// Maximum layer-tree nesting shown by the dock @@ -402,7 +311,8 @@ fn layer_name_layout(rect: Rect, left: f32) -> (Rect, bool) { /// Preserve the effect eye, preview and a readable name before spending space on nesting. fn effect_row_indent(width: f32, level: usize, preview: f32) -> f32 { - (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - ROW_RIGHT_PADDING).max(0.0)) + let remove_column = ROW_CONTROL_GAP + EFFECT_REMOVE_WIDTH + ROW_RIGHT_PADDING; + (level as f32 * INDENT).min((width - ROW_LEFT_PADDING - EYE_COLUMN_WIDTH - preview - THUMBNAIL_GAP - MIN_NAME_WIDTH - remove_column).max(0.0)) } /// X of the centre of the eye column at indent `level` in a row spanning from `left`. @@ -493,6 +403,10 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize let (_, rect) = ui.allocate_space(vec2(ui.available_width(), row_height)); let row = ui.interact(rect, ui.scope_id().with(("layer_row", layer.id.0)), Sense::click_and_drag()); row.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, highlighted, &layer.name)); + if app.layer_panel.reveal == Some(layer.id) { + app.layer_panel.reveal = None; + row.scroll_to_me(None); + } let painter = ui.painter().clone(); @@ -1017,7 +931,7 @@ fn blend_controls( (picked, field.changed().then_some((percent / 100.0, merge))) } -/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +/// Effect `effect` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level` #[allow(clippy::too_many_arguments)] fn effect_row( app: &mut TextureCraftApp, @@ -1076,11 +990,20 @@ fn effect_row( painter.line_segment([thumbnail.left_bottom(), thumbnail.right_top()], Stroke::new(HIDDEN_STRIKE_WIDTH, tokens.text_dim)); } - // Hide blend controls when the name needs the room + // Keep the remove hitbox clear of the overlay scrollbar + let remove = + Rect::from_min_max(pos2(rect.right() - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH, rect.top()), pos2(rect.right() - ROW_CONTROL_GAP, rect.bottom())); + let remove_hit = Rect::from_min_max(remove.min, pos2(remove.right().min(rect.right() - ui.spacing().scroll.bar_width), remove.bottom())); + let remove_response = ui.interact(remove_hit, ui.scope_id().with(("eff_remove", effect_id.0)), Sense::click()).on_hover_text(tr("Remove effect")); + remove_response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, trf("Remove effect {name}", &[("name", &effect.name)]))); + let remove_color = if remove_response.hovered() { tokens.text } else { tokens.text_dim }; + painter.text(remove.center(), egui::Align2::CENTER_CENTER, ic::X, egui::FontId::proportional(EYE_FONT_SIZE), remove_color); + + // Show blending controls only when the name has room let name_left = thumbnail.right() + THUMBNAIL_GAP; - let controls_left = rect.right() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; + let controls_left = remove.left() - ROW_CONTROL_GAP - EFFECT_BLEND_WIDTH; let show_blend = controls_left - ROW_CONTROL_GAP - name_left >= MIN_NAME_WIDTH; - let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { rect.right() - ROW_RIGHT_PADDING }; + let name_right = if show_blend { controls_left - ROW_CONTROL_GAP } else { remove.left() - ROW_RIGHT_PADDING }; let name_color = if visible { tokens.text } else { tokens.text_dim }; let renaming = app.ui.rename.as_ref().is_some_and(|(id, _)| *id == effect_id.0); if renaming { @@ -1115,6 +1038,9 @@ fn effect_row( if eye_response.clicked() { app.run("effect.set", json!({"effect": effect_id.0, "visible": !visible})); + } else if remove_response.clicked() { + app.run("effect.remove", json!({"effect": effect_id.0})); + return; } else if row.double_clicked() && !renaming { app.ui.rename = Some((effect_id.0, effect.name.clone())); } else if row.clicked() { @@ -1174,6 +1100,23 @@ fn effect_row( } } + // Rows list the stack top first and index 0 is its bottom, so up is one index higher + ui.separator(); + if let Some(index) = position(effect_id.0) { + let top = stack.len() - 1; + for (label, to, enabled) in [ + (tr("Move up"), index + 1, index < top), + (tr("Move down"), index.saturating_sub(1), index > 0), + (tr("Move to top"), top, index < top), + (tr("Move to bottom"), 0, index > 0), + ] { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + app.run("effect.move", json!({"effect": effect_id.0, "index": to})); + ui.close(); + } + } + } + // Blending options can apply across channels or effects ui.separator(); let blends = effect.kind.blends(); @@ -1409,6 +1352,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con run(app, ui, tr("Add white mask"), "mask.add.white", json!({"layer": layer_id}), layer.mask.is_none()); run(app, ui, tr("Add black mask"), "mask.add.black", json!({"layer": layer_id}), layer.mask.is_none()); run(app, ui, tr("Add mask with color selection"), "mask.add.colorSelection", json!({"layer": layer_id}), true); + run(app, ui, tr("Add mask with height combination"), "mask.add.heightCombination", json!({"layer": layer_id}), true); if !content_thumbnail { ui.separator(); mask_management_menu(app, ui, layer, false); @@ -1418,7 +1362,8 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con ui.separator(); solo_menu(app, ui, layer.id); ui.separator(); - run(app, ui, tr("Flatten layer"), "layer.flatten", json!({"layer": layer_id}), !layer.is_group()); + let flatten = if layer.is_group() { tr("Flatten folder") } else { tr("Flatten layer") }; + run(app, ui, flatten, "layer.flatten", json!({"layer": layer_id}), true); #[cfg(not(target_arch = "wasm32"))] if ui.button(tr("Create smart material")).clicked() { let file = crate::library_dir().join(format!("{}.tcmat", texturecraft_engine::formats::sanitize_resource_name(&layer.name))); @@ -1522,170 +1467,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 +1678,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 +1720,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 +1797,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 +1809,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 +1860,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 +1933,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 +1971,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 +1980,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 +2035,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 +2133,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 +2157,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 } => { @@ -3321,11 +2743,13 @@ mod layer_layout_tests { for level in 0..=14 { for preview in [18.0, 21.6, 28.0] { let indent = effect_row_indent(width, level, preview); - let eye_right = 7.0 + indent + 16.0; - let preview_left = 7.0 + indent + 22.0; - let name_left = preview_left + preview + 8.0; + let eye_right = ROW_LEFT_PADDING + indent + EYE_SIZE; + let preview_left = ROW_LEFT_PADDING + indent + EYE_COLUMN_WIDTH; + let name_left = preview_left + preview + THUMBNAIL_GAP; + let name_end = width - ROW_CONTROL_GAP - EFFECT_REMOVE_WIDTH - ROW_RIGHT_PADDING; + assert!(eye_right < preview_left); - assert!(name_left + 20.0 <= width - 6.0 + 0.001); + assert!(name_left + MIN_NAME_WIDTH <= name_end + 0.001, "width {width}, level {level}, preview {preview}"); } } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index f6a7928f..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, @@ -583,6 +585,9 @@ struct Panels<'a> { /// Room between a panel's edges and its contents const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); +/// Room around a panel of full-width list rows: none at the sides +pub(crate) const LIST_PANEL_MARGIN: Margin = Margin::symmetric(0, 4); + /// Narrowest Properties panel and so its dock column: the 300 point design width plus the solid scroll bar; narrower, the 3D projection settings' X, Y, Z fields (the widest row) overlap pub const PROPERTIES_MIN_WIDTH: f32 = 310.0; @@ -613,8 +618,13 @@ pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { return; } - // Properties draws full-width bands and tabs, so it keeps its own margins - let margin = if panel == Panel::Properties { Margin::ZERO } else { PANEL_BODY_MARGIN }; + // 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), @@ -627,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/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 935c6279..ac576220 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -10,7 +10,7 @@ use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor use rayon::prelude::*; use texturecraft_engine::Session; use texturecraft_engine::compose::{DisplayKind, ImageRes, display_tile_bytes, kinds_for}; -use texturecraft_engine::core::{BakedMap, Channel, LayerId}; +use texturecraft_engine::core::{AoMixing, BakedMap, Channel, LayerId}; use texturecraft_engine::geom::{Mesh, glam::Vec2}; use texturecraft_engine::session::ReleasedDab; #[cfg(not(target_arch = "wasm32"))] @@ -49,14 +49,25 @@ pub enum AuxView { /// A texture set's texels across and down, and its mesh material. pub type SetLayout = ((u32, u32), usize); -/// A viewport composite belongs to one document state and display size. -#[derive(Clone, Copy, PartialEq, Eq)] -struct CompositeKey { - mesh: u64, - revision: u64, - size: (u32, u32), - shift: u32, -} +mod composite_key; +mod composite_work; +#[cfg(not(target_arch = "wasm32"))] +mod device_stroke; +mod lit_environment; +mod mask_preview; +mod set_compositor; +#[cfg(not(target_arch = "wasm32"))] +mod viewport_brush_device; + +use composite_key::CompositeKey; +use composite_work::CompositeWork; +#[cfg(not(target_arch = "wasm32"))] +use device_stroke::DeviceStroke; +use lit_environment::LitEnvironment; +use mask_preview::MaskPreview; +use set_compositor::SetCompositor; +#[cfg(not(target_arch = "wasm32"))] +use viewport_brush_device::ViewportBrushDevice; /// The low poly's hard edges without a UV seam (vertex pairs) per material pub type MissingSeamEdges = Vec>; @@ -103,18 +114,6 @@ pub struct SceneSync { pub missing_seams: Option<(u64, MissingSeamEdges)>, } -/// Counts a frame's queued composite until submission completes or the frame is dropped. -struct CompositeWork { - in_flight: Arc, - started: Option, -} - -impl Drop for CompositeWork { - fn drop(&mut self) { - self.in_flight.fetch_sub(1, Ordering::AcqRel); - } -} - impl SceneSync { fn changes_base_color(&self, ts: usize) -> bool { self.sets.is_some() @@ -192,58 +191,6 @@ pub struct GpuState { pub ctx: egui::Context, } -#[cfg(not(target_arch = "wasm32"))] -struct BrushDevice(egui_wgpu::RenderState); - -#[cfg(not(target_arch = "wasm32"))] -impl brush_device::BrushDevice for BrushDevice { - fn start(&self, surface: brush_device::BrushSurface) -> Result, String> { - let mut renderer = self.0.renderer.write(); - let gpu = renderer.callback_resources.get_mut::().ok_or("GPU renderer unavailable")?; - DeviceStroke::start(&mut gpu.renderer, &self.0.device, &self.0.queue, surface) - } -} - -#[cfg(not(target_arch = "wasm32"))] -struct DeviceStroke(GpuBrushStroke); - -#[cfg(not(target_arch = "wasm32"))] -impl DeviceStroke { - fn start( - renderer: &mut Renderer, - device: &wgpu::Device, - queue: &wgpu::Queue, - surface: brush_device::BrushSurface, - ) -> Result, String> { - let brush_device::BrushSurface { mesh, bvh, uv, material, depth, settings, stencil, limit } = surface; - let stroke = renderer.start_gpu_brush(device, queue, BrushInput { mesh, bvh, uv, material, depth, settings, stencil, limit })?; - Ok(Box::new(Self(stroke))) - } -} - -#[cfg(not(target_arch = "wasm32"))] -impl brush_device::DeviceStroke for DeviceStroke { - fn append_world(&mut self, stamps: &[Stamp]) -> Result { - self.0.append_world(stamps) - } - - fn append_uv(&mut self, stamps: &[UvStamp]) -> Result { - self.0.append_uv(stamps) - } - - fn read_alpha(&self, tiles: &brush_device::BrushTiles) -> Result { - self.0.read_alpha(tiles) - } - - fn read_projection(&self, tiles: &brush_device::BrushTiles) -> Result { - self.0.read_projection(tiles) - } - - fn as_any(&self) -> &dyn std::any::Any { - &self.0 - } -} - /// Problems the GPU side hands to the UI, which shows them as toasts. #[derive(Default)] pub struct GpuReports { @@ -261,50 +208,6 @@ const PIPELINE_POLL: std::time::Duration = std::time::Duration::from_millis(30); const GPU_COMPOSITE_ERROR: &str = n_("GPU compositing reported a device error. See the app log for details."); const NO_COVERED_TEXELS: &str = n_("The texture set has no covered UV texels."); -#[derive(Default)] -struct SetCompositor { - current: Option, - stroke: Option, - rejected: Option<(CompositeKey, &'static str)>, - failed_key: Option, - failed: Arc, - reason: &'static str, - neutral: bool, - logged_status: Option<(&'static str, &'static str)>, - /// The environment the current program lights with, when it reads it (P6's Baked Lighting - /// Environment): a turned or changed environment compiles the program again - environment: Option, - /// The GPU reported the program's pipelines still compiling: keep the last result (no CPU - /// fallback) and plan the program again - pending: Arc, -} - -/// The viewport environment a program read its diffuse light from: name, rotation bits and the -/// identity of an imported environment image (a re-imported resource differs) -#[derive(Debug, PartialEq)] -struct LitEnvironment { - name: String, - rotation: u32, - image: usize, -} - -impl LitEnvironment { - fn of(session: &Session) -> Self { - let display = &session.doc.project.display; - Self { name: display.environment.clone(), rotation: display.env_rotation.to_bits(), image: Self::image(session) } - } - - fn image(session: &Session) -> usize { - let display = &session.doc.project.display; - display.environment_resource().and_then(|name| session.images.get(name)).map_or(0, |image| Arc::as_ptr(image) as usize) - } - - fn matches(&self, session: &Session) -> bool { - let display = &session.doc.project.display; - self.name == display.environment && self.rotation == display.env_rotation.to_bits() && self.image == Self::image(session) - } -} - /// The project the GPU compositor compiles for the view: while a layer is soloed, the material /// from its isolated copy (`compose::solo_project`, as the CPU compositor draws it); the mask view /// reads the document's own mask, as the CPU's `mask_image` does. The stroke lines of @@ -315,159 +218,6 @@ fn view_project(session: &Session, mask_view: bool) -> Cow<'_, texturecraft_engi soloed.map_or(Cow::Borrowed(&session.doc.project), Cow::Owned) } -impl SetCompositor { - fn uses_gpu(&self) -> bool { - self.current.is_some() && !self.failed.load(Ordering::Acquire) - } - - fn plan( - &mut self, - session: &Session, - ts: usize, - shift: u32, - global_reason: &'static str, - mask: Option, - ) -> Result, &'static str> { - let cache = session.caches.get(ts).ok_or(n_("The texture set is missing."))?; - let key = CompositeKey { mesh: session.mesh_id, revision: cache.material_revision, size: cache.size, shift }; - if self.failed.load(Ordering::Acquire) { - self.failed_key = self.current; - self.failed = Arc::default(); - self.stroke = None; - } - if !global_reason.is_empty() { - return Err(global_reason); - } - if self.failed_key == Some(key) { - return Err(GPU_COMPOSITE_ERROR); - } - let edits_view = !session.quick_mask.editing && mask.is_none_or(|id| session.stroke_mask_owner() == Some(session.doc.project.mask_owner(id))); - let padding = mask.is_none().then(|| cache.dilation.mixed_coverage()).flatten(); - let uncovered = mask.is_none() && !cache.dilation.fully_covered() && padding.is_none(); - - // A set fed by another set's stroke that is rejected for its material or coverage shows the stroke on release - let fed = session.stroke_texture_set() != Some(ts); - let fed_rejected = fed && (uncovered || self.rejected.is_some_and(|(rejected, _)| rejected == key)); - let stroke = session.pending_display_stroke(ts).filter(|_| edits_view && !fed_rejected); - if edits_view && session.stroke_texture_set() == Some(ts) && stroke.is_none() { - return Err(n_("This painting tool uses CPU compositing.")); - } - - if uncovered { - return Err(NO_COVERED_TEXELS); - } - let stroke_id = stroke.map(|(id, _)| id); - // A program lit by the environment is current only while the environment stays as it was - let waited = self.pending.swap(false, Ordering::AcqRel); - let current = self.current == Some(key) && !waited && self.environment.as_ref().is_none_or(|lit| lit.matches(session)); - let unchanged_stroke = self.stroke == stroke_id; - if current && unchanged_stroke && stroke.is_none_or(|(_, tiles)| tiles.is_empty()) { - return Ok(None); - } - if stroke.is_none() - && let Some((_, reason)) = self.rejected.filter(|(rejected, _)| *rejected == key) - { - return Err(reason); - } - let changed_tiles = if current - && (unchanged_stroke || self.stroke.is_none()) - && let Some((_, tiles)) = stroke - { - Some(tiles) - } else if stroke.is_none() - // Only over a preview the renderer accepted: a pending one never wrote its tiles - && !waited - && let Some(previous_id) = self.stroke - && let Some(previous) = self.current.filter(|old| old.mesh == key.mesh && old.size == key.size && old.shift == key.shift) - { - session.finished_display_stroke(ts, previous_id, previous.revision) - } else { - None - }; - let region = changed_tiles - .and_then(|tiles| CompositeRegion::from_tiles(tiles.iter().copied())) - .map(|r| if padding.is_some() { r.expanded(texturecraft_engine::texel::TILE) } else { r }); - if changed_tiles.is_some() && region.is_none() { - self.current = Some(key); - self.stroke = stroke_id; - return Ok(None); - } - let preview = stroke.and_then(|_| { - // A GPU neighbourhood stage can read earlier, still uncommitted CPU dabs well - // outside the changed output. Keep all sparse stroke tiles available in that case. - let project = &session.doc.project; - let anchors = project - .texture_sets - .get(ts) - .is_some_and(|set| project.render_tree(&set.stack).iter().any(|layer| project.layers.get(layer).is_some_and(|layer| layer.reads_anchor()))); - let bounds = if session.device_stroke().is_none() && (anchors || texturecraft_engine::compose::stack_reads_neighbours(project, ts)) { - None - } else { - region.map(|r| r.expanded(texturecraft_engine::texel::TILE).bounds()) - }; - session.display_stroke_pixels(ts, bounds) - }); - let pixels = preview.as_ref().unwrap_or(&session.doc.pixels); - #[cfg(not(target_arch = "wasm32"))] - // The stroke's coverage serves every set it feeds, in the same texels - let brush = if let Some(brush) = session.device_stroke().filter(|_| stroke.is_some()) { - let coverage = brush.stroke.as_any().downcast_ref::().ok_or(n_("This painting tool uses CPU compositing."))?; - let target = match brush.target { - PaintTarget::Layer(layer) if brush.erase => { - // The channels the commit erases; their values are unused - let channels = texturecraft_engine::paint::commit::commit_channels(&session.doc.pixels, layer, brush.values, true); - LiveBrushTarget::Layer { layer, values: channels.into_iter().map(|channel| (channel, [0.0; 3])).collect() } - } - PaintTarget::Layer(layer) => LiveBrushTarget::Layer { layer, values: brush.values.clone() }, - PaintTarget::Mask(effect) => LiveBrushTarget::Mask { effect, value: brush.mask_value, image: brush.mask_image.map(str::to_owned) }, - }; - Some(LiveBrush { target, opacity: brush.opacity, erase: brush.erase, alpha: coverage.view(), stencil: coverage.stencil() }) - } else { - None - }; - #[cfg(target_arch = "wasm32")] - let brush = None; - let project = view_project(session, mask.is_some()); - let program = match mask { - Some(owner) => CompositeProgram::try_compile_mask_preview(&project, pixels, ts, owner, region, brush), - None => CompositeProgram::try_compile_with_brush(&project, pixels, ts, region, brush), - }; - let mut program = match program { - Ok(program) => program, - Err(reason) => { - if stroke_id.is_none() { - self.rejected = Some((key, reason)); - } - return Err(reason); - } - }; - if let Some(padding) = padding { - program.set_coverage(padding, texturecraft_engine::session::DISPLAY_PADDING); - } - if let Err(reason) = program.set_surface_inputs(&session.mesh, &cache.gbuf, session.doc.baked.get(&ts)) { - if stroke_id.is_none() { - self.rejected = Some((key, reason)); - } - return Err(reason); - } - program.set_tile_images(&session.images); - self.environment = program.environment().map(|_| LitEnvironment::of(session)); - self.neutral = program.is_neutral(); - if !current { - self.failed = Arc::default(); - } - self.current = Some(key); - self.stroke = stroke_id; - Ok(Some(program)) - } -} - -struct MaskPreview { - ts: usize, - layer: LayerId, - compositor: SetCompositor, -} - /// UI-side bookkeeping of what the GPU already has. pub struct GpuLink { pub reset: Arc, @@ -548,6 +298,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { wake.request_repaint(); })); let mut renderer = Renderer::new(&rs.device, &rs.queue, rs.target_format); + // New composite pipelines compile on worker threads; the viewport keeps its last result renderer.set_asynchronous_compile(!cfg!(test)); rs.renderer.write().callback_resources.insert(GpuState { renderer, recreated: recreated.clone(), reports: reports.clone(), ctx: ctx.clone() }); @@ -575,7 +326,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { && info.backend != wgpu::Backend::Gl && std::env::var("TEXTURECRAFT_GPU_COMPOSITE").as_deref() != Ok("0"), #[cfg(not(target_arch = "wasm32"))] - brush_device: Some(Arc::new(BrushDevice(rs.clone()))), + brush_device: Some(Arc::new(ViewportBrushDevice(rs.clone()))), prefer_gpu_layers: true, material_start_preview: true, compositors: Vec::new(), @@ -600,11 +351,13 @@ impl GpuLink { if !self.gpu_composite_enabled || !self.prefer_gpu_layers { return None; } + let cache = session.caches.get(ts)?; let backend = || Some(brush_device::BrushBackend { device: self.brush_device.clone()?, surface: Arc::downgrade(&cache.gbuf) }); if session.quick_mask.editing { return (!self.quick_mask_failed.load(Ordering::Acquire)).then(backend).flatten(); } + let state = match session.view { ViewMode::Mask(layer) => { let preview = self.mask_preview.as_ref().filter(|preview| preview.ts == ts && preview.layer == layer)?; @@ -620,6 +373,7 @@ impl GpuLink { if !mask_selected { return None; } + &preview.compositor } _ => self.compositors.get(ts)?, @@ -628,6 +382,7 @@ impl GpuLink { if !state.uses_gpu() || state.current != Some(key) { return None; } + backend() } @@ -671,9 +426,11 @@ impl GpuLink { if compositor.uses_gpu() { return (n_("Mask: GPU"), n_("The graphics card composes the displayed mask.")); } + let reason = if compositor.failed.load(Ordering::Acquire) { GPU_COMPOSITE_ERROR } else { compositor.reason }; return (n_("Mask: CPU"), reason); } + let cpu = self.compositors.iter().find(|set| !set.uses_gpu()); let uses_gpu = self.compositors.iter().any(|set| set.uses_gpu() && !set.neutral); let reason = @@ -757,10 +514,12 @@ impl GpuLink { out.compositor_changed |= self.mask_preview.take().is_some(); return false; }; + let Some((ts, _, _)) = session.doc.project.locate(layer) else { self.mask_preview = None; return false; }; + if self.mask_preview.as_ref().is_none_or(|preview| preview.ts != ts || preview.layer != layer) { self.mask_preview = Some(MaskPreview { ts, layer, compositor: SetCompositor::default() }); out.compositor_changed = true; @@ -775,12 +534,12 @@ impl GpuLink { if session.stroke_mask_owner() == Some(session.doc.project.mask_owner(layer)) { session.clear_display_stroke_tiles(); } - // Aux now holds GPU pixels instead of the prior CPU upload. + + // Aux now holds GPU pixels instead of the prior CPU upload self.aux.remove(&ts); } - // A material view that is re-opened mid-stroke must rebuild from the - // complete coverage, since this view acknowledged the recent tiles: every set - // the stroke feeds (an instance of the layer too), not only the ones that saw it + + // Reopening a view mid-stroke needs the full coverage of each dependent set for (ts, material) in self.compositors.iter_mut().enumerate() { if material.stroke.is_some() || session.stroke_texture_set() == Some(ts) || session.pending_display_stroke(ts).is_some() { if material.current.take().is_some() { @@ -861,8 +620,8 @@ impl GpuLink { if resend || out.mesh.is_some() || self.shift != shift || self.sets.get(ts) != Some(layout) { self.compositors[ts] = SetCompositor::default(); let Some(cache) = session.caches.get_mut(ts) else { continue }; - // The renderer may recreate these textures. Dirty tiles will enter the - // upload queue after composition; sending them now sends blank pixels. + + // Replaced textures can receive dirty tiles only after recomposition cache.queue_ready_uploads(); self.pending_overviews.remove(&ts); if self.material_start_preview && cache.dirty.len() >= UPLOAD_CHUNK { @@ -879,6 +638,7 @@ impl GpuLink { self.quick_mask_failed = Arc::default(); out.sets = Some((sets.clone(), session.mesh.materials.len().max(1), shift)); + // Start compiling each set's pipelines now, so the first composites do not wait out.prewarm = (0..sets.len()).filter_map(|ts| CompositeProgram::compile(&session.doc.project, &session.doc.pixels, ts)).collect(); self.sets = sets; @@ -941,7 +701,8 @@ impl GpuLink { #[cfg(not(target_arch = "wasm32"))] let padding_pending = { let mut not_ready = padding_pending; - // Start at most one dense map at a time, with the active material first. + + // Start at most one dense map at a time, with the active material first let first = active.min(count); let (before, from_active) = session.caches.split_at_mut(first); let candidates = (first..count) @@ -949,14 +710,18 @@ impl GpuLink { .chain((0..first).zip(before)) .filter(|(ts, cache)| uses_cpu(*ts) && cache.size.0.max(cache.size.1) > 1024 && (!cache.dirty.is_empty() || !cache.settle.is_empty())); for (ts, cache) in candidates { - if !cache.dilation.is_ready() && (!not_ready.is_empty() || !cache.dilation.prepare_on_worker()) { + if !cache.dilation.is_ready() { + if not_ready.is_empty() { + cache.dilation.prepare_on_worker(); + } not_ready.insert(ts); } } self.cpu_padding_pending = !not_ready.is_empty(); not_ready }; - // At most one small full-atlas evaluation per frame, active material first. + + // At most one small full-atlas evaluation per frame, active material first let next_overview = if gpu_mask { None } else if self.pending_overviews.remove(&active) { @@ -980,8 +745,8 @@ impl GpuLink { } let first = self.upload_cursor.take().filter(|&set| set < count && out.mesh.is_none()).unwrap_or(active); let rotation = (first..count).chain(0..first.min(count)); - // While painting, share the first chunk with the next waiting set. An overloaded - // frame still submits at most one chunk in total, independent of material count. + + // An overloaded frame shares one upload chunk across all waiting materials let boost = uses_cpu(active) && (session.stroke_active() || demand.focused()) && active != first @@ -993,8 +758,10 @@ impl GpuLink { if cache.upload.is_empty() || self.pending_overviews.contains(&texture_set) { continue; } + let empty = Default::default(); let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + let ao_mixing = session.doc.project.texture_sets.get(texture_set).map_or(AoMixing::Multiply, |set| set.ao_mixing); let channels: Vec = cache.composite.channels.keys().copied().collect(); let sent = self.sent.entry(texture_set).or_default(); let kinds: Vec = @@ -1010,13 +777,14 @@ impl GpuLink { let bytes: Vec<_> = chunk .par_iter() .flat_map_iter(|&(x, y)| kinds.iter().map(move |&kind| (kind, x, y))) - .map(|(kind, x, y)| (texture_set, kind, x, y, display_tile_bytes(composite, baked, kind, x, y, out.tile_shift))) + .map(|(kind, x, y)| (texture_set, kind, x, y, display_tile_bytes(composite, baked, ao_mixing, kind, x, y, out.tile_shift))) .collect(); queued += bytes.len(); out.tiles.extend(bytes); if boosted { break; } + chunk_size = UPLOAD_CHUNK; if time_left_ms(queued) < MIN_SLICE_MS { self.upload_cursor = Some((texture_set + 1) % count); @@ -1116,6 +884,7 @@ impl GpuLink { if let Some(device) = stroke.device.and_then(|stroke| stroke.as_any().downcast_ref::()) { return (QuickMaskAlpha::Gpu(device.view()), stroke.opacity, stroke.erase); } + (QuickMaskAlpha::Cpu(stroke.alpha.clone()), stroke.opacity, stroke.erase) }); out.quick_masks.push(( @@ -1385,15 +1154,9 @@ pub(crate) mod tests { use texturecraft_render::headless::Headless; #[cfg(not(target_arch = "wasm32"))] - struct HeadlessBrush(Mutex); - + mod headless_brush; #[cfg(not(target_arch = "wasm32"))] - impl brush_device::BrushDevice for HeadlessBrush { - fn start(&self, surface: brush_device::BrushSurface) -> Result, String> { - let Headless { renderer, device, queue, .. } = &mut *self.0.lock().unwrap(); - DeviceStroke::start(renderer, device, queue, surface) - } - } + use headless_brush::HeadlessBrush; pub(crate) fn link() -> GpuLink { GpuLink { @@ -1664,7 +1427,8 @@ pub(crate) mod tests { s.update(); let all = texturecraft_engine::compose::all_tiles(1024, 1024); let mut gpu = link(); - // The zoomed square spans four by four tiles at the lower right of the atlas. + + // The zoomed square spans four by four tiles at the lower right of the atlas let bounds = crate::viewport::visible_uv_bounds([512, 512], (1024, 1024), 4.0 / 0.92, [-3.0, 3.0], 0.0); let out = gpu.sync_view(&mut s, None, None, 0, FRAME_BUDGET_MS, Some(bounds)); let coords: BTreeSet<_> = out.tiles.iter().map(|t| (t.2, t.3)).collect(); @@ -1731,10 +1495,11 @@ pub(crate) mod tests { for shift in 0..=TILE.ilog2() { s.caches[0].upload = [(1, 0)].into(); let scene = gpu.sync(&mut s, None, None, shift, 0.0); - // Changing the display scale recreates the set, including the other ready tiles. + + // Changing the display scale recreates the set, including the other ready tiles assert_eq!(scene.tiles.iter().filter(|(_, _, x, y, _)| (*x, *y) == (1, 0)).count(), DisplayKind::ALL.len()); for (_, kind, x, y, bytes) in &scene.tiles { - let full = tile_bytes(&s.caches[0].composite, &Default::default(), *kind, *x, *y); + let full = tile_bytes(&s.caches[0].composite, &Default::default(), AoMixing::Multiply, *kind, *x, *y); let step = 1usize << shift; let stride = kind.bytes_per_texel(); let rows = full.chunks_exact(TILE as usize * stride).step_by(step); @@ -1752,8 +1517,8 @@ pub(crate) mod tests { let update = link.sync(&mut session, None, None, 0, FRAME_BUDGET_MS); assert!(update.overview.is_none()); assert!(!update.tiles.is_empty()); - // The CPU may already have computed every tile, but the upload budget still - // leaves part of the material for a later frame. + + // The upload budget may defer tiles the CPU has already computed assert!(link.display_pending(&session)); link.material_start_preview = true; @@ -1814,6 +1579,7 @@ pub(crate) mod tests { if ready { break; } + assert!(frames < 2048); } println!("{size}: whole material visible on first rendered frame, detail finished after {frames} syncs"); @@ -1892,7 +1658,7 @@ pub(crate) mod tests { assert_eq!(link.compositor_status().0, "Layers: GPU"); assert_eq!(session.memory().geometry, geometry_bytes); - // A device error still enables the dense padding only on the CPU path. + // A device error still enables the dense padding only on the CPU path scene.composites[0].2.store(true, Ordering::Release); let scene = link.sync(&mut session, None, None, 0, 0.0); assert!(scene.composites.is_empty()); @@ -1901,6 +1667,45 @@ pub(crate) mod tests { assert!(session.memory().geometry > geometry_bytes, "only the CPU path allocates the dense padding map"); } + #[test] + fn seam_padding_falls_back_per_set_and_switching_to_island_padding_retries_gpu() { + let mut session = Session::new_project("seams", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let mut state = SetCompositor::default(); + execute(&mut session, "layer.add.fill", &json!({"ts":1,"color":[1.0,0.0,0.0]})).unwrap(); + + let initial = state.plan(&session, 1, 0, "", None); + + assert!(matches!(initial, Err(reason) if reason.contains("UV seams"))); + + execute(&mut session, "textureSet.settings", &json!({"ts":1,"uvPadding":"2d"})).unwrap(); + + assert!(state.plan(&session, 1, 0, "", None).unwrap().is_some()); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn changing_ao_mixing_updates_the_gpu_display() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let mut session = Session::new_project("ao mixing", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + session.doc.baked.entry(0).or_default().maps.insert(BakedMap::AmbientOcclusion, Arc::new(vec![0.25])); + session.doc.baked.get_mut(&0).unwrap().resolution = 1; + let mut link = link(); + link.gpu_composite_enabled = true; + let mut ambient = |session: &mut Session| { + let scene = link.sync(session, None, None, 0, 0.0); + assert_eq!(scene.composites.len(), 1); + let (_, errors, _) = scene.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + assert!(errors.is_empty(), "{errors:?}"); + read_display(&gpu, gpu.renderer.display_textures()[0][DisplayKind::Orm as usize], 64, 64)[0] + }; + let multiplied = ambient(&mut session); + + execute(&mut session, "textureSet.settings", &json!({"aoMixing":"none"})).unwrap(); + let unmixed = ambient(&mut session); + + assert!(unmixed > multiplied, "baked AO should darken the display only in Multiply mode"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn project_open_and_4k_resize_compose_multiple_sets_on_gpu() { @@ -1910,6 +1715,7 @@ pub(crate) mod tests { let mut original = Session::new_project("multi-material", primitives::material_ball(), "builtin:material_ball", None, 2048).unwrap(); assert_eq!(original.caches.len(), 2); for (ts, color) in [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]].into_iter().enumerate() { + execute(&mut original, "textureSet.settings", &json!({"ts":ts,"uvPadding":"2d"})).unwrap(); execute(&mut original, "textureSet.select", &json!({"ts":ts})).unwrap(); execute(&mut original, "layer.add.fill", &json!({"color":color})).unwrap(); } @@ -1954,7 +1760,7 @@ pub(crate) mod tests { assert_eq!(scene.composites[0].0, 1, "only the blurred set needs to be recomposited"); assert_eq!(link.compositor_status().0, "Layers: GPU"); - // A failed GPU submission for the second set leaves the first on the GPU. + // A failed GPU submission for the second set leaves the first on the GPU scene.composites[0].2.store(true, Ordering::Release); let _ = session.caches[1].dilation.source(0, 0); let before = session.caches[0].revision; @@ -1974,7 +1780,7 @@ pub(crate) mod tests { for material in texturecraft_engine::materials::MATERIALS { let mut session = Session::new_project("Material shelf", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); if material.id == "moss" { - // Adding sheen must keep an existing stack on the GPU. + // Adding sheen must keep an existing stack on the GPU for _ in 0..32 { execute(&mut session, "layer.add.fill", &json!({"color": [0.12, 0.19, 0.06]})).unwrap(); } @@ -1984,6 +1790,7 @@ pub(crate) mod tests { link.gpu_composite_enabled = true; let update = link.sync(&mut session, None, None, 0, 0.0); let (status, reason) = link.compositor_status(); + // Planned on the GPU is what counts here; each GPU path's pixels are its oracle tests' if status != "Layers: GPU" || update.composites.len() != 1 || !update.tiles.is_empty() { rejected.push(format!("{}: {status} ({reason})", material.id)); @@ -2078,9 +1885,15 @@ pub(crate) mod tests { assert_submitted_mask_view_matches_the_cpu(&mut session, layer, "earlier-model Dirt generator"); } - /// Every built-in material, smart mask and default generator on the baked sample composites on - /// the GPU (material, and mask view for the masks), with nothing left to the CPU. Their - /// pixels are each GPU path's oracle tests' (render crate), not this sweep's. + #[cfg(not(target_arch = "wasm32"))] + fn set_island_padding(session: &mut Session) { + for set in 0..session.set_count() { + execute(session, "textureSet.settings", &json!({"ts": set, "uvPadding": "2d"})).unwrap(); + } + } + + /// Checks material and mask routing on the baked sample with GPU-supported island padding. + /// Default generators that require the CPU must report the reason in the mask view. #[cfg(not(target_arch = "wasm32"))] #[test] fn builtin_library_and_default_generators_composite_on_the_gpu_on_the_baked_sample() { @@ -2088,6 +1901,8 @@ pub(crate) mod tests { const SIZE: u32 = 256; let mut session = texturecraft_engine::sample_session(SIZE, SIZE).unwrap(); + set_island_padding(&mut session); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 1.0], "roughness": 0.123})).unwrap(); let mut link = link(); link.gpu_composite_enabled = true; @@ -2102,10 +1917,11 @@ pub(crate) mod tests { session.undo().unwrap(); } - // The pedestal has edges, cavities and differently oriented faces. + // The pedestal has edges, cavities and differently oriented faces session.active_set = 1; execute(&mut session, "material.apply", &json!({"material": "gold_polished"})).unwrap(); let layer = session.selected_layer().unwrap(); + // `on_gpu`: the mask composes on the GPU, else on the CPU, saying why let mut check_mask = |session: &mut Session, name: &str, on_gpu: bool| { if !on_gpu { @@ -2116,6 +1932,7 @@ pub(crate) mod tests { } return; } + session.view = ViewMode::Material; if let Err(reason) = plan_library_preview(&mut link, session, None) { failures.push(format!("{name} on the material: {reason}")); @@ -2129,8 +1946,8 @@ pub(crate) mod tests { execute(&mut session, "mask.smart.apply", &json!({"name": mask.id, "layer": layer.0})).unwrap(); check_mask(&mut session, mask.id, true); } - // A default generator on the earlier model (ThinAreas) composes on the GPU; the others start - // on the reference app's controls, which compose on the CPU + + // Only the earlier generator model is supported here for generator in GeneratorKind::ALL { execute(&mut session, "mask.remove", &json!({"layer": layer.0})).unwrap(); execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap(); @@ -2163,7 +1980,7 @@ pub(crate) mod tests { let (width, height, bytes) = Readback::blocking(&gpu.device, &gpu.queue, gpu.renderer.display_textures()[0][kind as usize]).unwrap(); assert_eq!((width, height), (128, 128), "{material}: full-resolution material texture"); - let cpu = display_tile_bytes(&session.caches[0].composite, &Default::default(), kind, 0, 0, 0); + let cpu = display_tile_bytes(&session.caches[0].composite, &Default::default(), AoMixing::Multiply, kind, 0, 0, 0); for (x, y) in [(9, 7), (12, 21), (33, 55), (47, 15)] { let actual = &bytes[(y * width as usize + x) * 4..][..4]; let expected = &cpu[(y * 64 + x) * 4..][..4]; @@ -2216,9 +2033,10 @@ pub(crate) mod tests { if kind == DisplayKind::BaseColor { continue; } + let (width, height, actual) = Readback::blocking(&gpu.device, &gpu.queue, textures[0][kind as usize]).unwrap(); assert_eq!((width, height), (128, 128), "{kind:?}"); - let expected = display_tile_bytes(&session.caches[0].composite, &Default::default(), kind, 0, 0, 0); + let expected = display_tile_bytes(&session.caches[0].composite, &Default::default(), AoMixing::Multiply, kind, 0, 0, 0); let stride = kind.bytes_per_texel(); let (x, y) = (9, 15); let actual = &actual[(y * width as usize + x) * stride..][..stride]; @@ -2234,12 +2052,15 @@ pub(crate) mod tests { let mut session = Session::closed().unwrap(); execute(&mut session, "project.sample", &json!({})).unwrap(); + set_island_padding(&mut session); + assert_eq!(session.caches.len(), 2); let mut link = link(); link.gpu_composite_enabled = true; link.material_start_preview = false; let mut headless = Headless::for_tests().ok(); let opened = std::time::Instant::now(); + // The sample's own size; the resolution change below exercises the resize { let size = 2048; @@ -2274,7 +2095,7 @@ pub(crate) mod tests { execute(&mut session, "textureSet.resolution", &json!({"ts":ts,"resolution":128})).unwrap(); } - // Compare a few baked and generated sample pixels at 128². + // Compare a few baked and generated sample pixels at 128² let update = link.sync(&mut session, None, None, 0, 0.0); let (_, errors, _) = update.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); assert!(errors.is_empty(), "{errors:?}"); @@ -2293,8 +2114,10 @@ pub(crate) mod tests { for (map, kind) in DisplayKind::ALL.into_iter().take(3).enumerate() { let (width, _, bytes) = Readback::blocking(&gpu.device, &gpu.queue, gpu.renderer.display_textures()[ts][map]).unwrap(); assert_eq!(width, 128); - let cpu: BTreeMap<_, _> = - tiles.into_iter().map(|(x, y)| ((x, y), display_tile_bytes(&cache.composite, session.baked(ts).unwrap(), kind, x, y, 0))).collect(); + let cpu: BTreeMap<_, _> = tiles + .into_iter() + .map(|(x, y)| ((x, y), display_tile_bytes(&cache.composite, session.baked(ts).unwrap(), AoMixing::Multiply, kind, x, y, 0))) + .collect(); let stride = kind.bytes_per_texel(); let compare = |i: usize| { let (x, y) = (i % 128, i / 128); @@ -2330,8 +2153,11 @@ pub(crate) mod tests { if name.contains("llvmpipe") || name.contains("lavapipe") || name.contains("warp") || gpu.device.limits().max_texture_dimension_2d < 8192 { return; } + let mut session = Session::closed().unwrap(); execute(&mut session, "project.sample", &json!({})).unwrap(); + set_island_padding(&mut session); + let layer = *session.doc.project.texture_sets[0].stack.last().unwrap(); let paint = session.doc.pixels.layer_mut(layer, Channel::BaseColor, (2048, 2048)); let red = Arc::new([65535, 0, 0, 65535].repeat(TILE_AREA)); @@ -2495,8 +2321,7 @@ pub(crate) mod tests { mask }; - // Two plain fills (solo is about what the stack draws, not about patterns) with a half - // mask on the first, a folder holding a masked fill and an instance of the first fill + // Exercise solo selection across a masked fill, folder and instance let build = || { let mut session = Session::new_project("Solo", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); for color in [[0.7, 0.5, 0.4], [0.35, 0.6, 0.75]] { @@ -2729,7 +2554,7 @@ pub(crate) mod tests { let final_pixel = display(link.sync(&mut s, aux, None, 0, 0.0), mask_view, true); assert!(final_pixel.iter().zip(gray).all(|(a, b)| a.abs_diff(b) <= 1), "{final_pixel:?} vs {gray:?}"); if mask_view { - // The material display must still compose when leaving the independent mask view. + // The material display must still compose when leaving the independent mask view s.view = ViewMode::Material; assert_ne!(Some(display(link.sync(&mut s, None, None, 0, 0.0), false, true)), original_material); } else { @@ -2780,6 +2605,7 @@ pub(crate) mod tests { assert!(s.device_stroke().is_some(), "mask view {mask_view}: the image stroke runs on the device"); let live = display(&mut link, &mut s, aux); assert!(s.doc.pixels.masks.is_empty(), "live GPU painting keeps the document untouched"); + // Changing the gray mid-stroke leaves the stroke's image execute(&mut s, "tool.material", &json!({"maskImage": null, "maskValue": 0.0})).unwrap(); s.end_stroke().unwrap(); @@ -3050,6 +2876,10 @@ pub(crate) mod tests { let Ok(gpu) = Headless::for_tests() else { return }; let brush = Arc::new(HeadlessBrush(Mutex::new(gpu))); let mut s = Session::new_project("GPU instance stroke", primitives::material_ball(), "builtin:material_ball", None, SIZE).unwrap(); + for ts in 0..s.caches.len() { + execute(&mut s, "textureSet.settings", &json!({"ts":ts,"uvPadding":"2d"})).unwrap(); + } + let paint = s.selected_layer().unwrap(); execute(&mut s, "layer.instance", &json!({"layer": paint.0, "ts": 1})).unwrap(); execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap(); @@ -3220,7 +3050,8 @@ pub(crate) mod tests { assert_eq!(link.compositor_status().0, "Layers: CPU"); assert!(!first.quick_masks.is_empty()); assert!(first.tiles.iter().any(|(_, kind, ..)| *kind == DisplayKind::BaseColor)); - // Simulate a frame where CPU composition finished but the BaseColor upload remains queued. + + // Simulate a frame where CPU composition finished but the BaseColor upload remains queued first.tiles.retain(|(_, kind, ..)| *kind != DisplayKind::BaseColor); let before = display(&first); let revision = (s.caches[0].revision, s.caches[0].material_revision, s.quick_mask.revision); @@ -3245,7 +3076,7 @@ pub(crate) mod tests { assert!(s.quick_mask_stroke(0).is_some_and(|stroke| stroke.device.is_some())); display(&live); - // The explicit CPU preference still materializes coverage before the CPU overlay. + // The explicit CPU preference still materializes coverage before the CPU overlay link.prefer_gpu_layers = false; let fallback = link.sync(&mut s, aux, None, 0, 0.0); assert!(fallback.release_quick_mask && fallback.quick_masks.is_empty() && !fallback.aux.is_empty()); @@ -3395,7 +3226,8 @@ pub(crate) mod tests { if mask_view { session.view = ViewMode::Mask(layer); } - // Three authored sRGB bands with distinct colors and alpha, away from sample boundaries. + + // Three authored sRGB bands with distinct colors and alpha, away from sample boundaries let stencil = image::RgbaImage::from_fn(24, 24, |x, _| { image::Rgba(match x / 8 { 0 => [241, 107, 35, 0], @@ -3509,7 +3341,15 @@ pub(crate) mod tests { } else { uvs.map(|uv| { let (x, y) = texel(uv, size); - let tile = display_tile_bytes(&cpu.caches[0].composite, &Default::default(), DisplayKind::BaseColor, x / TILE, y / TILE, 0); + let tile = display_tile_bytes( + &cpu.caches[0].composite, + &Default::default(), + AoMixing::Multiply, + DisplayKind::BaseColor, + x / TILE, + y / TILE, + 0, + ); let i = ((y % TILE * TILE + x % TILE) * 4) as usize; tile[i..i + 4].try_into().unwrap() }) @@ -3618,6 +3458,7 @@ pub(crate) mod tests { if (red && r.saturating_sub(g) > 64) || (!red && g.saturating_sub(r) > 64) { break; } + assert!(count < 6, "brush pixel must change, got {r}, {g} at pass {pass}"); } if pass >= 4 { diff --git a/crates/ui-egui/src/gpu/composite_key.rs b/crates/ui-egui/src/gpu/composite_key.rs new file mode 100644 index 00000000..a37ed1d7 --- /dev/null +++ b/crates/ui-egui/src/gpu/composite_key.rs @@ -0,0 +1,8 @@ +/// A viewport composite belongs to one document state and display size. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct CompositeKey { + pub(super) mesh: u64, + pub(super) revision: u64, + pub(super) size: (u32, u32), + pub(super) shift: u32, +} diff --git a/crates/ui-egui/src/gpu/composite_work.rs b/crates/ui-egui/src/gpu/composite_work.rs new file mode 100644 index 00000000..0aab603f --- /dev/null +++ b/crates/ui-egui/src/gpu/composite_work.rs @@ -0,0 +1,13 @@ +use super::{Arc, AtomicUsize, Ordering}; + +/// Counts a frame's queued composite until submission completes or the frame is dropped. +pub(super) struct CompositeWork { + pub(super) in_flight: Arc, + pub(super) started: Option, +} + +impl Drop for CompositeWork { + fn drop(&mut self) { + self.in_flight.fetch_sub(1, Ordering::AcqRel); + } +} diff --git a/crates/ui-egui/src/gpu/device_stroke.rs b/crates/ui-egui/src/gpu/device_stroke.rs new file mode 100644 index 00000000..bd850944 --- /dev/null +++ b/crates/ui-egui/src/gpu/device_stroke.rs @@ -0,0 +1,38 @@ +use super::{BrushInput, GpuBrushStroke, Renderer, Stamp, TileImage, UvStamp, brush_device, wgpu}; + +pub(super) struct DeviceStroke(pub(super) GpuBrushStroke); + +impl DeviceStroke { + pub(super) fn start( + renderer: &mut Renderer, + device: &wgpu::Device, + queue: &wgpu::Queue, + surface: brush_device::BrushSurface, + ) -> Result, String> { + let brush_device::BrushSurface { mesh, bvh, uv, material, depth, settings, stencil, limit } = surface; + let stroke = renderer.start_gpu_brush(device, queue, BrushInput { mesh, bvh, uv, material, depth, settings, stencil, limit })?; + Ok(Box::new(Self(stroke))) + } +} + +impl brush_device::DeviceStroke for DeviceStroke { + fn append_world(&mut self, stamps: &[Stamp]) -> Result { + self.0.append_world(stamps) + } + + fn append_uv(&mut self, stamps: &[UvStamp]) -> Result { + self.0.append_uv(stamps) + } + + fn read_alpha(&self, tiles: &brush_device::BrushTiles) -> Result { + self.0.read_alpha(tiles) + } + + fn read_projection(&self, tiles: &brush_device::BrushTiles) -> Result { + self.0.read_projection(tiles) + } + + fn as_any(&self) -> &dyn std::any::Any { + &self.0 + } +} diff --git a/crates/ui-egui/src/gpu/lit_environment.rs b/crates/ui-egui/src/gpu/lit_environment.rs new file mode 100644 index 00000000..7627134a --- /dev/null +++ b/crates/ui-egui/src/gpu/lit_environment.rs @@ -0,0 +1,27 @@ +use super::{Arc, Session}; + +/// The viewport environment a program read its diffuse light from: name, rotation bits and the +/// identity of an imported environment image (a re-imported resource differs) +#[derive(Debug, PartialEq)] +pub(super) struct LitEnvironment { + pub(super) name: String, + pub(super) rotation: u32, + pub(super) image: usize, +} + +impl LitEnvironment { + pub(super) fn of(session: &Session) -> Self { + let display = &session.doc.project.display; + Self { name: display.environment.clone(), rotation: display.env_rotation.to_bits(), image: Self::image(session) } + } + + pub(super) fn image(session: &Session) -> usize { + let display = &session.doc.project.display; + display.environment_resource().and_then(|name| session.images.get(name)).map_or(0, |image| Arc::as_ptr(image) as usize) + } + + pub(super) fn matches(&self, session: &Session) -> bool { + let display = &session.doc.project.display; + self.name == display.environment && self.rotation == display.env_rotation.to_bits() && self.image == Self::image(session) + } +} diff --git a/crates/ui-egui/src/gpu/mask_preview.rs b/crates/ui-egui/src/gpu/mask_preview.rs new file mode 100644 index 00000000..be3389cc --- /dev/null +++ b/crates/ui-egui/src/gpu/mask_preview.rs @@ -0,0 +1,7 @@ +use super::{LayerId, SetCompositor}; + +pub(super) struct MaskPreview { + pub(super) ts: usize, + pub(super) layer: LayerId, + pub(super) compositor: SetCompositor, +} diff --git a/crates/ui-egui/src/gpu/set_compositor.rs b/crates/ui-egui/src/gpu/set_compositor.rs new file mode 100644 index 00000000..40a3f175 --- /dev/null +++ b/crates/ui-egui/src/gpu/set_compositor.rs @@ -0,0 +1,185 @@ +#[cfg(not(target_arch = "wasm32"))] +use super::{GpuBrushStroke, LiveBrush, LiveBrushTarget, PaintTarget}; + +use super::{ + Arc, AtomicBool, CompositeKey, CompositeProgram, CompositeRegion, GPU_COMPOSITE_ERROR, LayerId, LitEnvironment, NO_COVERED_TEXELS, Ordering, Session, n_, + view_project, +}; + +#[derive(Default)] +pub(super) struct SetCompositor { + pub(super) current: Option, + pub(super) stroke: Option, + pub(super) rejected: Option<(CompositeKey, &'static str)>, + pub(super) failed_key: Option, + pub(super) failed: Arc, + pub(super) reason: &'static str, + pub(super) neutral: bool, + pub(super) logged_status: Option<(&'static str, &'static str)>, + /// The environment the current program lights with, when it reads it (P6's Baked Lighting + /// Environment): a turned or changed environment compiles the program again + pub(super) environment: Option, + /// The GPU reported the program's pipelines still compiling: keep the last result (no CPU + /// fallback) and plan the program again + pub(super) pending: Arc, +} + +impl SetCompositor { + pub(super) fn uses_gpu(&self) -> bool { + self.current.is_some() && !self.failed.load(Ordering::Acquire) + } + + pub(super) fn plan( + &mut self, + session: &Session, + ts: usize, + shift: u32, + global_reason: &'static str, + mask: Option, + ) -> Result, &'static str> { + let cache = session.caches.get(ts).ok_or(n_("The texture set is missing."))?; + let key = CompositeKey { mesh: session.mesh_id, revision: cache.material_revision, size: cache.size, shift }; + if self.failed.load(Ordering::Acquire) { + self.failed_key = self.current; + self.failed = Arc::default(); + self.stroke = None; + } + if !global_reason.is_empty() { + return Err(global_reason); + } + + if self.failed_key == Some(key) { + return Err(GPU_COMPOSITE_ERROR); + } + + if mask.is_none() && cache.dilation.needs_seam_padding() { + let reason = n_("Padding across UV seams uses CPU compositing."); + self.rejected = Some((key, reason)); + return Err(reason); + } + + let edits_view = !session.quick_mask.editing && mask.is_none_or(|id| session.stroke_mask_owner() == Some(session.doc.project.mask_owner(id))); + let padding = mask.is_none().then(|| cache.dilation.mixed_coverage()).flatten(); + let uncovered = mask.is_none() && !cache.dilation.fully_covered() && padding.is_none(); + + // A set fed by another set's stroke that is rejected for its material or coverage shows the stroke on release + let fed = session.stroke_texture_set() != Some(ts); + let fed_rejected = fed && (uncovered || self.rejected.is_some_and(|(rejected, _)| rejected == key)); + let stroke = session.pending_display_stroke(ts).filter(|_| edits_view && !fed_rejected); + if edits_view && session.stroke_texture_set() == Some(ts) && stroke.is_none() { + return Err(n_("This painting tool uses CPU compositing.")); + } + + if uncovered { + return Err(NO_COVERED_TEXELS); + } + + let stroke_id = stroke.map(|(id, _)| id); + + // A program lit by the environment is current only while the environment stays as it was + let waited = self.pending.swap(false, Ordering::AcqRel); + let current = self.current == Some(key) && !waited && self.environment.as_ref().is_none_or(|lit| lit.matches(session)); + let unchanged_stroke = self.stroke == stroke_id; + if current && unchanged_stroke && stroke.is_none_or(|(_, tiles)| tiles.is_empty()) { + return Ok(None); + } + + if stroke.is_none() + && let Some((_, reason)) = self.rejected.filter(|(rejected, _)| *rejected == key) + { + return Err(reason); + } + + let changed_tiles = if current + && (unchanged_stroke || self.stroke.is_none()) + && let Some((_, tiles)) = stroke + { + Some(tiles) + } else if stroke.is_none() + // Only over a preview the renderer accepted: a pending one never wrote its tiles + && !waited + && let Some(previous_id) = self.stroke + && let Some(previous) = self.current.filter(|old| old.mesh == key.mesh && old.size == key.size && old.shift == key.shift) + { + session.finished_display_stroke(ts, previous_id, previous.revision) + } else { + None + }; + let region = changed_tiles + .and_then(|tiles| CompositeRegion::from_tiles(tiles.iter().copied())) + .map(|r| if padding.is_some() { r.expanded(texturecraft_engine::texel::TILE) } else { r }); + if changed_tiles.is_some() && region.is_none() { + self.current = Some(key); + self.stroke = stroke_id; + return Ok(None); + } + + let preview = stroke.and_then(|_| { + // Neighbourhood stages can sample uncommitted sparse dabs beyond the output region + let project = &session.doc.project; + let anchors = project + .texture_sets + .get(ts) + .is_some_and(|set| project.render_tree(&set.stack).iter().any(|layer| project.layers.get(layer).is_some_and(|layer| layer.reads_anchor()))); + let bounds = if session.device_stroke().is_none() && (anchors || texturecraft_engine::compose::stack_reads_neighbours(project, ts)) { + None + } else { + region.map(|r| r.expanded(texturecraft_engine::texel::TILE).bounds()) + }; + session.display_stroke_pixels(ts, bounds) + }); + let pixels = preview.as_ref().unwrap_or(&session.doc.pixels); + #[cfg(not(target_arch = "wasm32"))] + // The stroke's coverage serves every set it feeds, in the same texels + let brush = if let Some(brush) = session.device_stroke().filter(|_| stroke.is_some()) { + let coverage = brush.stroke.as_any().downcast_ref::().ok_or(n_("This painting tool uses CPU compositing."))?; + let target = match brush.target { + PaintTarget::Layer(layer) if brush.erase => { + // The channels the commit erases; their values are unused + let channels = texturecraft_engine::paint::commit::commit_channels(&session.doc.pixels, layer, brush.values, true); + LiveBrushTarget::Layer { layer, values: channels.into_iter().map(|channel| (channel, [0.0; 3])).collect() } + } + PaintTarget::Layer(layer) => LiveBrushTarget::Layer { layer, values: brush.values.clone() }, + PaintTarget::Mask(effect) => LiveBrushTarget::Mask { effect, value: brush.mask_value, image: brush.mask_image.map(str::to_owned) }, + }; + Some(LiveBrush { target, opacity: brush.opacity, erase: brush.erase, alpha: coverage.view(), stencil: coverage.stencil() }) + } else { + None + }; + #[cfg(target_arch = "wasm32")] + let brush = None; + let project = view_project(session, mask.is_some()); + let program = match mask { + Some(owner) => CompositeProgram::try_compile_mask_preview(&project, pixels, ts, owner, region, brush), + None => CompositeProgram::try_compile_with_brush(&project, pixels, ts, region, brush), + }; + let mut program = match program { + Ok(program) => program, + Err(reason) => { + if stroke_id.is_none() { + self.rejected = Some((key, reason)); + } + return Err(reason); + } + }; + if let Some(padding) = padding { + program.set_coverage(padding, texturecraft_engine::session::DISPLAY_PADDING); + } + if let Err(reason) = program.set_surface_inputs(&session.mesh, &cache.gbuf, session.doc.baked.get(&ts)) { + if stroke_id.is_none() { + self.rejected = Some((key, reason)); + } + return Err(reason); + } + + program.set_tile_images(&session.images); + self.environment = program.environment().map(|_| LitEnvironment::of(session)); + self.neutral = program.is_neutral(); + if !current { + self.failed = Arc::default(); + } + self.current = Some(key); + self.stroke = stroke_id; + Ok(Some(program)) + } +} diff --git a/crates/ui-egui/src/gpu/tests/headless_brush.rs b/crates/ui-egui/src/gpu/tests/headless_brush.rs new file mode 100644 index 00000000..9547860d --- /dev/null +++ b/crates/ui-egui/src/gpu/tests/headless_brush.rs @@ -0,0 +1,10 @@ +use super::{DeviceStroke, Headless, Mutex, brush_device}; + +pub(super) struct HeadlessBrush(pub(super) Mutex); + +impl brush_device::BrushDevice for HeadlessBrush { + fn start(&self, surface: brush_device::BrushSurface) -> Result, String> { + let Headless { renderer, device, queue, .. } = &mut *self.0.lock().unwrap(); + DeviceStroke::start(renderer, device, queue, surface) + } +} diff --git a/crates/ui-egui/src/gpu/viewport_brush_device.rs b/crates/ui-egui/src/gpu/viewport_brush_device.rs new file mode 100644 index 00000000..7aa17ca7 --- /dev/null +++ b/crates/ui-egui/src/gpu/viewport_brush_device.rs @@ -0,0 +1,11 @@ +use super::{DeviceStroke, GpuState, brush_device, egui_wgpu}; + +pub(super) struct ViewportBrushDevice(pub(super) egui_wgpu::RenderState); + +impl brush_device::BrushDevice for ViewportBrushDevice { + fn start(&self, surface: brush_device::BrushSurface) -> Result, String> { + let mut renderer = self.0.renderer.write(); + let gpu = renderer.callback_resources.get_mut::().ok_or("GPU renderer unavailable")?; + DeviceStroke::start(&mut gpu.renderer, &self.0.device, &self.0.queue, surface) + } +} diff --git a/crates/ui-egui/src/gpu_port_gate.rs b/crates/ui-egui/src/gpu_port_gate.rs index 9caebb13..f7d73705 100644 --- a/crates/ui-egui/src/gpu_port_gate.rs +++ b/crates/ui-egui/src/gpu_port_gate.rs @@ -24,6 +24,7 @@ fn cpu_reason(id: &str, mask: bool) -> Option { let mut session = Session::new_project("Library gate", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); let added = execute(&mut session, "layer.add.fill", &json!({"color": [0.6, 0.3, 0.2]})).unwrap(); let layer = LayerId(added["layer"].as_u64().unwrap()); + // A signed Height source next to the colour, so a filter that falls back only on Height counts assert!(session.doc.project.texture_sets[session.ts()].has_channel(Channel::Height)); if let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind { @@ -35,9 +36,11 @@ fn cpu_reason(id: &str, mask: bool) -> Option { if let Err(reason) = CompositeProgram::try_compile_region(project, pixels, ts, None) { return Some(format!("material: {reason}")); } + if mask && let Err(reason) = CompositeProgram::try_compile_mask_preview(project, pixels, ts, layer, None, None) { return Some(format!("mask preview: {reason}")); } + None } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 7d9be266..5aef076d 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -2,11 +2,11 @@ //! overrides (`UiState::keymap`, id → "Ctrl+Shift+E" or "" for unbound), conflict detection and //! the shortcut editor window (Help ▸ Shortcuts list) and the Edit ▸ Settings ▸ Shortcuts page. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::OnceLock; use crate::shortcut_dispatch::Dispatcher; -use craft_keymap::{Active, Chord, CommandDef, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes}; +use craft_keymap::{Active, Chord, CommandDef, CommandRef, ConflictKind, KeyInput, Layout, Lookup, Mods, Overrides, Platform, Scope, Scopes, Trigger}; use egui::{Event, Id, Key, KeyboardShortcut, Modifiers, RichText, vec2}; use egui_phosphor::regular as ic; @@ -189,22 +189,58 @@ pub fn format_shortcut(sc: &KeyboardShortcut) -> String { s } -/// Every bound shortcut as egui's shortcut type. -fn active(keymap: &Keymap) -> Vec { - bindings().iter().filter_map(|b| Some(parse(shortcut(keymap, b)?)?.to_egui_shortcut())).collect() +const REDO_COMMAND_ID: &str = "edit.redo"; +const ALTERNATE_REDO_SHORTCUT: Chord = Chord::new(Mods { shift: true, ..Mods::CMD }, craft_keymap::Key::Z); + +/// Keep the alternate in Redo's defaults unless a registered binding claims it. +fn alternate_redo_shortcut(overrides: &Overrides, platform: Platform) -> Option { + let alternate = Trigger::single(ALTERNATE_REDO_SHORTCUT); + let app_scope = Scope::app(); + let mut seen_variant_ids = BTreeSet::new(); + for (key, texts) in overrides.iter() { + let command; + let id = if key.contains(' ') { + let Some(parsed) = CommandRef::parse_key(key) else { continue }; + command = parsed; + + // The shared keymap prefers exact keys, then the first variant in key order + if command.key_text() != command.id || overrides.get(&command.id).is_some() || !seen_variant_ids.insert(command.id.clone()) { + continue; + } + + command.id.as_str() + } else { + key + }; + + let claims_alternate = texts + .iter() + .filter_map(|text| craft_keymap::Binding::parse(text).ok()) + .any(|binding| binding.scope_or(&app_scope).is_app() && binding.trigger.effective(platform) == alternate); + if claims_alternate && bindings().iter().any(|binding| binding.id == id) { + return None; + } + } + + Some(ALTERNATE_REDO_SHORTCUT) } -/// The catalog as craft-keymap sees it, in `bindings()` order: the first one listed wins a shared -/// shortcut. -fn catalog() -> Vec { +/// The catalog for craft-keymap in `bindings()` order. The first listed command wins a shared shortcut. +fn catalog(alternate_redo: Option) -> Vec { bindings() .iter() - .map(|b| { - let item = CommandDef::new(b.id, b.label, Scope::app()); - match b.default.and_then(parse) { - Some(chord) => item.with_default(craft_keymap::Binding::new(chord)), - None => item, + .map(|binding| { + let mut command = CommandDef::new(binding.id, binding.label, Scope::app()); + if let Some(chord) = binding.default.and_then(parse) { + command = command.with_default(craft_keymap::Binding::new(chord)); } + if binding.id == REDO_COMMAND_ID + && let Some(chord) = alternate_redo + { + command = command.with_default(craft_keymap::Binding::new(chord)); + } + + command }) .collect() } @@ -223,7 +259,8 @@ fn overrides(keymap: &Keymap) -> Overrides { let mut out = Overrides::new(); for (id, text) in keymap { let texts = if text.is_empty() { Vec::new() } else { vec![override_text(text)] }; - // Only an overlong id or text is refused, and neither can be a shortcut. + + // The shared keymap enforces its storage limits here let _ = out.insert(id.clone(), texts); } out @@ -231,7 +268,10 @@ fn overrides(keymap: &Keymap) -> Overrides { /// The keymap with `keymap`'s shortcuts for `platform`. fn resolved(keymap: &Keymap, platform: Platform) -> craft_keymap::Keymap { - craft_keymap::Keymap::new(catalog(), Scopes::new(), platform).with_overrides(overrides(keymap)).with_delete_keys(craft_keymap::DeleteKeys::Apart) + let overrides = overrides(keymap); + let commands = catalog(alternate_redo_shortcut(&overrides, platform)); + + craft_keymap::Keymap::new(commands, Scopes::new(), platform).with_overrides(overrides).with_delete_keys(craft_keymap::DeleteKeys::Apart) } /// The resolved keymap and the dispatcher that runs it against each frame's keys. @@ -261,6 +301,12 @@ impl Bindings { } } + /// Refresh browser capture from the same bindings used for dispatch. + #[cfg(any(test, target_arch = "wasm32"))] + pub(crate) fn sync_captured(&self) { + refresh_captured(&self.stored, self.map.platform(), || alternate_is_bound(&self.map)); + } + /// The ids of the commands this frame's key presses run, in press order. The presses are /// removed from the input. pub(crate) fn dispatch(&mut self, input: &mut egui::InputState) -> Vec { @@ -324,33 +370,61 @@ pub fn rebind(keymap: &mut Keymap, b: &Binding, value: &str) { } } -/// The bound shortcuts the browser must not act on, for the web build's `keydown` listener: -/// the keymap they were taken from and the shortcuts. -static CAPTURED: std::sync::Mutex)>> = std::sync::Mutex::new(None); +/// The keymap, platform and shortcuts for the web build's `keydown` listener. +static CAPTURED: std::sync::Mutex)>> = std::sync::Mutex::new(None); -/// Refresh [`captured`] when the keymap changed (once per frame; cheap when it didn't). +/// Refresh [`captured`] from stored shortcuts for the current platform. pub fn sync_captured(keymap: &Keymap) { - let mut c = CAPTURED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - if c.as_ref().is_some_and(|(k, _)| k == keymap) { + let platform = Platform::current(); + refresh_captured(keymap, platform, || alternate_is_bound(&resolved(keymap, platform))); +} + +fn alternate_is_bound(map: &craft_keymap::Keymap) -> bool { + !matches!(map.lookup(&ALTERNATE_REDO_SHORTCUT, false, &Active::NONE), Lookup::None) +} + +fn refresh_captured(keymap: &Keymap, platform: Platform, alternate_bound: impl FnOnce() -> bool) { + let mut captured = CAPTURED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if captured.as_ref().is_some_and(|(stored, stored_platform, _)| stored == keymap && *stored_platform == platform) { return; } - // Copy, cut and paste stay with the browser: egui reads them as clipboard events. + + // Copy, cut and paste stay with the browser because egui reads clipboard events let clipboard = [Key::C, Key::V, Key::X]; - let keys: Vec = active(keymap) - .into_iter() - .filter(|sc| { - let fkey = sc.logical_key.name().strip_prefix('F').is_some_and(|n| n.parse::().is_ok()); - (sc.modifiers.command || sc.modifiers.alt || fkey) && !(sc.modifiers.command && !sc.modifiers.shift && clipboard.contains(&sc.logical_key)) + let mut keys: Vec = bindings() + .iter() + .filter_map(|binding| parse(shortcut(keymap, binding)?)) + .filter(|chord| chord.effective(platform) != ALTERNATE_REDO_SHORTCUT) + .map(|chord| chord.to_egui_shortcut()) + .filter(|shortcut| { + let function_key = shortcut.logical_key.name().strip_prefix('F').is_some_and(|number| number.parse::().is_ok()); + let clipboard_key = shortcut.modifiers.command && !shortcut.modifiers.shift && clipboard.contains(&shortcut.logical_key); + (shortcut.modifiers.command || shortcut.modifiers.alt || function_key) && !clipboard_key }) .collect(); + + // Only admitted bindings can claim the alternate for the app + if alternate_bound() { + keys.push(ALTERNATE_REDO_SHORTCUT.to_egui_shortcut()); + } + log::debug!("browser shortcuts taken over: {}", keys.len()); - *c = Some((keymap.clone(), keys)); + *captured = Some((keymap.clone(), platform, keys)); } /// Whether a key press is one of the app's shortcuts the browser must leave alone. pub fn captured(mods: Modifiers, key: Key) -> bool { - let c = CAPTURED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - c.as_ref().is_some_and(|(_, keys)| keys.iter().any(|sc| sc.logical_key == key && mods.matches_logically(sc.modifiers))) + let captured = CAPTURED.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let Some((_, platform, keys)) = captured.as_ref() else { return false }; + + keys.iter().filter(|shortcut| shortcut.logical_key == key).any(|shortcut| { + // Undo and Redo distinguish Shift on the same letter + if key == Key::Z { + Mods::from_egui(&mods, *platform) == Mods::from_egui(&shortcut.modifiers, *platform) + } else { + mods.matches_logically(shortcut.modifiers) + } + }) } const CAPTURE: &str = "keymap_capture"; @@ -681,6 +755,7 @@ pub fn fixed_gestures_grid(ui: &mut egui::Ui) { pub fn fixed_gestures() -> Vec<(String, String)> { let stencil = crate::viewport::STENCIL_KEY.name(); let clone = crate::viewport::CLONE_SOURCE_KEY.name(); + let pick = crate::viewport::PICK_LAYER_KEY.name(); let keyed = |template: &str| trf(template, &[("key", &stencil)]); vec![ (tr("Alt + LMB drag").into(), tr("Orbit").into()), @@ -698,10 +773,11 @@ 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()), + (trf("{key} + LMB", &[("key", &pick)]), tr("Select the layer under the cursor; several there: pick one from a list").into()), (tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()), (tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()), (tr("Click the first point (Path tool)").into(), tr("Path: close it (needs 3 points)").into()), @@ -720,12 +796,35 @@ mod tests { fn the_browser_leaves_app_shortcuts_alone_but_keeps_the_clipboard() { let mut keymap = Keymap::new(); keymap.insert("file.close".into(), "Alt+W".into()); - sync_captured(&keymap); + + keymap.insert("edit.undo".into(), String::new()); + let mut resolved = bindings_for(&keymap); + resolved.sync_captured(); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; assert!(captured(ctrl, Key::S) && captured(ctrl, Key::O) && captured(ctrl, Key::D)); + assert!(captured(Modifiers { shift: true, ..ctrl }, Key::Z), "the second Redo key is taken over too"); assert!(captured(Modifiers::NONE, Key::F9) && captured(Modifiers::ALT, Key::W)); assert!(!captured(ctrl, Key::C) && !captured(ctrl, Key::V) && !captured(ctrl, Key::X), "clipboard keys reach the browser"); assert!(!captured(Modifiers::NONE, Key::M) && !captured(Modifiers::NONE, Key::F), "plain keys need no capture"); + + keymap.remove("edit.undo"); + keymap.insert("edit.redo".into(), String::new()); + resolved.sync(&keymap, Platform::Windows); + resolved.sync_captured(); + assert!(!captured(Modifiers { shift: true, ..ctrl }, Key::Z), "clearing Redo gives its second key back"); + + keymap.insert("file.save".into(), "Control+Shift+Z".into()); + resolved.sync(&keymap, Platform::Windows); + resolved.sync_captured(); + assert!(captured(Modifiers { shift: true, ..ctrl }, Key::Z), "a custom binding also takes the key from the browser"); + + resolved.sync(&Keymap::new(), Platform::Mac); + resolved.sync_captured(); + + let command = Modifiers::MAC_CMD | Modifiers::COMMAND; + assert!(captured(command | Modifiers::SHIFT, Key::Z)); + assert!(!captured(ctrl | Modifiers::SHIFT, Key::Z), "physical Control on macOS does not run Redo"); } #[test] @@ -733,8 +832,9 @@ 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")); + assert!(has(&format!("{} + LMB", crate::viewport::PICK_LAYER_KEY.name()), "Select the layer")); for (gesture, what) in [ ("Shift + LMB", "straight line"), ("Shift + RMB drag", "environment light"), @@ -884,6 +984,72 @@ mod tests { assert_eq!(run(Modifiers::SHIFT, Key::M), None, "Shift+M is not bound"); } + #[test] + fn a_second_default_key_yields_to_the_stored_shortcuts() { + let second_press = press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT); + let run = |keymap: &Keymap| bindings_for(keymap).command_of(&second_press); + let mut keymap = Keymap::new(); + + assert_eq!(run(&keymap).as_deref(), Some("edit.redo")); + assert_eq!(bindings_for(&keymap).command_of(&press(Key::Y, Modifiers::COMMAND)).as_deref(), Some("edit.redo")); + assert_eq!(shortcut_of(&keymap, "edit.redo"), Some("Ctrl+Y"), "menus keep showing the first key"); + + // Another item the user put on that key keeps it, without a shared-shortcut warning + keymap.insert("file.save".into(), "Ctrl+Shift+Z".into()); + assert_eq!(run(&keymap).as_deref(), Some("file.save")); + assert!(bindings_for(&keymap).conflict(binding("file.save")).is_none()); + + // Changing or clearing Redo replaces both of its keys + for stored in ["F7", ""] { + keymap = Keymap::from([("edit.redo".into(), stored.into())]); + assert_eq!(run(&keymap), None, "Redo stored as {stored:?}"); + } + + rebind(&mut keymap, binding("edit.redo"), "Ctrl+Y"); + + assert_eq!(run(&keymap).as_deref(), Some("edit.redo"), "reset restores the second key"); + } + + #[test] + fn an_unreadable_redo_setting_falls_back_to_both_defaults() { + let keymap = Keymap::from([("edit.redo".into(), "UnknownFutureKey".into())]); + let resolved = bindings_for(&keymap); + + assert_eq!(resolved.command_of(&press(Key::Y, Modifiers::COMMAND)).as_deref(), Some("edit.redo")); + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT)).as_deref(), Some("edit.redo")); + } + + #[test] + fn an_unknown_command_does_not_take_redos_second_key() { + let keymap = Keymap::from([("removed.command".into(), "Ctrl+Shift+Z".into())]); + let resolved = bindings_for(&keymap); + + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT)).as_deref(), Some("edit.redo")); + } + + #[test] + fn a_platform_equivalent_stored_shortcut_takes_redos_second_key() { + let keymap = Keymap::from([("file.save".into(), "Control+Shift+Z".into())]); + let resolved = bindings_for(&keymap); + + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT)).as_deref(), Some("file.save")); + assert!(resolved.conflict(binding("file.save")).is_none()); + } + + #[test] + fn a_shadowed_override_does_not_take_redos_second_key() { + let mut keymap = Keymap::from([("file.save {}".into(), "Ctrl+Shift+Z".into()), ("file.save".into(), "F7".into())]); + let mut resolved = bindings_for(&keymap); + let second_press = press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT); + + assert_eq!(resolved.command_of(&second_press).as_deref(), Some("edit.redo")); + + keymap.remove("file.save"); + resolved.sync(&keymap, Platform::Windows); + + assert_eq!(resolved.command_of(&second_press).as_deref(), Some("file.save")); + } + #[test] fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() { let mut keymap = Keymap::new(); @@ -900,10 +1066,14 @@ mod tests { #[test] fn ctrl_in_the_notation_is_the_command_key_on_macos() { let mut resolved = Bindings::default(); - resolved.sync(&Keymap::new(), Platform::Mac); + let keymap = Keymap::from([("file.close".into(), "Control+Shift+Z".into())]); + resolved.sync(&keymap, Platform::Mac); let cmd = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; + assert_eq!(resolved.command_of(&press(Key::S, cmd)).as_deref(), Some("file.save")); assert_eq!(resolved.command_of(&press(Key::S, Modifiers::CTRL)), None, "the Control key is another key"); + assert_eq!(resolved.command_of(&press(Key::Z, cmd | Modifiers::SHIFT)).as_deref(), Some("edit.redo")); + assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::CTRL | Modifiers::SHIFT)).as_deref(), Some("file.close")); } #[test] diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index 554161f3..cb0c546e 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -45,6 +45,9 @@ pub struct LayerPanel { pictures_begun: bool, /// The open stack, with `true` for a layer's mask. This belongs to the panel view. pub(crate) expanded_effects: Option<(LayerId, bool)>, + /// The selected layer the panel last drew, and the one whose row scrolls into view because the selection moved to it (a pick on the mesh, a command) + shown_selection: Option, + pub(crate) reveal: Option, } /// How soon to look again for pictures still rendering (milliseconds) @@ -59,6 +62,13 @@ impl LayerPanel { pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.begin_pictures(session, now); + // A newly selected layer scrolls into view once + let selected = session.selected_layer(); + if selected != self.shown_selection { + self.shown_selection = selected; + self.reveal = selected; + } + self.expanded_effects = self.expanded_effects.filter(|(layer, _)| session.doc.project.layers.contains_key(layer)); } diff --git a/crates/ui-egui/src/layer_pick_list.rs b/crates/ui-egui/src/layer_pick_list.rs new file mode 100644 index 00000000..0a03572a --- /dev/null +++ b/crates/ui-egui/src/layer_pick_list.rs @@ -0,0 +1,234 @@ +//! The layers under the pointer while R is held over the 3D view: a label names the top one live, and a click lists every layer there to pick from + +use egui::{Color32, Key, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; +use serde_json::json; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::geom::OrbitCamera; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::session::ViewMode; + +use crate::TextureCraftApp; +use crate::i18n::{tr, trf}; +use crate::state::Mode; +use crate::theme::Tokens; + +/// The list's row height, thumbnail side and the room around a row's contents (points) +const ROW_HEIGHT: f32 = 36.0; +const THUMBNAIL_SIZE: f32 = 28.0; +const ROW_PADDING: f32 = 6.0; + +/// The narrowest the list gets, so short names still give a comfortable click target (points) +const MIN_LIST_WIDTH: f32 = 160.0; + +/// How far the list sits right of and below the click, clear of the pointer (points) +const LIST_OFFSET: f32 = 8.0; + +/// Gap the list keeps from the view's edges +const VIEW_MARGIN: f32 = 4.0; + +/// Room between the list's frame and its rows (points) +const LIST_MARGIN: i8 = 2; + +/// Text sizes of a row's name and of the channels line under it +const NAME_FONT_SIZE: f32 = 12.0; +const CHANNELS_FONT_SIZE: f32 = 11.0; + +/// Width of the accent edge around the focused row (points) +const FOCUS_EDGE_WIDTH: f32 = 1.0; + +/// The list of layers laying something down where R + click landed +#[derive(Debug, PartialEq)] +pub struct LayerPickList { + /// Where the click landed on screen, and in viewport pixels for `layer.pickAt` + at: Pos2, + point: Vec2, + /// The view the list stays inside + bounds: Rect, + /// The viewport size and camera `point` was taken in: a change to either closes the list + viewport_and_camera: (Vec2, OrbitCamera), + /// The layers there, top first, each with the channels it changes there + rows: Vec<(LayerId, Vec)>, + /// The document revision the rows were read at: any change, or another project, closes the list + revision: u64, + /// The list's first frame: its top row takes the keyboard focus + opening: bool, + /// Closed by a press outside it: until every button is up, that press neither paints nor reopens it + closing: bool, +} + +/// The cached label for the texel under the pointer: (texture set, texel, document revision, view) and its text +type HoverLabel = ((usize, (u32, u32), u64, ViewMode), String); + +/// R + click at `at` (`point` in viewport pixels) in the view `bounds`: one layer there is selected straight away, several open the list +pub(crate) fn click(app: &mut TextureCraftApp, at: Pos2, point: Vec2, bounds: Rect) { + let viewport = app.session.viewport; + match app.session.layers_under(point, viewport) { + Ok((_, rows)) if rows.len() > 1 => { + app.layer_pick_list = Some(LayerPickList { + at, + point, + bounds, + viewport_and_camera: (viewport, app.session.camera), + rows, + revision: app.session.revision, + opening: true, + closing: false, + }); + } + _ => { + app.run("layer.pickAt", json!({"x": point.x, "y": point.y, "viewport": [viewport.x, viewport.y]})); + } + } +} + +/// Whether the list takes the views' clicks: open, or closing until the press that closed it ends +pub(crate) fn blocks_view_input(app: &TextureCraftApp) -> bool { + app.layer_pick_list.is_some() +} + +/// What the label at the pointer says over viewport pixel `point`: the top layer there and how many more, None off the mesh; recomputed only when the texel, document or view changes +pub(crate) fn hover_label(app: &TextureCraftApp, ui: &Ui, point: Vec2) -> Option { + let session = &app.session; + let (ts, texel) = session.texel_under(point, session.viewport)?; + let key = (ts, texel, session.revision, session.view); + let id = egui::Id::unique("layer_pick_hover_label"); + if let Some((cached, label)) = ui.data(|data| data.get_temp::(id)) + && cached == key + { + return Some(label); + } + + let layers = session.layers_at_texel(ts, texel); + let name = |id: &LayerId| session.doc.project.layers.get(id).map(|layer| layer.name.clone()).unwrap_or_default(); + let label = match layers.as_slice() { + [] => tr("No layer here").to_owned(), + [(top, _)] => name(top), + [(top, _), more @ ..] => trf("{name} +{n} more", &[("name", &name(top)), ("n", &more.len())]), + }; + ui.data_mut(|data| data.insert_temp::(id, (key, label.clone()))); + Some(label) +} + +/// The list's area, whose rect egui remembers between frames +fn area_id() -> egui::Id { + egui::Id::unique("layer_pick_list") +} + +/// Draws the open list; a row click selects its layer; Esc, a press outside or a document or view change closes it +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let (any_down, pressed_at, escape) = + ctx.input(|input| (input.pointer.any_down(), input.pointer.press_origin().filter(|_| input.pointer.any_pressed()), input.key_pressed(Key::Escape))); + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + match &mut app.layer_pick_list { + Some(list) if app.ui.mode != Mode::Painting || escape || list.revision != app.session.revision => app.layer_pick_list = None, + Some(list) if list.closing => { + if !any_down { + app.layer_pick_list = None; + } + } + Some(list) if list.viewport_and_camera != (app.session.viewport, app.session.camera) => app.layer_pick_list = None, + Some(list) if pressed_at.is_some_and(|at| shown.is_some_and(|rect| !rect.contains(at))) => list.closing = true, + _ => {} + } + + if app.layer_pick_list.as_ref().is_some_and(|list| list.closing) { + return; + } + + let Some(mut list) = app.layer_pick_list.take() else { return }; + + let tokens = Tokens::get(ctx); + let mut picked = None; + let width = list_width(app, ctx, &list.rows); + + // Open beside the pointer on the side with room + let bounds = list.bounds.shrink(VIEW_MARGIN); + let frame_width = width + 2.0 * f32::from(LIST_MARGIN); + let left = if list.at.x + LIST_OFFSET + frame_width > bounds.right() { list.at.x - LIST_OFFSET - frame_width } else { list.at.x + LIST_OFFSET }; + let at = pos2(left, list.at.y + LIST_OFFSET); + egui::Area::new(area_id()).order(egui::Order::Foreground).fixed_pos(at).constrain_to(bounds).show(ctx, |ui| { + egui::Frame::popup(ui.style()).fill(tokens.panel).inner_margin(egui::Margin::same(LIST_MARGIN)).show(ui, |ui| { + // A deep stack scrolls inside the view + egui::ScrollArea::vertical().max_height(bounds.height() - 2.0 * f32::from(LIST_MARGIN)).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + // Use egui's arrow navigation to move focus between rows + for (index, (layer, channels)) in list.rows.iter().enumerate() { + let response = row(app, ui, *layer, channels, width); + if list.opening && index == 0 { + response.request_focus(); + } + if response.clicked() { + picked = Some(*layer); + } + } + }); + }); + }); + + if let Some(layer) = picked { + let viewport = app.session.viewport; + app.run("layer.pickAt", json!({"x": list.point.x, "y": list.point.y, "viewport": [viewport.x, viewport.y], "layer": layer.0})); + } else { + list.opening = false; + app.layer_pick_list = Some(list); + } +} + +/// The rows' width: the widest name or channels line beside the thumbnail +fn list_width(app: &TextureCraftApp, ctx: &egui::Context, rows: &[(LayerId, Vec)]) -> f32 { + let text_width = |text: String, font: egui::FontId| ctx.fonts_mut(|fonts| fonts.layout_no_wrap(text, font, Color32::WHITE).size().x); + let widest = rows + .iter() + .map(|(layer, channels)| { + let name = text_width(layer_name(app, *layer), crate::theme::semibold(NAME_FONT_SIZE)); + name.max(text_width(channels_line(channels), egui::FontId::proportional(CHANNELS_FONT_SIZE))) + }) + .fold(0.0, f32::max); + (THUMBNAIL_SIZE + widest + ROW_PADDING * 3.0).max(MIN_LIST_WIDTH) +} + +/// One row: the layer's content thumbnail, its name and the channels it changes at the spot +fn row(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, channels: &[Channel], width: f32) -> egui::Response { + let tokens = Tokens::get(ui.ctx()); + let name = layer_name(app, layer); + let channels = channels_line(channels); + let (rect, _) = ui.allocate_exact_size(vec2(width, ROW_HEIGHT), Sense::hover()); + let response = ui.interact(rect, egui::Id::unique("layer_pick_row").with(layer.0), Sense::click()); + let selected = app.session.selected_layer() == Some(layer); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &name)); + + // Give keyboard focus a visible border + let painter = ui.painter(); + if response.hovered() || response.has_focus() { + painter.rect_filled(rect, tokens.radius, crate::dock::selected_layer_fill(&tokens)); + } + if response.has_focus() { + painter.rect_stroke(rect, tokens.radius, Stroke::new(FOCUS_EDGE_WIDTH, tokens.accent), egui::StrokeKind::Inside); + } + + let thumbnail = Rect::from_min_size(pos2(rect.left() + ROW_PADDING, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE)); + painter.rect_filled(thumbnail, crate::dock::THUMBNAIL_ROUNDING, tokens.field); + let target = ThumbTarget::Content { layer, channel: app.ui.layer_channel }; + + // Rows scrolled out of view ask for no thumbnail + if ui.is_rect_visible(thumbnail) + && let Some(texture) = app.layer_panel.texture_outside(ui.ctx(), &app.session, target) + { + painter.image(texture, thumbnail, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } + + let text_left = thumbnail.right() + ROW_PADDING; + painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_BOTTOM, name, crate::theme::semibold(NAME_FONT_SIZE), tokens.text_strong); + painter.text(pos2(text_left, rect.center().y), egui::Align2::LEFT_TOP, channels, egui::FontId::proportional(CHANNELS_FONT_SIZE), tokens.text_dim); + response +} + +fn layer_name(app: &TextureCraftApp, layer: LayerId) -> String { + app.session.doc.project.layers.get(&layer).map(|layer| layer.name.clone()).unwrap_or_default() +} + +/// The channels a layer changes at the spot, by their names +fn channels_line(channels: &[Channel]) -> String { + channels.iter().map(|channel| tr(channel.label())).collect::>().join(", ") +} diff --git a/crates/ui-egui/src/layer_toolbar.rs b/crates/ui-egui/src/layer_toolbar.rs index 83e028db..3c83a024 100644 --- a/crates/ui-egui/src/layer_toolbar.rs +++ b/crates/ui-egui/src/layer_toolbar.rs @@ -1,10 +1,13 @@ -//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons and remove +//! The Layers panel's top row: the displayed channel, the Add effect and Add mask menus, the add-layer buttons, the smart material picker and remove + +use std::path::PathBuf; use egui::{Align2, Color32, CornerRadius, FontId, Frame, Id, Painter, Pos2, Rect, Response, Sense, Shadow, Stroke, StrokeKind, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::Session; use texturecraft_engine::core::{Layer, LayerId}; +use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use crate::TextureCraftApp; @@ -21,12 +24,14 @@ mod bitmap_choice; mod item_icon; mod menu_icon; mod pick; +mod smart_material_choice; -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; +use smart_material_choice::SmartMaterialChoice; /// The row's height and its controls' height const BAR_HEIGHT: f32 = 40.0; @@ -37,14 +42,16 @@ const CONTROL_ROUNDING: u8 = 5; const SIDE_PADDING: f32 = 8.0; const CHANNEL_WIDTH: f32 = 88.0; +/// The channel list's width when the row gets tight: "Material" and its caret still fit, and the row fits a 1280 pt wide window's Layers panel +const CHANNEL_MIN_WIDTH: f32 = 70.0; /// A menu button: its icon, then its caret -const MENU_BUTTON_WIDTH: f32 = 32.0; +const MENU_BUTTON_WIDTH: f32 = 30.0; const MENU_ICON_X: f32 = 11.0; const MENU_CARET_INSET: f32 = 8.0; const MENU_ICON_SIZE: f32 = 14.0; const MASK_ICON_SIZE: f32 = 12.0; const CARET_SIZE: f32 = 11.0; -const BUTTON_WIDTH: f32 = 24.0; +const BUTTON_WIDTH: f32 = 23.0; const ICON_SIZE: f32 = 14.0; /// Air after the channel list, between the two menu buttons, before the add-layer buttons and between them const CHANNEL_GAP: f32 = 6.0; @@ -52,19 +59,19 @@ const MENU_GAP: f32 = 3.0; const GROUP_GAP: f32 = 8.0; const BUTTON_GAP: f32 = 2.0; const CHANNEL_TEXT_X: f32 = 8.0; -const CHANNEL_CARET_INSET: f32 = 10.0; +const CHANNEL_CARET_INSET: f32 = 9.0; const CHANNEL_CARET_SIZE: f32 = 12.0; const TEXT_SIZE: f32 = 12.0; /// The row's width besides the channel list's: its padding, the two menu buttons and their gaps const MENUS_ROW_WIDTH: f32 = 2.0 * SIDE_PADDING + CHANNEL_GAP + 2.0 * MENU_BUTTON_WIDTH + MENU_GAP; -/// The three add-layer buttons and Remove -const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + 3.0 * BUTTON_GAP; -/// The width every control takes in one row -const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_WIDTH + GROUP_GAP + LAYER_BUTTONS_WIDTH; +/// The three add-layer buttons, the smart material button and Remove +const LAYER_BUTTONS_WIDTH: f32 = 4.0 * BUTTON_WIDTH + MENU_BUTTON_WIDTH + 4.0 * BUTTON_GAP; +/// The smallest width that holds every control in one row, the channel list at its narrowest +const ONE_ROW_WIDTH: f32 = MENUS_ROW_WIDTH + CHANNEL_MIN_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; @@ -105,8 +112,9 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { let mut x = bar.left() + SIDE_PADDING; let control = |x: f32, top: f32, width: f32| Rect::from_min_size(pos2(x, top), vec2(width, CONTROL_HEIGHT)); - // Narrower still, the channel list gives up width before a menu button leaves the panel - let channel_width = CHANNEL_WIDTH.min(width - MENUS_ROW_WIDTH).max(0.0); + // Keep menu buttons inside by shrinking the channel control first + let channel_room = if two_rows { width - MENUS_ROW_WIDTH } else { width - MENUS_ROW_WIDTH - GROUP_GAP - LAYER_BUTTONS_WIDTH }; + let channel_width = CHANNEL_WIDTH.min(channel_room).max(0.0); channel_list(app, ui, control(x, top, channel_width), &tokens); x += channel_width + CHANNEL_GAP; @@ -119,16 +127,19 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { x += MENU_BUTTON_WIDTH + GROUP_GAP; let (top, mut x) = if two_rows { (top + BAR_HEIGHT, bar.left() + SIDE_PADDING) } else { (top, x) }; - for (glyph, label, command) in [ - (ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), - (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill"), - (ic::FOLDER_SIMPLE, tr("Add folder"), "layer.add.group"), - ] { + for (glyph, label, command) in [(ic::PAINT_BRUSH, tr("Add paint layer"), "layer.add.paint"), (ic::PAINT_BUCKET, tr("Add fill layer"), "layer.add.fill")] { if plain_button(ui, control(x, top, BUTTON_WIDTH), glyph, label, &tokens).clicked() { app.run(command, Value::Null); } x += BUTTON_WIDTH + BUTTON_GAP; } + let smart_materials = ui.scope_id().with("smart_material_picker"); + picker_button(ui, control(x, top, MENU_BUTTON_WIDTH), tr("Add smart material"), MenuIcon::Glyph(ic::STACK), smart_materials, &tokens); + x += MENU_BUTTON_WIDTH + BUTTON_GAP; + if plain_button(ui, control(x, top, BUTTON_WIDTH), ic::FOLDER_SIMPLE, tr("Add folder"), &tokens).clicked() { + app.run("layer.add.group", Value::Null); + } + x += BUTTON_WIDTH + BUTTON_GAP; let remove = control((bar.right() - SIDE_PADDING - BUTTON_WIDTH).max(x), top, BUTTON_WIDTH); if plain_button(ui, remove, ic::TRASH, &crate::keymap::tip(&app.ui.keymap, tr("Remove layer"), "layer.remove"), &tokens).clicked() { app.run("layer.remove", Value::Null); @@ -144,6 +155,7 @@ pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(layer) = selected { bitmap_picker(app, &anchor, popup(layer), layer); } + smart_material_picker(app, &anchor, smart_materials); } /// Layer `id` of the project, when there is one @@ -201,7 +213,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 +235,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 +272,29 @@ fn menu_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, caption: &s picked } +/// A button drawn like a menu button whose click opens or closes resource picker `popup`; it keeps its button face while the picker is open +fn picker_button(ui: &mut Ui, rect: Rect, label: &str, icon: MenuIcon, popup: Id, tokens: &Tokens) { + 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)); + if response.clicked() { + resource_picker::toggle(ui.ctx(), popup); + } + if response.hovered() || response.has_focus() || egui::Popup::is_id_open(ui.ctx(), popup) { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_ROUNDING), tokens.button); + } + button_face(ui.painter(), rect, icon, tokens); +} + +/// 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 +308,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 +317,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); @@ -461,3 +500,77 @@ fn bitmap_tabs(session: &Session) -> Vec> { let groups = vec![PickerGroup { header: Some(tr("Textures")), items: textures }, PickerGroup { header: Some(tr("Alphas")), items: alphas }]; vec![PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups }] } + +/// The smart material picker, hanging under `anchor` at its width while open: a pick adds the material above the selection, as a shelf click on a saved one does +fn smart_material_picker(app: &mut TextureCraftApp, anchor: &Response, popup: Id) { + // Opening the picker can be the first use of the saved library + if egui::Popup::is_id_open(&anchor.ctx, popup) { + crate::shelf::scan_library(app); + } + + let tabs = || smart_material_tabs(app.library.as_deref().unwrap_or_default()); + match resource_picker::show(anchor, popup, &mut app.thumbs, None, false, tabs) { + Some(SmartMaterialChoice::BuiltIn(id)) => { + app.run("material.apply", json!({"material": id})); + } + Some(SmartMaterialChoice::Saved(path)) => { + app.run("material.load", json!({"path": path.display().to_string()})); + } + None => {} + } +} + +/// The smart material picker's one tab: the built-in smart materials, then the ones the user saved +fn smart_material_tabs(library: &[PathBuf]) -> Vec> { + let built_in = MATERIALS + .iter() + .filter(|material| material.smart) + .map(|material| ResourcePickerItem { + id: SmartMaterialChoice::BuiltIn(material.id), + label: tr(material.label).to_owned(), + caption: Some(tr(material.category)), + picture: TilePicture::Material(material.id), + }) + .collect(); + let saved: Vec<_> = library + .iter() + // The load command requires a UTF-8 path + .filter(|path| !crate::shelf::is_saved_mask(path) && path.to_str().is_some()) + .map(|path| ResourcePickerItem { + id: SmartMaterialChoice::Saved(path.clone()), + label: crate::shelf::saved_material_name(path).to_owned(), + caption: None, + picture: TilePicture::Glyph(ic::SPHERE), + }) + .collect(); + let mut groups = vec![PickerGroup { header: Some(tr("Smart materials")), items: built_in }]; + if !saved.is_empty() { + groups.push(PickerGroup { header: Some(tr("Your assets")), items: saved }); + } + vec![PickerTab { icon: ic::STACK, name: tr("Smart materials"), groups }] +} + +#[cfg(all(test, unix))] +mod tests { + use std::os::unix::ffi::OsStringExt; + + use super::*; + + #[test] + fn the_smart_material_picker_lists_only_files_it_can_name_to_the_load_command() { + let unnameable = PathBuf::from(std::ffi::OsString::from_vec(b"/library/rust\xff.tcmat".to_vec())); + let tabs = smart_material_tabs(&[unnameable, PathBuf::from("/library/steel.tcmat")]); + + let saved: Vec<_> = tabs + .iter() + .flat_map(|tab| &tab.groups) + .flat_map(|group| &group.items) + .filter_map(|item| match &item.id { + SmartMaterialChoice::Saved(path) => Some(path.as_path()), + SmartMaterialChoice::BuiltIn(_) => None, + }) + .collect(); + + assert_eq!(saved, [std::path::Path::new("/library/steel.tcmat")]); + } +} 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/layer_toolbar/smart_material_choice.rs b/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs new file mode 100644 index 00000000..39e7bf9c --- /dev/null +++ b/crates/ui-egui/src/layer_toolbar/smart_material_choice.rs @@ -0,0 +1,10 @@ +//! A pick of the Layers toolbar's smart material picker + +use std::path::PathBuf; + +/// A built-in smart material by id, or one the user saved, by file +#[derive(Clone, PartialEq)] +pub(super) enum SmartMaterialChoice { + BuiltIn(&'static str), + Saved(PathBuf), +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2dc0e1e5..2ba2a331 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,12 +7,16 @@ #![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; mod auto_rebake; #[cfg(not(target_arch = "wasm32"))] mod autosave_name; +#[cfg(not(target_arch = "wasm32"))] +mod autosave_notice; mod bake_job; pub mod bake_mode; mod bake_preset; @@ -20,6 +24,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; @@ -75,12 +83,14 @@ mod inactive_set_hint; mod instance_properties; pub mod keymap; pub mod layer_panel; +pub mod layer_pick_list; mod layer_toolbar; mod layout_dialog; 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; @@ -92,6 +102,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"))] @@ -111,6 +122,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; @@ -187,8 +199,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; @@ -358,6 +375,8 @@ pub struct TextureCraftApp { pub moving_on_model: Option, /// The Properties popup a right click in a view opens. pub properties_popup: Option, + /// The layers under an R + click in the 3D view to pick one from + pub layer_pick_list: Option, properties_scroll: property_sheet::PropertiesScroll, /// The color selection the next click in the 3D or 2D view picks an ID color for pub picking_id_color: Option, @@ -398,6 +417,8 @@ pub struct TextureCraftApp { /// The dialog opening that owns the Project name widget's undo state. #[cfg(not(target_arch = "wasm32"))] project_name_editor_opening: Option, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: autosave_notice::AutosaveNotice, /// The brightness and accent the style was last built for. styled: Option<(theme::Brightness, theme::Accent)>, /// Whether the window had focus last frame. @@ -527,6 +548,7 @@ impl TextureCraftApp { last_paint_uv: None, moving_on_model: None, properties_popup: None, + layer_pick_list: None, properties_scroll: property_sheet::PropertiesScroll::default(), picking_id_color: None, picking_symmetry_plane: false, @@ -552,6 +574,8 @@ impl TextureCraftApp { unsaved_autosave_file: None, #[cfg(not(target_arch = "wasm32"))] project_name_editor_opening: None, + #[cfg(not(target_arch = "wasm32"))] + autosave_notice: Default::default(), styled: None, focused: true, #[cfg(not(target_arch = "wasm32"))] @@ -1075,14 +1099,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(); @@ -1097,6 +1129,7 @@ impl TextureCraftApp { if let Some((device, queue)) = gpu { return resize_on_gpu(task, &p, &device, &queue); } + task.run(&p) }); self.resize = Some(ResizeJob { progress, rx, project: self.session.project_id }); @@ -1129,10 +1162,12 @@ impl TextureCraftApp { if let Ok(output) = &result && !output.matches_session(&self.session) { - let (ts, resolution) = output.target(); - self.start_resize(ts, resolution); + let (ts, width, height) = output.target(); + drop(result); + self.start_resize_to(ts, width, height); return; } + if let Err(e) = result.and_then(|out| self.session.apply_resize(out)) { self.toast(e.to_string(), true); } @@ -1224,7 +1259,7 @@ impl TextureCraftApp { /// Every `prefs.autosave_minutes`, write a modified project to the autosave folder (encoded /// and written on a worker thread; the project data is shared copy-on-write). #[cfg(not(target_arch = "wasm32"))] - fn autosave(&mut self, now: f64) { + fn autosave(&mut self, ctx: &egui::Context, now: f64) { if self.save_job.is_some() { return; } @@ -1249,19 +1284,20 @@ impl TextureCraftApp { let dir = user_dir("autosave"); let path = self.autosave_path(&dir); let snapshot = self.session.project_snapshot(); + let reporter = self.autosave_notice.reporter(ctx); + let spawn_reporter = self.autosave_notice.reporter(ctx); + let target = path.clone(); let spawned = std::thread::Builder::new().name("texturecraft-autosave".into()).spawn(move || { let result = std::fs::create_dir_all(&dir).map_err(|e| e.to_string()).and_then(|_| reservation.save(&path, &snapshot).map_err(|error| error.to_string())); drop(snapshot); - drop(reservation); - match result { - Ok(()) => log::info!("autosaved {}", path.display()), - Err(e) => log::warn!("autosave to {} failed: {e}", path.display()), - } + // Report while the reservation still holds off the next autosave, so results arrive in the order of the attempts + reporter.report(path, result); + drop(reservation); }); if let Err(e) = spawned { - log::warn!("could not start autosave: {e}"); + spawn_reporter.report(target, Err(e.to_string())); } } } @@ -1423,19 +1459,20 @@ impl eframe::App for TextureCraftApp { #[cfg(not(target_arch = "wasm32"))] { self.poll_save(ctx); - self.autosave(now); + self.autosave(ctx, now); + autosave_notice::poll(self); } i18n::set_language(&self.ui.prefs.language); + self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); #[cfg(target_arch = "wasm32")] { - keymap::sync_captured(&self.ui.keymap); + self.bindings.sync_captured(); web_files::sync_unsaved(self); } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); #[cfg(not(target_arch = "wasm32"))] updates_ui::tick(self, ctx); - self.bindings.sync(&self.ui.keymap, craft_keymap::egui::platform(ctx)); menus::shortcuts(self, ctx); #[cfg(not(target_arch = "wasm32"))] { 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 b6df68af..bfb1d16e 100644 --- a/crates/ui-egui/src/log_panel.rs +++ b/crates/ui-egui/src/log_panel.rs @@ -1,6 +1,8 @@ //! The Log panel: the session's messages under a General and an Assets tab, one per channel -use egui::{Color32, RichText, Ui}; +use std::hash::{Hash, Hasher}; + +use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, Ui, vec2}; use texturecraft_engine::log::{LogEntry, LogLevel}; use crate::TextureCraftApp; @@ -8,8 +10,150 @@ use crate::i18n::tr; use crate::theme::Tokens; mod log_channel; +mod log_width_cache; pub use log_channel::LogChannel; +pub use log_width_cache::LogWidthCache; + +/// The width of the History and Log lists' scrollbars +const LIST_SCROLLBAR_WIDTH: f32 = 8.0; +const LIST_SCROLLBAR_RADIUS: u8 = 3; +/// The air between a list's scrollbar and the list's edge, and between the rows and the scrollbar +const LIST_SCROLLBAR_OUTER_MARGIN: f32 = 2.0; +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() { + // 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()); + } +} + +/// Show `total_rows` rows of `row_height` in `area` under a solid, always shown, themed scrollbar +pub(crate) fn panel_rows( + ui: &mut Ui, + area: egui::ScrollArea, + row_height: f32, + total_rows: usize, + add_rows: impl FnOnce(&mut Ui, std::ops::Range) -> R, +) -> egui::scroll_area::ScrollAreaOutput { + let tokens = Tokens::get(ui.ctx()); + let row_visuals = ui.visuals().clone(); + ui.scope(|ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.spacing_mut().scroll = egui::style::ScrollStyle { + bar_width: LIST_SCROLLBAR_WIDTH, + bar_outer_margin: LIST_SCROLLBAR_OUTER_MARGIN, + bar_inner_margin: LIST_SCROLLBAR_INNER_MARGIN, + ..egui::style::ScrollStyle::solid() + }; + + let visuals = ui.visuals_mut(); + visuals.extreme_bg_color = tokens.field; + // 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; + for widget in [&mut visuals.widgets.inactive, &mut visuals.widgets.hovered, &mut visuals.widgets.active] { + widget.corner_radius = egui::CornerRadius::same(LIST_SCROLLBAR_RADIUS); + } + + area.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show_rows(ui, row_height, total_rows, |ui, rows| { + *ui.visuals_mut() = row_visuals; + add_rows(ui, rows) + }) + }) + .inner +} + +/// The tab strip's and the list's inset from the panel's edges +const PANEL_INSET: f32 = 6.0; +const TAB_HEIGHT: f32 = 24.0; +const TAB_NAME_SIZE: f32 = 11.0; +/// The Assets tab's strip with its filter button, above the list +const FILTER_STRIP_HEIGHT: f32 = 30.0; +const LINE_HEIGHT: f32 = 19.0; +const LINE_TEXT_SIZE: f32 = 12.0; +/// Where a line's text starts in the list, and the air after the widest line +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 { + // 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()); + let open = app.ui.log_channel == channel; + let name = tr(channel.name()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, open, name)); + + let painter = ui.painter(); + painter.rect(rect, 0.0, if open { tokens.field } else { tokens.row }, outline, StrokeKind::Inside); + if open { + open_tab = rect; + } + let color = if open || response.hovered() { tokens.text } else { tokens.text_dim }; + painter.text(rect.center(), Align2::CENTER_CENTER, name, crate::theme::semibold(TAB_NAME_SIZE), color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(painter, rect, tokens.text_strong); + } + + if response.clicked() { + app.ui.log_channel = channel; + app.ui.log_selection.clear(); + app.ui.log_anchor = None; + } + } + open_tab +} + +/// 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()); + + // 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)); + reveal_focused_row(ui, &response, rect); + if !ui.is_rect_visible(rect) { + return response; + } + + let painter = ui.painter(); + if selected { + 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(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); + } + response +} + +/// Changes when the installed fonts do: fallback fonts arrive while the app runs, and widths change with them +fn font_key(ui: &Ui) -> u64 { + ui.fonts(|fonts| { + let mut hasher = std::hash::DefaultHasher::new(); + fonts.definitions().families.get(&egui::FontFamily::Proportional).hash(&mut hasher); + hasher.finish() + }) +} /// The entries a tab lists, as indices into the session log fn listed(app: &TextureCraftApp, channel: LogChannel) -> Vec { @@ -22,11 +166,11 @@ pub fn channel_of(entry: &LogEntry) -> LogChannel { } /// The line colour of a level: light grey for info, yellow-orange for warnings, red for errors -fn level_color(tk: &Tokens, level: LogLevel) -> Color32 { +fn level_color(tokens: &Tokens, level: LogLevel) -> Color32 { match level { - LogLevel::Info => tk.text, - LogLevel::Warning => tk.warning, - LogLevel::Error => tk.danger, + LogLevel::Info => tokens.text, + LogLevel::Warning => tokens.warning, + LogLevel::Error => tokens.danger, } } @@ -130,16 +274,8 @@ pub(crate) fn takes_copy(app: &TextureCraftApp, ctx: &egui::Context) -> bool { /// The Log panel body (a dock tab or rail popup) pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - for channel in LogChannel::ALL { - if ui.selectable_label(app.ui.log_channel == channel, tr(channel.name())).clicked() { - app.ui.log_channel = channel; - app.ui.log_selection.clear(); - app.ui.log_anchor = None; - } - } - }); - ui.separator(); + let tokens = Tokens::get(ui.ctx()); + let open_tab = channel_tabs(app, ui, &tokens); // A new session has a new log: indices chosen in the old one point at other lines if app.ui.log_id != app.session.log_id { @@ -148,15 +284,33 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { app.ui.log_anchor = None; } + // 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 }; + + // 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); +} + +/// The shown tab's lines, under the Assets tab's filter button +fn entries(app: &mut TextureCraftApp, ui: &mut Ui, tokens: &Tokens) { if shown_assets_filter(app) { - crate::unavailable::greyed(ui, |ui| ui.add(egui::Button::new(egui_phosphor::regular::WARNING).selected(false))); + let (strip, _) = ui.allocate_exact_size(vec2(ui.available_width(), FILTER_STRIP_HEIGHT), Sense::hover()); + let layout = egui::Layout::left_to_right(egui::Align::Center); + let mut strip_ui = ui.new_child(egui::UiBuilder::new().max_rect(strip.shrink2(vec2(PANEL_INSET, 0.0))).layout(layout)); + let filter = crate::unavailable::greyed(&mut strip_ui, |ui| ui.add(egui::Button::new(egui_phosphor::regular::WARNING).selected(false))); + filter.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, false, tr("Warnings"))); + ui.painter().hline(strip.x_range(), strip.bottom(), Stroke::new(1.0, tokens.field_border)); } - let tk = Tokens::get(ui.ctx()); 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))); @@ -169,16 +323,22 @@ pub(crate) fn body(app: &mut TextureCraftApp, ui: &mut Ui) { } } - egui::ScrollArea::vertical().id_salt(("log", shown.name())).auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { - for index in rows.iter().copied() { + // 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.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) + .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 text = RichText::new(entry.line()).color(level_color(&tk, entry.level)); - let band = ui.painter().add(egui::Shape::Noop); - let response = ui.add(egui::Label::new(text).selectable(false).sense(egui::Sense::click())); - if app.ui.log_selection.contains(&index) { - let rect = response.rect.expand2(egui::vec2(ui.spacing().item_spacing.x, 0.0)).intersect(ui.max_rect()); - ui.painter().set(band, egui::Shape::rect_filled(rect, 0.0, tk.accent_dim)); - } + + 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); select(app, &rows, index, 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 new file mode 100644 index 00000000..702759d5 --- /dev/null +++ b/crates/ui-egui/src/log_panel/log_width_cache.rs @@ -0,0 +1,92 @@ +use texturecraft_engine::log::{LogEntry, SessionLog}; + +use super::{LogChannel, channel_of}; + +/// The widest line of each Log tab, measuring each line once, when it is new +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LogWidthCache { + log_id: u64, + pixels_per_point: f32, + /// Identifies the fonts the lines were measured with + font_key: u64, + /// 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_entries: usize, + widest: [f32; LogChannel::ALL.len()], +} + +impl LogWidthCache { + /// The widest line of `channel`: new lines are measured, a cleared line or a new log, scale or font set measures all again + pub fn widest( + &mut self, + log: &SessionLog, + log_id: u64, + pixels_per_point: f32, + font_key: u64, + channel: LogChannel, + measure: impl Fn(&LogEntry) -> f32, + ) -> f32 { + 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_entries + appended_entries != log.len() { + *self = LogWidthCache { log_id, pixels_per_point, font_key, ..LogWidthCache::default() }; + } + + for (occurrence, entry) in log.entries_after(self.last_occurrence) { + let widest = &mut self.widest[channel_of(entry) as usize]; + *widest = widest.max(measure(entry)); + self.last_occurrence = occurrence; + self.measured_entries += 1; + } + + self.widest[channel as usize] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn width(entry: &LogEntry) -> f32 { + entry.line().len() as f32 + } + + #[test] + fn clearing_the_widest_line_narrows_the_tab() { + let mut log = SessionLog::new(); + log.info("Project", "short"); + log.info("Project", "a much longer line than the other one"); + let mut cache = LogWidthCache::default(); + 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); + } + + #[test] + fn a_new_log_is_measured_again() { + let mut log = SessionLog::new(); + log.info("Project", "a much longer line than the other one"); + let mut cache = LogWidthCache::default(); + let wide = cache.widest(&log, 1, 1.0, 1, LogChannel::General, width); + + let mut next = SessionLog::new(); + next.info("Project", "short"); + + assert!(cache.widest(&next, 2, 1.0, 1, LogChannel::General, width) < wide); + } + + #[test] + fn new_fonts_measure_the_lines_again() { + let mut log = SessionLog::new(); + log.info("Project", "a line"); + let mut cache = LogWidthCache::default(); + 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..1a7f37f9 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,11 @@ 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 escape_is_free && app.layer_pick_list.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + // The list opens over an armed eyedropper or point pick, so it closes first + app.layer_pick_list = None; } 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 +596,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/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 2ad606b1..c452c978 100644 --- a/crates/ui-egui/src/parity.rs +++ b/crates/ui-egui/src/parity.rs @@ -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/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..702cca51 100644 --- a/crates/ui-egui/src/property_sheet/axis_rows.rs +++ b/crates/ui-egui/src/property_sheet/axis_rows.rs @@ -2,10 +2,10 @@ 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}; +use super::slider::{DIAL_AIR, DIAL_RADIUS, KNOB_RADIUS, shown_value}; use super::switch_control::PILL_SIZE; use super::track::Track; use super::{BLOCK_MARGIN, PropertySheet, SMALL_TEXT_SIZE, StackSlider, TEXT_SIZE}; @@ -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,34 +138,41 @@ 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); + + // Reserve for track values while still measuring any wider typed value on display + self.measure_track_values(&slider.range, |end| shown_value(end, slider.decimals, slider.suffix)); + let shown = shown_value(*slider.value, slider.decimals, slider.suffix); + let typed = self.column_value_field(id, &slider.label, center_y, &shown, slider.suffix, *slider.value, &slider.typed, slider.decimals); *edit = Self::apply_typed(slider.value, typed, dragged); y += STACK_CAPTION_LINE + STACK_PART_LINE + STACK_GAP; } 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/factor_slider.rs b/crates/ui-egui/src/property_sheet/factor_slider.rs index eddf9f72..550223df 100644 --- a/crates/ui-egui/src/property_sheet/factor_slider.rs +++ b/crates/ui-egui/src/property_sheet/factor_slider.rs @@ -6,20 +6,29 @@ use super::PropertySheet; use super::slider::{KNOB_RADIUS, kept_in}; use super::track::Track; +/// Decimal places in the displayed factor +const FACTOR_DECIMALS: usize = 2; + impl PropertySheet<'_> { /// A factor (×1.50) on a track `doublings` halvings or doublings each way from ×1 (marked by the zero tick); a typed value may go past the track's ends, within `typed`. `Some(merge)` when it changed pub(crate) fn factor_slider(&mut self, label: &str, factor: &mut f32, doublings: f32, typed: RangeInclusive) -> Option { let (control, center_y) = self.row(label); let id = self.next_id(); + let track = Track { start: control.left() + KNOB_RADIUS, end: self.track_end(), center_y, zero: Some(0.0), ramp: false }; let track_range = -doublings..=doublings; let mut along = kept_in(factor.max(f32::MIN_POSITIVE).log2(), &track_range); + let dragged = self.track(id, label, &track, &mut along, &track_range); if dragged.is_some() { *factor = along.exp2(); } - let shown = format!("×{:.2}", *factor); - let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, 2); + + let format_factor = |factor: f32| format!("×{factor:.FACTOR_DECIMALS$}"); + self.measure_track_values(&track_range, |end| format_factor(end.exp2())); + let shown = format_factor(*factor); + + let entered = self.column_value_field(id, &label, center_y, &shown, "", *factor, &typed, FACTOR_DECIMALS); Self::apply_typed(factor, entered, dragged) } } 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..f93f3f0f 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; @@ -42,10 +43,12 @@ mod section_tabs; #[path = "property_sheet.rs"] mod sheet; mod sheet_measure; +mod sheet_measurements; 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 +65,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; @@ -120,6 +124,9 @@ const LOOSE_LABEL_AIR: f32 = 2.0; /// The narrowest value column at a slider's right end const VALUE_MIN_WIDTH: f32 = 26.0; +/// The most the value column reserves for values not on show yet, so a huge range leaves the tracks their length +const TRACK_VALUE_RESERVE_MAX: f32 = 72.0; + /// Air between a slider track's end and the value column, room for the knob and a gap const TRACK_TO_VALUE: f32 = 14.0; 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/property_sheet.rs b/crates/ui-egui/src/property_sheet/property_sheet.rs index e1e5b1b6..3ad52b78 100644 --- a/crates/ui-egui/src/property_sheet/property_sheet.rs +++ b/crates/ui-egui/src/property_sheet/property_sheet.rs @@ -1,13 +1,13 @@ +use std::ops::RangeInclusive; + use egui::{Color32, FontId, Id, Rect, Ui, pos2, vec2}; use super::{ - CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, VALUE_MIN_WIDTH, open_card::OpenCard, section_tabs, - sheet_measure::SheetMeasure, + CONTROL_HEIGHT, LABEL_COLUMN_MIN, LABEL_TO_CONTROL, SIDE_PADDING_POINTS, TEXT_SIZE, TRACK_TO_VALUE, TRACK_VALUE_RESERVE_MAX, VALUE_MIN_WIDTH, + open_card::OpenCard, section_tabs, sheet_measure::SheetMeasure, sheet_measurements::SheetMeasurements, }; use crate::theme::{Tokens, semibold}; -type SheetMeasures = egui::cache::FramePublisher; - /// The Properties panel being laid out this frame: where the controls column is, which card is open, and what this frame measured for the next one pub(crate) struct PropertySheet<'u> { pub(crate) ui: &'u mut Ui, @@ -29,15 +29,22 @@ pub(crate) struct PropertySheet<'u> { pub(super) held: bool, /// Sub-headers so far in the current folding section: a later one takes air above it pub(super) sub_headers: usize, + + /// The value font's widest digit, found on first use + pub(super) widest_digit: Option, } impl<'u> PropertySheet<'u> { /// Lays out `body` as one panel; when its measured columns change, egui reruns the frame unseen pub(crate) fn show(ui: &'u mut Ui, id_salt: impl egui::AsIdSalt, body: impl FnOnce(&mut PropertySheet<'_>) -> R) -> R { let id = ui.make_persistent_id(id_salt); - let used = ui.memory_mut(|memory| memory.caches.cache::().get(&id).copied()).unwrap_or_default(); + let viewport = ui.ctx().viewport_id(); + let measurements = ui.ctx().plugin_or_default::(); + let used = measurements.lock().get(viewport, id).unwrap_or_default(); + ui.spacing_mut().item_spacing = vec2(0.0, 0.0); let rect = ui.available_rect_before_wrap(); + let mut sheet = PropertySheet { tokens: Tokens::get(ui.ctx()), id, @@ -56,8 +63,10 @@ impl<'u> PropertySheet<'u> { info: None, held: false, sub_headers: 0, + widest_digit: None, ui, }; + let result = body(&mut sheet); sheet.close_card(); if !sheet.sections.is_empty() { @@ -65,9 +74,15 @@ impl<'u> PropertySheet<'u> { section_tabs::remember(sheet.ui, section_tabs::SectionTops { tops: std::mem::take(&mut sheet.sections), view_top }); } + let mut seen = sheet.seen; + + // Keep the previous width while a pointer may be dragging a track + if sheet.ui.input(|input| input.pointer.any_down()) { + seen.value_width = seen.value_width.max(used.value_width); + } + // Refresh visible sheets so measurements of closed sheets expire - let seen = sheet.seen; - sheet.ui.memory_mut(|memory| memory.caches.cache::().set(id, seen)); + measurements.lock().set(viewport, id, seen); if seen != used { sheet.ui.ctx().request_discard("Properties columns changed"); } @@ -91,6 +106,36 @@ impl<'u> PropertySheet<'u> { self.seen.value_width = self.seen.value_width.max(width); } + /// Reserves room for the track's formatted values, up to the limit for unseen values. + pub(super) fn measure_track_values(&mut self, range: &RangeInclusive, format_value: impl Fn(f32) -> String) { + let widest_digit = self.widest_digit(); + let [start, end] = [*range.start(), *range.end()] + .map(|limit| format_value(limit).chars().map(|character| if character.is_ascii_digit() { widest_digit } else { character }).collect::()); + + let distinct_end = (end != start).then_some(end); + let painter = self.ui.painter(); + for shown in std::iter::once(start).chain(distinct_end) { + let width = painter.layout_no_wrap(shown, semibold(TEXT_SIZE), Color32::WHITE).size().x.min(TRACK_VALUE_RESERVE_MAX); + self.seen.value_width = self.seen.value_width.max(width); + } + } + + /// Digits differ in width, so a value between a track's ends can be wider than either end + fn widest_digit(&mut self) -> char { + if let Some(digit) = self.widest_digit { + return digit; + } + + let painter = self.ui.painter(); + let widest = ('0'..='9') + .map(|digit| (digit, painter.layout_no_wrap(digit.to_string(), semibold(TEXT_SIZE), Color32::WHITE).size().x)) + .max_by(|one, other| one.1.total_cmp(&other.1)) + .map_or('0', |(digit, _)| digit); + + self.widest_digit = Some(widest); + widest + } + pub(super) fn text_width(&self, text: &str, font: FontId) -> f32 { self.ui.painter().layout_no_wrap(text.to_owned(), font, Color32::WHITE).size().x } diff --git a/crates/ui-egui/src/property_sheet/sheet_measurements.rs b/crates/ui-egui/src/property_sheet/sheet_measurements.rs new file mode 100644 index 00000000..c04bdf49 --- /dev/null +++ b/crates/ui-egui/src/property_sheet/sheet_measurements.rs @@ -0,0 +1,38 @@ +use egui::{ + Context, FullOutput, Id, Plugin, Ui, ViewportId, ViewportIdMap, + cache::{CacheTrait, FramePublisher}, +}; + +use super::sheet_measure::SheetMeasure; + +/// A sheet's previous measurements survive redraws of other native windows. +#[derive(Default)] +pub(super) struct SheetMeasurements { + by_viewport: ViewportIdMap>, +} + +impl SheetMeasurements { + pub(super) fn get(&self, viewport: ViewportId, sheet: Id) -> Option { + self.by_viewport.get(&viewport)?.get(&sheet).copied() + } + + pub(super) fn set(&mut self, viewport: ViewportId, sheet: Id, measure: SheetMeasure) { + self.by_viewport.entry(viewport).or_default().set(sheet, measure); + } +} + +impl Plugin for SheetMeasurements { + fn debug_name(&self) -> &'static str { + "Properties sheet measurements" + } + + fn on_end_pass(&mut self, ui: &mut Ui) { + if let Some(sheets) = self.by_viewport.get_mut(&ui.ctx().viewport_id()) { + sheets.evict_cache(); + } + } + + fn output_hook(&mut self, _context: &Context, output: &mut FullOutput) { + self.by_viewport.retain(|viewport, sheets| sheets.len() > 0 && output.viewport_output.contains_key(viewport)); + } +} diff --git a/crates/ui-egui/src/property_sheet/slider.rs b/crates/ui-egui/src/property_sheet/slider.rs index 3697880b..644eefea 100644 --- a/crates/ui-egui/src/property_sheet/slider.rs +++ b/crates/ui-egui/src/property_sheet/slider.rs @@ -130,7 +130,10 @@ impl PropertySheet<'_> { self.paint_dial(pos2(dial_x, center_y), *degrees); - let shown = if plus { format!("{:+.0}°", *degrees) } else { format!("{:.0}°", *degrees) }; + let format_angle = |angle: f32| if plus { format!("{angle:+.0}°") } else { format!("{angle:.0}°") }; + self.measure_track_values(&range, format_angle); + let shown = format_angle(*degrees); + let typed = self.column_value_field(id, &name, center_y, &shown, "°", *degrees, &range, 0); Self::apply_typed(degrees, typed, dragged) } @@ -255,7 +258,7 @@ impl PropertySheet<'_> { edit } - /// The value at the row's end, answering as `label`'s value; a click turns it into a field, which returns the typed value when done + /// The value at the row's end of a track over `range`, answering as `label`'s value; a click turns it into a field, which returns the typed value when done #[allow(clippy::too_many_arguments)] pub(super) fn value_field( &mut self, @@ -267,11 +270,12 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + self.measure_track_values(range, |end| shown_value(end, decimals, suffix)); + let shown = shown_value(value, decimals, suffix); self.column_value_field(id, &label, center_y, &shown, suffix, value, range, decimals) } - /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it + /// [`Self::value_field`] reading `shown`: the panel's value column grows to fit it. A caller with a track measures its range first #[allow(clippy::too_many_arguments)] pub(super) fn column_value_field( &mut self, @@ -303,7 +307,7 @@ impl PropertySheet<'_> { decimals: usize, suffix: &str, ) -> Option { - let shown = format!("{}{suffix}", shown_number(value, decimals)); + let shown = shown_value(value, decimals, suffix); self.value_text_field(id, ValueText { label: &label, right, width, center_y, shown: &shown, suffix }, value, range, decimals) } @@ -363,3 +367,10 @@ impl PropertySheet<'_> { pub(super) fn kept_in(value: f32, range: &RangeInclusive) -> f32 { value.max(*range.start()).min(*range.end()) } + +/// `value` as a slider's end reads it +pub(super) fn shown_value(value: f32, decimals: usize, suffix: &str) -> String { + let mut shown = shown_number(value, decimals); + shown.push_str(suffix); + shown +} 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/property_sheet/stacked_rows.rs b/crates/ui-egui/src/property_sheet/stacked_rows.rs index d7934290..6b961630 100644 --- a/crates/ui-egui/src/property_sheet/stacked_rows.rs +++ b/crates/ui-egui/src/property_sheet/stacked_rows.rs @@ -187,13 +187,14 @@ impl PropertySheet<'_> { info: None, held: self.held, sub_headers: self.sub_headers, + widest_digit: self.widest_digit, ui: &mut child, }; let result = body(&mut sheet); - let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, .. } = sheet; + let PropertySheet { named, seen, card, air_at, drawn_bottom, empty, sections, held, sub_headers, scope, band_scope, widest_digit, .. } = sheet; (self.named, self.seen, self.card, self.air_at, self.drawn_bottom, self.empty, self.sections) = (named, seen, card, air_at, drawn_bottom, empty, sections); - (self.held, self.sub_headers, self.scope, self.band_scope) = (held, sub_headers, scope, band_scope); + (self.held, self.sub_headers, self.scope, self.band_scope, self.widest_digit) = (held, sub_headers, scope, band_scope, widest_digit); let bottom = child.min_rect().bottom().max(top); let region = Rect::from_min_max(pos2(self.left, top), pos2(self.right, bottom)); @@ -305,6 +306,7 @@ impl PropertySheet<'_> { info: None, held: false, sub_headers: 0, + widest_digit: self.widest_digit, ui: &mut second_ui, }; let second_response = second_sheet.dropdown_button(second, &name(second_value), None::); diff --git a/crates/ui-egui/src/property_sheet/tests.rs b/crates/ui-egui/src/property_sheet/tests.rs index 28b126c4..be383128 100644 --- a/crates/ui-egui/src/property_sheet/tests.rs +++ b/crates/ui-egui/src/property_sheet/tests.rs @@ -10,9 +10,11 @@ use texturecraft_engine::folder_cmds::next_seed; mod filtering; mod gallery; +mod slider_test_row; use filtering::Filtering; use gallery::Gallery; +use slider_test_row::SliderTestRow; /// Width of the Properties panel the mockups are drawn at const PANEL_WIDTH: f32 = 300.0; @@ -1017,6 +1019,74 @@ fn a_ramps_value_ends_on_the_linked_tiling_value() { assert_eq!(ramp.right(), tiling.right(), "the ramp's value ends at {}, Tiling's at {}", ramp.right(), tiling.right()); } +fn value_row_track(harness: &Harness<'_, (SliderTestRow, f32)>) -> Rect { + harness.get_by_role_and_label(egui::Role::Slider, "Value").rect() +} + +/// A value gaining a minus sign or digits moves no track (the value column followed the widest number on show) +#[test] +fn tracks_stay_put_as_their_values_gain_a_sign_and_digits() { + let rows = [ + (SliderTestRow::Signed, [0.0, -0.88, 0.88, -1.0]), + (SliderTestRow::RelativeAngle, [0.0, -88.0, 88.0, -180.0]), + (SliderTestRow::Factor, [1.0, 16.0, 0.1, 8.0]), + (SliderTestRow::Captioned, [0.0, -888.0, 888.0, -1000.0]), + ]; + + for (row, [first, rest @ ..]) in rows { + let mut harness = builder(Brightness::MediumDark).build_ui_state(SliderTestRow::show, (row, first)); + harness.run_steps(3); + let before = value_row_track(&harness); + + for value in rest { + harness.state_mut().1 = value; + harness.run_steps(3); + assert_eq!(value_row_track(&harness), before, "the {row:?} track moved at {value}"); + } + } +} + +/// A range far past anything readable reserves only so much, and its track still ends in the panel's right half +#[test] +fn a_huge_range_leaves_its_track_its_length() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(SliderTestRow::show, (SliderTestRow::HugeRange, 1.0)); + harness.run_steps(3); + + // An inverted track can still report a wide rectangle + let track = value_row_track(&harness); + assert!(track.right() > PANEL_WIDTH / 2.0, "the track ends at {}", track.right()); +} + +/// Dragging back from a value past the track's ends narrows the column only once the drag ends +#[test] +fn a_drag_from_a_typed_value_moves_no_track_until_release() { + let mut harness = builder(Brightness::MediumDark).build_ui_state(SliderTestRow::show, (SliderTestRow::Factor, 1000.0)); + harness.run_steps(3); + let before = value_row_track(&harness); + + harness.drag_at(before.center()); + + // Past egui's longest click, the press becomes a drag + harness.run_steps(5); + + assert!(harness.state().1 < 1000.0, "the press moved no value"); + assert_eq!(value_row_track(&harness), before, "the track moved under the drag"); + + // A detached panel redraws between two passes of the held slider + let viewport = egui::ViewportId::from_hash_of("floating panel"); + let floating = + egui::RawInput { viewport_id: viewport, viewports: std::iter::once((viewport, egui::ViewportInfo::default())).collect(), ..Default::default() }; + harness.ctx.run_ui(floating, |_| {}).textures_delta.clear(); + harness.step(); + + assert_eq!(value_row_track(&harness), before, "the floating window changed the held track"); + + harness.drop_at(before.center()); + harness.run_steps(3); + + assert!(value_row_track(&harness).right() > before.right(), "the column stayed wide after the release"); +} + #[test] fn a_reopened_editor_starts_a_new_undo_step_after_a_hidden_release() { let context = egui::Context::default(); diff --git a/crates/ui-egui/src/property_sheet/tests/slider_test_row.rs b/crates/ui-egui/src/property_sheet/tests/slider_test_row.rs new file mode 100644 index 00000000..efb99f5b --- /dev/null +++ b/crates/ui-egui/src/property_sheet/tests/slider_test_row.rs @@ -0,0 +1,41 @@ +use egui::{Color32, Ui}; + +use super::{PANEL_WIDTH, swatch}; +use crate::property_sheet::{PropertySheet, StackSlider}; +use crate::theme::Tokens; + +#[derive(Clone, Copy, Debug)] +pub(super) enum SliderTestRow { + Signed, + RelativeAngle, + Factor, + Captioned, + HugeRange, +} + +impl SliderTestRow { + /// Draws one slider in isolation so other rows cannot keep its value column wide. + pub(super) fn show(ui: &mut Ui, (row, value): &mut (Self, f32)) { + let panel = Tokens::get(ui.ctx()).panel; + egui::Frame::NONE.fill(panel).show(ui, |ui| { + ui.set_width(PANEL_WIDTH); + PropertySheet::show(ui, "value row", |sheet| match row { + Self::Signed => { + sheet.signed_slider("Value", value, -1.0..=1.0, 2); + } + Self::RelativeAngle => { + sheet.relative_angle("Value", value, -180.0..=180.0); + } + Self::Factor => { + sheet.factor_slider("Value", value, 4.0, 0.0..=2000.0); + } + Self::Captioned => { + sheet.picture_sliders(&swatch(Color32::from_gray(128)), &mut [StackSlider::whole("Value", value, -1000.0..=1000.0)]); + } + Self::HugeRange => { + sheet.slider("Value", value, 0.0..=f32::MAX, 2); + } + }); + }); + } +} diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 3c10b66f..25f52fee 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -273,15 +273,15 @@ fn prepare_cpu_materials(session: &mut texturecraft_engine::Session, height_only if pending.is_empty() { return true; } + #[cfg(not(target_arch = "wasm32"))] let ready = { let waiting = |cache: &texturecraft_engine::SetCache| cache.size.0.max(cache.size.1) > 1024 && !cache.dilation.is_ready(); - let mut ready: Vec<_> = pending.iter().copied().filter(|&ts| !waiting(&session.caches[ts])).collect(); - if let Some(&ts) = pending.iter().find(|&&ts| waiting(&session.caches[ts])) - && session.caches[ts].dilation.prepare_on_worker() - { - ready.push(ts); + let ready: Vec<_> = pending.iter().copied().filter(|&ts| !waiting(&session.caches[ts])).collect(); + if let Some(&ts) = pending.iter().find(|&&ts| waiting(&session.caches[ts])) { + session.caches[ts].dilation.prepare_on_worker(); } + ready }; #[cfg(target_arch = "wasm32")] @@ -314,10 +314,17 @@ fn trace_scene(app: &TextureCraftApp, cpu_materials: bool) -> TraceScene { let composite = if cpu_materials || (need_height && height_strength != 0.0 && cache.composite.channels.contains_key(&Channel::Height)) { cache.composite.clone() } else { - // The GPU tracer copies material textures from the viewport. + // The GPU tracer copies material textures from the viewport Composite::with_size(&[], cache.size.0, cache.size.1) }; - Some(TraceSet { material: set.material, composite, height_strength }) + Some(TraceSet { + material: set.material, + composite, + 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 (mesh, bvh) = match geometry { @@ -380,7 +387,13 @@ fn composite_revisions(session: &texturecraft_engine::Session, composites: bool) /// compositing runs on the GPU, where the CPU cache's revision does not advance. fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { let revisions = composite_revisions(session, composites); - 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); @@ -449,6 +462,7 @@ fn show_cpu(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { ctx.request_repaint(); return; } + let size = render_size(rect); // The CPU tracer reads the composites themselves: every change restarts it @@ -522,6 +536,7 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { ui.ctx().request_repaint(); return true; } + let scene_key = gpu_scene_key(&app.session); app.render.gpu_error = None; if app.render.job.take().is_some() { 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..a7b76133 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 { @@ -372,7 +384,7 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: } /// Whether a library file is a saved smart mask (not a smart material) -fn is_saved_mask(path: &std::path::Path) -> bool { +pub(crate) fn is_saved_mask(path: &std::path::Path) -> bool { path.extension().is_some_and(|extension| extension == texturecraft_engine::smart_masks::SMART_MASK_EXT) } @@ -415,7 +427,7 @@ pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) { /// Read the user's saved smart materials (desktop library folder and the added library locations) unless they are already listed #[cfg(not(target_arch = "wasm32"))] -fn scan_library(app: &mut TextureCraftApp) { +pub(crate) fn scan_library(app: &mut TextureCraftApp) { if app.library.is_some() { return; } @@ -441,10 +453,10 @@ fn scan_library(app: &mut TextureCraftApp) { } #[cfg(target_arch = "wasm32")] -fn scan_library(_: &mut TextureCraftApp) {} +pub(crate) fn scan_library(_: &mut TextureCraftApp) {} /// A saved smart material's name: its file name without the extension -fn saved_material_name(path: &std::path::Path) -> &str { +pub(crate) fn saved_material_name(path: &std::path::Path) -> &str { path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_MATERIAL_NAME) } @@ -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 6365780f..8f455bff 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, @@ -672,7 +664,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. @@ -750,6 +741,15 @@ pub struct UiState { /// Identity of the log that owns the selected rows. #[serde(skip)] pub log_id: u64, + /// The History panel's last shown container and steps (added so far, done, undone): a change scrolls to the current step + #[serde(skip)] + pub history_shown: Option<(egui::Id, u64, usize, usize)>, + /// The History list's last height in points and whether the current step was on screen in it + #[serde(skip)] + pub history_view: Option<(f32, bool)>, + /// The widest line of each Log tab, measured once per line + #[serde(skip)] + pub log_widths: crate::log_panel::LogWidthCache, } pub(crate) const MAX_RECENT_PROJECTS: u16 = 100; @@ -889,7 +889,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(), @@ -918,6 +917,9 @@ impl Default for UiState { log_selection: Default::default(), log_anchor: None, log_id: 0, + history_shown: None, + history_view: None, + log_widths: Default::default(), } } } 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/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 8115da19..afc1704c 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -8,7 +8,7 @@ use texturecraft_engine::Tool; use crate::TextureCraftApp; use crate::drawn_icon::DrawnIcon; use crate::frame_gizmo::warp_toolbar::{self, WarpTarget}; -use crate::i18n::{tr, trf}; +use crate::i18n::{n_, tr, trf}; use crate::keymap::{shortcut_of, tip}; use crate::state::{Mode, ViewLayout}; use crate::theme::{GUTTER, Tokens, card}; @@ -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; @@ -586,11 +586,13 @@ pub fn status_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) { .show(ui, |ui| { ui.horizontal_centered(|ui| { if app.session.project_open { - let (label, reason) = app.gpu.as_ref().map_or((tr("Layers: CPU"), tr("The GPU renderer is unavailable.")), |gpu| { - let (label, reason) = gpu.compositor_status(); - (tr(label), tr(reason)) + let (label, reason) = app.gpu.as_ref().map_or((n_("Layers: CPU"), n_("The GPU renderer is unavailable.")), |gpu| gpu.compositor_status()); + let reason = tr(reason); + let status = ui.label(RichText::new(tr(label)).size(11.0)).on_hover_text(reason); + ui.ctx().accesskit_node_builder(status.id, |node| { + node.set_live(egui::accesskit::Live::Polite); + node.set_description(reason); }); - ui.label(RichText::new(label).size(11.0)).on_hover_text(reason); ui.separator(); } #[cfg(not(target_arch = "wasm32"))] 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 4b37f6e3..23b8a7ac 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -23,10 +23,12 @@ 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; +/// Hold this key with any tool and click the mesh to select the layer laying something down there +pub const PICK_LAYER_KEY: egui::Key = egui::Key::R; pub const VIEW_3D: u64 = 1; pub const VIEW_2D: u64 = 2; @@ -169,6 +171,7 @@ pub fn central(app: &mut TextureCraftApp, ui: &mut Ui) { sync.finish(app, ui, aux_view); crate::properties_popup::show(app, ui.ctx()); + crate::layer_pick_list::show(app, ui.ctx()); if mode == crate::state::Mode::Rendering { crate::render_mode::show(app, ui, full); @@ -310,7 +313,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; @@ -386,17 +389,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) @@ -614,7 +625,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!({})); } @@ -628,6 +639,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 @@ -821,13 +839,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 @@ -940,11 +958,26 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.run("tool.cloneSource", json!({"x": at.x, "y": at.y, "viewport": [viewport.x, viewport.y]})); } + // Layer picking takes precedence over the active painting tool + let r_held = layer_pick_key(app, ui); + if r_held + && !alt + && app.layer_pick_list.is_none() + && response.clicked_by(PointerButton::Primary) + && let Some(pointer) = response.interact_pointer_pos() + { + crate::layer_pick_list::click(app, pointer, local(pointer), rect); + } + + // The layer list consumes clicks before any armed picker + let layer_pick_takes_click = r_held || crate::layer_pick_list::blocks_view_input(app); + // A 3D generator's armed point pick: a click sets the point there instead of painting let point_pick = crate::generator_point_pick::armed_on(ui.ctx(), &app.session); if let Some(pick) = point_pick { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -959,10 +992,12 @@ 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 + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { @@ -975,11 +1010,11 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // A dismissing click cannot paint or place a decal through the rail popup let rail_popup = crate::rail_popup::blocks_paint_input(app, ui.ctx()); - crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held); + crate::properties_popup::open_on_right_click(app, ui, &response, rect, s_held || v_held || r_held); // A press that closes an open colour picker only closes it: it neither paints nor moves a projection let picker = crate::color_picker::blocks_view_press(ui.ctx()); - let popup = app.properties_popup.is_some() || rail_popup || picker; + let popup = app.properties_popup.is_some() || crate::layer_pick_list::blocks_view_input(app) || rail_popup || picker; // A pending ID color pick or eyedropper takes the next click instead of the brush let picking = app.picking_id_color.is_some() || app.picking_color.is_some(); @@ -998,6 +1033,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::screen_pick::SwatchColor::over_model(ui.ctx(), *color); } if !alt + && !layer_pick_takes_click && response.clicked_by(PointerButton::Primary) && let Some(position) = response.interact_pointer_pos() { @@ -1010,8 +1046,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } // Only a press on a projection handle moves the selected fill - let gizmo_free = - !adjusting && !alt && !holding && !s_held && !v_held && !focus_pick && !popup && !picking && touch.is_none() && !DecalDrop::blocks_input(ui.ctx()); + let gizmo_free = !adjusting + && !alt + && !holding + && !s_held + && !v_held + && !r_held + && !focus_pick + && !popup + && !picking + && touch.is_none() + && !DecalDrop::blocks_input(ui.ctx()); let gizmo = ShownGizmo::of(app, rect); let began_on_handle = handle_press(ui.ctx(), |at| gizmo.as_ref().is_some_and(|gizmo| gizmo.on_handle(rect, at))); let frame_drag = gizmo_free && began_on_handle && ShownGizmo::input(app, ui, &response, rect, gizmo.as_ref()); @@ -1028,6 +1073,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let plane_pick = !popup && !s_held && !v_held + && !r_held && !focus_pick && !picking && touch.is_none() @@ -1039,6 +1085,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !adjusting && !s_held && !v_held + && !r_held && !focus_pick && !popup && !picking @@ -1052,13 +1099,13 @@ 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 && !adjusting && !s_held && !v_held + && !r_held && !focus_pick && !picking && touch.is_none() @@ -1113,11 +1160,14 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin app.session.continue_stroke(local(pointer), pressure); remember_line_anchor(app, local(pointer)); } - if response.drag_stopped_by(PointerButton::Primary) - && let Err(error) = app.session.end_stroke() - { - app.toast(error.to_string(), true); - } + } + + // Finish a stroke even if a later keypress blocks painting + if response.drag_stopped_by(PointerButton::Primary) + && app.session.stroke_active() + && let Err(error) = app.session.end_stroke() + { + app.toast(error.to_string(), true); } let set_hover = app @@ -1136,6 +1186,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin add_callback(app, ui, rect, frame, sync); polygon_fill_box_overlay(ui, rect, fill_box); + // Announce the contributing layer while the pick key is held + if r_held + && app.layer_pick_list.is_none() + && let Some(hover) = response.hover_pos() + && let Some(label) = crate::layer_pick_list::hover_label(app, ui, local(hover)) + { + layer_pick_hint(ui, rect, hover, &label); + } + // Route shelf drops by asset type to a layer, decal, or brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); @@ -1143,6 +1202,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let mut symmetry_cursor = None; if tool_acts(app) && !navigating + && !r_held && response.hovered() && brush_tool(app.session.tool.tool) && (app.session.tool.tool != Tool::Path || adjusting) @@ -1223,35 +1283,24 @@ fn bake_visualization(app: &TextureCraftApp) -> Option bool { && !crate::framework::widget_has_keyboard(ui.ctx()) } +/// R held over a view in painting mode, outside a text field: clicks select the layer under the cursor +fn layer_pick_key(app: &TextureCraftApp, ui: &Ui) -> bool { + app.ui.mode == crate::state::Mode::Painting && ui.input(|input| input.key_down(PICK_LAYER_KEY)) && !ui.ctx().egui_wants_keyboard_input() +} + +/// The pointing hand and a label beside it naming the layer under it while the layer pick key is held, announced as it changes +fn layer_pick_hint(ui: &Ui, rect: Rect, hover: Pos2, label: &str) { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let font = egui::TextStyle::Small.resolve(ui.style()); + let mut text = egui::text::LayoutJob::simple_singleline(label.to_owned(), font, tokens.text); + text.wrap = egui::text::TextWrapping::truncate_at_width((rect.width() - 2.0 * LAYER_PICK_HINT_PADDING).max(0.0)); + let galley = painter.layout_job(text); + + let frame = layer_pick_hint_frame(rect, hover, galley.size()); + let at = frame.min + vec2(LAYER_PICK_HINT_PADDING, LAYER_PICK_HINT_PADDING); + painter.rect_filled(frame, egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), tokens.panel); + painter.rect_stroke( + frame, + egui::CornerRadius::same(LAYER_PICK_HINT_PADDING as u8), + Stroke::new(LAYER_PICK_HINT_BORDER_WIDTH, tokens.separator), + egui::StrokeKind::Inside, + ); + painter.galley(at, galley, tokens.text); + + let announced = ui.interact(frame, egui::Id::unique("layer_pick_hint"), egui::Sense::empty()); + announced.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, label)); + ui.ctx().accesskit_node_builder(announced.id, |node| node.set_live(egui::accesskit::Live::Polite)); +} + +/// The layer pick label's frame around text of `size`: beside the pointer, slid back inside `view` near its edges +fn layer_pick_hint_frame(view: Rect, hover: Pos2, size: egui::Vec2) -> Rect { + let inset = egui::Vec2::splat(LAYER_PICK_HINT_PADDING); + let size = (size + 2.0 * inset).min(view.size()); + let preferred = hover + egui::Vec2::splat(LAYER_PICK_HINT_OFFSET) - inset; + let origin = preferred.min(view.max - size).max(view.min); + Rect::from_min_size(origin, size) +} + +/// How far the layer pick label sits right of and below the pointer, and the room around its text (points) +const LAYER_PICK_HINT_OFFSET: f32 = 16.0; +const LAYER_PICK_HINT_PADDING: f32 = 4.0; + +/// Width of the layer pick label's border (points) +const LAYER_PICK_HINT_BORDER_WIDTH: f32 = 1.0; + /// Crosshair where the Clone tool reads from. fn clone_marker(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3) { if let Some(center) = project(app, rect, pos) { @@ -1813,6 +1909,11 @@ fn clone_marker_at(ui: &Ui, rect: Rect, center: Pos2) { } } +/// Whether the equipped tool's strokes go through the stencil: quick mask strokes never do, so it isn't shown or moved then +pub(crate) fn stencil_applies(app: &TextureCraftApp) -> 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) @@ -2288,6 +2389,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let painting = tool_acts(app) && !projection_hint && app.properties_popup.is_none() + && !crate::layer_pick_list::blocks_view_input(app) && !crate::rail_popup::blocks_paint_input(app, ui.ctx()) && !crate::color_picker::blocks_view_press(ui.ctx()) && !alt @@ -2615,6 +2717,22 @@ fn turn_environment(session: &mut Session, degrees: f32) { #[cfg(test)] mod tests { use super::*; + + #[test] + fn the_layer_pick_label_stays_inside_the_view_at_its_edges() { + let view = Rect::from_min_size(pos2(100.0, 50.0), vec2(400.0, 300.0)); + let size = vec2(120.0, 14.0); + for hover in [view.min, view.center(), view.right_center() - vec2(2.0, 0.0), view.max - vec2(2.0, 2.0)] { + let frame = layer_pick_hint_frame(view, hover, size); + + assert!(view.contains_rect(frame), "hover {hover:?}: {frame:?}"); + } + + let wide = layer_pick_hint_frame(view, view.center(), vec2(600.0, 14.0)); + + assert!(view.contains_rect(wide), "a label wider than the view still fits: {wide:?}"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn hovering_a_texture_set_row_previews_it_without_selecting_it() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index b8eff6e8..b9074d89 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -1,9 +1,6 @@ //! Floating windows and the dockable History panel -#[cfg(any(target_arch = "wasm32", test))] -use egui::vec2; -use egui::{RichText, Ui}; -use egui_phosphor::regular as ic; +use egui::{RichText, Ui, vec2}; use serde_json::json; use crate::TextureCraftApp; @@ -249,47 +246,65 @@ pub(crate) fn dialog_scroll_margin(ui: &egui::Ui) -> egui::Margin { margin } -/// The History panel body (a dock tab) +/// The height of one History row +const HISTORY_ROW_HEIGHT: f32 = 21.0; +/// Where a History row's name starts, from the panel's left edge +const HISTORY_NAME_LEFT: f32 = 12.0; +const HISTORY_NAME_SIZE: f32 = 12.0; +/// The current step's outline sits inside the row: a little air at the left, less before the scrollbar +const HISTORY_MARK_INSET_LEFT: f32 = 4.0; +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 = 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(); + + // 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(|(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; - // Bottom up: the Undo and Redo row keeps its place under a list that fills the rest of the panel - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - ui.horizontal(|ui| { - if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { - app.run("edit.undo", json!({})); - } - if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { - app.run("edit.redo", json!({})); - } - }); + // 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; + let current = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=top + HISTORY_ROW_HEIGHT); + ui.scroll_to_rect_animation(current, None, egui::style::ScrollAnimation::none()); + } - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - let done_count = done.len() as i64; - let rows = std::iter::once(RichText::new(tr("Project opened")).color(tokens.text_dim)) - .chain(done.iter().map(|label| RichText::new(tr_history(label)))) - .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", &tr_history(label))])).color(tokens.text_dim))); - for (row, text) in rows.enumerate() { - // Each row is the state after that many steps - let steps = done_count - row as i64; - if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - // Point history is consumed before the document rows shown here - jump = if steps >= 0 { - app.session.history_undo_steps(steps as usize) as i64 - } else { - -(app.session.history_redo_steps((-steps) as usize) as i64) - }; - } - } - }); - }); + 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; + + 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 { + app.session.history_undo_steps(steps as usize) as i64 + } else { + -(app.session.history_redo_steps((-steps) as usize) as i64) + }; + } + } }); + let current_top_in_view = current_row_top - list.state.clamped_offset().y; + let current_in_view = current_top_in_view < list.inner_rect.height() && current_top_in_view + HISTORY_ROW_HEIGHT > 0.0; + app.ui.history_view = Some((height, current_in_view)); + if jump > 0 { app.run("edit.undo", json!({ "steps": jump })); } else if jump < 0 { @@ -297,6 +312,43 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { } } +/// 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 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 +fn history_row(ui: &mut Ui, tokens: &Tokens, name: &str, color: egui::Color32, current: bool) -> egui::Response { + let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), HISTORY_ROW_HEIGHT), egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, current, name)); + crate::log_panel::reveal_focused_row(ui, &response, rect); + if !ui.is_rect_visible(rect) { + return response; + } + + let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); + if current { + let mark = egui::Rect::from_min_max(rect.min + vec2(HISTORY_MARK_INSET_LEFT, 0.0), rect.max - vec2(HISTORY_MARK_INSET_RIGHT, 0.0)); + painter.rect(mark, 0.0, tokens.field, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, tokens.row); + } + + // 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)); + let shown = painter.layout_job(job); + painter.galley(egui::pos2(rect.left() + HISTORY_NAME_LEFT, rect.center().y - shown.size().y / 2.0), shown, color); + if response.has_focus() { + crate::property_sheet::paint_focus_outline(&painter, rect, tokens.text_strong); + } + response +} + /// Browser File › Export Mesh: pick the download format #[cfg(target_arch = "wasm32")] fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) { diff --git a/crates/ui-egui/tests/autosave_notice.rs b/crates/ui-egui/tests/autosave_notice.rs new file mode 100644 index 00000000..5b735a38 --- /dev/null +++ b/crates/ui-egui/tests/autosave_notice.rs @@ -0,0 +1,69 @@ +//! A failed autosave is announced in the interface. This is its own test binary because the data +//! folder it breaks is fixed once for the whole process. + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use egui::accesskit::Live; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Removes the test's folder, also when an assertion fails +struct TempFolder(PathBuf); + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn notices(harness: &Harness<'_, TextureCraftApp>) -> usize { + // Other loaders name the broken data folder too: only the autosave's own notice counts + harness.state().toasts.iter().filter(|toast| toast.text.starts_with("Autosave to ") && toast.text.contains("autosave-notice")).count() +} + +/// Run frames until `done`, giving the autosave worker real time to finish. +fn run_until(harness: &mut Harness<'_, TextureCraftApp>, done: impl Fn(&Harness<'_, TextureCraftApp>) -> bool) { + let started = Instant::now(); + while !done(harness) { + assert!(started.elapsed() < Duration::from_secs(60), "the autosave did not report"); + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn a_failing_autosave_is_announced_once_until_it_works_again() { + let folder = TempFolder(std::env::temp_dir().join(format!("tc-autosave-notice-{}", std::process::id()))); + std::fs::create_dir_all(&folder.0).unwrap(); + let root = folder.0.join("data"); + // A file where the data folder should be, so the autosave folder cannot be created + std::fs::write(&root, b"not a folder").unwrap(); + texturecraft_ui_egui::set_data_root(root.clone()); + + let session = texturecraft_engine::sample_session(128, 32).unwrap(); + // Each frame is longer than the shortest autosave period, so every frame is due + let mut harness = Harness::builder() + .with_step_dt(61.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + // The notice is matched by its English text, whatever the system's language + harness.state_mut().ui.prefs.language = "en".into(); + // One frame applies the language before any autosave reports + harness.step(); + harness.state_mut().ui.prefs.autosave_minutes = 1; + harness.state_mut().session.modified = true; + + run_until(&mut harness, |harness| notices(harness) > 0); + for _ in 0..20 { + harness.step(); + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(notices(&harness), 1, "the same failure is not announced again"); + let announced = harness.query_all_by_label_contains("Autosave to ").any(|node| node.accesskit_node().live() == Live::Polite); + assert!(announced, "the notice is a live region, so a screen reader reads it"); + + std::fs::remove_file(&root).unwrap(); + run_until(&mut harness, |harness| notices(harness) == 0); +} 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/effect_rows.rs b/crates/ui-egui/tests/it/effect_rows.rs index 822525f0..27efc47b 100644 --- a/crates/ui-egui/tests/it/effect_rows.rs +++ b/crates/ui-egui/tests/it/effect_rows.rs @@ -1,4 +1,4 @@ -//! Effect rows in the layer stack: dragging one reorders its stack, its blend mode and opacity sit at its right, and its menu holds the Blending options +//! Effect rows in the layer stack: dragging one or its menu's Move items reorder its stack, its cross removes it, its blend mode and opacity sit at its right, and its menu holds the Blending options use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -65,6 +65,107 @@ fn dragging_an_effect_row_reorders_its_stack() { assert_eq!(order(&harness), [a, c, b]); } +/// An effect row's menu moves it one step or to an end of its stack; a move past an end is greyed +#[test] +fn an_effect_rows_menu_moves_it_within_its_stack() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + let menu_item = |harness: &mut Harness<'_, TextureCraftApp>, row: &str, item: &str| { + harness.get_by_label(row).click_secondary(); + harness.run_steps(3); + harness.get_by_label(item).click(); + harness.run_steps(3); + }; + + menu_item(&mut harness, "Effect A", "Move up"); + assert_eq!(order(&harness), [b, a, c]); + menu_item(&mut harness, "Effect A", "Move to top"); + assert_eq!(order(&harness), [b, c, a]); + menu_item(&mut harness, "Effect C", "Move down"); + assert_eq!(order(&harness), [c, b, a]); + menu_item(&mut harness, "Effect A", "Move to bottom"); + assert_eq!(order(&harness), [a, c, b]); + + harness.get_by_label("Effect A").click_secondary(); + harness.run_steps(3); + assert!(harness.get_by_label("Move down").accesskit_node().is_disabled(), "the bottom effect can't go lower"); + assert!(!harness.get_by_label("Move up").accesskit_node().is_disabled()); +} + +/// Alt+Up and Alt+Down move the selected effect one place in its stack; at its end it stays +#[test] +fn alt_up_and_down_move_the_selected_effect() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C")); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); + let order = + |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + let press = |harness: &mut Harness<'_, TextureCraftApp>, key: egui::Key| { + harness.key_press_modifiers(egui::Modifiers::ALT, key); + harness.run_steps(3); + }; + harness.get_by_label("Effect A").click(); + harness.run_steps(3); + + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, a, c]); + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, c, a]); + press(&mut harness, egui::Key::ArrowUp); + assert_eq!(order(&harness), [b, c, a], "the top effect stays"); + press(&mut harness, egui::Key::ArrowDown); + assert_eq!(order(&harness), [b, a, c]); +} + +/// The cross at an effect row's right end removes that effect alone, in one undo step +#[test] +fn an_effect_rows_cross_removes_it() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer")); + let mut add = + |name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect"); + let a = add("Effect A"); + add("Effect B"); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 1400.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|creation_context| TextureCraftApp::new(creation_context, session)); + harness.run_steps(4); + click_selected_content_thumbnail(&mut harness); + let undo_steps = harness.state().session.history_labels().len(); + + let at = harness.get_by_label("Remove effect Effect B").rect().center(); + harness.drag_at(at); + harness.drop_at(at); + harness.run_steps(3); + + let remaining = harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::>(); + assert_eq!(remaining, [a]); + assert_eq!(harness.state().session.history_labels().len(), undo_steps + 1); +} + /// An effect row's blend mode menu and opacity field sit at its right and set the displayed channel's blending, as on layer rows #[test] fn an_effect_row_sets_its_blend_mode_and_opacity() { @@ -85,9 +186,9 @@ fn an_effect_row_sets_its_blend_mode_and_opacity() { harness.state_mut().ui.layer_material_view = false; harness.run_steps(2); - // From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field + // Left of the remove cross: a 4-point gap, then the 82-point pair of mode menu and opacity field let row = harness.get_by_label("Effect A").rect(); - let pair_right = row.right() - 4.0; + let pair_right = harness.get_by_label("Remove effect Effect A").rect().left() - 4.0; let pair_left = pair_right - 82.0; let mode_at = egui::pos2(pair_left + 20.0, row.center().y); harness.drag_at(mode_at); 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 889b3df7..018616ec 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -1,12 +1,15 @@ -//! A click on a step of the History panel goes back or forward to it. +//! The History panel: a click on a step goes back or forward to it, the current step is marked and kept in view +use craft_behavior::dock::Action; +use egui::accesskit::Toggled; +use egui::{Event, Key, Modifiers, Rect, pos2, vec2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; -use texturecraft_ui_egui::docking::Panel; +use texturecraft_ui_egui::docking::{Dock, Panel, permissions}; /// Show document history so row clicks exercise the same command dispatch as the application fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { @@ -19,6 +22,25 @@ fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { harness } +/// Undo or redo one step from the keyboard, as the Edit menu's shortcuts do +fn press(harness: &mut Harness<'_, TextureCraftApp>, key: Key) { + harness.key_press_modifiers(Modifiers::COMMAND, key); + harness.run_steps(3); +} + +/// 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()))) + .filter(|(name, _)| names.contains(name)) + .collect() +} + /// Three document rows provide an intermediate target that detects both short and excessive jumps fn renamed_session() -> Session { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -49,6 +71,7 @@ fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { session.path_checkpoint(); let mut harness = history_harness(session); + // The list runs oldest first, so the first "Rename layer" row is the oldest step harness.get_all_by_label("Rename layer").next().unwrap().click(); harness.run_steps(3); @@ -60,7 +83,7 @@ fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { } } -/// A row jump traverses point history, while the Undo and Redo buttons still take one point step +/// A row jump traverses point history, while Ctrl+Z and Ctrl+Y still take one point step #[test] fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() { let mut session = renamed_session(); @@ -77,12 +100,10 @@ fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() let done = session.history_labels().len(); let mut harness = history_harness(session); - harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Z); assert_eq!(harness.state().session.tool.path.points, moved); assert_eq!(harness.state().session.history_labels().len(), done); - harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Y); assert_eq!(harness.state().session.tool.path.points, original); assert_eq!(harness.state().session.history_labels().len(), done); @@ -91,6 +112,7 @@ fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() assert_eq!(harness.state().session.tool.path.points, original); assert_eq!(harness.state().session.history_labels().len(), done); + // The list runs oldest first, so the first "Rename layer" row is the oldest step harness.get_all_by_label("Rename layer").next().unwrap().click(); harness.run_steps(3); @@ -126,15 +148,14 @@ fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() { assert_eq!(session.redo_labels().len(), 3); let mut harness = history_harness(session); - harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Y); assert_eq!(harness.state().session.tool.path.points.len(), 2); assert_eq!(harness.state().session.history_labels().len(), done - 3); - harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); - harness.run_steps(3); + press(&mut harness, Key::Z); assert_eq!(harness.state().session.tool.path.points, original); assert_eq!(harness.state().session.history_labels().len(), done - 3); + // The last undone row is the newest step, so clicking it redoes up to the end harness.get_all_by_label("Rename layer (undone)").last().unwrap().click(); harness.run_steps(3); @@ -193,3 +214,200 @@ fn clicking_a_history_step_returns_to_it() { assert_eq!(name(&h), "Step C"); assert!(!h.state().session.can_redo()); } + +/// The panel has no Undo and Redo buttons; exactly one row reads as the current step, it moves with Ctrl+Z, and undone rows stay clickable +#[test] +fn only_the_current_step_is_marked_selected() { + let mut harness = history_harness(renamed_session()); + + // Undo and redo live in the Edit menu and on their shortcuts, not in a button row under the list + assert!(harness.query_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).is_none()); + assert!(harness.query_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).is_none()); + + let before = current_rows(&harness); + assert_eq!(before.len(), 1); + assert_eq!(before[0].0, "Rename layer"); + + press(&mut harness, Key::Z); + let after = current_rows(&harness); + assert_eq!(after.len(), 1); + 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); + assert!(harness.state().session.redo_labels().is_empty()); +} + +/// Enough steps that the History cannot show them all at once +const STEPS_PAST_THE_PANEL: usize = 100; + +/// A session `steps` renames long, so its History list is taller than the panel +fn long_session(steps: usize) -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for step in 0..steps { + execute(&mut session, "layer.rename", &json!({"name": format!("Step {step}")})).unwrap(); + } + session +} + +/// Whether the entire current row is within the History list's viewport +fn current_shown(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + 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>) { + 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), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + modifiers: Modifiers::NONE, + }); + harness.run_steps(12); +} + +/// A History list longer than the panel opens at its newest step, not at "Project opened" +#[test] +fn a_long_history_shows_the_newest_step() { + let harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + + assert!(current_shown(&harness, "Rename layer")); + assert!(harness.query_by_label("Project opened").is_none_or(|row| !harness.ctx.content_rect().y_range().contains(row.rect().top()))); +} + +/// A list the user scrolled up stays there when a tool changes but the history doesn't +#[test] +fn scrolling_up_is_not_pulled_back() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + scroll_to_top(&mut harness); + assert!(!current_shown(&harness, "Rename layer")); + + execute(&mut harness.state_mut().session, "tool.select", &json!({"tool": "path"})).unwrap(); + harness.run_steps(4); + + assert!(!current_shown(&harness, "Rename layer")); +} + +/// Once the history is full, a new step keeps the step count and still comes into view +#[test] +fn the_newest_step_shows_past_the_history_cap() { + let steps = texturecraft_engine::session::MAX_HISTORY + 60; + let mut harness = history_harness(long_session(steps)); + let capped = harness.state().session.history_labels().len(); + assert!(capped < steps, "the history is full"); + scroll_to_top(&mut harness); + assert!(!current_shown(&harness, "Rename layer")); + + execute(&mut harness.state_mut().session, "layer.add.paint", &json!({})).unwrap(); + harness.run_steps(4); + + let newest = harness.state().session.history_labels().last().cloned().unwrap(); + assert_eq!(harness.state().session.history_labels().len(), capped); + assert!(current_shown(&harness, &newest)); +} + +/// A full history with a new step named like the newest one keeps its counts and names, and still comes into view +#[test] +fn a_repeated_step_shows_past_the_history_cap() { + let mut harness = history_harness(long_session(texturecraft_engine::session::MAX_HISTORY)); + let capped = harness.state().session.history_labels(); + scroll_to_top(&mut harness); + assert!(!current_shown(&harness, "Rename layer")); + + execute(&mut harness.state_mut().session, "layer.rename", &json!({"name": "Once more"})).unwrap(); + harness.run_steps(4); + + assert_eq!(harness.state().session.history_labels(), capped); + assert!(current_shown(&harness, "Rename layer")); +} + +/// A History window short enough to cut many rows off the list +const SHORT_HEIGHT: f32 = 220.0; + +/// Show History in a floating window `height` points tall, as dragging its bottom edge does +fn set_history_height(harness: &mut Harness<'_, TextureCraftApp>, height: f32) { + let rect = Rect::from_min_size(pos2(960.0, 190.0), vec2(300.0, height)); + let mut workspace = harness.state().ui.dock.workspace().clone(); + workspace.apply_all([Action::float(Panel::History, rect)], false, permissions).unwrap(); + harness.state_mut().ui.dock = Dock::from_value(serde_json::to_value(workspace).unwrap()); +} + +/// A list shortened on every frame, as a resize by dragging does, keeps the current step on screen without a new step +#[test] +fn a_history_shortened_over_several_frames_keeps_the_current_step_on_screen() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + + // Each height is more than a row shorter than the one before, from the 380 points the window opens at + for height in [340.0, 300.0, 260.0, SHORT_HEIGHT] { + set_history_height(&mut harness, height); + harness.step(); + } + harness.run_steps(4); + + assert!(current_shown(&harness, "Rename layer")); +} + +/// A list the user scrolled away from the current step stays there when it is made shorter +#[test] +fn shortening_a_scrolled_up_history_keeps_the_scroll() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + scroll_to_top(&mut harness); + + set_history_height(&mut harness, SHORT_HEIGHT); + harness.run_steps(4); + + assert!(!current_shown(&harness, "Rename layer")); + assert!(harness.query_by_label("Project opened").is_some()); +} + +/// A History list that moves to another container (rail popup to floating window) still shows the current step +#[test] +fn an_undocked_history_shows_the_newest_step() { + let session = long_session(STEPS_PAST_THE_PANEL); + let mut harness = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let icon = harness.get_all_by_role(egui::accesskit::Role::Button).find(|button| { + let label = button.accesskit_node().label().unwrap_or_default(); + label == "History" || label.starts_with("History (") + }); + icon.expect("the History icon on the rail").click(); + harness.run_steps(4); + assert!(current_shown(&harness, "Rename layer")); + + harness.get_by_label("Undock").click(); + harness.run_steps(4); + + assert!(current_shown(&harness, "Rename layer")); +} + +/// Shift+Tab walks from the current step up to the first row, past the rows on screen when the panel opened +#[test] +fn the_keyboard_reaches_rows_scrolled_out_of_view() { + let mut harness = history_harness(long_session(STEPS_PAST_THE_PANEL)); + 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>| { + let screen = harness.ctx.content_rect(); + harness.query_by_label("Project opened").is_some_and(|row| row.accesskit_node().is_focused() && screen.y_range().contains(row.rect().top())) + }; + // One press per step is enough to reach the first row + for _ in 0..harness.state().session.history_labels().len() + 1 { + if first_row_focused(&harness) { + break; + } + harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); + harness.run_steps(2); + } + + assert!(first_row_focused(&harness)); +} diff --git a/crates/ui-egui/tests/it/layer_toolbar.rs b/crates/ui-egui/tests/it/layer_toolbar.rs index 000ed20d..2fb95c72 100644 --- a/crates/ui-egui/tests/it/layer_toolbar.rs +++ b/crates/ui-egui/tests/it/layer_toolbar.rs @@ -1,11 +1,12 @@ //! The Layers panel's top row: Add effect greys what can't go where the selection is, Add mask adds a mask with its effect, and -//! Bitmap adds nothing until a texture is picked +//! Bitmap adds nothing until a texture is picked; Add smart material adds the smart material picked use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::{Value, json}; use texturecraft_engine::core::{Channel, EffectKind, LayerId, Source}; +use texturecraft_engine::materials::MATERIALS; use texturecraft_engine::paint::alphas; use texturecraft_engine::{StackTarget, execute}; use texturecraft_ui_egui::TextureCraftApp; @@ -130,6 +131,38 @@ fn the_bitmap_picker_closes_when_the_selection_moves_and_masks_no_other_layer() assert!(mask_kinds(&harness, opener).is_empty(), "nor the layer that opened it"); } +/// The selected texture set's top-level layers, bottom to top +fn stack(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let session = &harness.state().session; + session.doc.project.texture_set(session.ts()).unwrap().stack.clone() +} + +/// Add smart material opens a picker of the smart materials only; a pick adds its folder right above the selected layer +#[test] +fn add_smart_material_adds_the_picked_smart_material_above_the_selection() { + let (mut harness, layer) = app(); + let smart = MATERIALS.iter().find(|material| material.smart).unwrap(); + let simple = MATERIALS.iter().find(|material| !material.smart).unwrap(); + let tiles_of = |harness: &Harness<'_, TextureCraftApp>, label: &str| harness.query_all_by_label(label).map(|node| node.rect()).collect::>(); + let (smart_before, simple_before) = (tiles_of(&harness, smart.label), tiles_of(&harness, simple.label)); + + click_widget(&mut harness, Role::Button, "Add smart material"); + let new_tile = tiles_of(&harness, smart.label).into_iter().find(|tile| !smart_before.contains(tile)); + + assert!(egui::Popup::is_any_open(&harness.ctx), "the button opens the picker"); + assert_eq!(tiles_of(&harness, simple.label).len(), simple_before.len(), "simple materials stay out of it"); + + let before = stack(&harness); + click_at(&mut harness, new_tile.expect("a tile for the smart material").center()); + let after = stack(&harness); + let added: Vec<_> = after.iter().filter(|id| !before.contains(id)).copied().collect(); + + assert_eq!(added.len(), 1, "one folder added: {added:?}"); + let place = |id: LayerId| after.iter().position(|shown| *shown == id).unwrap(); + assert_eq!(place(added[0]), place(layer) + 1, "right above the selection"); + assert!(!egui::Popup::is_any_open(&harness.ctx), "the pick closes the picker"); +} + /// A floating Layers panel this narrow cannot hold the toolbar on one row const NARROW_LAYERS: [f32; 4] = [600.0, 200.0, 200.0, 400.0]; @@ -152,7 +185,7 @@ fn a_narrow_layers_panel_keeps_every_toolbar_button_inside_and_clickable() { harness.run_steps(SETTLE_FRAMES); let [left, _, width, _] = NARROW_LAYERS; - for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add folder", "Remove layer"] { + for label in ["Add effect", "Add mask", "Add paint layer", "Add fill layer", "Add smart material", "Add folder", "Remove layer"] { let button = harness.query_all_by_label_contains(label).find(|node| node.accesskit_node().role() == Role::Button).unwrap().rect(); assert!(button.left() >= left && button.right() <= left + width, "{label} at {button:?} stays inside the panel"); @@ -218,3 +251,23 @@ fn the_channel_list_starts_on_material_and_picks_a_channel_or_material_again() { assert!(harness.state().ui.layer_material_view, "Material shows the whole material again"); assert_eq!(harness.state().ui.layer_channel, Channel::Roughness, "the rows keep the last channel's blending"); } + +#[test] +fn add_smart_material_shows_the_keyboard_focus() { + let (mut harness, _) = app(); + let button = harness.get_by_role_and_label(Role::Button, "Add smart material").rect(); + let fills = |harness: &Harness<'_, TextureCraftApp>| { + harness + .output() + .shapes + .iter() + .filter(|clipped| matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == button && shape.fill != egui::Color32::TRANSPARENT)) + .count() + }; + assert_eq!(fills(&harness), 0, "no face at rest"); + + harness.get_by_role_and_label(Role::Button, "Add smart material").focus(); + harness.run_steps(3); + + assert!(fills(&harness) > 0, "the focused button is drawn"); +} diff --git a/crates/ui-egui/tests/it/layers_panel.rs b/crates/ui-egui/tests/it/layers_panel.rs index bd9048d2..ada4267c 100644 --- a/crates/ui-egui/tests/it/layers_panel.rs +++ b/crates/ui-egui/tests/it/layers_panel.rs @@ -2,7 +2,7 @@ //! document, and the thumbnail images arrive from the worker. use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use serde_json::{Value, json}; use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{Channel, LayerId}; @@ -238,7 +238,8 @@ fn deeply_nested_effect_visibility_is_reachable_in_a_narrow_panel() { let row = harness.get_by_label("Effect A").rect(); assert!(row.width() < 180.0, "the test must use a compact panel: {row:?}"); - let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 6.0).max(0.0); + // The nesting gives way to the row's edge, eye column, preview, gap, name and remove column + let indent = (row.width() - 7.0 - 22.0 - 21.6 - 8.0 - 20.0 - 27.0).max(0.0); click(&mut harness, egui::pos2(row.left() + 15.0 + indent, row.center().y)); let content = &harness.state().session.doc.project.layers[&layer].content_effects; @@ -385,7 +386,7 @@ fn narrow_harness() -> Harness<'static, TextureCraftApp> { #[test] fn layer_toolbar_stays_on_one_row_in_a_1280_by_800_window() { let h = narrow_harness(); - let buttons = ["Add paint layer", "Add fill layer", "Add folder"].map(|label| h.get_by_label(label).rect()); + let buttons = ["Add paint layer", "Add fill layer", "Add smart material", "Add folder"].map(|label| h.get_by_label(label).rect()); let wand = h.get_by_label("Add effect").rect(); let remove = h.query_all_by_label_contains("Remove layer").next().expect("the remove button").rect(); @@ -508,6 +509,19 @@ fn click_eye(h: &mut Harness<'_, TextureCraftApp>, name: &str, modifiers: egui:: h.run_steps(2); } +#[test] +fn the_row_menu_adds_a_height_combination_to_the_clicked_layers_mask() { + let (mut h, layer) = harness(); + let row = h.get_by_label("Masked fill").rect(); + right_click(&mut h, row.center()); + h.get_by_label("Add mask with height combination").click(); + h.run_steps(3); + + let mask = h.state().session.doc.project.layers[&layer].mask.clone().unwrap(); + assert_eq!(mask.effects.len(), 2, "the compare lands in the existing mask"); + assert!(mask.effects.iter().any(|effect| matches!(effect.kind, texturecraft_engine::core::EffectKind::Compare { .. }))); +} + #[test] fn the_context_menu_solos_a_layer_without_touching_the_document() { let (mut h, layer) = harness(); @@ -751,3 +765,260 @@ fn dragging_a_row_opacity_adds_one_undo_step() { assert!(opacity(&h) < before, "the drag lowers the opacity: {}", opacity(&h)); assert_eq!(h.state().session.history_labels().len(), steps + 1, "every frame of the drag merges into one step"); } + +/// When the selection moves to a layer below the panel's visible rows (a pick on the mesh, a command), its row scrolls into view +#[test] +fn a_newly_selected_layer_out_of_view_scrolls_into_view() { + let (mut h, _) = harness(); + for index in 0..20 { + execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": format!("Filler {index}")})).unwrap(); + } + h.run_steps(SETTLE_FRAMES); + let bottom = h.state().session.doc.project.texture_sets[h.state().session.ts()].stack[0]; + let name = h.state().session.doc.project.layers[&bottom].name.clone(); + + let before = h.get_by_label(&name).rect(); + assert!(before.top() > properties_top(&h), "the bottom layer starts out of view"); + execute(&mut h.state_mut().session, "layer.select", &json!({"layer": bottom.0})).unwrap(); + h.run_steps(SETTLE_FRAMES); + + let after = h.get_by_label(&name).rect(); + assert!(after.bottom() <= properties_top(&h), "its row is inside the panel"); +} + +/// The top of the Properties tab, which sits under the Layers panel +fn properties_top(h: &Harness<'_, TextureCraftApp>) -> f32 { + h.query_all(by().role(egui::Role::Tab).label_contains("Properties")).next().map(|tab| tab.rect().top()).unwrap_or(f32::MAX) +} + +/// Holding R and clicking the model lists the layers laying something down there instead of painting with the current tool; a row of the list, clicked or reached with the arrow keys and Enter, selects its layer, and Escape closes it +#[test] +fn r_and_a_click_on_the_model_list_the_layers_there_and_a_row_selects_one_without_painting() { + let (mut h, _) = harness(); + let session = &mut h.state_mut().session; + let lower = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Lower fill", "color": "#aa3322"})).unwrap(), "layer")); + let upper = LayerId(id(execute(session, "layer.add.fill", &json!({"name": "Upper fill", "color": "#2233aa"})).unwrap(), "layer")); + let empty = LayerId(id(execute(session, "layer.add.paint", &json!({"name": "Empty on top"})).unwrap(), "layer")); + h.run_steps(SETTLE_FRAMES); + let steps = h.state().session.history_labels().len(); + let view = h.state().viewport_rect; + let in_list = |h: &Harness<'_, TextureCraftApp>, name: &str| h.get_all_by_label(name).map(|node| node.rect()).find(|rect| view.contains(rect.center())); + let open_list = |h: &mut Harness<'_, TextureCraftApp>| { + let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + h.event(key(true)); + h.hover_at(view.center()); + h.run_steps(1); + click(h, view.center()); + h.event(key(false)); + h.run_steps(SETTLE_FRAMES); + }; + + open_list(&mut h); + + assert!(in_list(&h, "Upper fill").is_some() && in_list(&h, "Lower fill").is_some(), "both fills under the click are listed over the view"); + assert!(in_list(&h, "Empty on top").is_none(), "the empty top layer lays nothing down there"); + assert_eq!(h.state().session.selected_layer(), Some(empty), "opening the list selects nothing yet"); + + h.key_press(egui::Key::ArrowDown); + h.key_press(egui::Key::Enter); + h.run_steps(SETTLE_FRAMES); + + assert_eq!(h.state().session.selected_layer(), Some(lower), "Down from the top row and Enter select the second layer"); + assert!(h.state().layer_pick_list.is_none(), "picking closes the list"); + + open_list(&mut h); + let row = in_list(&h, "Upper fill").unwrap().center(); + click(&mut h, row); + h.run_steps(SETTLE_FRAMES); + + assert_eq!(h.state().session.selected_layer(), Some(upper), "the clicked row's layer is selected"); + assert_eq!(h.state().session.history_labels().len(), steps, "no stroke was painted"); + + // The first Escape moves egui's focus off the top row: the list must close on it all the same + open_list(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); + assert_eq!(h.state().session.selected_layer(), Some(upper), "and selects nothing"); +} + +/// Two fills over the whole model, so R + click opens the list; returns the 3D view +fn two_fills(h: &mut Harness<'_, TextureCraftApp>) -> egui::Rect { + for name in ["Lower fill", "Upper fill"] { + execute(&mut h.state_mut().session, "layer.add.fill", &json!({"name": name, "color": "#aa3322"})).unwrap(); + } + h.run_steps(SETTLE_FRAMES); + h.state().viewport_rect +} + +/// R + click at the middle of the 3D view +fn open_pick_list(h: &mut Harness<'_, TextureCraftApp>) { + let middle = h.state().viewport_rect.center(); + let key = |pressed| egui::Event::Key { key: egui::Key::R, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + h.event(key(true)); + h.hover_at(middle); + h.run_steps(1); + click(h, middle); + h.event(key(false)); + h.run_steps(SETTLE_FRAMES); + assert!(h.state().layer_pick_list.is_some(), "the list is open"); +} + +/// The list opened over an armed point pick is the innermost thing: Escape closes it first, and a press that closes it sets no point +#[test] +fn the_layer_pick_list_takes_escape_and_its_closing_press_before_an_armed_point_pick() { + let (mut h, _) = harness(); + let view = two_fills(&mut h); + execute(&mut h.state_mut().session, "mask.add.black", &Value::Null).unwrap(); + let effect = id(execute(&mut h.state_mut().session, "effect.add.generator", &json!({"generator": "3dDistance"})).unwrap(), "effect"); + h.run_steps(SETTLE_FRAMES); + let generator = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.effect(LayerId(effect)).unwrap().1.kind.clone(); + let armed = + |h: &Harness<'_, TextureCraftApp>| h.get_by_label("Pick 3D Position on the mesh").accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); + h.get_by_label("Pick 3D Position on the mesh").click(); + h.run_steps(SETTLE_FRAMES); + assert!(armed(&h), "the pick is armed"); + let before = generator(&h); + + open_pick_list(&mut h); + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list"); + assert!(armed(&h), "and leaves the point pick armed"); + + open_pick_list(&mut h); + click(&mut h, view.center() - egui::vec2(60.0, 40.0)); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "a press outside closes the list"); + assert_eq!(generator(&h), before, "and sets no point"); + assert!(armed(&h)); +} + +/// The list names layers of the stack it was opened on: an edit, an undo or another project closes it +#[test] +fn the_layer_pick_list_closes_when_the_document_changes() { + let (mut h, _) = harness(); + two_fills(&mut h); + open_pick_list(&mut h); + + execute(&mut h.state_mut().session, "edit.undo", &Value::Null).unwrap(); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none()); +} + +/// In the split view, a press on the 2D view that closes the list paints nothing there +#[test] +fn a_press_on_the_2d_view_that_closes_the_layer_pick_list_does_not_paint() { + let (mut h, _) = harness(); + two_fills(&mut h); + execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap(); + h.state_mut().ui.layout = texturecraft_ui_egui::state::ViewLayout::Split; + h.run_steps(SETTLE_FRAMES); + let view = h.state().viewport_rect; + let over_2d = egui::pos2(view.right() + view.width() * 0.5, view.center().y); + let steps = h.state().session.history_labels().len(); + open_pick_list(&mut h); + + click(&mut h, over_2d); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the press closes the list"); + assert_eq!(h.state().session.history_labels().len(), steps, "and paints no stroke"); + + click(&mut h, over_2d); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().session.history_labels().len() > steps, "the next press paints there"); +} + +/// The list holds the spot it was opened on: a view that changed size or camera no longer has it under that point +#[test] +fn the_layer_pick_list_closes_when_the_view_changes() { + let (mut h, _) = harness(); + two_fills(&mut h); + open_pick_list(&mut h); + + h.state_mut().session.camera.yaw += 0.5; + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the camera turned"); + + open_pick_list(&mut h); + h.set_size(egui::vec2(1300.0, 1000.0)); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "the view was resized"); +} + +#[test] +fn r_and_a_click_leaves_an_armed_eyedropper_armed() { + let (mut h, _) = harness(); + two_fills(&mut h); + h.state_mut().picking_color = Some(egui::Id::unique("armed eyedropper")); + h.run_steps(SETTLE_FRAMES); + assert!(h.state().picking_color.is_some(), "armed before the list opens"); + + open_pick_list(&mut h); + + assert!(h.state().picking_color.is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(SETTLE_FRAMES); + + assert!(h.state().layer_pick_list.is_none(), "Escape closes the list first"); + assert!(h.state().picking_color.is_some(), "and leaves the eyedropper armed"); +} + +#[test] +fn a_stroke_released_while_r_is_held_ends() { + let (mut h, _) = harness(); + execute(&mut h.state_mut().session, "layer.add.paint", &Value::Null).unwrap(); + h.run_steps(SETTLE_FRAMES); + let middle = h.state().viewport_rect.center(); + let end = middle + egui::vec2(60.0, 0.0); + h.drag_at(middle); + h.run_steps(1); + h.hover_at(middle + egui::vec2(30.0, 0.0)); + h.run_steps(1); + assert!(h.state().session.stroke_active(), "the stroke is under way"); + + h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.hover_at(end); + h.run_steps(1); + h.drop_at(end); + h.run_steps(SETTLE_FRAMES); + + assert!(!h.state().session.stroke_active()); +} + +#[test] +fn the_label_under_the_pointer_is_announced_while_r_is_held() { + let (mut h, _) = harness(); + let view = two_fills(&mut h); + h.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + h.hover_at(view.center()); + h.run_steps(SETTLE_FRAMES); + + let announced = h.query_all(by().label_contains("Upper fill +")).any(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite); + + assert!(announced, "the layer's name is announced without moving the focus"); +} + +#[test] +fn a_long_layer_pick_hint_stays_inside_the_viewport() { + let (mut harness, _) = harness(); + let view = two_fills(&mut harness); + let layer_name = "Wide fill ".repeat(24); + execute(&mut harness.state_mut().session, "layer.rename", &json!({"name": layer_name})).unwrap(); + + harness.event(egui::Event::Key { key: egui::Key::R, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }); + harness.hover_at(view.center()); + harness.run_steps(SETTLE_FRAMES); + + let hint = harness.query_all(by().label_contains(layer_name.trim())).find(|node| node.accesskit_node().live() == egui::accesskit::Live::Polite).unwrap(); + assert!(view.contains_rect(hint.rect()), "the whole hint fits in the viewport"); +} 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 eba3e084..27c94c13 100644 --- a/crates/ui-egui/tests/it/log_panel_680.rs +++ b/crates/ui-egui/tests/it/log_panel_680.rs @@ -7,6 +7,9 @@ use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +/// Enough lines that the Log cannot show them all at once +const LINES_PAST_THE_PANEL: usize = 100; + fn app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); let mut h = Harness::builder() @@ -131,18 +134,105 @@ fn mesh_reimport_clears_log_selection_within_the_same_project() { #[test] fn assets_has_a_greyed_filter_button_with_the_hint() { - let mut h = app(); - assert!(h.query_by_label(egui_phosphor::regular::WARNING).is_none(), "GENERAL has no filter button"); - h.get_by_label("ASSETS").click(); - h.run_steps(3); - let button = h.get_by_label(egui_phosphor::regular::WARNING); + let mut harness = app(); + assert!(harness.query_by_label("Warnings").is_none(), "GENERAL has no filter button"); + + harness.get_by_label("ASSETS").click(); + harness.run_steps(3); + + let button = harness.get_by_label("Warnings"); assert!(button.accesskit_node().is_disabled()); + let at = button.rect().center(); - h.hover_at(egui::pos2(1.0, 1.0)); - h.run_steps(2); - h.hover_at(at); - h.run_steps(30); - assert!(h.query_by_label(texturecraft_ui_egui::unavailable::NOT_AVAILABLE).is_some()); + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(2); + harness.hover_at(at); + harness.run_steps(30); + assert!(harness.query_by_label(texturecraft_ui_egui::unavailable::NOT_AVAILABLE).is_some()); +} + +/// The two tabs share the panel's width equally, side by side +#[test] +fn the_log_tabs_split_the_panel_width() { + let harness = app(); + let (general, assets) = (harness.get_by_label("GENERAL").rect(), harness.get_by_label("ASSETS").rect()); + + assert!((general.width() - assets.width()).abs() < 1.0, "{general:?} {assets:?}"); + assert!((general.right() - assets.left()).abs() < 1.0, "{general:?} {assets:?}"); +} + +/// The list's scrollbar keeps a gap to the list's frame, which ends where the tabs end +#[test] +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 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!(general.left() < bar.left() && bar.right() < frame_inside, "{bar:?} {assets:?}"); +} + +/// How many rows each painted text containing `part` has +fn painted_rows(harness: &Harness<'_, TextureCraftApp>, part: &str) -> Vec { + harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text().contains(part) => Some(text.galley.rows.len()), + _ => None, + }) + .collect() +} + +/// Log `message` and show it painted: the status bar repeats the newest message, so another follows it +fn log_behind_a_newer_line(harness: &mut Harness<'_, TextureCraftApp>, message: &str) { + harness.state_mut().session.log.info("Exporter", message.to_owned()); + harness.state_mut().session.log.info("Exporter", "newest"); + harness.run_steps(3); +} + +/// A line longer than the panel stays on one row +#[test] +fn a_long_line_stays_one_row() { + let mut harness = app(); + log_behind_a_newer_line(&mut harness, &"long ".repeat(400)); + + assert_eq!(painted_rows(&harness, "long long"), vec![1]); +} + +#[test] +fn a_multiline_message_scrolls_on_one_row_and_copies_verbatim() { + let mut harness = app(); + 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] @@ -209,3 +299,30 @@ fn the_assets_menu_clears_all_or_only_the_selected_lines() { assert!(h.state().session.log.iter().all(|entry| !entry.is_asset())); assert_eq!(h.state().session.log.len(), 3, "the GENERAL lines stay"); } + +/// Shift+Tab walks from the newest line to the first one, past the lines on screen when the panel opened +#[test] +fn the_keyboard_reaches_lines_scrolled_out_of_view() { + let mut harness = app(); + for number in 0..LINES_PAST_THE_PANEL { + harness.state_mut().session.log.info("Exporter", format!("line {number}")); + } + harness.run_steps(4); + line(&harness, &format!("[Exporter] line {}", LINES_PAST_THE_PANEL - 1)).focus(); + harness.run_steps(2); + + let first_line_focused = |harness: &Harness<'_, TextureCraftApp>| { + let screen = harness.ctx.content_rect(); + harness.query_all_by_label("[Exporter] first").any(|row| row.accesskit_node().is_focused() && screen.y_range().contains(row.rect().top())) + }; + // One press per line is enough to reach the first one + for _ in 0..harness.state().session.log.len() { + if first_line_focused(&harness) { + break; + } + harness.key_press_modifiers(Modifiers::SHIFT, egui::Key::Tab); + harness.run_steps(2); + } + + assert!(first_line_focused(&harness)); +} 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 88723d9a..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. 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/rail.rs b/crates/ui-egui/tests/it/rail.rs index 7dbd97f2..260b1c93 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -256,19 +256,19 @@ fn display_settings_remain_reachable_in_a_short_window() { assert!(harness.ctx.content_rect().contains_rect(setting), "the last setting must be reachable: {setting:?}"); } +/// The History panel has no Undo/Redo buttons (the Edit menu and Ctrl+Z/Ctrl+Y undo); its current step stays reachable #[test] -fn history_actions_remain_reachable_in_a_short_window() { +fn the_current_history_step_remains_reachable_in_a_short_window() { let mut harness = app_of_size(egui::vec2(1600.0, 400.0)); click_rail(&mut harness, "History"); - for label in ["Undo", "Redo"] { - let button = harness - .get_all_by_role(Role::Button) - .find(|button| button.accesskit_node().label().is_some_and(|text| text.ends_with(label))) - .expect("the History action") - .rect(); - assert!(harness.ctx.content_rect().contains_rect(button), "{label} must be reachable: {button:?}"); - } + let name = harness.state().session.history_labels().last().cloned().unwrap_or_else(|| "Project opened".to_owned()); + let current = harness + .get_all_by_role_and_label(Role::Button, &name) + .find(|row| row.accesskit_node().toggled() == Some(egui::accesskit::Toggled::True)) + .expect("the current History step") + .rect(); + assert!(harness.ctx.content_rect().contains_rect(current), "the current step must be reachable: {current:?}"); } #[test] 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/shortcut_keys.rs b/crates/ui-egui/tests/it/shortcut_keys.rs index 80aae4b3..abbd8bc8 100644 --- a/crates/ui-egui/tests/it/shortcut_keys.rs +++ b/crates/ui-egui/tests/it/shortcut_keys.rs @@ -56,6 +56,50 @@ fn a_held_key_runs_its_command_again() { assert!(!hidden(&h), "the repeat toggled it back"); } +#[test] +fn browser_capture_follows_redo_changes_in_the_stored_keymap() { + use texturecraft_ui_egui::keymap::{Keymap, captured, sync_captured}; + + let mut keymap = Keymap::from([("edit.undo".into(), String::new())]); + let redo_modifiers = Modifiers::COMMAND | Modifiers::SHIFT; + + sync_captured(&keymap); + assert!(captured(redo_modifiers, Key::Z)); + + keymap.insert("edit.redo".into(), String::new()); + sync_captured(&keymap); + assert!(!captured(redo_modifiers, Key::Z)); + + // Fill the shared resolver before the saved file command is admitted + for index in 0..craft_keymap::MAX_COMMANDS { + keymap.insert(format!("expired.{index}"), String::new()); + } + keymap.insert("file.save".into(), "Ctrl+Shift+Z".into()); + sync_captured(&keymap); + + assert!(!captured(redo_modifiers, Key::Z), "an ignored binding leaves the browser shortcut free"); + + sync_captured(&Keymap::new()); + assert!(captured(redo_modifiers, Key::Z), "reset restores capture"); +} + +#[test] +fn ctrl_shift_z_redoes_the_undone_step() { + let mut harness = harness(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.fill", &serde_json::Value::Null).unwrap(); + let labels_after_add = harness.state().session.history_labels(); + + harness.state_mut().session.undo().unwrap(); + harness.run_steps(2); + + assert_ne!(harness.state().session.history_labels(), labels_after_add, "the step is undone"); + + harness.event(press(Key::Z, Modifiers::COMMAND | Modifiers::SHIFT, false)); + harness.run_steps(2); + + assert_eq!(harness.state().session.history_labels(), labels_after_add); +} + #[test] fn a_shortcut_stored_in_the_settings_replaces_the_default() { let mut h = harness(); 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..2cdc2de8 100644 --- a/crates/ui-egui/tests/it/toolbar.rs +++ b/crates/ui-egui/tests/it/toolbar.rs @@ -1,11 +1,13 @@ //! Toolbar layout and input coverage use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; 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); @@ -211,3 +246,17 @@ fn toolbar_window_snapshots() { harness.render().unwrap().save(directory.join(format!("toolbar-{width}-{scale}.png"))).unwrap(); } } + +#[test] +fn compositor_status_announces_the_cpu_fallback_and_its_reason() { + let session = Session::new_project("Compositor status", texturecraft_engine::geom::primitives::cube(1.0), "builtin:cube", None, 128).unwrap(); + let context = eframe::CreationContext::_new_kittest(egui::Context::default()); + let app = TextureCraftApp::new(&context, session); + let mut harness = Harness::builder().build_ui_state(|ui, app| toolbar::status_bar(app, ui), app); + + harness.run(); + let status = harness.get_by_label("Layers: CPU"); + + assert_eq!(status.accesskit_node().live(), egui::accesskit::Live::Polite); + assert_eq!(status.accesskit_node().description().as_deref(), Some("The GPU renderer is unavailable.")); +} 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 872215fe..b35b8fcc 100644 --- a/crates/ui-egui/tests/list_panels.rs +++ b/crates/ui-egui/tests/list_panels.rs @@ -36,10 +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 scroll bar, which runs the visible height of the list -fn list_height(harness: &Harness<'_, TextureCraftApp>) -> f32 { - let bar = harness.get_all_by_role(Role::ScrollBar).find(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X).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] @@ -58,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"); } @@ -76,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 4a7e04ca..a9ee2976 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -22,7 +22,8 @@ Submitting the current name leaves history unchanged. The project file keeps its `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 -one just above itself. `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the +one just above itself. `effect.moveUp {effect?}` / `effect.moveDown {effect?}` move the named (or +selected) effect one place and reply `{moved}` (false at that end). `effect.copy {effect?}` and `effect.cut {effect?}` put an effect on the layer clipboard, and `effect.paste {layer?, target?}` adds it to another layer's content or mask. `layer.select {layers: [id], layer?}` selects several layers of one texture set at once (`layer` is the active one), and `{layer, range: true}` / `{layer, toggle: true}` do what Shift+click and @@ -37,7 +38,18 @@ layer, the others in stack order; `layer.duplicate` puts the copies in one block topmost selected layer. Without `layer`, `layer.remove`, `layer.duplicate`, `layer.group` and `layer.visible` act on every selected layer; each of them and `layer.move {layers, above | index}` also take an explicit `layers` list. `session.inspect` lists the -selection as `selectedLayers` (top row first). +selection as `selectedLayers` (top row first). A command that takes `layer` is checked against +the named layer of the active texture set, so it runs even with nothing selected. + +`layer.layersAt {x, y, viewport?}` lists the layers laying something down where the mesh is under a +viewport point, top first (`{layers: [{layer, name, channels}]}`, in the shown channels). +`layer.pickAt {x, y, viewport?, layer?}` selects the top one, or `layer` if it is listed there. +Both commands skip hidden texture sets and respect solo. A folder instance is listed by its own +row, with the channels drawn by its source. +`layer.flatten {layer}` on a folder replies with a new fill layer above it holding the folder's +result as image resources, and hides the folder; it is refused for a texture set with several UV +tiles, for a visible folder holding an anchor point that a layer outside it reads, and for a +folder whose layers' blend modes go past a channel's range (an image would clip the result). `mask.export {layer?, path}` writes the layer's evaluated mask as a 16-bit grayscale PNG at the texture set's resolution: black where the mesh does not cover the texture, with the orientation @@ -170,7 +182,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 @@ -231,6 +249,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 @@ -813,7 +852,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`; @@ -854,7 +893,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 e112294e..91dbffa1 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**. @@ -45,6 +46,23 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA one layer alone in the 3D and 2D views, optionally without its mask (Alt+Shift+click, or **Solo layer without its mask**), to judge a material hidden behind a mask. It is only a view: the document, the undo history, saving, exporting and baking never see it. +- **Pick a layer on the model:** hold R over the 3D view, with any tool: a label at the pointer + names the top layer laying something down there (the shown channel in a single-channel view) + and how many more. Click: one layer there is selected; several open a list at the pointer with + each one's thumbnail, name and the channels it changes there, to pick from (Up/Down, Enter, Esc + work too). Closed folders holding the picked layer open and its row scrolls into view. +- **Flatten folder:** a folder's right-click menu (or Ctrl+M) adds a fill layer holding the + folder's result as one image per channel, with the folder's mask painted into the new layer's + mask; the folder is kept and hidden. Layers that blend over the layers below the folder are baked + as they look over them at that moment. Flattening is refused for a texture set with several UV + tiles, when an outside layer reads one of the folder's anchor points, or when the resulting + values cannot be reproduced within the generated images' value ranges. +- **Effect rows:** a generator is named after its kind; the cross removes an effect; the menu's + Move up / down / to top / to bottom and Alt+Up / Alt+Down reorder its stack. +- **Smart materials from the Layers panel:** the toolbar's button opens a picker of the built-in + and saved smart materials. +- **Height combination masks** (Add mask menus) also set the layer's height to blend Normal. + On an instance, the mask belongs to the instance and the height blend follows the shared content. - **Several layers at once:** Shift+click a layer to select the rows from the last clicked one, Ctrl+click (Cmd+click on macOS) to add or take out one layer, Ctrl+A (Cmd+A) with the pointer over the Layers panel to select every shown row (folder rows and the layers of open folders). @@ -146,8 +164,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 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/packaging/nightly-release-tests.py b/packaging/nightly-release-tests.py index 55c08d86..840110b8 100755 --- a/packaging/nightly-release-tests.py +++ b/packaging/nightly-release-tests.py @@ -217,15 +217,21 @@ class TrustedSourcePreparation(unittest.TestCase): (indicator, expression), = job_conditions(jobs) self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected) - def test_no_nightly_schedule_is_registered(self): - for name, event in (("nightly.yml", "workflow_dispatch"), - ("nightly-sign.yml", "workflow_dispatch")): + def test_nightly_triggers_match_reviewed_schedule_and_dispatch(self): + expected = { + "nightly.yml": [" schedule:", " workflow_dispatch:"], + "nightly-sign.yml": [" workflow_dispatch:"], + } + for name, expected_triggers in expected.items(): source = (ROOT / ".github/workflows" / name).read_text() events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0] triggers = [line for line in events.splitlines() if line.startswith(" ") and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")] with self.subTest(workflow=name): - self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review") + self.assertEqual(triggers, expected_triggers, "schedule/activation needs explicit review") + producer = (ROOT / ".github/workflows/nightly.yml").read_text() + self.assertEqual(re.findall(r"(?m)^ - cron: '([^']+)'$", producer), ["0 6 * * *"], + "nightly schedule must remain pinned to the reviewed 06:00 UTC cron") def test_signer_serialization_contract_is_enforced(self): assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text()) @@ -360,7 +366,8 @@ class NightlyEnabledCallers(unittest.TestCase): source = (ROOT / ".github/workflows/nightly.yml").read_text() policy = json.loads(INSTALLED_POLICY.read_text()) self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS) - self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule") + self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"], + "automatic signer is limited to github-actions[bot]") def test_an_actor_outside_the_release_managers_is_refused(self): source = (ROOT / ".github/workflows/nightly.yml").read_text() @@ -824,19 +831,23 @@ def dispatch_triggers(source): class NightlyDispatchTransport(unittest.TestCase): - """The scheduled transport stays literally off and can only reach the signer branch.""" + """The scheduled transport runs only in its exact context and can only reach the signer branch.""" + + DISPATCH_GUARD = "github.repository == 'storytold/texturecraft' && github.event_name == 'workflow_run'" def setUp(self): self.source = (ROOT / ".github/workflows/nightly-dispatch.yml").read_text() - def test_every_dispatch_job_is_literal_off(self): + def test_dispatch_job_keeps_exact_context_guard(self): jobs = self.source.split("\njobs:\n", 1)[1] - headers = re.findall(r"(?m)^ (?![\s#])[^\n]+", jobs) + self.assertEqual(re.findall(r"(?m)^ ([^\s#][^:]*):", jobs), ["dispatch"]) conditions = job_conditions(jobs) - self.assertTrue(headers) - self.assertEqual(len(conditions), len(headers), "every job needs a literal-off condition") - for _, expression in conditions: - self.assertTrue(literal_off(expression), "nightly activation requires reviewed test update") + self.assertEqual(len(conditions), 1) + indicator, expression = conditions[0] + self.assertEqual(indicator, ">-") + self.assertFalse(literal_off(expression), "scheduled dispatch transport must be enabled") + self.assertEqual(" ".join(expression.split()), self.DISPATCH_GUARD, + "dispatch guard may only change with review") def test_only_a_completed_scheduled_producer_is_transported(self): self.assertEqual(re.findall(r"(?m)^ workflows: (.+)$", self.source), diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 73a02832..e1ce8ee1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -145,146 +145,6 @@ fn cmd_wasm() -> Result<(), String> { if failed == 0 { Ok(()) } else { Err(format!("{failed} package(s) failed the wasm check")) } } -/// The render crate's unit test modules that compile the most GPU pipelines, in groups tested in -/// a process each on Linux, all at once (Mesa keeps what a process compiled until it ends: on -/// lavapipe each group peaks under about 4 GB); the rest of its unit tests run in one more -/// process after them. -const RENDER_TEST_GROUPS: &[&[&str]] = &[ - &["gpu_composite::procedural_tests::", "gpu_composite::fill_projection::", "gpu_composite::lighting::", "gpu_composite::point::", "gpu_composite::brush::"], - &[ - "gpu_composite::stack::", - "gpu_composite::packages::", - "gpu_composite::pipelines::", - "gpu_neighbourhood::gather::", - "gpu_neighbourhood::box_family::", - "gpu_neighbourhood::tests::", - ], - &["gpu_composite::udim::"], -]; - -/// Where Ubuntu's mesa-vulkan-drivers puts the Vulkan driver files -const VULKAN_DRIVER_DIR: &str = "/usr/share/vulkan/icd.d"; - -/// The environment of the render crate's tests on Linux CI (`CI` set): Mesa's lavapipe through -/// Vulkan alone (its driver file the only one the loader sees), with LLVM's optimisation passes -/// off, as they cost more than the tests' shaders then run. A variable the caller set wins. An -/// error when lavapipe is missing, so the tests cannot fall back to another adapter or skip. -fn render_ci_env() -> Result, String> { - if !cfg!(target_os = "linux") || std::env::var_os("CI").is_none() { - return Ok(Vec::new()); - } - // A driver file the caller named under either variable, else lavapipe's from the system - let set = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); - let given = set("VK_DRIVER_FILES").or_else(|| set("VK_ICD_FILENAMES")); - let driver = - match given { - Some(files) => files, - None => { - let found = - std::fs::read_dir(VULKAN_DRIVER_DIR).into_iter().flatten().flatten().map(|entry| entry.path()).find(|path| { - path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.starts_with("lvp_icd") && name.ends_with(".json")) - }); - let Some(found) = found else { - return Err(format!("CI runs the render tests on lavapipe, but {VULKAN_DRIVER_DIR} has no lvp_icd*.json (install mesa-vulkan-drivers)")); - }; - found.display().to_string() - } - }; - let defaults = [ - ("WGPU_BACKEND", "vulkan".to_owned()), - ("VK_DRIVER_FILES", driver.clone()), - ("VK_ICD_FILENAMES", driver), - ("GALLIVM_PERF", "nopt".to_owned()), - // Each group's adapter on two threads: the groups run at once - ("LP_NUM_THREADS", "2".to_owned()), - ("TC_CI_LAVAPIPE", "1".to_owned()), - ]; - // A variable the caller set wins; an empty one counts as unset - Ok(defaults.into_iter().filter(|(name, _)| std::env::var_os(name).is_none_or(|value| value.is_empty())).collect()) -} - -/// `cargo test --workspace`. The render crate's unit tests run in a few processes at once, with -/// two malloc arenas on Linux: they compile many GPU pipelines on Mesa, which keeps what it -/// compiled until the process ends, so one process for all of them outgrows a 16 GB runner, and -/// the default per-thread arenas fragment that memory. A MALLOC_ARENA_MAX the caller set wins. -/// On Linux CI they run on lavapipe ([`render_ci_env`]); the Windows gate sets up lavapipe in -/// its own script, and its groups run at once as well, which halves the gate's longest step. -fn cmd_test() -> Result<(), String> { - let render_env = render_ci_env()?; - for (name, value) in &render_env { - eprintln!("render tests with {name}={value}"); - } - let test = |args: &[&str], filter: &[&str], env: &[(&str, String)]| { - let mut c = cargo(); - c.arg("test").args(args); - if !filter.is_empty() { - c.arg("--").args(filter); - } - if std::env::var_os("MALLOC_ARENA_MAX").is_none() { - c.env("MALLOC_ARENA_MAX", "2"); - } - c.envs(env.iter().map(|(name, value)| (name, value))); - let what = format!("cargo test {} {}", args.join(" "), if filter.is_empty() { String::new() } else { format!("-- {}", filter.join(" ")) }); - (c, what.trim_end().to_owned()) - }; - const RENDER: &str = "texturecraft-render"; - let mut failed = Vec::new(); - for (c, what) in [ - test(&["--workspace", "--exclude", RENDER], &[], &[]), - test(&["-p", RENDER, "--doc"], &[], &render_env), - test(&["-p", RENDER, "--test", "*"], &[], &render_env), - ] { - failed.extend(run(c, &what).err()); - } - // Built once before the groups start, so they do not wait on each other's build - let (c, what) = test(&["-p", RENDER, "--lib", "--no-run"], &[], &[]); - if let Err(error) = run(c, &what) { - failed.push(error); - return Err(failed.join("; ")); - } - let groups = RENDER_TEST_GROUPS.iter().map(|group| test(&["-p", RENDER, "--lib"], group, &render_env)).collect(); - failed.extend(run_at_once(groups).err()); - let rest: Vec<&str> = RENDER_TEST_GROUPS.iter().copied().flatten().flat_map(|module| ["--skip", module]).collect(); - let (c, what) = test(&["-p", RENDER, "--lib"], &rest, &render_env); - failed.extend(run(c, &what).err()); - if failed.is_empty() { Ok(()) } else { Err(failed.join("; ")) } -} - -/// Runs `commands` at once, each with its output captured and printed whole when it ends, then -/// each one's exit; an error naming every command that failed. -fn run_at_once(commands: Vec<(Command, String)>) -> Result<(), String> { - let printing = std::sync::Mutex::new(()); - let results: Vec<(String, Result<(), String>)> = std::thread::scope(|scope| { - let runs: Vec<_> = commands - .into_iter() - .enumerate() - .map(|(index, (mut command, what))| { - eprintln!("$ [{}] {what}", index + 1); - let printing = &printing; - scope.spawn(move || { - let result = match command.output() { - Ok(output) => { - let _turn = printing.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - eprintln!("\n===== [{}] {what}: {} =====", index + 1, output.status); - eprint!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); - if output.status.success() { Ok(()) } else { Err(format!("{what}: exited with {}", output.status)) } - } - Err(error) => Err(format!("{what}: failed to spawn: {error}")), - }; - (what, result) - }) - }) - .collect(); - runs.into_iter().map(|run| run.join().unwrap_or_else(|_| (String::from("a command"), Err(String::from("its thread panicked"))))).collect() - }); - eprintln!(); - for (index, (what, result)) in results.iter().enumerate() { - eprintln!(" [{}] {:<4} {what}", index + 1, if result.is_ok() { "ok" } else { "FAIL" }); - } - let failed: Vec = results.into_iter().filter_map(|(_, result)| result.err()).collect(); - if failed.is_empty() { Ok(()) } else { Err(failed.join("; ")) } -} - fn cmd_ci() -> Result<(), String> { let cargo_step = |args: &'static [&'static str]| { move || { @@ -299,7 +159,7 @@ fn cmd_ci() -> Result<(), String> { ("fmt", Box::new(cargo_step(&["fmt", "--all", "--", "--check"]))), ("layers", Box::new(cmd_layers)), ("clippy", Box::new(cargo_step(&["clippy", "--workspace", "--all-targets", "--", "-D", "warnings"]))), - ("test", Box::new(cmd_test)), + ("test", Box::new(cargo_step(&["test", "--workspace"]))), ]; // The check compiles for wasm32 and gives the same answer on any host, so the non-Windows legs // cover it and the slower Windows leg skips it. A skipped step is not in the list, so the