From 7a3b95e7982d06e03f7bafbe783327e380a23e0b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:38:08 +0000 Subject: [PATCH 01/34] Export: JPEG 2000 file types, lossless, as a raw codestream (j2k) or a JP2 file (jp2) Encoded by the j2k crate (MIT OR Apache-2.0, pure Rust; craft-image-codecs only reads JPEG 2000), which needs Rust 1.96, so the README asks for 1.96. --- Cargo.lock | 71 +++++++++++++++++++- Cargo.toml | 3 + README.md | 2 +- crates/engine/src/file_cmds.rs | 2 +- crates/formats/Cargo.toml | 2 + crates/formats/src/export/jpeg2000.rs | 54 +++++++++++++++ crates/formats/src/export/mod.rs | 20 +++++- crates/formats/src/export/tests.rs | 71 +++++++++++++++++++- crates/ui-egui/src/export_window.rs | 4 +- crates/ui-egui/tests/it/export_file_types.rs | 21 +++--- docs/control-protocol.md | 2 +- docs/features.md | 2 +- 12 files changed, 228 insertions(+), 26 deletions(-) create mode 100644 crates/formats/src/export/jpeg2000.rs diff --git a/Cargo.lock b/Cargo.lock index d82d26f7..c0494fe8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1832,6 +1832,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" +[[package]] +name = "fearless_simd" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" + [[package]] name = "filetime" version = "0.2.29" @@ -2394,7 +2400,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" dependencies = [ - "fearless_simd", + "fearless_simd 0.4.1", ] [[package]] @@ -2760,6 +2766,63 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "j2k" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5dcb93d62c580930297896f25933b034bf665534568626787dbf0f03027e7b0" +dependencies = [ + "j2k-core", + "j2k-native", + "j2k-types", + "moxcms", + "thiserror 2.0.21", +] + +[[package]] +name = "j2k-codec-math" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a38b1ddbaa04c07213dba6180ed1168f0e96bfa35890542c414d872cea0c7d58" +dependencies = [ + "j2k-types", +] + +[[package]] +name = "j2k-core" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae969eb19e9b3a8d65c4342f9921717be407571cc0fbc44e4379daa0b588d01c" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "j2k-native" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "971da314ca1501363f686b6796d309ebbda7d2f88d34671c38d79132f7cb59ff" +dependencies = [ + "fearless_simd 1.3.0", + "j2k-codec-math", + "j2k-profile", + "j2k-types", + "libm", + "rayon", +] + +[[package]] +name = "j2k-profile" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c1c0cc7e85f2ab1cc85c9a6d2bad3680319c0cdf558f3be14b4ccdbd6917fca" + +[[package]] +name = "j2k-types" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "716edd556741a415294d955121f76d41b7d8d650554fb09f30d0654b15127ac9" + [[package]] name = "jni" version = "0.22.4" @@ -5218,6 +5281,8 @@ dependencies = [ "gltf", "half", "image", + "j2k", + "j2k-core", "png", "quick-xml 0.41.0", "rayon", @@ -5757,7 +5822,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" dependencies = [ "bytemuck", - "fearless_simd", + "fearless_simd 0.4.1", "guillotiere", "log", "peniko", @@ -7113,7 +7178,7 @@ dependencies = [ "memchr", "nix", "typed-path", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "zeroize", "zopfli", ] diff --git a/Cargo.toml b/Cargo.toml index de6fc98d..d2a340de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,9 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } half = "2" exr = { version = "1.73", default-features = false } +# JPEG 2000 writing (craft-image-codecs only reads it); j2k 0.13 needs Rust 1.99 +j2k = "0.11.3" +j2k-core = "0.11.3" eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" diff --git a/README.md b/README.md index 345c32c1..29b1daea 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). +You need Rust 1.96 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). **File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none. Japanese, Chinese, Korean and Arabic interface text uses the fonts of diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 006bb979..d13dbee3 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 516e0f5d..e83f5d56 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -32,6 +32,8 @@ half = { workspace = true } quick-xml = { workspace = true } zip = { workspace = true } exr = { workspace = true } +j2k = { workspace = true } +j2k-core = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/formats/src/export/jpeg2000.rs b/crates/formats/src/export/jpeg2000.rs new file mode 100644 index 00000000..b4c2218e --- /dev/null +++ b/crates/formats/src/export/jpeg2000.rs @@ -0,0 +1,54 @@ +//! JPEG 2000, lossless (reversible 5/3 wavelet): a raw codestream (.j2k) or one in a JP2 file (.jp2) + +use j2k::{ + J2kChannelAssociation, J2kChannelDefinition, J2kChannelType, J2kFileBoxMetadata, J2kFileColorSpec, J2kFileWrapOptions, J2kLosslessEncodeOptions, + J2kLosslessSamples, encode_j2k_lossless, wrap_j2k_codestream, +}; +use j2k_core::Colorspace; + +/// Encode `bytes` (8-bit or native-endian 16-bit L, LA, RGB or RGBA samples) of a `width`×`height` image; `jp2` wraps it in a JP2 file that records `icc` +pub(super) fn write_jpeg2000( + bytes: Vec, + (width, height): (u32, u32), + component_count: usize, + depth: u8, + jp2: bool, + icc: Option<&[u8]>, +) -> Result, String> { + // The encoder reads 16-bit samples little-endian + let bytes = if depth == 16 { bytes.as_chunks::<2>().0.iter().flat_map(|sample| u16::from_ne_bytes(*sample).to_le_bytes()).collect() } else { bytes }; + let components = u16::try_from(component_count).map_err(|_| format!("{component_count} components"))?; + let input = J2kLosslessSamples { data: &bytes, width, height, components, bit_depth: depth, signed: false }; + let codestream = encode_j2k_lossless(input, &J2kLosslessEncodeOptions::default()).map_err(|error| error.to_string())?.codestream; + drop(bytes); + if !jp2 { + return Ok(codestream); + } + + // The last component of LA and RGBA is opacity, for the whole image + let color_count = if component_count >= 3 { 3 } else { 1 }; + let definitions: Vec = (0..components) + .map(|channel_index| { + if channel_index < color_count { + J2kChannelDefinition { + channel_index, + channel_type: J2kChannelType::Color, + association: J2kChannelAssociation::Color { index: channel_index + 1 }, + } + } else { + J2kChannelDefinition { channel_index, channel_type: J2kChannelType::Opacity, association: J2kChannelAssociation::WholeImage } + } + }) + .collect(); + let mut options = J2kFileWrapOptions::jp2(); + options.color = match icc { + Some(profile) if color_count == 3 => J2kFileColorSpec::IccProfile(profile), + _ if color_count == 3 => J2kFileColorSpec::Enumerated(Colorspace::SRgb), + _ => J2kFileColorSpec::Enumerated(Colorspace::Grayscale), + }; + if component_count.is_multiple_of(2) { + options.metadata = J2kFileBoxMetadata { palette: None, component_mappings: &[], channel_definitions: &definitions }; + } + + wrap_j2k_codestream(&codestream, options).map_err(|error| error.to_string()) +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f2134a0c..de1454fc 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -26,6 +26,7 @@ use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; +mod jpeg2000; mod map_override; use encoding::Encoding; pub use map_override::MapOverride; @@ -93,10 +94,14 @@ pub enum FileFormat { Pgm, /// A PSD containing only its merged image. Psd, + /// JPEG 2000 codestream, lossless + J2k, + /// JPEG 2000 in a JP2 file, lossless + Jp2, } impl FileFormat { - pub const ALL: [FileFormat; 11] = [ + pub const ALL: [FileFormat; 13] = [ FileFormat::Png, FileFormat::Jpeg, FileFormat::Tga, @@ -108,6 +113,8 @@ impl FileFormat { FileFormat::Jng, FileFormat::Pgm, FileFormat::Psd, + FileFormat::J2k, + FileFormat::Jp2, ]; pub fn extension(self) -> &'static str { @@ -123,6 +130,8 @@ impl FileFormat { FileFormat::Jng => "jng", FileFormat::Pgm => "pgm", FileFormat::Psd => "psd", + FileFormat::J2k => "j2k", + FileFormat::Jp2 => "jp2", } } @@ -150,7 +159,7 @@ impl FileFormat { /// float for TIFF and HDR). pub fn bit_depths(self) -> &'static [u8] { match self { - FileFormat::Png | FileFormat::Pgm | FileFormat::Psd => &[8, 16], + FileFormat::Png | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2 => &[8, 16], FileFormat::Tiff => &[8, 16, 32], FileFormat::Exr => &[16, 32], FileFormat::Hdr => &[32], @@ -1216,7 +1225,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd | FileFormat::J2k) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1323,6 +1332,11 @@ fn encode( FileFormat::Pgm => CodecFormat::Pnm, FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)), FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), + FileFormat::J2k | FileFormat::Jp2 => { + let profile = embed.and_then(crate::icc::profile); + let jp2 = format == FileFormat::Jp2; + return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, profile.as_deref()).map_err(|error| encoding_error(&error)); + } FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), }; let layout = match component_count { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 392148a1..45312b0d 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -366,8 +366,9 @@ fn every_format_encodes_and_decodes() { let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); preset.maps.push(gray_alpha); - // JNG, PGM and PSD have tests of their own (the image crate reads none of them) - for format in FileFormat::ALL.into_iter().filter(|f| !matches!(f, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd)) { + // JNG, PGM, PSD and JPEG 2000 have tests of their own (the image crate reads none of them) + let own_tests = |format: &FileFormat| matches!(format, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2); + for format in FileFormat::ALL.into_iter().filter(|format| !own_tests(format)) { for &depth in format.bit_depths() { let mut opts = ExportOptions::new(preset.clone()); opts.format_override = Some(format); @@ -917,7 +918,7 @@ fn exr_carries_the_chromaticities_of_the_space() { #[test] fn formats_without_a_place_for_a_colour_space_say_so() { let data = vec![0.25f32; 4 * 4 * 3]; - for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] { + for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr, FileFormat::J2k] { let mut warnings = Vec::new(); encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}"); @@ -1245,6 +1246,70 @@ fn jng_has_jpeg_colour_and_lossless_alpha() { assert!(!gray.bytes.windows(4).any(|w| w == b"IDAT")); } +/// A JPEG 2000 file's component planes +fn jpeg2000_planes(bytes: &[u8]) -> Vec> { + let mut decoder = j2k::J2kDecoder::new(bytes).unwrap(); + let decoded = decoder.decode_native_components().unwrap(); + decoded + .planes() + .iter() + .map(|plane| match plane.bytes_per_sample() { + 1 => plane.data().iter().map(|byte| u16::from(*byte)).collect(), + _ => plane.data().chunks(2).map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect(), + }) + .collect() +} + +#[test] +fn jpeg2000_is_lossless_at_8_and_16_bits() { + let fx = Fx::new(&[Channel::BaseColor, Channel::Opacity, Channel::Roughness, Channel::Metallic, Channel::Normal]); + let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); + let jp2_signature = [0, 0, 0, 12, b'j', b'P', b' ', b' ']; + let codestream_signature = [0xFF, 0x4F, 0xFF, 0x51]; + for depth in [8u8, 16] { + let mut png_options = ExportOptions::new(preset.clone()); + png_options.bit_depth_override = Some(depth); + let png = fx.render(&png_options); + for format in [FileFormat::J2k, FileFormat::Jp2] { + let mut options = png_options.clone(); + options.format_override = Some(format); + let files = fx.render(&options); + assert_eq!(files.len(), png.len()); + + for (file, reference) in files.iter().zip(&png) { + assert!(file.name.ends_with(format.extension()), "{}", file.name); + let signature: &[u8] = if format == FileFormat::Jp2 { &jp2_signature } else { &codestream_signature }; + assert!(file.bytes.starts_with(signature), "{}", file.name); + + // Every sample is the PNG's, with alpha the last component + let image = decode(reference); + let components = usize::from(image.color().channel_count()); + let expected = image.to_rgba16(); + let planes = jpeg2000_planes(&file.bytes); + assert_eq!(planes.len(), components, "{}", file.name); + for (component, plane) in planes.iter().enumerate() { + let source = if components <= 2 && component == 1 { 3 } else { component }; + for (texel, sample) in expected.pixels().zip(plane) { + let want = if depth == 8 { texel[source] / 257 } else { texel[source] }; + assert_eq!(*sample, want, "{} component {component}", file.name); + } + } + } + } + } +} + +#[test] +fn jp2_records_a_chosen_colour_space_as_an_icc_profile() { + let data = vec![0.25f32; 8 * 8 * 3]; + let profile = crate::icc::profile(ColorSpace::AcesCg).unwrap(); + let mut warnings = Vec::new(); + let bytes = + encode(Encoding { format: FileFormat::Jp2, depth: 8, dither: false }, (8, 8), 3, data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); + assert!(bytes.windows(profile.len()).any(|window| window == profile.as_slice()), "the profile is in the file"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + #[test] fn tiff_32f_holds_linear_floats() { let fx = Fx::new(&default_channels()); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 6a46f757..c4a07d5f 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -81,8 +81,8 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [ ("tiff", Some(FileFormat::Tiff)), ("hdr", Some(FileFormat::Hdr)), ("exr", Some(FileFormat::Exr)), - ("j2k", None), - ("jp2", None), + ("j2k", Some(FileFormat::J2k)), + ("jp2", Some(FileFormat::Jp2)), ("webp", Some(FileFormat::Webp)), ("psd", Some(FileFormat::Psd)), ("sbsar", None), diff --git a/crates/ui-egui/tests/it/export_file_types.rs b/crates/ui-egui/tests/it/export_file_types.rs index 8967fe80..a1a020eb 100644 --- a/crates/ui-egui/tests/it/export_file_types.rs +++ b/crates/ui-egui/tests/it/export_file_types.rs @@ -46,22 +46,21 @@ fn entries(h: &Harness<'_, TextureCraftApp>, labels: &[&str]) -> Vec { const TYPES: [&str; 14] = ["bmp", "jpeg", "jng", "pgm", "png", "targa", "tiff", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"]; #[test] -fn the_file_type_list_is_the_reference_one_with_three_greyed() { +fn the_file_type_list_is_the_reference_one_with_sbsar_greyed() { let mut h = harness(); open_combo(&mut h, "Based on output template"); assert_eq!(entries(&h, &TYPES), TYPES.map(String::from).to_vec()); - // Bottom up, so no tooltip covers the next entry - for name in ["sbsar", "jp2", "j2k"] { - assert!(h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} is greyed"); - h.get_all_by_label(name).last().unwrap().scroll_to_me(); - h.run_steps(6); - let at = h.get_all_by_label(name).last().unwrap().rect().center(); - h.hover_at(at); - h.run_steps(30); - assert!(h.query_by_label("Not available yet").is_some(), "{name} at {at:?}"); + assert!(h.get_all_by_label("sbsar").last().unwrap().accesskit_node().is_disabled(), "sbsar is greyed"); + h.get_all_by_label("sbsar").last().unwrap().scroll_to_me(); + h.run_steps(6); + let at = h.get_all_by_label("sbsar").last().unwrap().rect().center(); + h.hover_at(at); + h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "sbsar at {at:?}"); + for name in ["j2k", "jp2", "psd"] { + assert!(!h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} can be picked"); } - assert!(!h.get_all_by_label("psd").last().unwrap().accesskit_node().is_disabled()); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7873145d..c3a44fc8 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -74,7 +74,7 @@ and names it in `warnings`. Materials omit any map with incomplete tiles or a UD shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, -`hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for +`hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and `export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. diff --git a/docs/features.md b/docs/features.md index 42ea07a6..3da74d2d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,7 +164,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in - PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 + PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, From c561a0578fcaac25490603bdb005f35d6efdddde Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:44:12 +0000 Subject: [PATCH 02/34] Export: PSD file type writes every output map of a texture set as a layer of one file The layers and the merged image are written with craft-psd's PsdBuilder. The USD asset and MaterialX leave the PSD out (with a warning for the USD asset). --- crates/engine/src/file_cmds.rs | 19 +- crates/engine/tests/it/materialx.rs | 4 +- crates/engine/tests/it/usd_asset.rs | 13 + crates/formats/src/export/layered_psd.rs | 112 +++++++ crates/formats/src/export/map_renderer.rs | 149 +++++++++ crates/formats/src/export/mod.rs | 370 +++++++++------------ crates/formats/src/export/planned_layer.rs | 10 + crates/formats/src/export/rendered_map.rs | 13 + crates/formats/src/export/tests.rs | 130 +++++--- crates/formats/src/mesh_export/usd.rs | 10 +- crates/ui-egui/src/export_templates.rs | 21 +- crates/ui-egui/src/export_window.rs | 44 ++- 12 files changed, 608 insertions(+), 287 deletions(-) create mode 100644 crates/formats/src/export/layered_psd.rs create mode 100644 crates/formats/src/export/map_renderer.rs create mode 100644 crates/formats/src/export/planned_layer.rs create mode 100644 crates/formats/src/export/rendered_map.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index d13dbee3..70194399 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name and warns about later duplicates)", always, plan ), @@ -457,6 +457,7 @@ fn plan(session: &mut Session, params: &Value) -> Result { "size": size, "sourceSize": source_size, "warnings": output.warnings, + "layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::>(), })); } } @@ -763,7 +764,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s /// warning: the textures of the command are already written. #[cfg(not(target_arch = "wasm32"))] fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Option { - match build_usd_asset(session, dir, exports) { + match build_usd_asset(session, dir, exports, warnings) { Ok(path) => Some(path), Err(error) => { warnings.push(format!("{USD_ASSET_FAILED}: {error}")); @@ -773,7 +774,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset } #[cfg(not(target_arch = "wasm32"))] -fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result { +fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec) -> Result { use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings}; let project = &session.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); @@ -794,6 +795,12 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset // A map that lost any file (a tile of a UDIM map) is not bound: its `` name would read a file it does not own kept.retain(|file| !skipped_maps.contains(&file.map)); + if kept.iter().any(|file| file.format == FileFormat::Psd) { + let warning = format!("The USD asset doesn't read PSD files, so the material of texture set \"{}\" leaves out its PSD maps", texture_set.name); + if !warnings.contains(&warning) { + warnings.push(warning); + } + } by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept)); } } @@ -841,7 +848,7 @@ fn reserve_export_names( plans.retain(|plan| { let name = plan.name.to_ascii_lowercase(); if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) { - blocked_maps.insert(plan.map); + blocked_maps.extend(plan.maps()); warnings.push(format!( "\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names", plan.name @@ -854,7 +861,7 @@ fn reserve_export_names( return true; } - blocked_maps.insert(plan.map); + blocked_maps.extend(plan.maps()); if fallback { warnings.push(format!( "MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names", diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index b69391bd..3f6ba0a9 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -197,8 +197,10 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() { ) .unwrap(); + // A PSD holds every map of the texture set as a layer let all = names(&result); - assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}"); + let template_file = if format == "psd" { ".psd".to_string() } else { format!("_baseColor.{ext}") }; + assert!(all.iter().any(|f| f.ends_with(&template_file)), "{format}: the template's files keep the file type: {all:?}"); let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}")); let text = std::fs::read_to_string(mtlx).unwrap(); let wanted = if format == "tiff" { "tif" } else { "png" }; diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index e6ef7bd9..a370c7e1 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -407,3 +407,16 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { assert!(dir.join(&read.file).is_file(), "{} was written", read.file); } } + +#[test] +fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { + let mut s = ball(); + let dir = temp("psd"); + + let r = export(&mut s, &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!(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}"); +} diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs new file mode 100644 index 00000000..e90f8e6e --- /dev/null +++ b/crates/formats/src/export/layered_psd.rs @@ -0,0 +1,112 @@ +//! A texture set's PSD: each output map a layer, a `/` in its name a layer group + +use craft_psd::{Compression, GroupSpec, LayerSpec, PixelData, PsdBuilder}; +use texturecraft_texel::linear_to_srgb; + +use super::encoding::Encoding; +use super::map_renderer::MapRenderer; +use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer}; +use crate::{FormatError, Result}; + +/// Where alpha sits in an RGBA texel +const ALPHA_INDEX: usize = 3; + +/// Render the layers of `planned` one at a time and write them as one PSD +pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result { + let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; + let size = renderer.size(tile)?; + + // Each layer as straight RGBA in 0-1, sRGB-encoded where the map's file would be, dropped once quantized + let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES]; + let mut pixels = Vec::with_capacity(layers.len()); + let mut embedded = None; + for layer in layers.iter().rev() { + let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; + embedded = map.embed.or(embedded); + let rgba = to_rgba(&map.data, map.component_count, &map.srgb); + drop(map); + over(&mut composite, &rgba); + let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; + let bytes = quantize_integer(encoding, size.0, PSD_RGBA_PLANES, rgba.into_iter())?; + pixels.push((layer.name.as_str(), pixel_data(bytes, bit_depth))); + } + if let Some(space) = embedded { + warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name())); + } + + let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: false }; + let composite = pixel_data(quantize_integer(encoding, size.0, PSD_RGBA_PLANES, composite.into_iter())?, bit_depth); + + let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?; + if bytes.len() as u64 >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!("\"{name}\" would reach the 2 GiB PSD file limit; use a smaller export size or fewer PSD maps"))); + } + + Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings }) +} + +/// L, LA, RGB or RGBA samples as RGBA (gray repeated, opaque without alpha), sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn to_rgba(data: &[f32], component_count: usize, srgb: &[bool]) -> Vec { + let encode = |component: usize, value: f32| if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; + data.chunks_exact(component_count.max(1)) + .flat_map(|texel| { + let encoded = |component| encode(component, texel.get(component).copied().unwrap_or(0.0)); + match component_count { + 1 => [encoded(0), encoded(0), encoded(0), 1.0], + 2 => [encoded(0), encoded(0), encoded(0), encoded(1)], + 3 => [encoded(0), encoded(1), encoded(2), 1.0], + _ => [encoded(0), encoded(1), encoded(2), encoded(3)], + } + }) + .collect() +} + +/// Lay straight-alpha RGBA `layer` over `below`, in place +fn over(below: &mut [f32], layer: &[f32]) { + for (under, top) in below.as_chunks_mut::().0.iter_mut().zip(layer.as_chunks::().0) { + let (top_alpha, under_alpha) = (top[ALPHA_INDEX], under[ALPHA_INDEX]); + let alpha = top_alpha + under_alpha * (1.0 - top_alpha); + if alpha <= 0.0 { + continue; + } + + for (value, top_value) in under.iter_mut().zip(top).take(ALPHA_INDEX) { + *value = (top_value * top_alpha + *value * under_alpha * (1.0 - top_alpha)) / alpha; + } + under[ALPHA_INDEX] = alpha; + } +} + +/// Native-endian quantized RGBA samples as the PSD builder takes them +fn pixel_data(bytes: Vec, depth: u8) -> PixelData { + if depth == 16 { PixelData::Rgba16(bytes.as_chunks::<2>().0.iter().map(|sample| u16::from_ne_bytes(*sample)).collect()) } else { PixelData::Rgba8(bytes) } +} + +/// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front +pub(super) fn write_layers((width, height): (u32, u32), depth: u8, layers: Vec<(&str, PixelData)>, composite: PixelData) -> craft_psd::Result> { + let mut builder = PsdBuilder::new(width, height).depth(u16::from(depth)).compression(Compression::Raw); + + // The builder stacks bottom up, so the groups open and close in that order too + let mut open: Vec<&str> = Vec::new(); + for (path, pixels) in layers { + let mut parts: Vec<&str> = path.split('/').collect(); + let name = parts.pop().unwrap_or_default(); + let shared = open.iter().zip(&parts).take_while(|(open, part)| open == part).count(); + for _ in shared..open.len() { + builder.end_group()?; + } + open.truncate(shared); + for group in parts.iter().skip(shared) { + builder.begin_group(GroupSpec::new(*group)); + open.push(group); + } + + builder.push_layer(LayerSpec::new(name, 0, 0, width, height, pixels)); + } + for _ in open { + builder.end_group()?; + } + + builder.composite(composite); + builder.to_bytes() +} diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs new file mode 100644 index 00000000..c19064c5 --- /dev/null +++ b/crates/formats/src/export/map_renderer.rs @@ -0,0 +1,149 @@ +use rayon::prelude::*; +use texturecraft_core::{TextureSet, TileGrid}; +use texturecraft_texel::{ColorSpace, DilationMap}; + +use super::rendered_map::RenderedMap; +use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, 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 +pub(super) struct MapRenderer<'a> { + options: &'a ExportOptions, + set: &'a TextureSet, + sampler: Sampler<'a>, + dilation_map: 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, +} + +impl<'a> MapRenderer<'a> { + pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> 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) { + return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); + } + + if input.coverage.len() != width as usize * height as usize { + 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 { + 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)), + }; + let sampler = Sampler { + set, + comp: input.composite, + baked: input.baked, + coverage: input.coverage, + res: width, + tile_res, + scales: set.block_scales(), + normal_override: options.normal_format, + project_normal: input.project.normal_format, + }; + Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) + } + + /// The export size of a file of `tile` (None: the whole set). + pub(super) fn size(&self, tile: Option) -> Result<(u32, u32)> { + 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.size); + Ok((scale(w), scale(h))) + } + + /// The composite texels a file of `tile` covers: one tile, or the whole set + fn region(&self, tile: Option) -> Result<(u32, u32, u32, u32)> { + match (tile, self.grid) { + (Some(t), Some(g)) => { + let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; + + // A tile smaller than its block fills the block's top-left corner + let side = tile_side(self.set, t, self.tile_res); + Ok((bx * self.tile_res, by * self.tile_res, side, side)) + } + _ => Ok((0, 0, self.width, self.height)), + } + } + + /// Map `map_index` of the preset for `tile`, as `format` at `bit_depth` holds it + pub(super) fn render(&self, map_index: usize, tile: Option, format: FileFormat, bit_depth: u8) -> Result { + let options = self.options; + let map = options.preset.maps.get(map_index).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; + 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 (x0, y0, w, h) = self.region(tile)?; + let size = self.size(tile)?; + let sampler = &self.sampler; + let dilation_map = self.dilation_map.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 Some(at) = at else { continue }; + let mut cache = None; + for (component, (_, source)) in channel_layout.iter().enumerate() { + 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 }; + } + } + } + }); + + // Diffuse into the texels the dilation did not reach + if matches!(options.padding, Padding::DilationDiffusion(_)) { + let known: Vec = (y0..y0 + h) + .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) + .map(|(x, y)| sampler.covered(x, y) || dilation_map.is_some_and(|d| d.source(x, y).is_some())) + .collect(); + + // Keep diffusion within each UV tile when rendering an atlas + 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, &known, block as usize); + } + + let mut data = resize(data, (w, h), component_count, size); + + // Integer sRGB converts in `encode`; other color spaces convert here + let space = options.space_for_map(map, format, bit_depth); + let float = format.holds_float(bit_depth); + let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; + if convert { + data.par_chunks_mut(component_count).for_each(|px| { + if let [r, g, b, ..] = px { + [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); + } + }); + } + let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); + + // A colour space the user chose is written into the colour maps (data maps have none) + let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); + Ok(RenderedMap { data, size, component_count, srgb, embed }) + } +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index de1454fc..6a07413e 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -21,15 +21,21 @@ use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; -use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; +use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; mod jpeg2000; +mod layered_psd; mod map_override; +mod map_renderer; +mod planned_layer; +mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; +use map_renderer::MapRenderer; +pub use planned_layer::PlannedLayer; /// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture /// width tilts the normal 45°, at any resolution. @@ -37,6 +43,8 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; 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; const MAX_TEMPLATE: usize = 256; @@ -92,7 +100,7 @@ pub enum FileFormat { Jng, /// Portable graymap (binary). Pgm, - /// A PSD containing only its merged image. + /// Photoshop document: every output map of a texture set in this format as a layer of one file Psd, /// JPEG 2000 codestream, lossless J2k, @@ -517,6 +525,16 @@ pub struct PlannedFile { /// covers every tile refers to); None when the file isn't tiled. pub udim_name: Option, pub warnings: Vec, + /// A PSD's output maps, top layer first (`map` is the first); empty for a file of one map + pub layers: Vec, +} + +impl PlannedFile { + /// The output maps the file writes + pub fn maps(&self) -> impl Iterator + '_ { + let own = self.layers.is_empty().then_some(self.map); + own.into_iter().chain(self.layers.iter().map(|layer| layer.map)) + } } // --------------------------------------------------------------------------------------------- @@ -592,8 +610,7 @@ pub fn sanitize_file_path(s: &str) -> String { s.split('/').map(sanitize_file_stem).collect::>().join("/") } -/// The files `opts` produces for texture set `ts`, without rendering (for the export dialog). -/// Template variables: [`FILE_TOKENS`]. +/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; @@ -607,9 +624,10 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let mut active_files = BTreeSet::new(); let mut active_dirs = BTreeSet::new(); let mut out = Vec::new(); + + // Maps written as PSD layers, with their tile, bit depth and warnings + let mut psd_layers: Vec<(Option, PlannedLayer, u8, Vec)> = Vec::new(); let tiles: Vec> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() }; - let grid = set.tile_grid(); - let block_resolution = set.block_resolution(); for (i, map) in opts.preset.maps.iter().enumerate() { if !map.channels.iter().any(|(_, s)| source_present(set, s)) { continue; @@ -619,7 +637,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let format = own.and_then(|o| o.format).or(opts.format_override).unwrap_or(map.format); let bit_depth = format.depth(own.and_then(|o| o.bit_depth).or(opts.bit_depth_override).unwrap_or(map.bit_depth)); let enabled = own.is_none_or(|o| o.enabled); - let psd_channels = (enabled && format == FileFormat::Psd).then(|| layout(set, map).len()); let dither = bit_depth == 8 && !format.holds_float(bit_depth) && own.and_then(|o| o.dither).unwrap_or(opts.dither); let space = opts.space_for_map(map, format, bit_depth); let requested_space = opts.space_for_depth(format, bit_depth); @@ -636,25 +653,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export // Append `$udim` to names for separate UV tiles let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; for &tile in &tiles { - if let Some(channels) = psd_channels { - let size = match (tile, grid) { - (Some(tile), Some(_)) => { - let side = tile_side(set, tile, block_resolution); - let side = scale_export_side(side, block_resolution, opts.size); - (side, side) - } - (_, Some(grid)) => { - let side = opts.size.unwrap_or(block_resolution); - (side.saturating_mul(grid.cols), side.saturating_mul(grid.rows)) - } - (_, None) => { - let side = opts.size.unwrap_or(block_resolution); - (side, side) - } - }; - check_psd_size(size, channels, bit_depth)?; - } - // A name of the project, mesh or texture set never adds a folder let no_folder = |name: &str| name.replace('/', "_"); let stem = template @@ -678,7 +676,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export }); let stem = sanitize_file_path(&stem); let ext = format.extension(); - let mut name = format!("{stem}.{ext}"); let mut warnings = Vec::new(); if color_map && format == FileFormat::Pgm @@ -698,51 +695,123 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export format.extension().to_uppercase() )); } + let packs_colour = |name: &str| { + (color_map && requested_space != space) + .then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())) + }; - // Compare names case-insensitively for Windows and macOS - let mut k = 2; - while used.contains(&name.to_ascii_lowercase()) { - name = format!("{stem}_{k}.{ext}"); - k += 1; + // The PSD's own name holds the tile number, so its layers are named without the one appended + if format == FileFormat::Psd { + if enabled { + let appended = tile.filter(|_| template != map.file).map(|number| format!(".{number}")); + let name = appended.as_deref().and_then(|suffix| stem.strip_suffix(suffix)).unwrap_or(&stem).to_string(); + warnings.extend(packs_colour(&name)); + psd_layers.push((tile, PlannedLayer { map: i, name, dither }, bit_depth, warnings)); + } + continue; } - if k > 2 { - warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); - } - let lower = name.to_ascii_lowercase(); - used.insert(lower.clone()); + + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); if !enabled { continue; } - if active_dirs.contains(&lower) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); - } - let mut prefix = lower.as_str(); - while let Some((folder, _)) = prefix.rsplit_once('/') { - if active_files.contains(folder) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); - } - active_dirs.insert(folder.to_owned()); - prefix = folder; - } - active_files.insert(lower); - - if color_map && requested_space != space { - warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())); - } + claim_path(&mut active_files, &mut active_dirs, &name)?; + warnings.extend(packs_colour(&name)); // Use a UDIM name only when substituting its tile recovers the output name // Truncation or literal placeholder text can make that substitution ambiguous - let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| { - let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() }; - format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "") - }); - out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings }); + let udim_name = token_stem + .filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)) + .map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "")); + out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() }); } } + + // Each tile's PSD maps are the layers of one file named after the texture set + let psd_stem = sanitize_file_stem(&format!("{mesh_name}_{}", set.name)); + for &tile in &tiles { + let in_tile: Vec<_> = psd_layers.iter().filter(|(layer_tile, ..)| *layer_tile == tile).collect(); + let Some((_, first, ..)) = in_tile.first() else { continue }; + + let bit_depth = in_tile.iter().map(|(_, _, depth, _)| *depth).max().unwrap_or(8); + let folder_count: usize = in_tile.iter().map(|(_, layer, ..)| layer.name.matches('/').count()).sum(); + check_psd_size(psd_size(set, tile, opts.size), in_tile.len(), folder_count, bit_depth)?; + + let mut warnings: Vec = Vec::new(); + for warning in in_tile.iter().flat_map(|(.., layer_warnings)| layer_warnings) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + let stem = sanitize_file_stem(&tile.map_or_else(|| psd_stem.clone(), |number| format!("{psd_stem}.{number}"))); + let ext = FileFormat::Psd.extension(); + let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + claim_path(&mut active_files, &mut active_dirs, &name)?; + let udim_name = tile.filter(|number| stem == format!("{psd_stem}.{number}")).map(|_| format!("{psd_stem}.{renamed}.{ext}")); + let layers: Vec = in_tile.iter().map(|(_, layer, ..)| layer.clone()).collect(); + let dither = layers.iter().any(|layer| layer.dither); + out.push(PlannedFile { name, map: first.map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers }); + } Ok(out) } +/// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added +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; + while used.contains(&name.to_ascii_lowercase()) { + renamed = format!("_{k}"); + name = format!("{stem}{renamed}.{ext}"); + k += 1; + } + if !renamed.is_empty() { + warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\"")); + } + + used.insert(name.to_ascii_lowercase()); + (name, renamed) +} + +/// Record exported file `name` and its folders, refusing a name that is already a folder or a folder that is already a file, ignoring case +fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: &str) -> Result<()> { + let lower = name.to_ascii_lowercase(); + if dirs.contains(&lower) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder"))); + } + + let mut prefix = lower.as_str(); + while let Some((folder, _)) = prefix.rsplit_once('/') { + if files.contains(folder) { + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); + } + dirs.insert(folder.to_owned()); + prefix = folder; + } + files.insert(lower); + Ok(()) +} + +/// The size of a texture set's PSD 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); + (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) + } + } +} + /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { let mut files = Vec::new(); @@ -906,137 +975,23 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result) -> 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) { - return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name))); - } - - if input.coverage.len() != width as usize * height as usize { - return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len()))); - } - if planned.is_empty() { return Ok(Vec::new()); } - // Padding stays inside each UV tile - let dilation_map = 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)), - }; - let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); - let diffuse = matches!(options.padding, Padding::DilationDiffusion(_)); - let sampler = Sampler { - set, - comp: input.composite, - baked: input.baked, - coverage: input.coverage, - res: width, - tile_res, - scales: set.block_scales(), - normal_override: options.normal_format, - project_normal: input.project.normal_format, - }; - + let renderer = MapRenderer::new(input, options)?; planned .into_iter() .map(|planned_file| { - let map = options.preset.maps.get(planned_file.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?; - let channel_layout = layout(set, map); - let component_count = channel_layout.len(); - let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); - - // The texels written: one tile, or the whole set - let (x0, y0, w, h) = match (planned_file.tile, grid) { - (Some(t), Some(g)) => { - let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?; - - // A tile smaller than its block fills the block's top-left corner - let side = tile_side(set, t, tile_res); - (bx * tile_res, by * tile_res, side, side) - } - _ => (0, 0, width, height), - }; - - // An atlas scales by the requested size per tile - let scale = |value| scale_export_side(value, tile_res, options.size); - let size = (scale(w), scale(h)); if planned_file.format == FileFormat::Psd { - check_psd_size(size, component_count, planned_file.bit_depth)?; + return layered_psd::render_psd(&renderer, planned_file); } - 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.as_ref().and_then(|d| d.source(x, y)) { - Some((sx, sy)) => Some(At::Texel(sx, sy)), - None => beyond_default.then_some(At::Default), - } - }; - let Some(at) = at else { continue }; - let mut cache = None; - for (component, (_, source)) in channel_layout.iter().enumerate() { - 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 }; - } - } - } - }); - - // Diffuse into the texels the dilation did not reach - if diffuse { - let known: Vec = (y0..y0 + h) - .flat_map(|y| (x0..x0 + w).map(move |x| (x, y))) - .map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some())) - .collect(); - - // Keep diffusion within each UV tile when rendering an atlas - let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) }; - diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, block as usize); - } - - let mut data = resize(data, (w, h), component_count, size); - - // Integer sRGB converts in `encode`; other color spaces convert here - let space = options.space_for_map(map, planned_file.format, planned_file.bit_depth); - let float = planned_file.format.holds_float(planned_file.bit_depth); - let rgb = component_count >= 3; + let map = renderer.render(planned_file.map, planned_file.tile, planned_file.format, planned_file.bit_depth)?; let mut warnings = planned_file.warnings; - let color_map = map.is_color(); - let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709; - - if convert { - data.par_chunks_mut(component_count).for_each(|px| { - if let [r, g, b, ..] = px { - [*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]); - } - }); - } - let srgb: Vec = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - - // A colour space the user chose is written into the colour maps (data maps have none) - let embed = (options.color_space.is_some() && color_map && rgb).then_some(space); - let bytes = encode( - Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }, - size, - component_count, - data, - &srgb, - embed, - &mut warnings, - )?; - Ok(ExportedFile { name: planned_file.name, bytes, width: size.0, height: size.1, warnings }) + let encoding = Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither }; + let bytes = encode(encoding, map.size, map.component_count, map.data, &map.srgb, map.embed, &mut warnings)?; + Ok(ExportedFile { name: planned_file.name, bytes, width: map.size.0, height: map.size.1, warnings }) }) .collect() } @@ -1225,7 +1180,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd | FileFormat::J2k) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::J2k) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1330,7 +1285,6 @@ fn encode( FileFormat::Bmp => CodecFormat::Bmp, FileFormat::Webp => CodecFormat::WebP, FileFormat::Pgm => CodecFormat::Pnm, - FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)), FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), FileFormat::J2k | FileFormat::Jp2 => { let profile = embed.and_then(crate::icc::profile); @@ -1338,6 +1292,7 @@ fn encode( return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, profile.as_deref()).map_err(|error| encoding_error(&error)); } FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), + FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")), }; let layout = match component_count { 1 => ChannelLayout::Gray, @@ -1384,35 +1339,38 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp Ok(bytes) } -fn check_psd_size((width, height): (u32, u32), channels: usize, depth: u8) -> Result<()> { +/// The PSD file of a texture set (its merged image and `layer_count` RGBA layers in `folder_count` groups) must fit PSD's side and 2 GiB limits +fn check_psd_size((width, height): (u32, u32), layer_count: usize, folder_count: usize, depth: u8) -> Result<()> { + // A layer record with its names, and each of a group's two records, stays below this + const PSD_RECORD_BYTES: u64 = 2048; + if width == 0 || height == 0 || width > PSD_MAX_SIDE_PIXELS || height > PSD_MAX_SIDE_PIXELS { return Err(FormatError::Invalid(format!("PSD size {width}×{height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side"))); } - // Measure the flat file's overhead without allocating any pixel buffers - let overhead = flat_psd((width, height), channels, depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; - let sample_bytes = u64::from(width) * u64::from(height) * channels as u64 * u64::from(depth / 8); - if overhead + sample_bytes >= PSD_MAX_FILE_BYTES { - return Err(FormatError::Invalid(format!("PSD size {width}×{height} would reach the 2 GiB file limit; use a smaller export size or another format"))); + // Measure the merged image's overhead without allocating any pixel buffers + let merged = flat_psd((width, height), depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?; + let records = PSD_RECORD_BYTES * (layer_count as u64 + 2 * folder_count as u64); + let planes = PSD_RGBA_PLANES as u64 * (1 + layer_count as u64); + let sample_bytes = u64::from(width) * u64::from(height) * planes * u64::from(depth / 8); + if merged + records + sample_bytes >= PSD_MAX_FILE_BYTES { + return Err(FormatError::Invalid(format!( + "a PSD of {layer_count} maps at {width}×{height} would reach the 2 GiB file limit; use a smaller export size, fewer PSD maps or another format" + ))); } Ok(()) } -fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_psd::PsdFile { - use craft_psd::{ColorMode, Compression, Header, ImageData, ImageResource, PsdFile, Version}; - - const PSD_ALPHA_NAMES_RESOURCE_ID: u16 = 1006; - let color_mode = if channels <= 2 { ColorMode::Grayscale } else { ColorMode::Rgb }; - let header = Header::new(Version::Psd, width, height, channels as u16, u16::from(depth), color_mode); - - // A Pascal name marks the extra plane as a channel separate from merged transparency - let resources = if matches!(channels, 2 | 4) { vec![ImageResource::new(PSD_ALPHA_NAMES_RESOURCE_ID, b"\x05Alpha".to_vec())] } else { Vec::new() }; +/// A PSD of only an RGBA merged image with no pixels yet, to measure +fn flat_psd((width, height): (u32, u32), depth: u8) -> craft_psd::PsdFile { + use craft_psd::{ColorMode, Compression, Header, ImageData, PsdFile, Version}; + let header = Header::new(Version::Psd, width, height, PSD_RGBA_PLANES as u16, u16::from(depth), ColorMode::Rgb); PsdFile { header, color_mode_data: Vec::new(), - resources, + resources: Vec::new(), layer_info: None, layer_info_placement: Default::default(), global_layer_mask: None, @@ -1423,26 +1381,6 @@ fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_ps } } -/// Write a merged PSD image with raw planes, including an extra alpha plane when present. -fn psd(bytes: Vec, size: (u32, u32), channels: usize, depth: u8) -> craft_psd::Result> { - let mut file = flat_psd(size, channels, depth); - let planes = &mut file.image_data.data; - planes.try_reserve_exact(bytes.len()).map_err(|_| craft_psd::PsdError::OutOfMemory("cannot allocate PSD planes"))?; - if depth == 16 { - let samples = bytes.as_chunks::<2>().0; - for channel in 0..channels { - planes.extend(samples.iter().skip(channel).step_by(channels).flat_map(|sample| u16::from_ne_bytes(*sample).to_be_bytes())); - } - } else { - for channel in 0..channels { - planes.extend(bytes.iter().skip(channel).step_by(channels).copied()); - } - } - drop(bytes); - - file.to_bytes() -} - /// A JNG file: the colour as JPEG, alpha (when present) as lossless 8-bit deflate data. fn jng(bytes: &[u8], (w, h): (u32, u32), n: usize) -> std::result::Result, String> { use std::io::Write; diff --git a/crates/formats/src/export/planned_layer.rs b/crates/formats/src/export/planned_layer.rs new file mode 100644 index 00000000..4f0adf39 --- /dev/null +++ b/crates/formats/src/export/planned_layer.rs @@ -0,0 +1,10 @@ +/// An output map written as a layer of a texture set's PSD (see [`super::list_outputs`]) +#[derive(Clone, Debug, PartialEq)] +pub struct PlannedLayer { + /// Index into the preset's maps + pub map: usize, + /// The map's file name, a `/` separating the groups the layer sits in + pub name: String, + /// 8-bit samples written with dithering + pub dither: bool, +} diff --git a/crates/formats/src/export/rendered_map.rs b/crates/formats/src/export/rendered_map.rs new file mode 100644 index 00000000..df388464 --- /dev/null +++ b/crates/formats/src/export/rendered_map.rs @@ -0,0 +1,13 @@ +use texturecraft_texel::ColorSpace; + +/// One output map's linear samples at its export size, ready to encode +pub(super) struct RenderedMap { + /// Interleaved L, LA, RGB or RGBA samples + pub data: Vec, + pub size: (u32, u32), + pub component_count: usize, + /// Per component: whether encoding applies the sRGB transfer + pub srgb: Vec, + /// The colour space recorded in the file, when the user chose one for a colour map + pub embed: Option, +} diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 45312b0d..1cdf688e 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1122,45 +1122,89 @@ fn pgm_is_a_binary_graymap() { } #[test] -fn psd_holds_the_merged_image_planar() { +fn psd_holds_every_map_as_a_layer_over_their_merged_image() { let fx = Fx::new(&default_channels()); - let f = &fx.render(&one_map(FileFormat::Psd, 8, rgba_half_alpha()))[0]; - let b = &f.bytes; - assert_eq!(&b[0..4], b"8BPS"); - assert_eq!(u16::from_be_bytes([b[12], b[13]]), 4, "channels"); - assert_eq!((u32::from_be_bytes(b[14..18].try_into().unwrap()), u32::from_be_bytes(b[18..22].try_into().unwrap())), (64, 64)); - assert_eq!((u16::from_be_bytes([b[22], b[23]]), u16::from_be_bytes([b[24], b[25]])), (8, 3), "8-bit RGB"); - let parsed = craft_psd::PsdFile::from_bytes(b).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 4 * 64 * 64); - let plane = |c: usize| &samples[c * 64 * 64..(c + 1) * 64 * 64]; - assert!(plane(3).iter().all(|a| *a == 128), "alpha plane"); - let png = decode(&fx.render(&one_map(FileFormat::Png, 8, rgba_half_alpha()))[0]).to_rgba8(); - assert_eq!(plane(0)[64 * 10 + 40], png.get_pixel(40, 10)[0], "the red plane holds the same values as a PNG"); + let mut png_options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); + png_options.bit_depth_override = Some(8); + let pngs = fx.render(&png_options); + let mut options = png_options.clone(); + options.format_override = Some(FileFormat::Psd); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, roughness()))[0]; - assert_eq!((u16::from_be_bytes([f16.bytes[12], f16.bytes[13]]), u16::from_be_bytes([f16.bytes[22], f16.bytes[23]])), (1, 16)); - assert_eq!(f16.bytes.len(), 26 + 12 + 2 + 2 * 64 * 64); + let planned = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + let files = fx.render(&options); - let mut gray_alpha = roughness(); - gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); - let f16 = &fx.render(&one_map(FileFormat::Psd, 16, gray_alpha))[0]; - let parsed = craft_psd::PsdFile::from_bytes(&f16.bytes).unwrap(); - assert!(!parsed.merged_has_alpha()); - assert_eq!(parsed.alpha_channel_names(), ["Alpha"]); - let samples = parsed.decode_merged().unwrap(); - assert_eq!(samples.len(), 2 * 2 * 64 * 64); - assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0])); + assert_eq!(planned.len(), 1, "one PSD for the texture set: {planned:?}"); + assert_eq!(planned[0].layers.len(), pngs.len()); + assert_eq!(files.len(), 1); + assert_eq!(files[0].name, "sphere_Body_Set.psd"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layers: Vec<_> = parsed.iter_layers().collect(); + assert_eq!(layers.len(), pngs.len()); + + // The file stacks bottom up, so the first map is the top layer + for (layer, png) in layers.iter().rev().zip(&pngs) { + assert_eq!(format!("{}.png", layer.name()), png.name); + assert_eq!(layer.rgba8().unwrap().data, decode(png).to_rgba8().into_raw(), "{}: the layer holds the map's texels", png.name); + } + let top = layers.last().unwrap().rgba8().unwrap().data; + assert!(top.as_chunks::<4>().0.iter().all(|texel| texel[3] == u8::MAX), "the base colour is opaque"); + assert_eq!(parsed.composite_rgba8().unwrap().data, top, "the merged image shows the opaque top layer"); + + options.bit_depth_override = Some(16); + let deep = &fx.render(&options)[0]; + assert_eq!(craft_psd::PsdFile::from_bytes(&deep.bytes).unwrap().header.depth, 16); +} + +#[test] +fn psd_folder_templates_become_layer_groups_of_one_file_not_folders() { + let fx = Fx::new(&default_channels()); + let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 }); + let preset = ExportPreset { name: "t".into(), maps: vec![rough("Body/$textureSet_Rough"), rough("Top/Inner/Leaf"), rough("Mask")] }; + let mut options = ExportOptions::new(preset); + options.format_override = Some(FileFormat::Psd); + + let files = fx.render(&options); + + assert_eq!(files.iter().map(|f| f.name.as_str()).collect::>(), ["sphere_Body_Set.psd"], "no folder for a PSD's layers"); + let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + + // The tree lists bottom up and the first map is the top layer + let groups: Vec<_> = tree.iter().rev().filter(|node| node.is_group()).map(name).collect(); + assert_eq!(groups, ["Body", "Top"]); + let body = tree.iter().find(|node| node.is_group() && name(node) == "Body").unwrap(); + assert_eq!(body.children().iter().map(name).collect::>(), ["Body_Set_Rough"], "$textureSet is filled in inside a layer name"); + assert!(tree.iter().any(|node| !node.is_group() && name(node) == "Mask")); +} + +#[test] +fn psd_layer_groups_follow_the_slashes_of_their_names() { + let pixel = || craft_psd::PixelData::Rgba8(vec![10, 20, 30, 255]); + let layers = vec![("Mask", pixel()), ("Body/Rough", pixel()), ("Body/Color", pixel()), ("Top/Inner/Leaf", pixel())]; + + let bytes = layered_psd::write_layers((1, 1), 8, layers, pixel()).unwrap(); + + let parsed = craft_psd::PsdFile::from_bytes(&bytes).unwrap(); + let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name(); + let tree = parsed.layer_tree(); + assert_eq!( + tree.iter().map(|node| (name(node), node.is_group())).collect::>(), + [("Mask".to_string(), false), ("Body".to_string(), true), ("Top".to_string(), true)] + ); + assert_eq!(tree[1].children().iter().map(name).collect::>(), ["Rough", "Color"]); + let inner = &tree[2].children()[0]; + assert!(inner.is_group() && name(inner) == "Inner"); + assert_eq!(inner.children().iter().map(name).collect::>(), ["Leaf"]); } #[test] fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { let mut fx = Fx::new(&default_channels()); - fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + // Four tile columns: the atlas is 32768 wide, each tile's layer and merged image well under 2 GiB + fx.project.texture_sets[0].uv_tiles = vec![1001, 1004]; let mut options = one_map(FileFormat::Psd, 8, roughness()); - options.size = Some(16_384); + options.size = Some(8192); options.atlas = true; let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); @@ -1171,7 +1215,7 @@ fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() { } #[test] -fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { +fn psd_plan_counts_every_layer_against_the_version_one_byte_limit() { let fx = Fx::new(&default_channels()); let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha()); options.size = Some(16_384); @@ -1179,19 +1223,23 @@ fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() { let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); assert!(error.to_string().contains("PSD") && error.to_string().contains("2 GiB"), "{error}"); - options.bit_depth_override = Some(8); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); - options.bit_depth_override = None; - options.preset.maps[0].channels.pop(); - assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); + options.size = Some(8192); + for copy in ["second", "third"] { + assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1); + let mut map = options.preset.maps[0].clone(); + map.file = copy.into(); + options.preset.maps.push(map); + } + let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); + assert!(error.to_string().contains("3 maps") && error.to_string().contains("2 GiB"), "{error}"); } #[test] -fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() { - // These RGBA16 planes are 32 bytes below 2 GiB before headers and the alpha name - let (width, height) = (10_924, 24_573); - assert!(check_psd_size((width, height), 4, 16).is_err()); - assert!(check_psd_size((width, height - 1), 4, 16).is_ok()); +fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() { + // One RGBA16 layer and the merged image: 87360 bytes over 2 GiB, a row less 87424 bytes below + let (width, height) = (10_924, 12_287); + assert!(check_psd_size((width, height), 1, 0, 16).is_err()); + assert!(check_psd_size((width, height - 1), 1, 0, 16).is_ok()); let mut fx = Fx::new(&default_channels()); fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011]; diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 49125502..db2c514d 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -386,11 +386,16 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: /// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, /// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has /// no data for. `project_normal` is the project's normal convention, used by normal maps that -/// follow it. +/// follow it. A PSD holds several maps as layers, so it binds nothing pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { let mut out: Vec = Vec::new(); let mut seen_maps = Vec::new(); for file in files { + // A PSD's merged image is no one map's texture + if file.format == FileFormat::Psd { + continue; + } + // The first tile stands for all the tiles of a map if seen_maps.contains(&file.map) { continue; @@ -412,7 +417,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm } let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; - let normal = (slot == 3).then(|| { + let normal = (SLOTS[slot].0 == "Normal").then(|| { opts.normal_format.unwrap_or(match source { SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, @@ -585,6 +590,7 @@ mod texture_binding_tests { tile: None, udim_name: None, warnings: Vec::new(), + layers: Vec::new(), } } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index beaf660f..3e7ab2b6 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -928,10 +928,25 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result { + for layer in layers { + let name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); + if let Some(slot) = index(layer).and_then(|i| names.get_mut(i)) { + *slot = Some(format!("{file} › {name}")); + } + } + } + None => { + if let Some(slot) = index(f).and_then(|i| names.get_mut(i)) { + *slot = Some(file.to_string()); + } + } } } Ok(names) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c4a07d5f..c7f8b11f 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -533,28 +533,36 @@ fn file_type_text(t: &FileType) -> String { /// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { - let mut p = set_params(app, ts); - if let Some(o) = p.as_object_mut() { - o.remove("maps"); + let mut params = set_params(app, ts); + if let Some(object) = params.as_object_mut() { + object.remove("maps"); } let preset = app.session.export_preset(&set_template(app, ts)); - let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", &p) else { return Vec::new() }; + let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", ¶ms) else { return Vec::new() }; let mut rows: Vec = Vec::new(); - for f in plan.as_array().into_iter().flatten() { - let Some(map) = f.get("map").and_then(serde_json::Value::as_u64).map(|m| m as usize) else { continue }; - if rows.iter().any(|r| r.map == map) { - continue; - } + let index = |value: &serde_json::Value| value.get("map").and_then(serde_json::Value::as_u64).map(|map| map as usize); + for file in plan.as_array().into_iter().flatten() { + // A PSD writes each of its layers' maps + let layers = file.get("layers").and_then(serde_json::Value::as_array).filter(|layers| !layers.is_empty()); + let maps: Vec = match layers { + Some(layers) => layers.iter().filter_map(index).collect(), + None => index(file).into_iter().collect(), + }; + for map in maps { + if rows.iter().any(|row| row.map == map) { + continue; + } - let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); - let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; - let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); - let pattern = preset - .as_ref() - .and_then(|p| p.maps.get(map)) - .map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m))) - .unwrap_or_default(); - rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); + let format = file.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string(); + let bit_depth = file.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8; + let dithering = file.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false); + let pattern = preset + .as_ref() + .and_then(|preset| preset.maps.get(map)) + .map(|map_spec| map_spec.file.replace("$channel", texturecraft_engine::formats::export::channel_label(map_spec))) + .unwrap_or_default(); + rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } }); + } } rows } From 269bfb02707a9961c35f3bffafcd0c7a676db9d4 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:48:11 +0000 Subject: [PATCH 03/34] Export: an output map can have its own size, which wins over the export size A texture set's Output maps row has a size list (Export size, or 128x128 to 8192x8192); file.exportTextures and export.plan take it as maps[].size, and a PSD is as large as its largest layer. --- crates/engine/src/file_cmds.rs | 14 +++++-- crates/engine/tests/it/export_file_types.rs | 12 ++++++ crates/formats/src/export/layered_psd.rs | 12 +++--- crates/formats/src/export/map_override.rs | 5 ++- crates/formats/src/export/map_renderer.rs | 8 ++-- crates/formats/src/export/mod.rs | 21 +++++++--- crates/formats/src/export/tests.rs | 27 +++++++++++++ crates/ui-egui/src/export_window.rs | 22 ++++++++++- crates/ui-egui/src/state/map_export.rs | 5 ++- crates/ui-egui/src/state/set_export.rs | 6 ++- .../ui-egui/tests/it/export_map_overrides.rs | 39 ++++++++++++++++++- crates/ui-egui/tests/it/output_templates.rs | 10 ++--- 12 files changed, 151 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 70194399..f29efdf9 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -375,12 +375,12 @@ pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result Result> { let mut overrides = std::collections::BTreeMap::new(); let Some(list) = params.get("maps").filter(|value| !value.is_null()) else { return Ok(overrides) }; - let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?}"))?; + let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?, size?}"))?; for settings in list { let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count); let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?; @@ -399,6 +399,10 @@ fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result Result { 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 size = scale_export_side(source_size, block_size, options.size); + + // 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); files.push(json!({ "ts": set_index, diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index e4f0e56f..70355b80 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -27,3 +27,15 @@ fn the_new_file_types_dithering_and_diffusion_export() { assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == false), "float files are never dithered"); assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err()); } + +#[test] +fn a_map_size_wins_over_the_export_size_in_the_plan() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + + let plan = execute(&mut s, "export.plan", &json!({"ts": 0, "size": 512, "maps": [{"map": 0, "size": 128}]})).unwrap(); + + let files = plan.as_array().unwrap(); + assert!(files.iter().filter(|file| file["map"] == 0).all(|file| file["size"] == 128), "{plan}"); + assert!(files.iter().filter(|file| file["map"] != 0).all(|file| file["size"] == 512), "{plan}"); + assert!(execute(&mut s, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err()); +} diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index e90f8e6e..9064de7f 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -5,16 +5,17 @@ use texturecraft_texel::linear_to_srgb; use super::encoding::Encoding; use super::map_renderer::MapRenderer; -use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer}; +use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer, resize}; use crate::{FormatError, Result}; /// Where alpha sits in an RGBA texel const ALPHA_INDEX: usize = 3; -/// Render the layers of `planned` one at a time and write them as one PSD +/// Render the layers of `planned` one at a time and write them as one PSD the size of the largest; smaller maps are scaled up to it pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result { let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; - let size = renderer.size(tile)?; + let sizes = layers.iter().map(|layer| renderer.size(layer.map, tile)).collect::>>()?; + let size = sizes.into_iter().max_by_key(|(width, height)| u64::from(*width) * u64::from(*height)).unwrap_or((1, 1)); // Each layer as straight RGBA in 0-1, sRGB-encoded where the map's file would be, dropped once quantized let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES]; @@ -23,8 +24,9 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result for layer in layers.iter().rev() { let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; embedded = map.embed.or(embedded); - let rgba = to_rgba(&map.data, map.component_count, &map.srgb); - drop(map); + let data = resize(map.data, map.size, map.component_count, size); + let rgba = to_rgba(&data, map.component_count, &map.srgb); + drop(data); over(&mut composite, &rgba); let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; let bytes = quantize_integer(encoding, size.0, PSD_RGBA_PLANES, rgba.into_iter())?; diff --git a/crates/formats/src/export/map_override.rs b/crates/formats/src/export/map_override.rs index 5ea62f5c..aec6ef56 100644 --- a/crates/formats/src/export/map_override.rs +++ b/crates/formats/src/export/map_override.rs @@ -14,10 +14,13 @@ pub struct MapOverride { /// Instead of the export's dithering of 8-bit files. #[serde(default)] pub dither: Option, + /// Output size (power of two) instead of the export's + #[serde(default)] + pub size: Option, } impl Default for MapOverride { fn default() -> Self { - MapOverride { enabled: true, format: None, bit_depth: None, dither: None } + MapOverride { enabled: true, format: None, bit_depth: None, dither: None, size: None } } } diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index c19064c5..e4a6e7f7 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -56,12 +56,12 @@ impl<'a> MapRenderer<'a> { Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) } - /// The export size of a file of `tile` (None: the whole set). - pub(super) fn size(&self, tile: Option) -> Result<(u32, u32)> { + /// The export size of map `map_index`'s file of `tile` (None: the whole set) + pub(super) fn size(&self, map_index: usize, tile: Option) -> Result<(u32, u32)> { 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.size); + let scale = |value| scale_export_side(value, self.tile_res, self.options.map_size(map_index)); Ok((scale(w), scale(h))) } @@ -87,7 +87,7 @@ impl<'a> MapRenderer<'a> { let component_count = channel_layout.len(); let inverted: Vec = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect(); let (x0, y0, w, h) = self.region(tile)?; - let size = self.size(tile)?; + let size = self.size(map_index, tile)?; let sampler = &self.sampler; let dilation_map = self.dilation_map.as_ref(); let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 6a07413e..26ef58fc 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -441,6 +441,11 @@ pub struct ExportOptions { } impl ExportOptions { + /// The output size of the preset's map `map`: its own, else the export's (None: the texture set's) + pub fn map_size(&self, map: usize) -> Option { + self.maps.get(&map).and_then(|own| own.size).or(self.size) + } + /// The colour space colour maps use at this format's default depth. pub fn space_for(&self, format: FileFormat) -> ColorSpace { self.space_for_depth(format, format.default_depth()) @@ -614,10 +619,10 @@ pub fn sanitize_file_path(s: &str) -> String { pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; - if let Some(s) = opts.size - && (!s.is_power_of_two() || s > MAX_IMAGE_SIZE) - { - return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); + for s in opts.size.iter().chain(opts.maps.values().filter_map(|own| own.size.as_ref())) { + if !s.is_power_of_two() || *s > MAX_IMAGE_SIZE { + return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}"))); + } } let mut used = BTreeSet::new(); @@ -736,7 +741,11 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let bit_depth = in_tile.iter().map(|(_, _, depth, _)| *depth).max().unwrap_or(8); let folder_count: usize = in_tile.iter().map(|(_, layer, ..)| layer.name.matches('/').count()).sum(); - check_psd_size(psd_size(set, tile, opts.size), in_tile.len(), folder_count, bit_depth)?; + let size = in_tile + .iter() + .map(|(_, layer, ..)| psd_size(set, tile, opts.map_size(layer.map))) + .max_by_key(|(width, height)| u64::from(*width) * u64::from(*height)); + check_psd_size(size.unwrap_or((1, 1)), in_tile.len(), folder_count, bit_depth)?; let mut warnings: Vec = Vec::new(); for warning in in_tile.iter().flat_map(|(.., layer_warnings)| layer_warnings) { @@ -793,7 +802,7 @@ fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: & Ok(()) } -/// The size of a texture set's PSD for `tile` (None: the whole set, an atlas of a UV-tiled one) +/// 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()) { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 1cdf688e..f050b2b6 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -556,6 +556,33 @@ fn gray_map(file: &str, src: SourceRef) -> MapSpec { MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() } } +#[test] +fn an_output_with_its_own_size_keeps_it() { + let fx = Fx::new(&default_channels()); + let preset = ExportPreset { + name: "sizes".into(), + maps: vec![ + gray_map("small", SourceRef::Channel { channel: Channel::Roughness, component: 0 }), + gray_map("set_size", SourceRef::Channel { channel: Channel::Metallic, component: 0 }), + ], + }; + let mut options = ExportOptions::new(preset); + options.maps.insert(0, MapOverride { size: Some(32), ..MapOverride::default() }); + + for (export_size, other) in [(None, RES), (Some(128), 128)] { + let files = fx.render(&ExportOptions { size: export_size, ..options.clone() }); + assert_eq!(find(&files, "small.png").width, 32, "its own size wins over {export_size:?}"); + assert_eq!(find(&files, "set_size.png").width, other); + } + + // A PSD is as large as its largest layer + options.format_override = Some(FileFormat::Psd); + assert_eq!(fx.render(&options)[0].width, RES); + + options.maps.insert(0, MapOverride { size: Some(100), ..MapOverride::default() }); + assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "a size that isn't a power of two is refused"); +} + #[test] fn validation_rejects_bad_presets() { let ok = ExportPreset { name: "Mine".into(), maps: vec![gray_map("$mesh_$textureSet_$channel ($colorSpace) $project", SourceRef::Constant(1.0))] }; diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c7f8b11f..0e6b30b1 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -507,6 +507,9 @@ pub(crate) fn set_params(app: &TextureCraftApp, set_index: usize) -> serde_json: settings["bitDepth"] = json!(file_type.bit_depth); settings["dithering"] = json!(file_type.dithering); } + if let Some(size) = map.size { + settings["size"] = json!(size); + } settings }) .collect(); @@ -608,6 +611,7 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { ui.label(file_type_text(&row.inherited)); } } + map_size_combo(ui, ("exp_map_size", ts, row.map), &mut m.size); }); ui.end_row(); } @@ -619,13 +623,29 @@ fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { Some(1) => m.enabled = false, Some(2) => m.enabled = !m.enabled, Some(3) if m.file_type.is_none() => m.file_type = Some(row.inherited.clone()), - Some(4) => m.file_type = None, + Some(4) => (m.file_type, m.size) = (None, None), _ => {} } } o.maps.retain(|_, m| *m != MapExport::default()); } +/// An output map's size: the export's, or its own, which wins over it +fn map_size_combo(ui: &mut Ui, id: (&str, usize, usize), size: &mut Option) { + let shown = size.map_or_else(|| tr("Export size").to_string(), |side| format!("{side}x{side}")); + egui::ComboBox::from_id_salt(id) + .selected_text(shown) + .show_ui(ui, |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}")); + } + }) + .response + .on_hover_text(tr("This map's own size, which wins over the export size")); +} + /// Count the files planned across all selected texture sets. fn selected_texture_count(app: &mut TextureCraftApp) -> usize { let mut count = 0; diff --git a/crates/ui-egui/src/state/map_export.rs b/crates/ui-egui/src/state/map_export.rs index 339ee1bb..2b8a3e37 100644 --- a/crates/ui-egui/src/state/map_export.rs +++ b/crates/ui-egui/src/state/map_export.rs @@ -10,6 +10,9 @@ pub struct MapExport { pub enabled: bool, #[serde(default)] pub file_type: Option, + /// The map's own size in texels per side, which wins over the export size + #[serde(default)] + pub size: Option, } fn enabled_by_default() -> bool { @@ -18,6 +21,6 @@ fn enabled_by_default() -> bool { impl Default for MapExport { fn default() -> Self { - MapExport { enabled: true, file_type: None } + MapExport { enabled: true, file_type: None, size: None } } } diff --git a/crates/ui-egui/src/state/set_export.rs b/crates/ui-egui/src/state/set_export.rs index 0fb05522..7bb10770 100644 --- a/crates/ui-egui/src/state/set_export.rs +++ b/crates/ui-egui/src/state/set_export.rs @@ -26,7 +26,11 @@ pub struct SetExport { impl SetExport { /// Whether anything is overridden (the set is marked "*"). pub fn any(&self) -> bool { - self.preset.is_some() || self.file_type.is_some() || self.size.is_some() || self.padding.is_some() || self.maps.values().any(|m| m.file_type.is_some()) + self.preset.is_some() + || self.file_type.is_some() + || self.size.is_some() + || self.padding.is_some() + || self.maps.values().any(|m| m.file_type.is_some() || m.size.is_some()) } /// Whether the set exports as the global settings say (no override, every map ticked). diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 937ce100..0aefd54e 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -119,7 +119,7 @@ fn export_writes_a_map_with_its_own_file_type() { let _ = std::fs::remove_dir_all(&dir); 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 }) }); + 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); @@ -147,7 +147,7 @@ fn a_map_the_template_no_longer_has_is_ignored() { 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 }); + o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None }); h.state_mut().ui.export.sets.insert(0, o); h.run_steps(3); assert_eq!(selected(&h), before, "the export still plans every file"); @@ -163,3 +163,38 @@ fn each_row_names_its_own_map() { assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}"); } } + +#[test] +fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() { + let mut h = harness(); + let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; + let combo = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list"); + combo.click(); + h.run_steps(4); + click(&mut h, "128x128"); + assert_eq!(maps(&h).get(&first).and_then(|map| map.size), Some(128), "{:?}", maps(&h)); + assert!(h.query_by_label("*").is_some(), "the set is marked"); + + let dir = std::env::temp_dir().join(format!("tc-export-map-sizes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let set_count = h.state().session.set_count(); + let export = &mut h.state_mut().ui.export; + export.dir = dir.display().to_string(); + export.skip = (1..set_count).collect(); + h.run_steps(3); + click(&mut h, "Export"); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + + h.run_steps(1); + } + h.run_steps(2); + + let sizes: Vec = + std::fs::read_dir(&dir).unwrap().flatten().filter_map(|entry| image::image_dimensions(entry.path()).ok()).map(|(width, _)| width).collect(); + assert_eq!(sizes.iter().filter(|width| **width == 128).count(), 1, "the map at its own size: {sizes:?}"); + assert!(sizes.iter().filter(|width| **width != 128).all(|width| *width == 256), "the others at the set's: {sizes:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 061c2779..fb791acb 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -188,7 +188,7 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() { 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 }); + o.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.preset = "Two".into(); @@ -208,7 +208,7 @@ 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 }); + o.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; @@ -270,7 +270,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { let mut h = harness(&library); // The first texture set leaves out the template's first map - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone(); @@ -284,7 +284,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() { fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() { let library = TemplateLibrary::new("stale"); let mut h = harness(&library); - let off = MapExport { enabled: false, file_type: None }; + let off = MapExport { enabled: false, file_type: None, size: None }; h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() }); h.run_steps(2); let saved = h.state().session.export_preset("Mine").unwrap(); @@ -321,7 +321,7 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { let mut external = saved.clone(); external.maps.swap(0, 1); harness.state_mut().run("export.preset.save", json!({"preset": external})).unwrap(); - let disabled = MapExport { enabled: false, file_type: None }; + let disabled = MapExport { enabled: false, file_type: None, size: None }; harness.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, disabled.clone())].into(), ..SetExport::default() }); harness.run_steps(3); From b569f3dbe8825008d719ae1abff77157451a7a8d Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:50:37 +0000 Subject: [PATCH 04/34] Export textures: Export shader settings writes _shaders.json, the shader's model and settings and the texture sets using it The tick is saved with the export settings like Export USD asset; the window sends every texture set of the export with its last command (shaderParameters of file.exportTextures), and the browser adds the file to its download. --- crates/engine/src/file_cmds.rs | 14 +++- crates/engine/src/lib.rs | 1 + crates/engine/src/shader_parameters.rs | 73 +++++++++++++++++++ crates/engine/tests/it/export_file_types.rs | 34 +++++++++ crates/ui-egui/src/export_window.rs | 26 +++++-- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/state/export_job.rs | 2 + crates/ui-egui/src/web_files.rs | 7 ++ .../tests/it/export_shader_parameters.rs | 39 ++++++++++ crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/side_panels.rs | 5 +- 11 files changed, 198 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/shader_parameters.rs create mode 100644 crates/ui-egui/tests/it/export_shader_parameters.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index f29efdf9..2688061c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -58,7 +58,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -670,6 +670,7 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { let reserved_patterns: Vec<_> = taken_names.keys().filter(|name| name.contains("")).cloned().collect(); let material = params.get("materialX").and_then(Value::as_bool).unwrap_or(false); let usd_asset = usd_asset_param(session, params, &options, &sets)?; + let shader_sets = crate::shader_parameters::shader_parameters_param(&session.doc.project, params, &sets, "file.exportTextures")?; let mut warnings = Vec::new(); let mut udim_patterns = Vec::new(); @@ -729,6 +730,17 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { if let Some(exports) = &usd_asset { written.extend(write_usd_asset(session, dir, exports, &mut warnings)); } + if let Some(shader_sets) = shader_sets { + let path = dir.join(crate::shader_parameters::shader_parameters_file(&session.doc.project.name)); + let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets); + + // The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is + let text = serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string()); + match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) { + Ok(()) => written.push(path), + Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), + } + } session.log.info("MapExporter", format!("Exported {} textures to {}", written.len(), dir.display())); let mut response = json!({ "files": written.iter().map(|path| path.display().to_string()).collect::>(), "warnings": warnings }); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 23c6b489..8248263b 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -72,6 +72,7 @@ pub mod resource_cmds; pub mod session; mod session_log; pub mod set_cmds; +pub mod shader_parameters; pub mod smart_masks; mod solo; mod stylized_lighting_params; diff --git a/crates/engine/src/shader_parameters.rs b/crates/engine/src/shader_parameters.rs new file mode 100644 index 00000000..a090ecb8 --- /dev/null +++ b/crates/engine/src/shader_parameters.rs @@ -0,0 +1,73 @@ +//! Export shaders parameters: the project's shader, its settings and the texture sets using it, as JSON + +use serde_json::{Value, json}; +use texturecraft_core::Project; + +use crate::Result; +use crate::commands::bad; + +/// The project's one shader, its parameters and the names of `sets` (they all use it) +pub fn shader_parameters(project: &Project, sets: &[usize]) -> Value { + let display = &project.display; + let model = if display.spec_gloss { "specularGlossiness" } else { "metallicRoughness" }; + let names: Vec<&str> = sets.iter().filter_map(|ts| project.texture_sets.get(*ts)).map(|set| set.name.as_str()).collect(); + + json!({ + "shaders": [{ + "model": model, + "parameters": { + "aoIntensity": display.ao_intensity, + "ior": display.ior, + "scatterColor": display.scatter_color, + "scatterRadius": display.scatter_radius, + "displacement": display.displacement, + "parallax": display.parallax, + }, + "textureSets": names, + }] + }) +} + +/// The JSON file's name for project `name` +pub fn shader_parameters_file(name: &str) -> String { + format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name)) +} + +/// The texture sets `shaderParameters` asks to list: `true` takes the command's own `sets`, a list gives them all; None when it asks for no file +pub fn shader_parameters_param(project: &Project, params: &Value, sets: &[usize], cmd: &str) -> Result>> { + match params.get("shaderParameters") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(sets.to_vec())), + Some(Value::Array(indexes)) => indexes + .iter() + .map(|index| { + index + .as_u64() + .and_then(|index| usize::try_from(index).ok()) + .filter(|index| *index < project.texture_sets.len()) + .ok_or_else(|| bad(cmd, "`shaderParameters` lists texture set indexes")) + }) + .collect::>>() + .map(Some), + Some(_) => Err(bad(cmd, "`shaderParameters` must be true, false or a list of texture set indexes")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_json_names_the_shader_its_settings_and_its_texture_sets() { + let mut s = crate::sample_session(128, 32).unwrap(); + s.doc.project.display.ior = 1.33; + + let value = shader_parameters(&s.doc.project, &[1]); + + let shader = &value["shaders"][0]; + assert_eq!(shader["model"], "metallicRoughness"); + assert!((shader["parameters"]["ior"].as_f64().unwrap() - 1.33).abs() < 1e-6); + assert_eq!(shader["textureSets"], json!([s.doc.project.texture_sets[1].name])); + assert!(shader_parameters_file("Material Ball").ends_with("_shaders.json")); + } +} diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 70355b80..6f9638c8 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -39,3 +39,37 @@ fn a_map_size_wins_over_the_export_size_in_the_plan() { assert!(files.iter().filter(|file| file["map"] != 0).all(|file| file["size"] == 512), "{plan}"); assert!(execute(&mut s, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err()); } + +#[test] +fn shader_parameters_write_the_shaders_json_next_to_the_textures() { + let mut s = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = std::env::temp_dir().join(format!("tc_export_shader_parameters_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "ts": 1, "shaderParameters": [0, 1]})).unwrap(); + + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&s.doc.project.name)); + assert!(r["files"].as_array().unwrap().iter().any(|f| f.as_str() == Some(file.to_str().unwrap())), "{r}"); + let written: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let names: Vec<&str> = s.doc.project.texture_sets.iter().take(2).map(|set| set.name.as_str()).collect(); + assert_eq!(written["shaders"][0]["textureSets"], json!(names)); + assert!(execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "shaderParameters": "yes"})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() { + let mut s = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = std::env::temp_dir().join(format!("tc_export_shader_parameters_blocked_{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&s.doc.project.name)); + std::fs::create_dir_all(&file).unwrap(); + + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "ts": 0, "shaderParameters": true})).unwrap(); + + let files = r["files"].as_array().unwrap(); + assert!(!files.is_empty() && files.iter().all(|f| f.as_str() != Some(file.to_str().unwrap())), "{r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 0e6b30b1..1c1d2db4 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -272,7 +272,15 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, usd_asset: e.usd_asset, ..Default::default() }); + e.job = Some(crate::state::ExportJob { + total: pending.len(), + pending, + preview, + directory: dir, + usd_asset: e.usd_asset, + shader_parameters: e.shader_parameters, + ..Default::default() + }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -373,6 +381,11 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { } } + // The last command writes the shader parameters, listing every texture set of the export + if let Some(job) = app.ui.export.job.as_ref().filter(|job| job.shader_parameters && job.pending.is_empty()) { + params["shaderParameters"] = job.preview.iter().filter_map(|plan| plan.index).collect(); + } + let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; @@ -394,8 +407,8 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { }; let files: Vec = response_strings(&response, "files").map(relative).collect(); let mut lines = vec![set(), ConsoleLine::Step(tr("Saving texture files").into())]; - // The USD asset is no texture: it stays in the list of written files only - for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd")) { + // The USD asset and the shader parameters are no textures: they stay in the list of written files only + for file in files.iter().filter(|file| !file.to_ascii_lowercase().ends_with(".usd") && !file.to_ascii_lowercase().ends_with(".json")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); lines.push(ConsoleLine::Step(trf("Saved texture {file}", &[("file", &stem)]))); @@ -772,6 +785,7 @@ fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { } /// A greyed checkbox with its tooltip and the "not available" hint +#[cfg(target_arch = "wasm32")] fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { let mut off = false; ui.add_enabled(false, egui::Checkbox::new(&mut off, label)).on_disabled_hover_ui(|ui| { @@ -801,6 +815,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] settings.color_space, settings.usd_asset, settings.materialx, + settings.shader_parameters, ) = ( defaults.dir, defaults.format, @@ -813,6 +828,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] defaults.color_space, defaults.usd_asset, defaults.materialx, + defaults.shader_parameters, ); crate::export_templates::select(app, defaults.preset); } @@ -874,8 +890,8 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] #[cfg(target_arch = "wasm32")] crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); - // Unavailable export controls stay disabled - unavailable_checkbox(ui, tr("Export shader settings"), tr("Save the settings of each shader instance in a JSON file")); + ui.checkbox(&mut app.ui.export.shader_parameters, tr("Export shader settings")) + .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); ui.add_space(8.0); egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { let settings = &mut app.ui.export; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0c767e1b..570fb3ab 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -368,6 +368,9 @@ pub struct ExportUi { /// `file.exportTextures`). #[serde(default)] pub materialx: bool, + /// Also write `_shaders.json`: the shader's settings and the texture sets using it (`shaderParameters` of `file.exportTextures`) + #[serde(default)] + pub shader_parameters: bool, /// Texture sets excluded from export. pub skip: Vec, /// Per texture set (by index) overrides of the settings above. @@ -442,6 +445,7 @@ impl Default for ExportUi { color_space: String::new(), usd_asset: false, materialx: false, + shader_parameters: false, skip: Vec::new(), sets: Default::default(), owner: Vec::new(), diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index cf4a87de..853ca813 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -20,6 +20,8 @@ pub struct ExportJob { /// Also write the mesh and materials as a USD asset with the last texture set, as ticked when /// Export was clicked. pub usd_asset: bool, + /// Also write the shader parameters with the last texture set, listing every texture set of the export, as ticked when Export was clicked + pub shader_parameters: bool, /// The params of the texture sets written so far, for the USD asset. pub sent: Vec, /// Warning messages already shown in this export. diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 3991e3c8..8daad344 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -364,6 +364,13 @@ mod web { // Keep one file for each case-insensitive name in the download texturecraft_engine::formats::skip_repeated_names(&mut files); + if app.ui.export.shader_parameters { + let sets: Vec = jobs.iter().map(|(set_index, _)| *set_index).collect(); + let parameters = texturecraft_engine::shader_parameters::shader_parameters(&app.session.doc.project, &sets); + let name = texturecraft_engine::shader_parameters::shader_parameters_file(&app.session.doc.project.name); + let bytes = serde_json::to_vec_pretty(¶meters).map_err(|e| e.to_string())?; + files.push(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() }); + } app.session.log.warnings("MapExporter", files.iter().flat_map(|file| file.warnings.iter().cloned())); let file_count = files.len(); diff --git a/crates/ui-egui/tests/it/export_shader_parameters.rs b/crates/ui-egui/tests/it/export_shader_parameters.rs new file mode 100644 index 00000000..60d561e7 --- /dev/null +++ b/crates/ui-egui/tests/it/export_shader_parameters.rs @@ -0,0 +1,39 @@ +//! Export textures › SETTINGS: Export shader settings writes `_shaders.json`, the +//! shader's settings and every texture set of the export, with the export's last texture set + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable as _; +use texturecraft_ui_egui::TextureCraftApp; + +#[test] +fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.prefs.language = "en".into(); + h.run_steps(4); + let dir = std::env::temp_dir().join(format!("tc-export-shader-parameters-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + + h.get_by_role_and_label(egui::Role::CheckBox, "Export shader settings").click(); + h.run_steps(4); + assert!(h.state().ui.export.shader_parameters); + h.get_all_by_label("Export").last().unwrap().click(); + for _ in 0..64 { + h.run_steps(1); + if h.state().ui.export.job.is_none() { + break; + } + } + h.run_steps(2); + + let project = &h.state().session.doc.project; + let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&project.name)); + let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap_or_else(|_| panic!("{} was written", file.display()))).unwrap(); + let names: Vec<&str> = project.texture_sets.iter().map(|set| set.name.as_str()).collect(); + assert_eq!(json["shaders"][0]["textureSets"], serde_json::json!(names), "every texture set of the export, written once: {json}"); + assert!(json["shaders"][0]["parameters"]["ior"].is_number()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index c8d7f0f3..d24faf45 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -28,6 +28,7 @@ mod export_overrides; mod export_progress; mod export_reference_texts; mod export_settings; +mod export_shader_parameters; mod export_template_guards; mod export_usd_asset; mod file_dialogs; diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index aab7c36d..8d5162d5 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -118,8 +118,9 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); - assert!(!says_not_available(&mut harness, "Export USD asset")); - assert!(says_not_available(&mut harness, "Export shader settings")); + for label in ["Export USD asset", "Export shader settings"] { + assert!(!says_not_available(&mut harness, label), "{label}"); + } harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); From 20270b4f38a6fa9bbfde34067692a6e409452919 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:36:43 +0000 Subject: [PATCH 05/34] Export textures: Esc closes the window as Cancel does, after an open list, rename or channel question Fixes #284 --- crates/ui-egui/src/export_window.rs | 16 +++++++++++++ crates/ui-egui/src/menus.rs | 3 +++ crates/ui-egui/src/state.rs | 4 ++++ crates/ui-egui/tests/it/export_settings.rs | 26 +++++++++++++++++++++ crates/ui-egui/tests/it/output_templates.rs | 26 +++++++++++++++++++++ 5 files changed, 75 insertions(+) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 1c1d2db4..aa005e46 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1466,6 +1466,19 @@ fn cancel(app: &mut TextureCraftApp) { app.ui.windows.export = false; } +/// Escape closes the window as Cancel does, read in `menus::shortcuts`; an open dropdown, channel question, template rename or text field takes it first +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, popup_open: bool) { + let export = &app.ui.export; + if popup_open || export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some() { + return; + } + + if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { + app.ui.export.job = None; + cancel(app); + } +} + pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export { // The window opens on SETTINGS again; an export stops with it @@ -1651,6 +1664,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { }); crate::export_templates::ask(app, ctx); + // egui drops a field's focus on Escape before the next frame's shortcuts run, so keep whether one had the keyboard + app.ui.export.field_had_keyboard = ctx.egui_wants_keyboard_input(); + // Dismissal must run before the next write if canceled || !open { app.ui.export.job = None; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1d4588ea..dec4bc37 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -526,6 +526,9 @@ 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 app.ui.windows.export { + // Escape is the window's Cancel; nothing behind the window reads it + crate::export_window::keys_in(app, input, !escape_is_free); } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 570fb3ab..fbcd6053 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -414,6 +414,9 @@ pub struct ExportUi { /// Output templates tab: F2 asked to rename the selected preset. #[serde(skip)] pub rename_key: bool, + /// A text field of the window had the keyboard when the last frame ended + #[serde(skip)] + pub field_had_keyboard: bool, /// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit). #[serde(skip)] pub ask: Option, @@ -460,6 +463,7 @@ impl Default for ExportUi { pending_drop: None, renaming: None, rename_key: false, + field_had_keyboard: false, ask: None, opened_with: None, job: None, diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 98af3660..6f1212e0 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -72,6 +72,32 @@ fn closing_the_window_is_cancel() { assert_eq!(h.state().ui.export.size, 0); } +#[test] +fn escape_is_cancel() { + let mut h = harness(); + h.state_mut().ui.export.size = 2048; + h.run_steps(3); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0, "the opening settings are back"); +} + +#[test] +fn escape_in_an_open_dropdown_closes_only_the_dropdown() { + let mut h = harness(); + open_combo(&mut h, "Based on output template"); + assert!(h.query_by_label("png").is_some()); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.query_by_label("png").is_none(), "the dropdown closed"); + assert!(h.state().ui.windows.export, "the window stays open"); +} + #[test] fn the_lists_hold_the_reference_entries() { let mut h = harness(); diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index fb791acb..2dacd6cd 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -152,6 +152,8 @@ fn the_right_click_menu_renames_and_removes_user_templates_only() { assert_eq!(h.state().ui.export.renaming.as_deref(), Some("Mine")); h.key_press(egui::Key::Escape); h.run_steps(4); + assert!(h.state().ui.export.renaming.is_none(), "Escape ends the rename"); + assert!(h.state().ui.windows.export, "and leaves the window open"); right_click(&mut h, "Mine"); click(&mut h, "Remove"); @@ -491,6 +493,29 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() { assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some()); } +#[test] +fn escape_in_a_file_name_field_leaves_the_field_and_keeps_the_window() { + let library = TemplateLibrary::new("escape-in-a-field"); + let mut h = harness(&library); + let field = name_field(&h, 0).center(); + h.hover_at(field); + for pressed in [true, false] { + h.event(Event::PointerButton { pos: field, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + h.step(); + } + h.run_steps(4); + assert!(h.ctx.egui_wants_keyboard_input(), "the field has the keyboard"); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().ui.windows.export, "the window stays open"); + assert!(!h.ctx.egui_wants_keyboard_input(), "the field let go of the keyboard"); + h.key_press(egui::Key::Escape); + h.run_steps(4); + assert!(!h.state().ui.windows.export, "a second Escape is Cancel"); +} + #[test] fn escape_closes_the_from_popup_without_assigning() { let library = TemplateLibrary::new("drop-escape"); @@ -510,6 +535,7 @@ fn escape_closes_the_from_popup_without_assigning() { assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup"); assert!(h.state().ui.export.pending_drop.is_none()); + assert!(h.state().ui.windows.export, "the window stays open"); assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned"); } From 276f5d9f78b9e464227713392cc03c56ce6295d8 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:41:32 +0000 Subject: [PATCH 06/34] Output templates: hovering a channel swatch shows the file its output writes, small, with each channel and its source; export.preview samples one output map --- crates/engine/src/file_cmds.rs | 77 +++++++-- crates/engine/tests/it/export_maps.rs | 19 +++ crates/formats/src/export/map_preview.rs | 69 ++++++++ crates/formats/src/export/map_renderer.rs | 12 +- crates/formats/src/export/mod.rs | 19 +++ crates/formats/src/export/tests.rs | 25 +++ crates/formats/src/lib.rs | 4 +- crates/ui-egui/src/export_templates.rs | 156 ++++++++++++++---- .../src/export_templates/map_preview_cache.rs | 59 +++++++ .../export_templates/map_preview_pictures.rs | 43 +++++ .../src/export_templates/planned_output.rs | 12 ++ .../ui-egui/src/export_templates/row_edit.rs | 2 + crates/ui-egui/tests/it/output_templates.rs | 20 +++ docs/control-protocol.md | 2 +- 14 files changed, 454 insertions(+), 65 deletions(-) create mode 100644 crates/formats/src/export/map_preview.rs create mode 100644 crates/ui-egui/src/export_templates/map_preview_cache.rs create mode 100644 crates/ui-egui/src/export_templates/map_preview_pictures.rs create mode 100644 crates/ui-egui/src/export_templates/planned_output.rs diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 2688061c..b1d6ac31 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -12,13 +12,16 @@ use serde_json::{Value, json}; use texturecraft_core::{NormalFormat, PROJECT_EXT}; use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::PlannedFile; -use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile}; +use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p}; use crate::session::{Document, Session}; use crate::{EngineError, Result, cmd}; +/// export.preview's picture width when the params name none +const DEFAULT_PREVIEW_SIDE_PIXELS: u32 = 128; + pub fn specs() -> Vec { vec![ cmd!( @@ -80,6 +83,15 @@ pub fn specs() -> Vec { always, plan ), + cmd!( + "export.preview", + "Preview an output map", + [], + None, + "{map: index into the preset's maps, side?: px (default 128, at most 512), plus the params of export.plan (the first texture set `ts` names)} → {width, height, channels: [\"R\", ...], pixels: [8-bit values as an sRGB file stores them, channels interleaved, row by row]}, or null when the texture set writes no file for the map", + always, + preview + ), ] } @@ -289,31 +301,50 @@ impl Session { let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); - let empty = Default::default(); for &set_index in sets { - let cache = self.caches.get(set_index).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?; let plans = select(set_index, plans); if plans.is_empty() { continue; } - let composite = - self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?; - let coverage = cache.gbuf.coverage_mask(); - let input = ExportInput { - project: &self.doc.project, - ts: set_index, - composite: &composite, - baked: self.doc.baked.get(&set_index).unwrap_or(&empty), - coverage: &coverage, - mesh_name: &mesh_name, - }; - out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?); + let files = + self.with_export_input(set_index, &mesh_name, |input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe))?; + out.extend(files); } Ok(out) } + + /// Run `with` on texture set `set_index`'s export input: its document composite, coverage and baked maps + fn with_export_input(&self, set_index: usize, mesh_name: &str, with: impl FnOnce(&ExportInput) -> Result) -> Result { + let missing = || EngineError::Other(format!("no texture set {set_index}")); + 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 = cache.gbuf.coverage_mask(); + let empty = Default::default(); + let input = ExportInput { + project: &self.doc.project, + ts: set_index, + composite: &composite, + baked: self.doc.baked.get(&set_index).unwrap_or(&empty), + coverage: &coverage, + mesh_name, + }; + with(&input) + } + + /// A picture at most `side` pixels wide of output map `map` for the first texture set `params` names; None when it writes no file for the map + pub fn export_preview(&mut self, params: &Value, map: usize, side: u32) -> Result> { + let options = export_options(self, params, "export.preview")?; + let Some(&set_index) = sets_param(self, params, "export.preview")?.first() else { return Ok(None) }; + + if self.solo.is_none() { + self.update(); + } + let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); + self.with_export_input(set_index, &mesh_name, |input| MapPreview::sample(input, &options, map, side).map_err(fe)) + } } fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> { @@ -432,6 +463,22 @@ fn set_index(s: &Session, v: &Value, cmd: &str) -> Result { v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`")) } +fn preview(session: &mut Session, params: &Value) -> Result { + let map = u64p(params, "map").and_then(|map| usize::try_from(map).ok()); + let map = map.ok_or_else(|| bad("export.preview", "`map` (an output map index) is required"))?; + let side = u64p(params, "side").map_or(DEFAULT_PREVIEW_SIDE_PIXELS, |side| side.clamp(1, u64::from(texturecraft_formats::MAX_PREVIEW_SIDE)) as u32); + + Ok(match session.export_preview(params, map, side)? { + Some(preview) => json!({ + "width": preview.width, + "height": preview.height, + "channels": preview.channels.iter().map(|dest| format!("{dest:?}")).collect::>(), + "pixels": preview.pixels, + }), + None => Value::Null, + }) +} + fn plan(session: &mut Session, params: &Value) -> Result { use texturecraft_formats::export::{list_set_outputs, scale_export_side}; diff --git a/crates/engine/tests/it/export_maps.rs b/crates/engine/tests/it/export_maps.rs index 991b5f32..30ec6b0a 100644 --- a/crates/engine/tests/it/export_maps.rs +++ b/crates/engine/tests/it/export_maps.rs @@ -105,3 +105,22 @@ fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() { } assert_eq!(result["files"].as_array().unwrap().len(), names.len()); } + +#[test] +fn export_preview_shows_a_packed_map_small_and_nothing_for_a_left_out_one() { + let mut s = session(); + let preset = s.export_preset("Unity HDRP (Mask Map)").unwrap(); + let mask = preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let params = json!({"preset": preset.name, "ts": 0, "map": mask, "side": 16}); + + let preview = execute(&mut s, "export.preview", ¶ms).unwrap(); + let (width, height) = (preview["width"].as_u64().unwrap(), preview["height"].as_u64().unwrap()); + assert!(width <= 16 && height > 0, "{preview}"); + assert_eq!(preview["channels"], json!(["R", "G", "B", "A"]), "the mask map packs four channels"); + assert_eq!(preview["pixels"].as_array().unwrap().len() as u64, width * height * 4); + + let left_out = json!({"preset": preset.name, "ts": 0, "map": mask, "maps": [{"map": mask, "enabled": false}]}); + assert!(execute(&mut s, "export.preview", &left_out).unwrap().is_null(), "a map the export leaves out has no file to show"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name})).is_err(), "the map is required"); + assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name, "map": preset.maps.len()})).is_err()); +} diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs new file mode 100644 index 00000000..a72202d7 --- /dev/null +++ b/crates/formats/src/export/map_preview.rs @@ -0,0 +1,69 @@ +//! A small picture of one output map, sampled from the texture set as the export samples it + +use rayon::prelude::*; +use texturecraft_texel::linear_to_srgb; + +use super::{At, Dest, ExportInput, ExportOptions, Sampler, layout, list_outputs}; +use crate::{FormatError, Result}; + +/// The largest preview side: a preview is a glance, never a second export +pub const MAX_PREVIEW_SIDE: u32 = 512; + +/// One output map, small: its channels in file order and the 8-bit values an sRGB file of it stores (colour channels sRGB-encoded, data as is) +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MapPreview { + pub width: u32, + pub height: u32, + pub channels: Vec, + /// `channels.len()` values per pixel, row by row + pub pixels: Vec, +} + +impl MapPreview { + /// Output map `map` of `options`' template for `input`'s set, at most `side` wide; None when it writes no file; texels off the UV islands show the default + pub fn sample(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result> { + let set = input.project.texture_set(input.ts)?; + let spec = options.preset.maps.get(map).ok_or_else(|| FormatError::Invalid(format!("the template has no output map {map}")))?; + let planned = list_outputs(input.project, input.ts, input.mesh_name, options)?; + if !planned.iter().any(|file| file.maps().any(|written| written == map)) { + return Ok(None); + } + + let (composite_width, height) = (input.composite.resolution, input.composite.height); + if composite_width == 0 || height == 0 || input.coverage.len() != composite_width as usize * height as usize { + return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage"))); + } + + let width = side.clamp(1, MAX_PREVIEW_SIDE).min(composite_width); + let rows = ((u64::from(width) * u64::from(height) / u64::from(composite_width)) as u32).max(1); + let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); + let sampler = Sampler::new(input, options, set, tile_res); + let channel_layout = layout(set, spec); + let count = channel_layout.len(); + let color = spec.is_color(); + let max_sample = f32::from(u8::MAX); + + // The texel under the centre of preview pixel `i` of `out` pixels across `of` texels + let texel = |i: u32, out: u32, of: u32| ((u64::from(i) * 2 + 1) * u64::from(of) / (2 * u64::from(out))).min(u64::from(of) - 1) as u32; + + let mut pixels = vec![0u8; width as usize * rows as usize * count]; + pixels.par_chunks_mut(width as usize * count).enumerate().for_each(|(row, values)| { + let y = texel(row as u32, rows, height); + for column in 0..width { + let x = texel(column, width, composite_width); + let at = if sampler.covered(x, y) { At::Texel(x, y) } else { At::Default }; + let mut cache = None; + for (component, (dest, source)) in channel_layout.iter().enumerate() { + let sample = sampler.sample(source, at, &mut cache); + let value = if spec.inverted.contains(dest) { 1.0 - sample } else { sample }; + let stored = if color && *dest != Dest::A { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; + if let Some(slot) = values.get_mut(column as usize * count + component) { + *slot = (stored * max_sample + 0.5) as u8; + } + } + } + }); + + Ok(Some(MapPreview { width, height: rows, channels: channel_layout.iter().map(|(dest, _)| *dest).collect(), pixels })) + } +} diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index e4a6e7f7..71dfba2e 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -42,17 +42,7 @@ impl<'a> MapRenderer<'a> { } Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)), }; - let sampler = Sampler { - set, - comp: input.composite, - baked: input.baked, - coverage: input.coverage, - res: width, - tile_res, - scales: set.block_scales(), - normal_override: options.normal_format, - project_normal: input.project.normal_format, - }; + let sampler = Sampler::new(input, options, set, tile_res); Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res }) } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 26ef58fc..f21dbf66 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -29,11 +29,13 @@ mod encoding; mod jpeg2000; mod layered_psd; mod map_override; +mod map_preview; mod map_renderer; mod planned_layer; mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; +pub use map_preview::{MAX_PREVIEW_SIDE, MapPreview}; use map_renderer::MapRenderer; pub use planned_layer::PlannedLayer; @@ -870,6 +872,23 @@ pub fn rnm(base: Vec3, detail: Vec3) -> Vec3 { (t * t.dot(u) / t.z.max(1e-4) - u).try_normalize().unwrap_or(base) } +impl<'a> Sampler<'a> { + /// The sampler of `input`'s texture set `set`, whose atlas blocks are `tile_res` texels wide + fn new(input: &ExportInput<'a>, options: &ExportOptions, set: &'a TextureSet, tile_res: u32) -> Sampler<'a> { + Sampler { + set, + comp: input.composite, + baked: input.baked, + coverage: input.coverage, + res: input.composite.resolution, + tile_res, + scales: set.block_scales(), + normal_override: options.normal_format, + project_normal: input.project.normal_format, + } + } +} + impl Sampler<'_> { fn channel(&self, c: Channel, at: At) -> [f32; 3] { match at { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index f050b2b6..14bb5238 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1715,3 +1715,28 @@ fn write_files_accepts_a_long_nested_folder_and_stem() { assert!(paths[0].is_file()); std::fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn a_map_preview_holds_the_values_its_file_stores() { + let mut fx = Fx::new(&default_channels()); + fx.set_all(Channel::Metallic, |x, _| [x as f32 / 63.0; 3]); + fx.set_all(Channel::Roughness, |_, y| [y as f32 / 63.0; 3]); + let mut options = ExportOptions::new(builtin_preset("Unity HDRP (Mask Map)").unwrap()); + let mask = options.preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap(); + let base = options.preset.maps.iter().position(|map| map.file.contains("BaseMap")).unwrap(); + options.preset.maps[mask].inverted.push(Dest::R); + let files = fx.render(&options); + + // The packed data map, one channel inverted, and the sRGB colour map + for (index, suffix) in [(mask, "MaskMap"), (base, "BaseMap")] { + let file = decode(find(&files, suffix)); + let preview = MapPreview::sample(&fx.input(), &options, index, RES).unwrap().unwrap(); + assert_eq!((preview.width, preview.height), file.dimensions()); + assert_eq!(preview.channels.len(), usize::from(file.color().channel_count()), "{suffix}"); + assert!(preview.pixels == file.into_bytes(), "{suffix}: the preview shows what the file stores"); + } + + let small = MapPreview::sample(&fx.input(), &options, mask, 8).unwrap().unwrap(); + assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map"); + assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a46a6f62..274f3a10 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -42,8 +42,8 @@ pub mod project_file; pub mod zip_read; pub use export::{ - Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, - render_maps, skip_repeated_names, + 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 mesh_export::{ diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 3e7ab2b6..532d4a3c 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -20,7 +20,10 @@ use crate::widgets::{chip, icon_button_without_tooltip}; mod channel_target; mod map_drag; mod map_lists; +mod map_preview_cache; +mod map_preview_pictures; mod pending_drop; +mod planned_output; mod row_edit; mod source_pick; mod swatch_look; @@ -28,7 +31,10 @@ mod swatch_look; pub use channel_target::ChannelTarget; use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; +use map_preview_cache::MapPreviewCache; +use map_preview_pictures::MapPreviewPictures; pub use pending_drop::PendingDrop; +use planned_output::PlannedOutput; use row_edit::RowEdit; use source_pick::SourcePick; use swatch_look::SwatchLook; @@ -86,6 +92,9 @@ const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; /// Side of the corner mark of an inverted swatch const INVERTED_MARK_POINTS: f32 = 8.0; +/// A swatch's file preview: the file's width, and the side of each channel's picture beside it +const PREVIEW_FILE_WIDTH_POINTS: f32 = 150.0; +const PREVIEW_CHANNEL_WIDTH_POINTS: f32 = 34.0; /// A channel swatch: its side, the label's size and offset from the top, and the bars that show /// which channels of the source it reads @@ -762,7 +771,11 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { return; } }; - let preview = preview_names(app, &preset); + let params = plan_params(app, &preset); + let preview = params.as_ref().map_err(String::clone).and_then(|params| planned_outputs(app, params)); + if let Ok(params) = ¶ms { + MapPreviewCache::keep_current(app, ui.ctx(), params); + } let mut edit = RowEdit::default(); // The selected template in a strip, "Current preset:" in bold @@ -815,21 +828,22 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { // Every row takes the column's width, not the width a wider row before it left let row_width = ui.available_width(); for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { - let file = preview.as_ref().ok().and_then(|names| names.get(index).cloned().flatten()); - let planned = match file { - Some(file) => format!("{} {file}", ic::ARROW_RIGHT), - None => tr("Not exported: no source in this texture set").to_string(), - }; - changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, &planned, &mut edit)).inner; + let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); + changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, planned, &mut edit)).inner; ui.add_space(ROW_GAP_POINTS); } }); }); ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); + // The hovered output's pictures show from the next frame on + if let (Some(index), Ok(params)) = (edit.hovered_output, ¶ms) { + MapPreviewCache::fill(app, ui.ctx(), params, index); + } + // Count only maps that have sources in the current set - if let Ok(names) = &preview { - let exported = names.iter().flatten().count(); + if let Ok(planned) = &preview { + let exported = planned.iter().flatten().count(); egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); @@ -916,45 +930,57 @@ fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec Result>, String> { - let mut p = crate::export_window::set_params(app, app.session.ts()); - p["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; +/// The `export.plan` and `export.preview` params of `preset` for the current texture set with the window's settings +fn plan_params(app: &TextureCraftApp, preset: &ExportPreset) -> Result { + let mut params = crate::export_window::set_params(app, app.session.ts()); + params["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; // The set's map overrides apply only to its own template - if let Some(p) = p.as_object_mut() { - p.remove("maps"); + if let Some(params) = params.as_object_mut() { + params.remove("maps"); } - let plan = texturecraft_engine::execute(&mut app.session, "export.plan", &p).map_err(|e| e.to_string())?; - let mut names = vec![None; preset.maps.len()]; + Ok(params) +} + +/// The file each map of `params`' template writes for the texture set (None: no sources), via `export.plan`; a PSD's maps each get the file and their layer +fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result>, String> { + let plan = texturecraft_engine::execute(&mut app.session, "export.plan", params).map_err(|e| e.to_string())?; + let map_count = params.pointer("/preset/maps").and_then(Value::as_array).map_or(0, Vec::len); let index = |value: &Value| value.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()); - for f in plan.as_array().into_iter().flatten() { - let Some(file) = f.get("file").and_then(Value::as_str) else { continue }; - let layers = f.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()); - match layers { - // A PSD's maps each show the file and their layer + + let mut outputs = vec![None; map_count]; + for file in plan.as_array().into_iter().flatten() { + let Some(name) = file.get("file").and_then(Value::as_str) else { continue }; + + let output = PlannedOutput { + file: name.to_string(), + size: file.get("size").and_then(Value::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), + }; + match file.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()) { Some(layers) => { for layer in layers { - let name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); - if let Some(slot) = index(layer).and_then(|i| names.get_mut(i)) { - *slot = Some(format!("{file} › {name}")); + let layer_name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); + if let Some(slot) = index(layer).and_then(|i| outputs.get_mut(i)) { + *slot = Some(PlannedOutput { file: format!("{name} › {layer_name}"), ..output.clone() }); } } } None => { - if let Some(slot) = index(f).and_then(|i| names.get_mut(i)) { - *slot = Some(file.to_string()); + if let Some(slot) = index(file).and_then(|i| outputs.get_mut(i)) { + *slot = Some(output); } } } } - Ok(names) + Ok(outputs) } /// One output map row: drag grip, file name, "$", the channel swatches, then file type, bit depth, /// duplicate and remove. `planned` is the file it writes for the current texture set. -fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: &str, edit: &mut RowEdit) -> bool { +fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { @@ -971,11 +997,11 @@ fn output_row(ui: &mut Ui, index: usize, count: usize, map: &mut MapSpec, split: grip(ui, index, count, edit); let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { ui.label(tr("File name without extension; variables insert names")); - ui.label(planned); + ui.label(planned_text(planned)); }); changed |= name.changed(); changed |= token_menu(ui, &mut map.file); - changed |= channel_swatches(ui, index, map, split, edit); + changed |= channel_swatches(ui, index, map, split, planned, edit); // The lists and icons at the row's right end: file format and duplicate, bit depth and remove ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); @@ -1280,9 +1306,61 @@ fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: } } +/// "→ ", or why the output writes nothing +fn planned_text(planned: Option<&PlannedOutput>) -> String { + match planned { + Some(planned) => format!("{} {}", ic::ARROW_RIGHT, planned.file), + None => tr("Not exported: no source in this texture set").to_string(), + } +} + +/// Below a swatch's tooltip: the file its output writes, each channel with its source, then the file's size and type (built-in templates' swatches show it too) +fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&PlannedOutput>) { + let tokens = Tokens::get(ui.ctx()); + ui.separator(); + let Some(planned) = planned else { + ui.label(RichText::new(planned_text(None)).color(tokens.text_dim)); + return; + }; + + ui.label(RichText::new(&planned.file).color(tokens.text_strong)); + if let Some(Some(pictures)) = MapPreviewCache::get(ui.ctx(), index) { + preview_pictures(ui, map, &pictures); + } + let file_type = planned.format.map_or("", FileFormat::extension); + let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); + ui.label(RichText::new(format!("{size} x {size} · {file_type} {depth}", size = planned.size)).color(tokens.text_dim)); +} + +/// The file's picture with each channel's grey picture, letter and source beside it +fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { + let tokens = Tokens::get(ui.ctx()); + let picture = |texture, width: f32| egui::Image::new(texture).fit_to_exact_size(vec2(width, width * pictures.aspect)).corner_radius(tokens.radius); + ui.horizontal_top(|ui| { + ui.add(picture(&pictures.file, PREVIEW_FILE_WIDTH_POINTS)); + if pictures.channels.is_empty() { + return; + } + + ui.vertical(|ui| { + for (dest, texture) in &pictures.channels { + let target = ChannelTarget::One(*dest); + let source = source_of(map, target).cloned().unwrap_or(SourceRef::Constant(CLEARED_VALUE)); + let inverted = map.inverted.contains(dest); + ui.horizontal(|ui| { + ui.add(picture(texture, PREVIEW_CHANNEL_WIDTH_POINTS)); + ui.label(RichText::new(target_label(target)).color(tokens.text_strong)); + ui.label(RichText::new(swatch_tooltip(map, &source, target, inverted)).color(tokens.text_dim)); + }); + } + }); + }); +} + /// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. -fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, edit: &mut RowEdit) -> bool { +/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. Hovering one +/// shows the file the output writes. +fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let tokens = Tokens::get(ui.ctx()); let mut changed = false; let shows_split = *split || !rgb_collapsed(map); @@ -1297,12 +1375,18 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo name = trf("{swatch}, inverted", &[("swatch", &name)]); } let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; - let response = swatch(ui, label, &name, &look).on_hover_ui(|ui| { + let response = swatch(ui, label, &name, &look); + if response.contains_pointer() { + edit.hovered_output = Some(index); + } + let hover = |ui: &mut Ui| { ui.label(&tooltip); if inverted { ui.label(tr("Inverted")); } - }); + output_preview(ui, index, map, planned); + }; + let response = response.on_hover_ui(hover).on_disabled_hover_ui(hover); // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); diff --git a/crates/ui-egui/src/export_templates/map_preview_cache.rs b/crates/ui-egui/src/export_templates/map_preview_cache.rs new file mode 100644 index 00000000..c35a0c58 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_cache.rs @@ -0,0 +1,59 @@ +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use serde_json::Value; + +use super::map_preview_pictures::MapPreviewPictures; +use crate::TextureCraftApp; + +/// Pixels across an output map's hover preview: enough to read the packing, cheap to sample +const PREVIEW_SIDE_PIXELS: u32 = 150; + +/// The output maps' hover pictures for one set of export params and one document revision, by output map index (None: no file for that map) +#[derive(Clone, Default)] +pub(super) struct MapPreviewCache { + key: u64, + pictures: HashMap>>, +} + +impl MapPreviewCache { + fn id() -> egui::Id { + egui::Id::unique("export_map_preview_cache") + } + + fn key(app: &TextureCraftApp, params: &Value) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + params.to_string().hash(&mut hasher); + app.session.revision.hash(&mut hasher); + hasher.finish() + } + + /// Output map `index`'s pictures once made; None until then + pub(super) fn get(ctx: &egui::Context, index: usize) -> Option>> { + ctx.data(|data| data.get_temp::(Self::id()).and_then(|cache| cache.pictures.get(&index).cloned())) + } + + /// Forget pictures made for other params or an older document, so `get` never shows them + pub(super) fn keep_current(app: &TextureCraftApp, ctx: &egui::Context, params: &Value) { + let key = Self::key(app, params); + ctx.data_mut(|data| { + let cache = data.get_temp_mut_or_default::(Self::id()); + if cache.key != key { + *cache = MapPreviewCache { key, pictures: HashMap::new() }; + } + }); + } + + /// Make output map `index`'s pictures for `params` unless they are made, and draw again to show them + pub(super) fn fill(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value, index: usize) { + if Self::get(ctx, index).is_some() { + return; + } + + let preview = app.session.export_preview(params, index, PREVIEW_SIDE_PIXELS).ok().flatten(); + let pictures = preview.map(|preview| Arc::new(MapPreviewPictures::new(ctx, &preview, index))); + ctx.data_mut(|data| data.get_temp_mut_or_default::(Self::id()).pictures.insert(index, pictures)); + ctx.request_repaint(); + } +} diff --git a/crates/ui-egui/src/export_templates/map_preview_pictures.rs b/crates/ui-egui/src/export_templates/map_preview_pictures.rs new file mode 100644 index 00000000..817cf3e8 --- /dev/null +++ b/crates/ui-egui/src/export_templates/map_preview_pictures.rs @@ -0,0 +1,43 @@ +use egui::{Color32, ColorImage, TextureHandle, TextureOptions}; +use texturecraft_engine::formats::{Dest, MapPreview}; + +/// An output map's file, small, then each of its channels in grey, as textures to draw +pub(super) struct MapPreviewPictures { + pub(super) file: TextureHandle, + /// Empty for a one-channel file, whose picture is its channel + pub(super) channels: Vec<(Dest, TextureHandle)>, + /// Height over width + pub(super) aspect: f32, +} + +impl MapPreviewPictures { + /// The pictures of `preview`, the preview of output map `index` + pub(super) fn new(ctx: &egui::Context, preview: &MapPreview, index: usize) -> MapPreviewPictures { + let size = [preview.width as usize, preview.height as usize]; + let pixel_count = size[0] * size[1]; + let count = preview.channels.len().max(1); + let value = |pixel: usize, channel: usize| preview.pixels.get(pixel * count + channel).copied().unwrap_or(0); + let load = |name: String, image: ColorImage| ctx.load_texture(name, image, TextureOptions::LINEAR); + + // The file as a viewer shows it: its colour, or its first channel in grey; alpha left out + let color = preview.channels.starts_with(&[Dest::R, Dest::G, Dest::B]); + let file = (0..pixel_count) + .map(|pixel| if color { Color32::from_rgb(value(pixel, 0), value(pixel, 1), value(pixel, 2)) } else { Color32::from_gray(value(pixel, 0)) }) + .collect(); + let channels = if preview.channels.len() > 1 { + let channel = |(k, dest): (usize, &Dest)| { + let image = ColorImage::from_gray_iter(size, (0..pixel_count).map(|pixel| value(pixel, k))); + (*dest, load(format!("export_map_preview_{index}_{k}"), image)) + }; + preview.channels.iter().enumerate().map(channel).collect() + } else { + Vec::new() + }; + + MapPreviewPictures { + file: load(format!("export_map_preview_{index}"), ColorImage::new(size, file)), + channels, + aspect: preview.height as f32 / preview.width.max(1) as f32, + } + } +} diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs new file mode 100644 index 00000000..e81666d4 --- /dev/null +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -0,0 +1,12 @@ +use texturecraft_engine::formats::FileFormat; + +/// A file an output map writes for the current texture set, as `export.plan` lists it +#[derive(Clone)] +pub(super) struct PlannedOutput { + pub(super) file: String, + /// Pixels per side (export.plan never plans an atlas, so every file is square) + pub(super) size: u64, + pub(super) format: Option, + pub(super) bit_depth: u8, + pub(super) dithering: bool, +} diff --git a/crates/ui-egui/src/export_templates/row_edit.rs b/crates/ui-egui/src/export_templates/row_edit.rs index 6568dac9..2143edfb 100644 --- a/crates/ui-egui/src/export_templates/row_edit.rs +++ b/crates/ui-egui/src/export_templates/row_edit.rs @@ -6,4 +6,6 @@ pub(super) struct RowEdit { pub(super) action: Option, /// A map dropped on a channel swatch, to ask which of its channels to use. pub(super) pending: Option, + /// The output map whose channel swatch the pointer is on, for its file preview + pub(super) hovered_output: Option, } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 2dacd6cd..92a3847b 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -639,3 +639,23 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() { assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}"); assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}"); } + +#[test] +fn hovering_a_channel_swatch_shows_the_file_its_output_writes() { + let library = TemplateLibrary::new("map-preview"); + let mut h = harness(&library); + let swatch = + h.get_all_by_role(egui::Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with("B: Metallic"))).unwrap().rect().center(); + let pictures = h.query_all_by_role(egui::Role::Image).count(); + let roughness_lines = h.query_all_by_label("Roughness, gray value").count(); + let file_names = h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count(); + assert!(h.query_by_label_contains(" · png").is_none(), "nothing shows before the hover"); + + h.hover_at(swatch); + h.run_steps(30); + + assert!(h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count() > file_names, "the file's name"); + assert!(h.query_by_label_contains(" · png").is_some(), "the file's size and type"); + assert!(h.query_all_by_role(egui::Role::Image).count() > pictures, "the file and its channels, small"); + assert!(h.query_all_by_label("Roughness, gray value").count() > roughness_lines, "another channel's source is named"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c3a44fc8..6c51fb6c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -76,7 +76,7 @@ shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, `hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and -`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by +`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `export.preview` takes the same params plus `map` (an index into the template's maps) and `side` (pixels, at most 512) and returns that map for the first texture set `ts` names, small: `{width, height, channels, pixels}` with the 8-bit values an sRGB file stores, or null when the set writes no file for it. `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its From a0d996fc0c954b1bff9e8d5abd3b959e3346a289 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:19:39 +0000 Subject: [PATCH 07/34] Export textures: the window's look and the Settings tab on the reference's columns, with sentence-case tabs and the bottom bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The window's own look (export_window/export_look, drawn): controls a step darker than the window with a light edge, hovered and lit faces a step lighter, boxed checks, rounded sentence-case tabs that open into the body, orange only on Export, scroll bars in a 12 px strip beside each list. Settings lays out on the reference's columns and pitches: the texture set list (the selected row in the frame colour with a light edge), General Export Parameters with Normal map format and Color space under Padding (Color space says in its tooltip that data maps stay linear), the output directory as a field with "…", the extra-file ticks under the parameters, and a set's page with one pen column for its parameters and its Output maps rows. The tab row's right-hand control sits 9 px above the divider. ui_snapshots export_window_snapshots captures every tab at the reference window size. --- crates/ui-egui/src/export_window.rs | 1227 +++++++++-------- crates/ui-egui/src/export_window/drawn.rs | 305 ++++ .../ui-egui/src/export_window/export_look.rs | 118 ++ .../ui-egui/src/export_window/page_place.rs | 26 + .../ui-egui/tests/it/export_map_overrides.rs | 26 +- crates/ui-egui/tests/it/export_overrides.rs | 2 +- .../tests/it/export_reference_texts.rs | 2 +- crates/ui-egui/tests/it/export_settings.rs | 10 +- .../tests/it/export_template_guards.rs | 17 +- crates/ui-egui/tests/it/output_templates.rs | 11 +- crates/ui-egui/tests/it/side_panels.rs | 7 +- crates/ui-egui/tests/ui_snapshots.rs | 86 ++ 12 files changed, 1266 insertions(+), 571 deletions(-) create mode 100644 crates/ui-egui/src/export_window/drawn.rs create mode 100644 crates/ui-egui/src/export_window/export_look.rs create mode 100644 crates/ui-egui/src/export_window/page_place.rs diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index aa005e46..86635088 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -14,42 +14,151 @@ use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; use crate::theme::{Tokens, caption, semibold}; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::icon_button; +pub(crate) mod drawn; +pub(crate) mod export_look; mod inherited_settings; mod map_row; +mod page_place; +pub(crate) use export_look::ExportLook; use inherited_settings::InheritedSettings; use map_row::MapRow; +use page_place::PagePlace; /// The reference window's size; a smaller screen gets a smaller window const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); /// Space kept free around the content on a small screen: the title bar, the frame and a gap const WINDOW_VIEWPORT_MARGIN_POINTS: f32 = 72.0; -/// Width of the texture set list -const LIST_WIDTH: f32 = 250.0; -const ICON: f32 = 20.0; -/// Width of the label column of the parameter rows, as in the reference -const LABEL_COLUMN_WIDTH: f32 = 200.0; -/// Width of the value column of the parameter rows -const VALUE_WIDTH: f32 = 360.0; -/// Width of the first File type list; the bit depth list fills the rest of the row -const FILE_TYPE_WIDTH: f32 = 166.0; -/// Width of the dilation button, with room for its drop-down arrow -const DILATION_BUTTON_WIDTH: f32 = 60.0; -/// Size of a drop-down arrow, and its distance from the button's right edge -const CARET_SIZE: f32 = 10.0; -const CARET_INSET: f32 = 6.0; -/// A tab: padding around its name, the accent line on top of the open one, the name's size -const TAB_PADDING: egui::Vec2 = egui::vec2(10.0, 6.0); -const TAB_ACCENT_HEIGHT: f32 = 2.0; -const TAB_TEXT_SIZE: f32 = 12.5; -/// Height of a full-width row of the texture set list and where its text starts -const LIST_ROW_HEIGHT: f32 = 24.0; -const LIST_ROW_INDENT: f32 = 16.0; +/// The content runs nearly to the window's frame: one point inside its edge +const CONTENT_INSET: i8 = 1; +/// The widest dilation the slider offers, the cap `export.run` puts on its `dilation` +const MAX_DILATION_PIXELS: u32 = 256; + +// Layout in points from the window content's top left corner, measured on the locked mocks + +/// The tab row's height, down to the divider under it +pub(crate) const TAB_ROW_HEIGHT: f32 = 42.0; +/// The tabs' top edge +const TAB_TOP: f32 = 16.0; +/// The first tab's left edge +const TABS_LEFT: f32 = 7.5; +/// Middle of the controls at the tab row's right end, 9 points of air above the divider +const TAB_ROW_CONTROLS_Y: f32 = 19.5; +/// From the window's left edge to the buttons there +const LEFT_MARGIN: f32 = 7.5; +/// From the window's right edge to the buttons there +const RIGHT_MARGIN: f32 = 10.5; +/// The bottom bar's height under its divider +const FOOTER_HEIGHT: f32 = 46.0; +/// Middle of the bottom bar's buttons, from the window's bottom +const FOOTER_MIDDLE_FROM_BOTTOM: f32 = 22.5; /// Width of the bottom bar's buttons, the same for all as in the reference -const FOOTER_BUTTON_WIDTH: f32 = 126.0; -/// Width of the keyboard focus outline on the window's drawn controls -const FOCUS_OUTLINE_WIDTH: f32 = 2.0; +const FOOTER_BUTTON_WIDTH: f32 = 117.5; +/// Gap between the bottom bar's buttons +const FOOTER_BUTTON_GAP: f32 = 6.5; +/// Air between the texture count and Cancel +const COUNT_GAP: f32 = 14.5; +/// Open output directory: the air around its name +const OPEN_DIRECTORY_PADDING: f32 = 24.0; +/// Open output directory: its distance from the window's right edge +const OPEN_DIRECTORY_FROM_RIGHT: f32 = 12.0; +/// The strip at a list's right edge that holds its scroll bar +pub(crate) const GUTTER: f32 = 12.0; +/// Size of the menu (≡) and reset glyphs of the lists and pages +const MENU_ICON_SIZE: f32 = 14.0; + +/// Width of the texture set list +const SET_LIST_WIDTH: f32 = 240.7; +/// Centre of the set list's menu, x +const SET_MENU_X: f32 = 227.5; +/// Centre of the set list's menu, y +const SET_MENU_Y: f32 = 57.0; +/// Top of the set list's first row, Global settings +const SET_ROWS_TOP: f32 = 70.0; +/// Height of a set list row +const SET_ROW_HEIGHT: f32 = 25.0; +/// Where a set row's check box starts +const SET_CHECK_LEFT: f32 = 18.8; +/// Where a set row's name starts +const SET_NAME_LEFT: f32 = 36.7; +/// Where Global settings starts, having no check box +const GLOBAL_NAME_LEFT: f32 = 16.0; +/// The override mark's distance from its row's end +const OVERRIDE_MARK_FROM_RIGHT: f32 = 14.0; +/// Side of a check box's click area +const CHECK_HIT_SIZE: f32 = 20.0; +/// How far a check box's click area reaches past its box on each side +const CHECK_HIT_OVERHANG: f32 = 3.5; + +/// A page's label column +const LABEL_LEFT: f32 = 257.6; +/// Where a page's controls start +const CONTROLS_LEFT: f32 = 455.0; +/// Where a page's controls end, from the window's right edge +const CONTROLS_RIGHT_MARGIN: f32 = 112.8; +/// A page header's glyph, from the window's right edge +const PAGE_ICON_FROM_RIGHT: f32 = 22.6; +/// Middle of the Global settings page's header +const GLOBAL_HEADER_Y: f32 = 71.0; +/// Middle of its reset glyph +const GLOBAL_ICON_Y: f32 = 70.0; +/// Middle of its first parameter row +const GLOBAL_FIRST_ROW_Y: f32 = 115.0; +/// Pitch of its parameter rows +const GLOBAL_ROW_PITCH: f32 = 35.5; +/// From the last parameter row to the first tick +const CHECKS_GAP: f32 = 30.0; +/// Pitch of the ticks +const CHECK_PITCH: f32 = 24.0; +/// The page's least width before it scrolls +const MIN_PAGE_WIDTH: f32 = 640.0; +/// The Global settings page's height under the tab row +const GLOBAL_PAGE_HEIGHT: f32 = 376.0; +/// The ticks sit a point in from the labels +const CHECK_INDENT: f32 = 1.0; +/// A tick's label starts after its box and the gap +const CHECK_LABEL_ROOM: f32 = 18.0; +/// Width of the output directory's "…" and reset buttons +const BROWSE_WIDTH: f32 = 22.0; +/// Gap before them +const BROWSE_GAP: f32 = 4.0; +/// Room the file type list keeps for its chevron past its longest entry +const FILE_TYPE_ROOM: f32 = 36.0; +/// Gap between two controls on one row +const PAIR_GAP: f32 = 6.6; +/// Width of the dilation width's dropdown +const DILATION_WIDTH: f32 = 56.4; + +/// Middle of a texture set page's header +const SET_HEADER_Y: f32 = 74.0; +/// Middle of its first override row +const SET_FIRST_ROW_Y: f32 = 121.0; +/// Pitch of its override rows +const SET_ROW_PITCH: f32 = 36.0; +/// Centre of the override pens +const PEN_CENTRE: f32 = 464.4; +/// Where an inherited value's text starts +const VALUE_LEFT: f32 = 479.4; +/// Where an override's control starts +const OVERRIDE_LEFT: f32 = 480.3; +/// The divider above Output maps +const SET_DIVIDER_Y: f32 = 257.0; +/// Middle of the Output maps header +const MAPS_HEADER_Y: f32 = 288.0; +/// Top of the first Output maps row +const MAPS_TOP: f32 = 318.0; +/// Pitch of the Output maps rows +const MAP_ROW_PITCH: f32 = 34.0; +/// Where an Output maps row's tick starts +const MAP_CHECK_LEFT: f32 = 258.6; +/// Where its file name starts +const MAP_NAME_LEFT: f32 = 280.1; +/// The inherited bit depth's text, after the file type's +const BITS_TEXT_OFFSET: f32 = 32.0; +/// Width of a map's file type list +const MAP_FORMAT_WIDTH: f32 = 61.2; +/// Width of a map's own size list +const MAP_SIZE_WIDTH: f32 = 100.0; /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -104,9 +213,16 @@ pub(crate) fn depth_label(format: Option, bit_depth: u8, dithering: } } -/// A file type list and its bit depth list; `from_template` adds "Based on output template" -/// (an empty `format`), which leaves the bit depth to the template. -fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, format: &mut String, bit_depth: &mut u8, dithering: &mut bool) { +/// A file type list and its bit depth list in `rects`; `from_template` adds "Based on output template" (an empty `format`) +fn file_type_lists( + ui: &mut Ui, + id: (&str, usize, usize), + from_template: bool, + rects: [egui::Rect; 2], + format: &mut String, + bit_depth: &mut u8, + dithering: &mut bool, +) { let parsed = FileFormat::from_extension(format); // A depth the type does not have (or none) becomes its default @@ -116,10 +232,7 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f (*bit_depth, *dithering) = (f.default_depth(), false); } let shown = if format.is_empty() { tr("Based on output template").to_string() } else { file_type_name(format) }; - - // Tall enough for the whole list - let list = egui::ComboBox::from_id_salt(("type", id)).width(if from_template { FILE_TYPE_WIDTH } else { 90.0 }).height(f32::INFINITY); - list.selected_text(shown).show_ui(ui, |ui| { + drawn::combo(ui, rects[0], ("type", id), shown, |ui| { if from_template { if ui.selectable_label(format.is_empty(), tr("Based on output template")).clicked() { format.clear(); @@ -141,18 +254,21 @@ fn file_type_lists(ui: &mut Ui, id: (&str, usize, usize), from_template: bool, f } } }); + + // A file type with one bit depth (or none) shows its bit depth list greyed let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; - ui.add_enabled_ui(options.len() > 1, |ui| { - // On the global page the bit depth list fills the row - let width = if from_template { VALUE_WIDTH - FILE_TYPE_WIDTH - ui.spacing().item_spacing.x } else { 120.0 }; - egui::ComboBox::from_id_salt(("bits", id)).width(width).selected_text(shown).show_ui(ui, |ui| { - for (d, dither) in options { - if ui.selectable_label((*bit_depth, *dithering) == (d, dither), depth_label(parsed, d, dither)).clicked() { - (*bit_depth, *dithering) = (d, dither); - } + if options.len() < 2 { + drawn::disabled_combo(ui, rects[1], &shown, tr("Bit depth")); + return; + } + + drawn::combo(ui, rects[1], ("bits", id), shown, |ui| { + for (depth, dither) in options { + if ui.selectable_label((*bit_depth, *dithering) == (depth, dither), depth_label(parsed, depth, dither)).clicked() { + (*bit_depth, *dithering) = (depth, dither); } - }); + } }); } @@ -190,10 +306,10 @@ pub(crate) fn template_groups(app: &TextureCraftApp, builtins: &[ExportPreset]) (first, rest) } -/// A template dropdown over `first` and `rest`; true when `current` changed -fn template_combo(ui: &mut Ui, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { +/// A template dropdown in `rect` over `first` and `rest`; true when `current` changed +fn template_combo(ui: &mut Ui, rect: egui::Rect, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { let mut changed = false; - egui::ComboBox::from_id_salt(id).width(VALUE_WIDTH).selected_text(current.clone()).show_ui(ui, |ui| { + drawn::combo(ui, rect, id, current.clone(), |ui| { for (name, have) in first { if *have { changed |= ui.selectable_value(current, (*name).to_string(), *name).on_hover_text(*name).changed(); @@ -535,16 +651,14 @@ fn set_template(app: &TextureCraftApp, ts: usize) -> String { app.ui.export.sets.get(&ts).and_then(|o| o.preset.clone()).unwrap_or_else(|| app.ui.export.preset.clone()) } -/// Shorten a long file name pattern at the front, as the reference's Output maps rows do -fn elide_front(text: &str) -> String { - const SHOWN: usize = 26; - let n = text.chars().count(); - if n <= SHOWN { text.to_string() } else { format!("…{}", text.chars().skip(n - (SHOWN - 1)).collect::()) } +/// A file type and bit depth as an Output maps row shows them ("png 8 bits"), and the two apart +fn file_type_text(t: &FileType) -> String { + let (format, bits) = file_type_parts(t); + format!("{format} {bits}") } -/// A file type and bit depth as an Output maps row shows them ("png 8 bits") -fn file_type_text(t: &FileType) -> String { - format!("{} {}", file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) +fn file_type_parts(t: &FileType) -> (String, String) { + (file_type_name(&t.format), depth_label(FileFormat::from_extension(&t.format), t.bit_depth, t.dithering)) } /// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for @@ -583,80 +697,114 @@ fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec { rows } -/// The Output maps section of texture set `ts`'s page -fn output_maps(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize) { +/// 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 rows = map_rows(app, ts); let template = set_template(app, ts); - let o = app.ui.export.sets.entry(ts).or_default(); - if o.maps_template != template { - o.maps.clear(); - o.maps_template = template; + let overrides = app.ui.export.sets.entry(ts).or_default(); + if overrides.maps_template != template { + overrides.maps.clear(); + overrides.maps_template = template; } + let mut menu = None; - header(ui, tr("Output maps"), |ui| { - list_menu(ui, |ui| { - for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(i); - } + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(MAPS_HEADER_Y), tr("Output maps"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, MAPS_HEADER_Y), tr("Output maps menu"), |ui| { + for (i, label) in [tr("Check all"), tr("Uncheck all"), tr("Invert all")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(i); } - ui.separator(); - for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { - if ui.button(label).clicked() { - menu = Some(3 + i); - } + } + ui.separator(); + for (i, label) in [tr("Override every item"), tr("Clear all overrides")].into_iter().enumerate() { + if ui.button(label).clicked() { + menu = Some(3 + i); + } + } + ui.separator(); + }); + + // The rows scroll under the header, the scroll bar in its strip at the window's right edge + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(("exp_maps_scroll", ts)).auto_shrink([false; 2]).show(ui, |ui| { + let height = rows.len() as f32 * MAP_ROW_PITCH; + 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()); } - ui.separator(); }); }); - egui::Grid::new(("exp_maps", ts)).num_columns(3).spacing(vec2(8.0, 6.0)).show(ui, |ui| { - for row in &rows { - let m = o.maps.entry(row.map).or_default(); - ui.checkbox(&mut m.enabled, ""); - ui.add(egui::Label::new(elide_front(&row.pattern)).selectable(false)).on_hover_text(&row.pattern); - ui.horizontal(|ui| { - if icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), m.file_type.is_some(), ICON).clicked() { - m.file_type = if m.file_type.is_some() { None } else { Some(row.inherited.clone()) }; - } - match &mut m.file_type { - Some(t) => file_type_combo(ui, ("exp_map", ts, row.map), t), - None => { - ui.label(file_type_text(&row.inherited)); - } - } - map_size_combo(ui, ("exp_map_size", ts, row.map), &mut m.size); - }); - ui.end_row(); - } - }); + for row in &rows { - let m = o.maps.entry(row.map).or_default(); + let map_export = overrides.maps.entry(row.map).or_default(); match menu { - Some(0) => m.enabled = true, - Some(1) => m.enabled = false, - Some(2) => m.enabled = !m.enabled, - Some(3) if m.file_type.is_none() => m.file_type = Some(row.inherited.clone()), - Some(4) => (m.file_type, m.size) = (None, None), + Some(0) => map_export.enabled = true, + Some(1) => map_export.enabled = false, + Some(2) => map_export.enabled = !map_export.enabled, + Some(3) if map_export.file_type.is_none() => map_export.file_type = Some(row.inherited.clone()), + Some(4) => (map_export.file_type, map_export.size) = (None, None), _ => {} } } - o.maps.retain(|_, m| *m != MapExport::default()); + overrides.maps.retain(|_, map_export| *map_export != MapExport::default()); } -/// An output map's size: the export's, or its own, which wins over it -fn map_size_combo(ui: &mut Ui, id: (&str, usize, usize), size: &mut Option) { +/// 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) { + 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)); + let name_left = place.x(MAP_NAME_LEFT); + let shown = drawn::fitted(ui, &row.pattern, place.x(CONTROLS_LEFT) - name_left, true, false); + drawn::check(ui, ui.scope_id().with(("exp_map_tick", ts, row.map)), hit, egui::pos2(check_left, y), &mut map_export.enabled, None, &shown); + let color = if map_export.enabled { look.text } else { look.text_dim }; + drawn::label_at(ui, name_left, y, &shown, color, false).on_hover_text(&row.pattern); + + let pen = egui::pos2(place.x(PEN_CENTRE), y); + if drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, tr("Enable override"), true, map_export.file_type.is_some()).clicked() { + map_export.file_type = if map_export.file_type.is_some() { None } else { Some(row.inherited.clone()) }; + } + + // The map's size list keeps the row's right end; the file type and bit depth come before it + let right = place.right - CONTROLS_RIGHT_MARGIN; + let size_rect = drawn::control_rect(right - MAP_SIZE_WIDTH, right, y); + match &mut map_export.file_type { + Some(FileType { format, bit_depth, dithering }) => { + let format_rect = drawn::control_rect(place.x(OVERRIDE_LEFT), place.x(OVERRIDE_LEFT) + MAP_FORMAT_WIDTH, y); + let bits_rect = drawn::control_rect(format_rect.right() + PAIR_GAP, size_rect.left() - PAIR_GAP, y); + file_type_lists(ui, ("exp_map", ts, row.map), false, [format_rect, bits_rect], format, bit_depth, dithering); + } + 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); +} + +/// A map's inherited file type: "png" and "8 bits" in their columns, one text to assistive technology +fn inherited_file_type(ui: &mut Ui, place: PagePlace, y: f32, inherited: &FileType) { + let look = ExportLook::get(ui.ctx()); + let (format, bits) = file_type_parts(inherited); + let format_rect = drawn::text_at(ui, place.x(VALUE_LEFT), y, &format, look.text, false); + let bits_rect = drawn::text_at(ui, place.x(VALUE_LEFT + BITS_TEXT_OFFSET), y, &bits, look.text, false); + let text = file_type_text(inherited); + let response = + ui.interact(format_rect.union(bits_rect), ui.scope_id().with(("exp_map_inherited", place.y(0.0).to_bits(), y.to_bits())), egui::Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &text)); +} + +/// 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}")); - egui::ComboBox::from_id_salt(id) - .selected_text(shown) - .show_ui(ui, |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}")); - } - }) - .response - .on_hover_text(tr("This map's own size, which wins over the export size")); + 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}")); + } + }) + .response + .on_hover_text(tr("This map's own size, which wins over the export size")); } /// Count the files planned across all selected texture sets. @@ -670,54 +818,10 @@ fn selected_texture_count(app: &mut TextureCraftApp) -> usize { count } -/// The keyboard focus outline of a drawn control: inside `response`'s rect, in the strong text -/// colour, so it differs from the accent of the selected one and the fill of the hovered one -fn paint_focus(ui: &Ui, response: &egui::Response) { - if response.has_focus() { - let stroke = egui::Stroke::new(FOCUS_OUTLINE_WIDTH, Tokens::get(ui.ctx()).text_strong); - ui.painter().rect_stroke(response.rect, 0.0, stroke, egui::StrokeKind::Inside); - } -} - -/// A window tab: a box, lighter and with an accent line on top when open -fn tab_button(ui: &mut Ui, label: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let color = if selected { tokens.text_strong } else { tokens.text }; - let galley = ui.painter().layout_no_wrap(label.to_string(), semibold(TAB_TEXT_SIZE), color); - let (rect, response) = ui.allocate_exact_size(galley.size() + 2.0 * TAB_PADDING, egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Tab, true, selected, label)); - - let painter = ui.painter(); - let fill = match (selected, response.hovered()) { - (true, _) => tokens.panel, - (false, true) => tokens.row_hover, - (false, false) => tokens.row, - }; - painter.rect(rect, 0.0, fill, egui::Stroke::new(1.0, tokens.separator), egui::StrokeKind::Inside); - if selected { - painter.rect_filled(egui::Rect::from_min_size(rect.min, vec2(rect.width(), TAB_ACCENT_HEIGHT)), 0.0, tokens.accent); - } - painter.galley(rect.min + TAB_PADDING, galley, color); - paint_focus(ui, &response); - response -} - -/// A bottom bar button, as wide as the others -fn footer_button(text: &str) -> egui::Button<'_> { - egui::Button::new(text).min_size(vec2(FOOTER_BUTTON_WIDTH, 0.0)) -} - -/// A header with a menu or tool at its right end -fn header(ui: &mut Ui, title: &str, right: impl FnOnce(&mut Ui)) { - ui.horizontal(|ui| { - ui.label(caption(title)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), right); - }); -} - -/// The menu button of a list header -fn list_menu(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { - ui.menu_button(RichText::new(ic::LIST_CHECKS).size(15.0), add); +/// The menu button (≡) of a list or page header centred on `centre`, called `name` for assistive technology; its menu holds `add` +fn list_menu(ui: &mut Ui, centre: egui::Pos2, name: &str, add: impl FnOnce(&mut Ui)) { + let response = drawn::icon_button(ui, centre, ic::LIST, MENU_ICON_SIZE, name, true, false); + egui::Popup::menu(&response).show(add); } /// Check all, Uncheck all, Invert all over the texture sets @@ -736,52 +840,53 @@ fn set_checks_menu(app: &mut TextureCraftApp, ui: &mut Ui) { ui.separator(); } -/// Output directory: the path as a button that opens the folder picker, and a reset -#[cfg(not(target_arch = "wasm32"))] -fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.label(tr("Output directory")); - ui.horizontal(|ui| { - let dir = app.ui.export.dir.clone(); - let button = egui::Button::new(dir.as_str()).truncate(); - if ui.add_sized(vec2(VALUE_WIDTH - 24.0, 20.0), button).on_hover_text(dir.as_str()).clicked() { - app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { - if let Some(d) = paths.first() { - app.ui.export.dir = d.display().to_string(); - } - }); - } - if ui.small_button("R").on_hover_text(tr("Reset to default")).clicked() { - app.ui.export.dir = ExportUi::default().dir; - } - }); - ui.end_row(); +/// A parameter's name at the label column, its middle at `y` +fn row_label(ui: &mut Ui, place: PagePlace, y: f32, text: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), y, text, look.text, false); } -/// The dilation width: a button showing it, with a slider in its menu (only for paddings that -/// have a width) -fn dilation_button(ui: &mut Ui, padding: &str, dilation: &mut u32) { +/// Output directory at `y`: the path as a field that opens the folder picker, "…" and a reset +#[cfg(not(target_arch = "wasm32"))] +fn output_directory(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, y: f32) { + row_label(ui, place, y, tr("Output directory")); + let right = place.right - CONTROLS_RIGHT_MARGIN; + let dir = app.ui.export.dir.clone(); + let field = drawn::control_rect(place.x(CONTROLS_LEFT), right - BROWSE_WIDTH - BROWSE_GAP, y); + let path = drawn::field_button(ui, field, ui.scope_id().with("exp_dir"), &dir).on_hover_text(dir.as_str()); + let browse_rect = drawn::control_rect(right - BROWSE_WIDTH, right, y); + let browse_name = tr("Choose the output folder"); + let browse = drawn::button_with_id(ui, ui.scope_id().with("exp_dir_browse"), browse_rect, "…", browse_name, false, true).on_hover_text(browse_name); + if path.clicked() || browse.clicked() { + app.ask_file(FileDialog::folder().directory(dir), Bound::App, |app, paths| { + if let Some(directory) = paths.first() { + app.ui.export.dir = directory.display().to_string(); + } + }); + } + let reset = drawn::control_rect(right + BROWSE_GAP, right + BROWSE_GAP + BROWSE_WIDTH, y); + let reset_id = ui.scope_id().with("exp_dir_reset"); + let reset_name = tr("Reset to default"); + if drawn::button_with_id(ui, reset_id, reset, ic::ARROW_COUNTER_CLOCKWISE, reset_name, false, true).on_hover_text(reset_name).clicked() { + app.ui.export.dir = ExportUi::default().dir; + } +} + +/// The dilation width in `rect`: a dropdown with a slider in its menu, greyed for paddings without a width +fn dilation_button(ui: &mut Ui, rect: egui::Rect, id_salt: &str, padding: &str, dilation: &mut u32) { let enabled = has_width(padding); + let response = drawn::combo_button(ui, rect, ui.scope_id().with(("exp_dilation", id_salt)), &dilation.to_string(), enabled); + if !enabled { + response.on_hover_text(tr("This padding mode does not use a dilation width")); + return; + } // The menu stays open while the slider is used - let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let r = ui.add_enabled_ui(enabled, |ui| { - let button = egui::Button::new(dilation.to_string()).min_size(vec2(DILATION_BUTTON_WIDTH, 0.0)); - egui::containers::menu::MenuButton::from_button(button).config(config).ui(ui, |ui| { - ui.label(tr("Dilation (pixels)")); - ui.add(egui::Slider::new(dilation, 0..=256).step_by(1.0)); - }) + let response = response.on_hover_text(tr("Dilation in pixels")); + egui::Popup::menu(&response).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { + ui.label(tr("Dilation (pixels)")); + ui.add(egui::Slider::new(dilation, 0..=MAX_DILATION_PIXELS).step_by(1.0)); }); - - // The drop-down arrow is drawn apart, so the button's name stays the number - let tokens = Tokens::get(ui.ctx()); - let arrow_color = if enabled { tokens.text } else { tokens.text_dim }; - let arrow_at = r.response.rect.right_center() - vec2(CARET_INSET, 0.0); - ui.painter().text(arrow_at, egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(CARET_SIZE), arrow_color); - if enabled { - r.response.on_hover_text(tr("Dilation in pixels")); - } else { - r.response.on_disabled_hover_text(tr("This padding mode does not use a dilation width")); - } } /// A greyed checkbox with its tooltip and the "not available" hint @@ -794,13 +899,21 @@ fn unavailable_checkbox(ui: &mut Ui, label: &str, tooltip: &str) { }); } -/// The Global settings page -fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { - let mut reset = false; - header(ui, tr("General Export Parameters"), |ui| { - reset = icon_button(ui, ic::ARROW_COUNTER_CLOCKWISE, tr("Restore the default export parameters"), false, ICON).clicked(); - }); - if reset { +/// A tick of the global page at `y` with its label after it +fn page_check(ui: &mut Ui, place: PagePlace, y: f32, on: &mut bool, label: &str) -> egui::Response { + let left = place.x(LABEL_LEFT + CHECK_INDENT); + let width = CHECK_LABEL_ROOM + drawn::text_width(ui, label, false); + let hit = egui::Rect::from_min_max(egui::pos2(left, y - CHECK_HIT_SIZE / 2.0), egui::pos2(left + width, y + CHECK_HIT_SIZE / 2.0)); + drawn::check(ui, ui.scope_id().with(("exp_check", label)), hit, egui::pos2(left, y), on, Some(label), label) +} + +/// The Global settings page, laid out from `place` +fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, builtins: &[ExportPreset]) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(GLOBAL_HEADER_Y), tr("General Export Parameters"), look.text, true); + let reset_at = place.right_inset(PAGE_ICON_FROM_RIGHT, GLOBAL_ICON_Y); + let reset_tip = tr("Restore the default export parameters"); + if drawn::icon_button(ui, reset_at, ic::ARROW_COUNTER_CLOCKWISE, MENU_ICON_SIZE, reset_tip, true, false).on_hover_text(reset_tip).clicked() { let defaults = ExportUi::default(); let settings = &mut app.ui.export; ( @@ -832,167 +945,186 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ); crate::export_templates::select(app, defaults.preset); } + + // One row per parameter at the reference's pitch; the browser has no output directory + let mut rows = (0..).map(|k| place.y(GLOBAL_FIRST_ROW_Y + k as f32 * GLOBAL_ROW_PITCH)); + let mut next_row = || rows.next().unwrap_or_default(); + let (left, right) = (place.x(CONTROLS_LEFT), place.right - CONTROLS_RIGHT_MARGIN); + #[cfg(not(target_arch = "wasm32"))] + output_directory(app, ui, place, next_row()); + + let y = next_row(); + row_label(ui, place, y, tr("Output template")); let (first, rest) = template_groups(app, builtins); - egui::Grid::new("exp_grid").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - // The browser downloads the files instead - #[cfg(not(target_arch = "wasm32"))] - output_directory(app, ui); - ui.label(tr("Output template")); - let mut picked = app.ui.export.preset.clone(); - if template_combo(ui, "exp_preset", &mut picked, &first, &rest) { - crate::export_templates::select(app, picked); + let mut picked = app.ui.export.preset.clone(); + if template_combo(ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { + crate::export_templates::select(app, picked); + } + + // The file type list fits its longest entry, the bit depth list fills the rest + let y = next_row(); + row_label(ui, place, y, tr("File type")); + let type_right = left + drawn::text_width(ui, tr("Based on output template"), false) + FILE_TYPE_ROOM; + let rects = [drawn::control_rect(left, type_right, y), drawn::control_rect(type_right + PAIR_GAP, right, y)]; + let settings = &mut app.ui.export; + file_type_lists(ui, ("exp_global", 0, 0), true, rects, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); + + let y = next_row(); + row_label(ui, place, y, tr("Size")); + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_size", size_label(settings.size), |ui| { + ui.selectable_value(&mut settings.size, 0, size_label(0)); + ui.separator(); + ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); + for size in SIZES { + ui.selectable_value(&mut settings.size, size, size_label(size)); } - ui.end_row(); - ui.label(tr("File type")); - ui.horizontal(|ui| { - let settings = &mut app.ui.export; - file_type_lists(ui, ("exp_global", 0, 0), true, &mut settings.format, &mut settings.bit_depth, &mut settings.dithering); - }); - ui.end_row(); - ui.label(tr("Size")); - let settings = &mut app.ui.export; - egui::ComboBox::from_id_salt("exp_size").width(VALUE_WIDTH).selected_text(size_label(settings.size)).show_ui(ui, |ui| { - ui.selectable_value(&mut settings.size, 0, size_label(0)); - ui.separator(); - ui.selectable_value(&mut settings.size, SIZE_OF_LARGEST_SET, size_label(SIZE_OF_LARGEST_SET)); - for size in SIZES { - ui.selectable_value(&mut settings.size, size, size_label(size)); - } - }); - ui.end_row(); - ui.label(tr("Padding")); - ui.horizontal(|ui| { - let width = VALUE_WIDTH - DILATION_BUTTON_WIDTH - ui.spacing().item_spacing.x; - egui::ComboBox::from_id_salt("exp_pad").width(width).selected_text(tr(padding_label(&settings.padding))).show_ui(ui, |ui| { - for (value, label) in PADDINGS { - ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); - } - }); - dilation_button(ui, &settings.padding, &mut settings.dilation); - }); - ui.end_row(); }); - // The browser downloads the textures only, so it has no USD asset to add - #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.usd_asset, tr("Export USD asset")) - .on_hover_text(tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures")); - #[cfg(target_arch = "wasm32")] - unavailable_checkbox( - ui, - tr("Export USD asset"), - tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"), - ); + let y = next_row(); + row_label(ui, place, y, tr("Padding")); + let padding_rect = drawn::control_rect(left, right - DILATION_WIDTH - PAIR_GAP, y); + drawn::combo(ui, padding_rect, "exp_pad", tr(padding_label(&settings.padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(&mut settings.padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, drawn::control_rect(right - DILATION_WIDTH, right, y), "global", &settings.padding, &mut settings.dilation); - // The MaterialX export sits below the USD one; the browser downloads the textures only - #[cfg(not(target_arch = "wasm32"))] - ui.checkbox(&mut app.ui.export.materialx, tr("Export MaterialX")); - #[cfg(target_arch = "wasm32")] - crate::unavailable::checkbox(ui, false, tr("Export MaterialX")); + let y = next_row(); + row_label(ui, place, y, tr("Normal map format")); + let normal_label = match settings.normal_format.as_str() { + "openGl" => "OpenGL", + "directX" => "DirectX", + _ => tr("From template / project"), + }; + drawn::combo(ui, drawn::control_rect(left, right, y), "exp_nf", normal_label, |ui| { + for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { + ui.selectable_value(&mut settings.normal_format, value.to_string(), label); + } + }); - ui.checkbox(&mut app.ui.export.shader_parameters, tr("Export shader settings")) - .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); - ui.add_space(8.0); - egui::Grid::new("exp_grid_more").num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let settings = &mut app.ui.export; - ui.label(tr("Normal map format")); - let normal_label = match settings.normal_format.as_str() { - "openGl" => "OpenGL", - "directX" => "DirectX", - _ => tr("From template / project"), + let y = next_row(); + row_label(ui, place, y, tr("Color space")); + let shown = if settings.color_space.is_empty() { tr("Default").to_string() } else { settings.color_space.clone() }; + let color_space = drawn::combo(ui, drawn::control_rect(left, right, y), "exp_cs", shown, |ui| { + ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); + for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { + ui.selectable_value(&mut settings.color_space, name.to_string(), name); + } + }); + color_space.response.on_hover_text(tr("Color maps only: normal, roughness, metallic and other data maps stay linear")); + + // The extra files, ticked under the parameters + let mut checks = (0..).map(|k| y + CHECKS_GAP + k as f32 * CHECK_PITCH); + let mut next_check = || checks.next().unwrap_or_default(); + let usd_tip = tr("Also write .usd next to the textures: the whole mesh, with a material per texture set that reads the exported textures"); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.usd_asset, tr("Export USD asset")).on_hover_text(usd_tip); + #[cfg(not(target_arch = "wasm32"))] + page_check(ui, place, next_check(), &mut settings.materialx, tr("Export MaterialX")); + #[cfg(target_arch = "wasm32")] + { + let at = |y: f32| { + egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::pos2(place.x(LABEL_LEFT), y - CHECK_HIT_SIZE / 2.0), vec2(right, CHECK_HIT_SIZE))) }; - egui::ComboBox::from_id_salt("exp_nf").selected_text(normal_label).show_ui(ui, |ui| { - for (value, label) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] { - ui.selectable_value(&mut settings.normal_format, value.to_string(), label); - } - }); - ui.end_row(); - ui.label(tr("Color space")); - let shown = if settings.color_space.is_empty() { tr("Default") } else { settings.color_space.as_str() }; - egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| { - ui.selectable_value(&mut settings.color_space, String::new(), tr("Default")); - for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] { - ui.selectable_value(&mut settings.color_space, name.to_string(), name); - } - }); - ui.end_row(); - }); + ui.scope_builder(at(next_check()), |ui| unavailable_checkbox(ui, tr("Export USD asset"), usd_tip)); + ui.scope_builder(at(next_check()), |ui| crate::unavailable::checkbox(ui, false, tr("Export MaterialX"))); + } + page_check(ui, place, next_check(), &mut settings.shader_parameters, tr("Export shader settings")) + .on_hover_text(tr("Save the settings of each shader instance in a JSON file")); } -/// The left column: Global settings, then a row per texture set with its export tick; a click -/// on a row shows the set's page, "*" marks a set with overrides -fn set_list(app: &mut TextureCraftApp, ui: &mut Ui) { - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| list_menu(ui, |ui| set_checks_menu(app, ui))); - }); - let header = list_row(ui, tr("Global settings"), app.ui.export.page.is_none()); - if header.clicked() { +/// The texture set list in `area`: Global settings, then a tick and a page per texture set, "*" on one with overrides +fn set_list(app: &mut TextureCraftApp, ui: &mut Ui, area: egui::Rect) { + let top = area.top() - TAB_ROW_HEIGHT; + list_menu(ui, egui::pos2(area.left() + SET_MENU_X, top + SET_MENU_Y), tr("Texture set list menu"), |ui| set_checks_menu(app, ui)); + let rows_right = area.right() - GUTTER; + let header = egui::Rect::from_min_max(egui::pos2(area.left(), top + SET_ROWS_TOP), egui::pos2(rows_right, top + SET_ROWS_TOP + SET_ROW_HEIGHT)); + if list_row(ui, header, tr("Global settings"), app.ui.export.page.is_none()).clicked() { app.ui.export.page = None; } - // Many texture sets scroll inside the list; the footer stays in view - let list_height = ui.available_height(); - egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| set_rows(app, ui)); + // Many texture sets scroll under Global settings, the scroll bar in its strip at the list's right + let rows = egui::Rect::from_min_max(egui::pos2(area.left(), header.bottom()), area.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("export_texture_sets").auto_shrink([false; 2]).show(ui, |ui| set_rows(app, ui, rows.width() - GUTTER)); + }); } -/// A row across the whole list, its name in bold; the selected one framed -fn list_row(ui: &mut Ui, text: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), LIST_ROW_HEIGHT), egui::Sense::click()); +/// A list row across `rect`, its name in bold +fn list_row(ui: &mut Ui, rect: egui::Rect, text: &str, selected: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_list_row", text)), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, text)); - - let painter = ui.painter(); - if selected { - painter.rect(rect, 0.0, tokens.row_selected, egui::Stroke::new(1.0, tokens.accent), egui::StrokeKind::Inside); - } else if response.hovered() { - painter.rect_filled(rect, 0.0, tokens.row_hover); - } - let font = semibold(egui::TextStyle::Body.resolve(ui.style()).size); - painter.text(rect.left_center() + vec2(LIST_ROW_INDENT, 0.0), egui::Align2::LEFT_CENTER, text, font, tokens.text_strong); - paint_focus(ui, &response); + paint_row(ui, rect, selected, response.hovered()); + drawn::text_at(ui, rect.left() + GLOBAL_NAME_LEFT, rect.center().y, text, look.text, true); + drawn::paint_focus(ui, &response); response } -/// A row per texture set: its export tick, its name and the override mark -fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui) { +/// A list row's face: the selected one in the frame colour with a light edge; a hairline under every row +fn paint_row(ui: &Ui, rect: egui::Rect, selected: bool, hovered: bool) { + let look = ExportLook::get(ui.ctx()); + let painter = ui.painter(); + if selected { + painter.rect(rect, 0.0, look.chrome, egui::Stroke::new(1.0, look.outline), egui::StrokeKind::Inside); + } else if hovered { + painter.rect_filled(rect, 0.0, look.raised); + } + painter.rect_filled(egui::Rect::from_min_max(rect.left_bottom(), rect.right_bottom() + vec2(0.0, 1.0)), 0.0, look.chrome); +} + +/// A row per texture set, `width` wide: its export tick, its name and the override mark +fn set_rows(app: &mut TextureCraftApp, ui: &mut Ui, width: f32) { + let look = ExportLook::get(ui.ctx()); + ui.spacing_mut().item_spacing.y = 0.0; for i in 0..app.session.set_count() { let name = app.session.doc.project.texture_sets.get(i).map(|t| t.name.clone()).unwrap_or_default(); + let (row, _) = ui.allocate_exact_size(vec2(width, SET_ROW_HEIGHT), egui::Sense::hover()); + let y = row.center().y; + + // The tick leaves the set in or out, the name after it opens the set's page + let name_area = egui::Rect::from_min_max(egui::pos2(row.left() + SET_NAME_LEFT - drawn::CHECK_LABEL_GAP, row.top()), row.max); + let selected = app.ui.export.page == Some(i); + paint_row(ui, row, selected, ui.rect_contains_pointer(name_area)); let mut on = !app.ui.export.skip.contains(&i); - ui.horizontal(|ui| { - if ui.checkbox(&mut on, "").changed() { - if on { - app.ui.export.skip.retain(|x| *x != i); - } else { - app.ui.export.skip.push(i); - } + let tick_area = egui::Rect::from_min_max(row.min, egui::pos2(name_area.left(), row.bottom())); + let tick_name = trf("Include {set}", &[("set", &name)]); + if drawn::check(ui, ui.scope_id().with(("exp_set_tick", i)), tick_area, egui::pos2(row.left() + SET_CHECK_LEFT, y), &mut on, None, &tick_name).changed() + { + if on { + app.ui.export.skip.retain(|x| *x != i); + } else { + app.ui.export.skip.push(i); } - if ui.selectable_label(app.ui.export.page == Some(i), name).clicked() { - app.ui.export.page = Some(i); - } - if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label("*").on_hover_text(tr("Override(s) active")); - }); - } - }); - ui.separator(); + } + + let page = ui.interact(name_area, ui.scope_id().with(("exp_set_row", i)), egui::Sense::click()); + page.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, &name)); + if page.clicked() { + app.ui.export.page = Some(i); + } + + let color = if on { look.text } else { look.text_dim }; + drawn::text_at(ui, row.left() + SET_NAME_LEFT, y, &name, color, true); + drawn::paint_focus(ui, &page); + if app.ui.export.sets.get(&i).is_some_and(SetExport::any) { + drawn::label_at(ui, row.right() - OVERRIDE_MARK_FROM_RIGHT, y, "*", look.text_dim, true).on_hover_text(tr("Override(s) active")); + } } } -/// A texture set page row: the label, the override toggle, then the inherited value as text or, -/// overridden, `edit`; true when the toggle was clicked -fn override_row(ui: &mut Ui, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui)) -> bool { - ui.label(label); - let mut toggled = false; - ui.horizontal(|ui| { - toggled = icon_button(ui, ic::PENCIL_SIMPLE, tr("Enable override"), on, ICON).clicked(); - if on { - edit(ui); - } else { - ui.label(inherited); - } - }); - ui.end_row(); +/// A texture set page row at `y`: label, pen, then the inherited value or `edit`; true when the pen was clicked +fn override_row(ui: &mut Ui, place: PagePlace, y: f32, label: &str, on: bool, inherited: &str, edit: impl FnOnce(&mut Ui, egui::Rect)) -> bool { + let look = ExportLook::get(ui.ctx()); + row_label(ui, place, y, label); + let pen = egui::pos2(place.x(PEN_CENTRE), y); + let toggled = drawn::icon_button(ui, pen, ic::PENCIL_SIMPLE, drawn::CHEVRON_SIZE, tr("Enable override"), true, on).clicked(); + if on { + edit(ui, drawn::control_rect(place.x(OVERRIDE_LEFT), place.right - CONTROLS_RIGHT_MARGIN, y)); + } else { + drawn::label_at(ui, place.x(VALUE_LEFT), y, inherited, look.text, false); + } toggled } @@ -1016,23 +1148,18 @@ fn toggle(o: &mut SetExport, row: usize, from: &InheritedSettings) { } } -/// A file type dropdown (without "Based on output template") and its bit depth -fn file_type_combo(ui: &mut Ui, id: (&str, usize, usize), t: &mut FileType) { - file_type_lists(ui, id, false, &mut t.format, &mut t.bit_depth, &mut t.dithering); -} - -/// A texture set's page: its overrides of the global settings -fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[ExportPreset]) { +/// 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); // "Based on output template": the override starts from what the template writes - if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|o| o.file_type.is_none()) { + if app.ui.export.format.is_empty() && app.ui.export.sets.get(&ts).is_none_or(|set_export| set_export.file_type.is_none()) { from.file_type = template_file_type(app, ts); } let (first, rest) = template_groups(app, builtins); - let first: Vec<(&str, bool)> = first.into_iter().filter(|(n, _)| !NOT_PER_SET.contains(n)).collect(); + 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 { @@ -1041,86 +1168,87 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, builtins: &[Expor }; let inherited_padding = tr(padding_label(&global.padding)).to_string(); - let o = app.ui.export.sets.entry(ts).or_default(); + let look = ExportLook::get(ui.ctx()); + let overrides = app.ui.export.sets.entry(ts).or_default(); let mut all = None; - header(ui, tr("General Export Parameters"), |ui| { - list_menu(ui, |ui| { - if ui.button(tr("Override every item")).clicked() { - all = Some(true); - } - if ui.button(tr("Clear all overrides")).clicked() { - all = Some(false); - } - ui.separator(); - }); + drawn::label_at(ui, place.x(LABEL_LEFT), place.y(SET_HEADER_Y), tr("General Export Parameters"), look.text, true); + list_menu(ui, place.right_inset(PAGE_ICON_FROM_RIGHT, SET_HEADER_Y), tr("General Export Parameters menu"), |ui| { + if ui.button(tr("Override every item")).clicked() { + all = Some(true); + } + if ui.button(tr("Clear all overrides")).clicked() { + all = Some(false); + } + ui.separator(); }); + + let row_y = |row: usize| place.y(SET_FIRST_ROW_Y + row as f32 * SET_ROW_PITCH); let mut toggled = None; - egui::Grid::new(("exp_set_grid", ts)).num_columns(2).min_col_width(LABEL_COLUMN_WIDTH).spacing(vec2(12.0, 8.0)).show(ui, |ui| { - let on = o.preset.is_some(); - if override_row(ui, tr("Output template"), on, &from.preset, |ui| { - if let Some(p) = &mut o.preset { - template_combo(ui, "exp_set_preset", p, &first, &rest); - } - }) { - toggled = Some(0); + if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), &from.preset, |ui, rect| { + if let Some(preset) = &mut overrides.preset { + template_combo(ui, rect, "exp_set_preset", preset, &first, &rest); } - let on = o.file_type.is_some(); - if override_row(ui, tr("File type"), on, &inherited_file_type, |ui| { - if let Some(t) = &mut o.file_type { - file_type_combo(ui, ("exp_set", ts, usize::MAX), t); - } - }) { - toggled = Some(1); + }) { + toggled = Some(0); + } + if override_row(ui, place, row_y(1), tr("File type"), overrides.file_type.is_some(), &inherited_file_type, |ui, rect| { + if let Some(file_type) = &mut overrides.file_type { + let type_rect = rect.with_max_x(rect.left() + MAP_FORMAT_WIDTH); + let rects = [type_rect, rect.with_min_x(type_rect.right() + PAIR_GAP)]; + file_type_lists(ui, ("exp_set", ts, usize::MAX), false, rects, &mut file_type.format, &mut file_type.bit_depth, &mut file_type.dithering); } - let on = o.size.is_some(); - if override_row(ui, tr("Size"), on, &inherited_size, |ui| { - if let Some(size) = &mut o.size { - egui::ComboBox::from_id_salt("exp_set_size").width(VALUE_WIDTH).selected_text(set_size_label(*size, own)).show_ui(ui, |ui| { - for r in SIZES { - ui.selectable_value(size, r, set_size_label(r, own)); - } - }); - } - }) { - toggled = Some(2); + }) { + toggled = Some(1); + } + 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| { + for side in SIZES { + ui.selectable_value(size, side, set_size_label(side, own)); + } + }); } - let on = o.padding.is_some(); - if override_row(ui, tr("Padding"), on, &inherited_padding, |ui| { - if let Some((padding, dilation)) = &mut o.padding { - egui::ComboBox::from_id_salt("exp_set_pad").width(260.0).selected_text(tr(padding_label(padding))).show_ui(ui, |ui| { - for (v, l) in PADDINGS { - ui.selectable_value(padding, v.to_string(), tr(l)); - } - }); - dilation_button(ui, padding, dilation); - } - }) { - toggled = Some(3); + }) { + toggled = Some(2); + } + if override_row(ui, place, row_y(3), tr("Padding"), overrides.padding.is_some(), &inherited_padding, |ui, rect| { + if let Some((padding, dilation)) = &mut overrides.padding { + drawn::combo(ui, rect.with_max_x(rect.right() - DILATION_WIDTH - PAIR_GAP), "exp_set_pad", tr(padding_label(padding)), |ui| { + for (value, label) in PADDINGS { + ui.selectable_value(padding, value.to_string(), tr(label)); + } + }); + dilation_button(ui, rect.with_min_x(rect.right() - DILATION_WIDTH), "set", padding, dilation); } - }); + }) { + toggled = Some(3); + } if let Some(row) = toggled { - toggle(o, row, &from); + toggle(overrides, row, &from); } match all { Some(true) => { for row in 0..4 { - let on = [o.preset.is_some(), o.file_type.is_some(), o.size.is_some(), o.padding.is_some()]; + let on = [overrides.preset.is_some(), overrides.file_type.is_some(), overrides.size.is_some(), overrides.padding.is_some()]; if !on.get(row).copied().unwrap_or(true) { - toggle(o, row, &from); + toggle(overrides, row, &from); } } } Some(false) => { - o.preset = None; - o.file_type = None; - o.size = None; - o.padding = None; + overrides.preset = None; + overrides.file_type = None; + overrides.size = None; + overrides.padding = None; } None => {} } - ui.add_space(8.0); - ui.separator(); - egui::ScrollArea::vertical().id_salt("exp_maps_scroll").auto_shrink([false; 2]).show(ui, |ui| output_maps(app, ui, ts)); + + // A divider across the page, then the output maps + let page_left = place.x(SET_LIST_WIDTH + 1.0); + drawn::divider(ui, egui::Rect::from_min_max(egui::pos2(page_left, place.y(SET_DIVIDER_Y)), egui::pos2(place.right, place.y(SET_DIVIDER_Y) + 1.0))); + let maps_area = egui::Rect::from_min_max(egui::pos2(page_left, place.y(MAPS_TOP)), egui::pos2(place.right, bottom)); + output_maps(app, ui, ts, place, maps_area); if app.ui.export.sets.get(&ts).is_some_and(SetExport::is_default) { app.ui.export.sets.remove(&ts); } @@ -1169,7 +1297,7 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; ui.painter().rect_filled(strip, 0.0, tk.chrome); ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); - paint_focus(ui, &response); + drawn::paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal); @@ -1479,6 +1607,87 @@ pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, p } } +/// 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) { + 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) + }; + if let Some(job) = &app.ui.export.job { + let done = job.total - job.pending.len(); + let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; + if drawn::button(ui, slot(0.0), tr("Cancel Export"), false, true).clicked() { + app.ui.export.job = None; + } + let bar = drawn::control_rect(window.left() + LEFT_MARGIN, slot(0.0).left() - FOOTER_BUTTON_GAP, y); + let look = ExportLook::get(ui.ctx()); + ui.put(bar, egui::ProgressBar::new(progress).fill(look.outline).text(format!("{:.0}%", progress * 100.0))); + return; + } + + // OUTPUT TEMPLATES shows no count; a template edit that does not validate holds Save and Export + let templates_tab = app.ui.export.tab == 1; + let draft_valid = app.ui.export.draft.as_ref().is_none_or(|draft| draft.validate().is_ok()); + let any = !export_selection(app).is_empty() && draft_valid; + let export = drawn::button(ui, slot(0.0), tr("Export"), true, any); + if export.on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")).clicked() { + *do_export = true; + } + + // Saving closes the window without starting an export + let save = drawn::button(ui, slot(1.0), tr("Save settings"), false, draft_valid); + if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { + app.ui.windows.export = false; + } + let cancel = drawn::button(ui, slot(2.0), tr("Cancel"), false, true); + if cancel.on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { + *canceled = true; + } + if !templates_tab { + let look = ExportLook::get(ui.ctx()); + let count = trf("{n} textures selected for export", &[("n", &selected_texture_count(app))]); + 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); + } + + // Only on SETTINGS + let reset_rect = drawn::control_rect(window.left() + LEFT_MARGIN, window.left() + LEFT_MARGIN + FOOTER_BUTTON_WIDTH, y); + if app.ui.export.tab == 0 + && 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); + app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; + } +} + +/// The SETTINGS tab in `body`: the texture set list, a divider, then the selected page +fn settings_tab(app: &mut TextureCraftApp, ui: &mut Ui, window: egui::Rect, body: egui::Rect, presets: &[ExportPreset]) { + let list = body.with_max_x(body.left() + SET_LIST_WIDTH); + set_list(app, ui, list); + drawn::divider(ui, egui::Rect::from_min_max(list.right_top(), list.right_bottom() + vec2(1.0, 0.0))); + let page = body.with_min_x(list.right() + 1.0); + match app.ui.export.page { + Some(ts) if ts < app.session.set_count() => { + let place = PagePlace { left: window.left(), top: window.top(), right: window.right() }; + set_page(app, ui, ts, place, body.bottom(), presets); + } + + // A short or narrow window scrolls the page, so every control stays reachable + _ => { + ui.scope_builder(egui::UiBuilder::new().max_rect(page), |ui| { + egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false; 2]).show(ui, |ui| { + let size = vec2(ui.available_width().max(MIN_PAGE_WIDTH), GLOBAL_PAGE_HEIGHT); + let (content, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let place = PagePlace { left: content.left() - list.width() - 1.0, top: content.top() - TAB_ROW_HEIGHT, right: content.right() }; + global_page(app, ui, place, presets); + }); + }); + } + } +} + pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.export { // The window opens on SETTINGS again; an export stops with it @@ -1515,14 +1724,18 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut do_export = false; let mut canceled = false; let presets = texturecraft_engine::formats::builtin_presets(); - // The reference size on a screen that has room for it, smaller on a smaller one; resizable from there. - // The window's size counts its frame and title bar, the reference size only the content + let look = ExportLook::get(ctx); + + // The reference size where the screen has room, resizable from there; the size counts the frame and title bar let style = ctx.global_style(); + let title_frame = egui::Frame::window(&style); + let frame = title_frame.inner_margin(CONTENT_INSET); let title_height = ctx.fonts_mut(|fonts| fonts.row_height(&egui::TextStyle::Heading.resolve(&style))) + style.spacing.item_spacing.y; - let chrome = egui::Frame::window(&style).total_margin().sum() + vec2(0.0, title_height); + let chrome = vec2(frame.total_margin().sum().x, title_frame.total_margin().sum().y + title_height); let window_size = (REFERENCE_WINDOW_SIZE_POINTS + chrome).min(ctx.content_rect().size() - vec2(WINDOW_VIEWPORT_MARGIN_POINTS, WINDOW_VIEWPORT_MARGIN_POINTS)); - let dialog = crate::windows::dialog(ctx, "export_textures", tr("Export Textures"), &mut open).default_size(window_size); + let dialog = + crate::windows::dialog(ctx, "export_textures", tr("Export textures"), &mut open).title_frame(title_frame).frame(frame).default_size(window_size); dialog.show(ctx, |ui| { // Nothing to export without a project if !app.session.project_open { @@ -1530,137 +1743,67 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { - // While exporting: the progress and Cancel Export - if let Some(job) = &app.ui.export.job { - let done = job.total - job.pending.len(); - let progress = if job.total == 0 { 1.0 } else { done as f32 / job.total as f32 }; - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Cancel Export")).clicked() { - app.ui.export.job = None; - } - let percent = format!("{:.0}%", progress * 100.0); - ui.add(egui::ProgressBar::new(progress).text(percent)); - }); - }); - } else { - // OUTPUT TEMPLATES edits the templates only: no count, nothing to reset, save or export there - let templates_tab = app.ui.export.tab == 1; - let selected = if templates_tab { 0 } else { selected_texture_count(app) }; - ui.horizontal(|ui| { - // Only on SETTINGS - if app.ui.export.tab == 0 - && ui.add(footer_button(tr("Reset all"))).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); - app.ui.export = ExportUi { opened_with, owner, owner_id, ..ExportUi::default() }; - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Nothing to write without a ticked texture set - let any = !export_selection(app).is_empty() && !templates_tab; - if ui - .add_enabled(any, footer_button(tr("Export"))) - .on_hover_text(tr("Write the selected textures, and the extra files ticked in the settings")) - .clicked() - { - do_export = true; - } + look.apply(ui.style_mut()); + let window = ui.max_rect(); + ui.allocate_rect(window, egui::Sense::hover()); + let body = + egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_ROW_HEIGHT), egui::pos2(window.right(), window.bottom() - FOOTER_HEIGHT)); - // Saving closes the window without starting an export - let save = ui.add_enabled(!templates_tab, footer_button(tr("Save settings"))); - if save.on_hover_text(tr("Keep these settings for the next export and close the window")).clicked() { - app.ui.windows.export = false; - } - if ui.add(footer_button(tr("Cancel"))).on_hover_text(tr("Close the window and go back to the settings it opened with")).clicked() { - canceled = true; - } - if !templates_tab { - ui.label(trf("{n} textures selected for export", &[("n", &selected)])); - } - }); - }); + // The tabs, and the tab's own control at the row's right end + let tab_strip = egui::Rect::from_min_max(egui::pos2(window.left(), window.top() + TAB_TOP), egui::pos2(window.right(), body.top())); + let labels = [tr("Settings"), tr("Output templates"), tr("List of exports")]; + if let Some(tab) = drawn::tabs(ui, tab_strip, window.left() + TABS_LEFT, &labels, usize::from(app.ui.export.tab)) { + app.ui.export.tab = tab as u8; + } + let right = window.right() - RIGHT_MARGIN; + let row_y = window.top() + TAB_ROW_CONTROLS_Y; + match app.ui.export.tab { + 1 => { + let strip = egui::Rect::from_min_max(egui::pos2(window.center().x, window.top()), egui::pos2(right, body.top())); + ui.scope_builder( + egui::UiBuilder::new().max_rect(strip).layout(egui::Layout::right_to_left(egui::Align::Center)), + crate::export_templates::naming_pattern, + ); } - ui.separator(); - ui.add_space(8.0); - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.horizontal(|ui| { - // Boxed tabs side by side - ui.scope(|ui| { - ui.spacing_mut().item_spacing.x = 0.0; - for (i, t) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() { - if tab_button(ui, &t.to_uppercase(), app.ui.export.tab == i as u8).clicked() { - app.ui.export.tab = i as u8; - } - } - }); + 2 => { + let width = drawn::text_width(ui, tr("Open output directory"), false) + OPEN_DIRECTORY_PADDING; + let rect = drawn::control_rect(window.right() - OPEN_DIRECTORY_FROM_RIGHT - width, window.right() - OPEN_DIRECTORY_FROM_RIGHT, row_y); - // The file list opens the destination folder - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if app.ui.export.tab == 2 { - // The browser downloads the files instead - #[cfg(target_arch = "wasm32")] - crate::unavailable::greyed(ui, |ui| ui.button(tr("Open output directory"))); - #[cfg(not(target_arch = "wasm32"))] - if ui.button(tr("Open output directory")).clicked() { - open_output_directory(app); - } - } else if app.ui.export.tab == 1 { - crate::export_templates::naming_pattern(ui); - } else if ui.add(footer_button(tr("Include all"))).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { - app.ui.export.skip.clear(); - for o in app.ui.export.sets.values_mut() { - o.maps.values_mut().for_each(|m| m.enabled = true); - } - app.ui.export.sets.retain(|_, o| !o.is_default()); - } - }); - }); - ui.separator(); - let body = egui::Rect::from_min_size(ui.cursor().min, vec2(ui.available_width(), ui.available_height().max(0.0))); - - // The tabs size their columns from the body's width. A child that cannot widen the - // resizable window holds them, so an overflow is clipped instead of growing the window each frame - let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); - body_ui.shrink_clip_rect(body); - ui.advance_cursor_after_rect(body); - let ui = &mut body_ui; - 'tab: { - ui.set_height(body.height()); - match app.ui.export.tab { - 1 => { - crate::export_templates::tab(app, ui, &presets); - break 'tab; - } - 2 => { - list_tab(app, ui); - break 'tab; - } - _ => {} - } - - ui.vertical(|ui| { - ui.set_width(LIST_WIDTH); - set_list(app, ui); - }); - ui.separator(); - - // A short or narrow window scrolls the settings, so the footer and every control stay reachable - ui.vertical(|ui| { - egui::ScrollArea::both().id_salt("export_settings_page").auto_shrink([false, false]).min_scrolled_height(0.0).show(ui, |ui| match app - .ui - .export - .page - { - Some(ts) if ts < app.session.set_count() => set_page(app, ui, ts, &presets), - _ => global_page(app, ui, &presets), - }); - }); + // The browser downloads the files instead + #[cfg(target_arch = "wasm32")] + drawn::button(ui, rect, tr("Open output directory"), false, false).on_hover_text(tr(NOT_AVAILABLE)); + #[cfg(not(target_arch = "wasm32"))] + if drawn::button(ui, rect, tr("Open output directory"), false, true).clicked() { + open_output_directory(app); } - }); - }); + } + _ => { + let rect = drawn::control_rect(right - FOOTER_BUTTON_WIDTH, right, row_y); + if drawn::button(ui, rect, tr("Include all"), false, true).on_hover_text(tr("Select every texture set, UV tile and output map")).clicked() { + app.ui.export.skip.clear(); + for o in app.ui.export.sets.values_mut() { + o.maps.values_mut().for_each(|m| m.enabled = true); + } + app.ui.export.sets.retain(|_, o| !o.is_default()); + } + } + } + + 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); + + // 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)); + body_ui.shrink_clip_rect(body); + let ui = &mut body_ui; + let mut row = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); + row.set_height(body.height()); + match app.ui.export.tab { + 1 => crate::export_templates::tab(app, &mut row, &presets), + 2 => list_tab(app, &mut row), + _ => settings_tab(app, ui, window, body, &presets), + } }); crate::export_templates::ask(app, ctx); diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs new file mode 100644 index 00000000..fe55c374 --- /dev/null +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -0,0 +1,305 @@ +//! The Export textures window's own controls, drawn at the places its layout gives them: tabs, +//! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`]) + +use egui::{Align2, Color32, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui_phosphor::regular as ic; + +use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE}; +use crate::theme::semibold; + +/// Side and corner radius of a check box +const CHECK_SIZE: f32 = 13.0; +const CHECK_RADIUS: u8 = 2; + +/// The tick inside a check box: its three points from the box's left edge and centre, and its width +const TICK_POINTS: [(f32, f32); 3] = [(3.2, 0.2), (5.6, 2.6), (9.8, -2.6)]; +const TICK_WIDTH: f32 = 1.7; + +/// Air between a check box and its label +pub(crate) const CHECK_LABEL_GAP: f32 = 5.0; + +/// From a dropdown's left edge to its value, and from its right edge to its chevron's centre +pub(crate) const VALUE_INSET: f32 = 7.0; +pub(crate) const CHEVRON_INSET: f32 = 11.0; + +/// Size of a chevron and of the window's icons +pub(crate) const CHEVRON_SIZE: f32 = 12.0; + +/// The air on either side of a tab's name +const TAB_PADDING: f32 = 14.0; +/// A tab's corner radius +const TAB_RADIUS: u8 = 4; +/// Gap between tabs +const TAB_GAP: f32 = 3.0; +/// How far a tab reaches under the divider, where the body's colour covers its lower corners +const TAB_OVERLAP: f32 = 4.0; + +/// Hit area of an icon button around its glyph +const ICON_HIT_SIZE: f32 = 20.0; + +/// Width of the keyboard focus outline on the window's drawn controls +const FOCUS_OUTLINE_WIDTH: f32 = 2.0; + +/// Whether a control that cannot be used looks greyed; a built-in template's cards keep their look +pub(crate) fn looks_disabled(ui: &Ui, enabled: bool) -> bool { + !enabled && ui.visuals().disabled_alpha() < 1.0 +} + +/// The window's regular and semibold text +pub(crate) fn font(bold: bool) -> FontId { + if bold { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) } +} + +/// Width of `text` in the window's font +pub(crate) fn text_width(ui: &Ui, text: &str, bold: bool) -> f32 { + ui.painter().layout_no_wrap(text.to_owned(), font(bold), Color32::WHITE).size().x +} + +/// `text` with its left edge at `left` and its middle at `y` +pub(crate) fn text_at(ui: &Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Rect { + ui.painter().text(pos2(left, y), Align2::LEFT_CENTER, text, font(bold), color) +} + +/// `text` cut with "…" at its end (or its start, for file names) to fit `room` +pub(crate) fn fitted(ui: &Ui, text: &str, room: f32, from_start: bool, bold: bool) -> String { + if text_width(ui, text, bold) <= room { + return text.to_owned(); + } + + let chars: Vec = text.chars().collect(); + (1..chars.len()) + .map(|cut| { + if from_start { + format!("…{}", chars[cut..].iter().collect::()) + } else { + format!("{}…", chars[..chars.len() - cut].iter().collect::()) + } + }) + .find(|shown| text_width(ui, shown, bold) <= room) + .unwrap_or_else(|| "…".to_owned()) +} + +/// A glyph centred on `centre` +pub(crate) fn glyph(ui: &Ui, centre: Pos2, glyph: &str, size: f32, color: Color32) { + ui.painter().text(centre, Align2::CENTER_CENTER, glyph, FontId::proportional(size), color); +} + +/// The keyboard focus outline of a drawn control, in the text colour +pub(crate) fn paint_focus(ui: &Ui, response: &Response) { + if response.has_focus() { + let stroke = Stroke::new(FOCUS_OUTLINE_WIDTH, ExportLook::get(ui.ctx()).text); + ui.painter().rect_stroke(response.rect, CONTROL_RADIUS, stroke, StrokeKind::Inside); + } +} + +/// A horizontal or vertical divider line, one point thick +pub(crate) fn divider(ui: &Ui, rect: Rect) { + ui.painter().rect_filled(rect, 0.0, ExportLook::get(ui.ctx()).divider); +} + +/// Sentence-case rounded tabs along `strip`'s bottom from `left`, the open one joined to the body; returns the clicked one +pub(crate) fn tabs(ui: &mut Ui, strip: Rect, left: f32, labels: &[&str], open: usize) -> Option { + let look = ExportLook::get(ui.ctx()); + let bottom = strip.bottom(); + divider(ui, Rect::from_min_max(pos2(strip.left(), bottom - 1.0), pos2(strip.right(), bottom))); + let mut clicked = None; + let mut x = left; + for (index, label) in labels.iter().enumerate() { + let selected = index == open; + let width = text_width(ui, label, selected) + 2.0 * TAB_PADDING; + let rect = Rect::from_min_max(pos2(x, strip.top()), pos2(x + width, bottom)); + let response = ui.interact(rect, ui.scope_id().with(("export_tab", index)), Sense::click()); + response.widget_info(|| WidgetInfo::selected(Role::Tab, true, selected, *label)); + + // The tab's lower corners reach under the divider and are covered by the body's colour + let painter = ui.painter(); + let face = Rect::from_min_max(rect.min, pos2(rect.right(), bottom + TAB_OVERLAP)); + let below = Rect::from_min_max(pos2(rect.left(), bottom - 1.0), pos2(rect.right(), bottom + TAB_OVERLAP + 1.0)); + if selected { + painter.rect(face, TAB_RADIUS, look.window, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.rect_filled(below.shrink2(vec2(1.0, 0.0)), 0.0, look.window); + } else { + let fill = if response.hovered() { look.raised } else { look.chrome }; + painter.rect_filled(face.with_min_y(face.top() + 1.0), TAB_RADIUS, fill); + painter.rect_filled(below, 0.0, look.window); + painter.rect_filled(below.with_max_y(bottom), 0.0, look.divider); + } + let color = if selected { look.text } else { look.text_dim }; + painter.text(rect.center() + vec2(0.0, 1.0), Align2::CENTER_CENTER, *label, font(selected), color); + paint_focus(ui, &response); + if response.clicked() { + clicked = Some(index); + } + x += width + TAB_GAP; + } + clicked +} + +/// A check box from `left` with its middle at `y`: dim and ticked when on, dark with a light edge when off +pub(crate) fn paint_check(ui: &Ui, left: f32, y: f32, on: bool) { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_min_size(pos2(left, y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE)); + let painter = ui.painter(); + if on { + painter.rect_filled(rect, CHECK_RADIUS, look.text_dim); + let points = TICK_POINTS.iter().map(|(dx, dy)| pos2(left + dx, y + dy)).collect(); + painter.add(egui::Shape::line(points, Stroke::new(TICK_WIDTH, look.window))); + } else { + painter.rect(rect, CHECK_RADIUS, look.control, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } +} + +/// A check box at `at` (its left edge's middle) with `label` after it, toggled by a click in `hit` +pub(crate) fn check(ui: &mut Ui, id: Id, hit: Rect, at: Pos2, on: &mut bool, label: Option<&str>, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let mut response = ui.interact(hit, id, Sense::click()); + if response.clicked() { + *on = !*on; + response.mark_changed(); + } + let checked = *on; + response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, checked, name)); + paint_check(ui, at.x, at.y, checked); + if let Some(label) = label { + text_at(ui, at.x + CHECK_SIZE + CHECK_LABEL_GAP, at.y, label, look.text, false); + } + paint_focus(ui, &response); + response +} + +/// The rect of a control `left`..`right` with its middle at `y` +pub(crate) fn control_rect(left: f32, right: f32, y: f32) -> Rect { + Rect::from_min_max(pos2(left, y - CONTROL_HEIGHT / 2.0), pos2(right, y + CONTROL_HEIGHT / 2.0)) +} + +/// A dropdown's chevron, pointing up while its list is open, drawn just inside the right edge of the button `rect` +pub(crate) fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, open: bool) { + let centre = pos2(rect.right() + VALUE_INSET - CHEVRON_INSET, rect.center().y); + glyph(ui, centre, if open { ic::CARET_UP } else { ic::CARET_DOWN }, CHEVRON_SIZE, visuals.fg_stroke.color); +} + +/// A dropdown filling `rect`, showing `shown`, its list as wide as it and flush under it +pub(crate) fn combo( + ui: &mut Ui, + rect: Rect, + id: impl std::hash::Hash + std::fmt::Debug, + shown: impl Into, + list: impl FnOnce(&mut Ui) -> R, +) -> egui::InnerResponse> { + let look = ExportLook::get(ui.ctx()); + let shown: String = shown.into(); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + egui::ComboBox::from_id_salt(id) + .width(rect.width()) + .height(f32::INFINITY) + .selected_text(shown) + .wrap_mode(egui::TextWrapMode::Truncate) + .icon(chevron_icon) + .popup_style(look.list_style()) + .show_ui(ui, list) + }) + .inner +} + +/// A button drawn as a dropdown showing `shown`, for a menu that is no option list; lighter when it cannot be used +pub(crate) fn combo_button(ui: &mut Ui, rect: Rect, id: Id, shown: &str, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, shown)); + let (fill, color) = match (enabled, response.hovered()) { + (false, _) => (look.raised, look.text_dim), + (true, true) => (look.raised, look.text), + (true, false) => (look.control, look.text), + }; + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, fill, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), color); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} + +/// A field showing `text` cut with "…" at its end that acts as a button, as the output directory does +pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| WidgetInfo::labeled(Role::Button, true, text)); + let border = if response.hovered() { look.outline } else { look.control_border }; + ui.painter().rect(rect, CONTROL_RADIUS, look.control, Stroke::new(1.0, border), StrokeKind::Inside); + let shown = fitted(ui, text, rect.width() - 2.0 * VALUE_INSET, false, false); + text_at(ui, rect.left() + VALUE_INSET, rect.center().y, &shown, look.text, false); + paint_focus(ui, &response); + response +} + +/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim +pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, shown: &str, name: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", name)), Sense::hover()); + response.widget_info(|| { + let mut info = WidgetInfo::labeled(Role::ComboBox, false, name); + info.current_text_value = Some(shown.to_owned()); + info + }); + let painter = ui.painter(); + painter.rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), look.text_dim); + glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, look.text_dim); + response +} + +/// Text that reads as a label to assistive technology and tests: `text` from `left`, its middle at `y`; its response takes a tooltip +pub(crate) fn label_at(ui: &mut Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Response { + let rect = text_at(ui, left, y, text, color, bold); + let response = ui.interact(rect, ui.scope_id().with(("export_label", text, left.to_bits(), y.to_bits())), Sense::hover()); + response.widget_info(|| WidgetInfo::labeled(Role::Label, true, text)); + response +} + +/// A button filling `rect`: a step darker than the window with a light edge, or the accent for the one primary action +pub(crate) fn button(ui: &mut Ui, rect: Rect, label: &str, primary: bool, enabled: bool) -> Response { + let id = ui.scope_id().with(("export_button", label)); + button_with_id(ui, id, rect, label, label, primary, enabled) +} + +/// [`button`] for one of several buttons with the same label (each output map card's "$") +pub(crate) fn button_with_id(ui: &mut Ui, id: Id, rect: Rect, label: &str, name: &str, primary: bool, enabled: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, id, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name)); + let (fill, border) = match (primary, enabled && response.hovered()) { + (true, _) => (look.accent, look.accent), + (false, true) => (look.raised, look.outline), + (false, false) => (look.control, look.control_border), + }; + let painter = ui.painter(); + let fade = if enabled { 1.0 } else { ui.visuals().disabled_alpha() }; + painter.rect(rect, CONTROL_RADIUS, fill.gamma_multiply(fade), Stroke::new(1.0, border.gamma_multiply(fade)), StrokeKind::Inside); + let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text }; + painter.text(rect.center(), Align2::CENTER_CENTER, label, font(primary), color); + paint_focus(ui, &response); + response +} + +/// A glyph that acts as a button, centred on `centre`; `lit` frames it as switched on +pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name: &str, enabled: bool, lit: bool) -> Response { + let look = ExportLook::get(ui.ctx()); + let rect = Rect::from_center_size(centre, vec2(ICON_HIT_SIZE, ICON_HIT_SIZE)); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let response = ui.interact(rect, ui.scope_id().with(("export_icon", name, centre.x as i32, centre.y as i32)), sense); + response.widget_info(|| WidgetInfo::selected(Role::Button, enabled, lit, name)); + if lit { + ui.painter().rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside); + } + let color = match (enabled, lit || response.hovered()) { + (false, _) if looks_disabled(ui, enabled) => look.control_border, + (false, _) => look.text_dim, + (true, true) => look.text, + (true, false) => look.text_dim, + }; + glyph(ui, centre, icon, size, color); + paint_focus(ui, &response); + response +} diff --git a/crates/ui-egui/src/export_window/export_look.rs b/crates/ui-egui/src/export_window/export_look.rs new file mode 100644 index 00000000..866dad2f --- /dev/null +++ b/crates/ui-egui/src/export_window/export_look.rs @@ -0,0 +1,118 @@ +use egui::{Color32, CornerRadius, Stroke, Style, TextStyle, style::StyleModifier}; + +use crate::theme::{Tokens, lerp_color}; + +/// Text size of the whole window, labels and values alike +pub(crate) const TEXT_SIZE: f32 = 12.0; + +/// Height and corner radius of the window's controls: dropdowns, fields and buttons +pub(crate) const CONTROL_HEIGHT: f32 = 25.0; +pub(crate) const CONTROL_RADIUS: u8 = 3; + +/// Height of an option in an open list +const OPTION_HEIGHT: f32 = 22.0; +/// An open list's margin round its options +const LIST_MARGIN: i8 = 3; +/// An option's text inset, lining up with the dropdown's value above it +const OPTION_INSET: f32 = 3.0; + +/// A scroll bar's strip beside its list: the bar and the air on either side of it +const SCROLL_BAR_WIDTH: f32 = 4.0; +const SCROLL_BAR_MARGIN: f32 = 4.0; + +/// How far the dividers sit below the frame colour, so they read on it +const DIVIDER_DARKENING: f32 = 0.26; + +/// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter +#[derive(Clone, Copy)] +pub(crate) struct ExportLook { + pub(crate) window: Color32, + pub(crate) control: Color32, + pub(crate) control_border: Color32, + /// A step lighter than controls: hover, lit and unusable faces + pub(crate) raised: Color32, + pub(crate) chrome: Color32, + pub(crate) divider: Color32, + pub(crate) outline: Color32, + pub(crate) text: Color32, + pub(crate) text_dim: Color32, + pub(crate) accent: Color32, +} + +impl ExportLook { + pub(crate) fn get(ctx: &egui::Context) -> Self { + let tokens = Tokens::get(ctx); + Self { + window: tokens.panel, + control: tokens.row, + control_border: tokens.field_border, + raised: tokens.separator, + chrome: tokens.chrome, + divider: lerp_color(tokens.chrome, Color32::BLACK, DIVIDER_DARKENING), + outline: tokens.button_border, + text: tokens.text, + text_dim: tokens.text_dim, + accent: tokens.accent, + } + } + + /// 12 point text, the window's control colours, scroll bars in their own strip beside the list + pub(crate) fn apply(&self, style: &mut Style) { + for text_style in [TextStyle::Body, TextStyle::Button] { + if let Some(font) = style.text_styles.get_mut(&text_style) { + font.size = TEXT_SIZE; + } + } + style.spacing.interact_size.y = CONTROL_HEIGHT; + style.spacing.button_padding.x = super::drawn::VALUE_INSET; + style.spacing.scroll = egui::style::ScrollStyle { + bar_width: SCROLL_BAR_WIDTH, + bar_inner_margin: SCROLL_BAR_MARGIN, + bar_outer_margin: SCROLL_BAR_MARGIN, + ..egui::style::ScrollStyle::solid() + }; + + // The scroll strip shows no track, only the bar + style.visuals.extreme_bg_color = Color32::TRANSPARENT; + let widgets = &mut style.visuals.widgets; + for (state, fill, border) in [ + (&mut widgets.inactive, self.control, self.control_border), + (&mut widgets.hovered, self.raised, self.outline), + (&mut widgets.active, self.raised, self.outline), + (&mut widgets.open, self.control, self.control_border), + ] { + state.weak_bg_fill = fill; + state.bg_stroke = Stroke::new(1.0, border); + state.corner_radius = CornerRadius::same(CONTROL_RADIUS); + state.expansion = 0.0; + } + + // Scroll bars and checks use the strong fill: the raised grey + widgets.inactive.bg_fill = self.raised; + widgets.hovered.bg_fill = self.outline; + widgets.active.bg_fill = self.outline; + widgets.inactive.fg_stroke.color = self.text; + widgets.open.fg_stroke.color = self.text; + style.visuals.selection.bg_fill = self.chrome; + style.visuals.selection.stroke = Stroke::new(1.0, self.text); + } + + /// An open list: flush under its button, one light edge, the chosen option in the frame colour + pub(crate) fn list_style(&self) -> StyleModifier { + let look = *self; + StyleModifier::new(move |style: &mut Style| { + look.apply(style); + style.spacing.interact_size.y = OPTION_HEIGHT; + style.spacing.menu_margin = egui::Margin::same(LIST_MARGIN); + style.spacing.button_padding.x = OPTION_INSET; + style.spacing.item_spacing.y = 0.0; + style.visuals.window_fill = look.control; + style.visuals.window_stroke = Stroke::new(1.0, look.control_border); + style.visuals.menu_corner_radius = CornerRadius::same(CONTROL_RADIUS); + style.visuals.widgets.hovered.weak_bg_fill = look.raised; + style.visuals.widgets.hovered.bg_stroke = Stroke::NONE; + style.visuals.widgets.inactive.bg_stroke = Stroke::NONE; + style.visuals.widgets.active.bg_stroke = Stroke::NONE; + }) + } +} diff --git a/crates/ui-egui/src/export_window/page_place.rs b/crates/ui-egui/src/export_window/page_place.rs new file mode 100644 index 00000000..7a8c8269 --- /dev/null +++ b/crates/ui-egui/src/export_window/page_place.rs @@ -0,0 +1,26 @@ +use egui::{Pos2, pos2}; + +/// Where a Settings page lays out from: the window's left edge, the tab row's top and the page's right edge +#[derive(Clone, Copy)] +pub(super) struct PagePlace { + pub(super) left: f32, + pub(super) top: f32, + pub(super) right: f32, +} + +impl PagePlace { + /// `x` from the window's left edge + pub(super) fn x(&self, x: f32) -> f32 { + self.left + x + } + + /// `y` from the top of the tab row + pub(super) fn y(&self, y: f32) -> f32 { + self.top + y + } + + /// A point `from_right` in from the page's right edge, at `y` from the tab row's top + pub(super) fn right_inset(&self, from_right: f32, y: f32) -> Pos2 { + pos2(self.right - from_right, self.top + y) + } +} diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 0aefd54e..80fec55b 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -2,7 +2,7 @@ //! name pattern, and its own file type and bit depth. use egui_kittest::Harness; -use egui_kittest::kittest::Queryable as _; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; @@ -52,13 +52,17 @@ fn the_rows_show_each_map_with_its_pattern_and_file_type() { assert!(h.query_all_by_label("png 8 bits").next().is_some()); assert!(h.query_all_by_label("png 16 bits").next().is_some(), "height is 16-bit in the default template"); - // A pattern longer than the column is cut at the front, the whole one is its tooltip + // A pattern longer than the column (the packed template's) is cut at the front, the whole one is its tooltip + h.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + h.run_steps(4); let preset = texturecraft_engine::formats::builtin_preset(&h.state().ui.export.preset).unwrap(); - let long = - plan(&mut h).iter().map(|f| preset.maps[f["map"].as_u64().unwrap() as usize].file.clone()).find(|p| p.chars().count() > 26).expect("a long pattern"); - let cut: String = format!("…{}", long.chars().skip(long.chars().count() - 25).collect::()); + let long = preset.maps.iter().map(|map| map.file.clone()).max_by_key(|file| file.chars().count()).unwrap(); + let cut = h + .query_all_by_label_contains("…") + .find_map(|node| node.accesskit_node().value().filter(|text| long.ends_with(text.trim_start_matches('…')))) + .expect("the pattern's end, cut at the front"); assert!(h.query_by_label(&long).is_none(), "{long} is cut"); - let at = h.get_all_by_label(&cut).next().unwrap().rect().center(); + let at = h.get_all_by_role_and_label(egui::Role::Label, &cut).next().unwrap().rect().center(); h.hover_at(at); h.run_steps(30); assert!(h.query_by_label(&long).is_some(), "the tooltip has the whole {long}"); @@ -78,15 +82,15 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() { assert_eq!(maps(&h).values().filter(|m| !m.enabled).count(), 1); assert!(h.query_by_label("*").is_none(), "a left-out map is not an override"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); assert_eq!(selected(&h), before - rows); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Invert all"); assert_eq!(selected(&h), before); assert!(!h.state().ui.export.sets.contains_key(&0), "nothing left to remember"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Uncheck all"); click(&mut h, "Include all"); assert_eq!(selected(&h), before, "Include all ticks the output maps too"); @@ -103,10 +107,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { assert!(first.file_type.is_some(), "{m:?}"); assert!(h.query_by_label("*").is_some(), "the set is marked"); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + 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); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Output maps menu"); click(&mut h, "Clear all overrides"); assert!(maps(&h).is_empty()); } diff --git a/crates/ui-egui/tests/it/export_overrides.rs b/crates/ui-egui/tests/it/export_overrides.rs index 9edb2ee5..30454094 100644 --- a/crates/ui-egui/tests/it/export_overrides.rs +++ b/crates/ui-egui/tests/it/export_overrides.rs @@ -30,7 +30,7 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { /// Open the General Export Parameters menu fn page_menu(h: &mut Harness<'_, TextureCraftApp>) { - h.get_all_by_label(egui_phosphor::regular::LIST_CHECKS).nth(1).unwrap().click(); + h.get_by_label("General Export Parameters menu").click(); h.run_steps(4); } diff --git a/crates/ui-egui/tests/it/export_reference_texts.rs b/crates/ui-egui/tests/it/export_reference_texts.rs index 6dd4c494..94e77c81 100644 --- a/crates/ui-egui/tests/it/export_reference_texts.rs +++ b/crates/ui-egui/tests/it/export_reference_texts.rs @@ -49,7 +49,7 @@ fn the_window_has_the_reference_size() { let h = harness(egui::vec2(1600.0, 960.0)); let reset = window_button_rect(&h, "Reset all", 1600.0); let export = window_button_rect(&h, "Export", 1600.0); - let tabs = h.get_by_label("SETTINGS").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Settings").rect(); let width = export.max.x - reset.min.x; let height = export.max.y - tabs.min.y; diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index 6f1212e0..3fbf0e4e 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -145,14 +145,14 @@ fn a_saved_legacy_preset_name_resolves_to_its_current_name() { fn the_set_list_menu_checks_unchecks_and_inverts() { let mut h = harness(); let sets = h.state().session.set_count(); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Uncheck all"); assert_eq!(h.state().ui.export.skip.len(), sets); - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Invert all"); assert!(h.state().ui.export.skip.is_empty()); h.state_mut().ui.export.skip = vec![0]; - click(&mut h, egui_phosphor::regular::LIST_CHECKS); + click(&mut h, "Texture set list menu"); click(&mut h, "Check all"); assert!(h.state().ui.export.skip.is_empty()); } @@ -163,9 +163,7 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() { let default = h.state().ui.export.dir.clone(); h.state_mut().ui.export.dir = "/somewhere/else".into(); h.run_steps(3); - hover(&mut h, "R"); - assert!(h.query_by_label("Reset to default").is_some()); - click(&mut h, "R"); + click(&mut h, "Reset to default"); assert_eq!(h.state().ui.export.dir, default); hover(&mut h, "16"); diff --git a/crates/ui-egui/tests/it/export_template_guards.rs b/crates/ui-egui/tests/it/export_template_guards.rs index 3290256a..f92f5fe5 100644 --- a/crates/ui-egui/tests/it/export_template_guards.rs +++ b/crates/ui-egui/tests/it/export_template_guards.rs @@ -3,7 +3,7 @@ use egui::Key; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_ui_egui::TextureCraftApp; @@ -166,3 +166,18 @@ fn the_settings_dropdown_asks_about_an_unfinished_edit_too() { texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into()); assert_eq!(selected(&h), "Beta tpl", "a valid edit switches at once"); } + +#[test] +fn output_templates_keeps_export_and_save_until_an_edit_does_not_validate() { + let library = Library::new("footer-on-templates"); + let mut h = harness(&library); + // The window's footer is drawn after the app's own menus, which have an Export too + let disabled = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_all_by_label(label).last().unwrap().accesskit_node().is_disabled(); + assert!(!disabled(&h, "Export"), "Export works from the templates tab"); + assert!(!disabled(&h, "Save settings"), "Save settings works from the templates tab"); + + break_draft(&mut h); + + assert!(disabled(&h, "Export"), "an invalid edit holds Export"); + assert!(disabled(&h, "Save settings"), "an invalid edit holds Save settings"); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 92a3847b..d11fe0d8 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -338,12 +338,12 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() { } #[test] -fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { +fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_has_no_count_or_reset() { let library = TemplateLibrary::new("bottom-bar"); let h = harness(&library); let naming = h.get_by_label("Naming pattern").rect(); - let tabs = h.get_by_label("OUTPUT TEMPLATES").rect(); + let tabs = h.get_by_role_and_label(egui::Role::Tab, "Output templates").rect(); let presets = h.get_by_label("Presets").rect(); assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}"); @@ -352,13 +352,12 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() { assert!(h.query_by_label(absent).is_none(), "{absent}"); } assert!(h.query_by_label_contains("textures selected for export").is_none()); - for greyed in ["Save settings", "Export"] { + for active in ["Save settings", "Export", "Cancel"] { // The rail at the right edge has an Export button of its own let button = - h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap(); - assert!(button.accesskit_node().is_disabled(), "{greyed}"); + h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(active)).unwrap(); + assert!(!button.accesskit_node().is_disabled(), "{active}"); } - assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled()); } #[test] diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 8d5162d5..84238f84 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -112,9 +112,10 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() { harness.run_steps(SETTLE_FRAMES); assert!(harness.state().ui.windows.export, "Export Textures... opens the Export textures window"); - for label in - ["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS", "Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] - { + for tab in ["Settings", "Output templates", "List of exports"] { + assert!(harness.query_by_role_and_label(egui::Role::Tab, tab).is_some(), "{tab}"); + } + for label in ["Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] { assert!(harness.query_by_label(label).is_some(), "{label}"); } assert!(harness.query_by_label_contains("textures selected for export").is_some()); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index cda0398b..b7370ceb 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3000,3 +3000,89 @@ fn sheet_scroll_end_snapshots() { harness.run_steps(30); save(&mut harness, &output_dir, "sheet-end-scrolled-medium"); } + +/// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light +#[test] +#[ignore] +fn export_window_snapshots() { + use texturecraft_ui_egui::state::{FileType, MapExport, SetExport}; + + // Below General Export Parameters, where the 1112x662 window draws nothing + const EMPTY_SPOT: egui::Pos2 = egui::pos2(736.0, 530.0); + + 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 (brightness, theme) = match std::env::var("TC_SNAPSHOT_THEME").as_deref() { + Ok("dark") => (Brightness::Dark, "dark"), + Ok("light") => (Brightness::Light, "light"), + _ => (Brightness::MediumDark, "medium"), + }; + + // Ball and Base, then enough texture sets that the set list scrolls + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let template = session.doc.project.texture_sets[0].clone(); + while session.doc.project.texture_sets.len() < 60 { + let mut set = template.clone(); + set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1); + session.doc.project.texture_sets.push(set); + } + let mut harness = + Harness::builder().with_size(egui::vec2(1112.0, 662.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.prefs.brightness = brightness; + harness.set_render_cursor(false); + { + let e = &mut harness.state_mut().ui.export; + e.dir = "/home/user/Documents/TextureCraft/export".into(); + e.preset = "Document channels + Normal + AO (No Alpha)".into(); + e.padding = "infinite".into(); + e.skip = vec![4]; + } + harness.state_mut().ui.windows.export = true; + harness.run_steps(4); + let color_space = harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Default")).unwrap().rect(); + harness.hover_at(color_space.center()); + harness.run_steps(30); + save(&mut harness, &output_dir, &format!("ep-settings-global-{theme}")); + harness.hover_at(egui::pos2(1.0, 1.0)); + + harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Based on output template")).unwrap().click(); + harness.run_steps(3); + save(&mut harness, &output_dir, &format!("ep-settings-file-type-open-{theme}")); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + // The closed list keeps the keyboard focus (and its ring) until a click lands on the page's empty column + harness.hover_at(EMPTY_SPOT); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { pos: EMPTY_SPOT, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.step(); + } + harness.hover_at(egui::pos2(1.0, 1.0)); + harness.run_steps(3); + + // Base with its own size and its height map as 32-bit exr + { + let e = &mut harness.state_mut().ui.export; + e.page = Some(1); + let mut set = SetExport { size: Some(1024), ..SetExport::default() }; + set.maps_template = e.preset.clone(); + let template = texturecraft_engine::formats::builtin_preset(&e.preset).unwrap(); + let height = template.maps.iter().position(|map| texturecraft_engine::formats::export::channel_label(map) == "height").unwrap(); + set.maps.insert(height, MapExport { file_type: Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), ..MapExport::default() }); + set.maps.insert(2, MapExport { enabled: false, ..MapExport::default() }); + e.sets.insert(1, set); + } + save(&mut harness, &output_dir, &format!("ep-settings-set-{theme}")); + + harness.state_mut().ui.export.page = None; + harness.state_mut().ui.export.tab = 1; + harness.state_mut().ui.export.preset = "Unreal Engine (Packed)".into(); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Unreal Engine (Packed)").scroll_to_me(); + save(&mut harness, &output_dir, &format!("ep-templates-unreal-{theme}")); + + harness.state_mut().ui.export.preset = "Document channels + Normal + AO (No Alpha)".into(); + harness.state_mut().ui.export.tab = 2; + save(&mut harness, &output_dir, &format!("ep-list-{theme}")); +} From bde768fdf7c7c05bac1bb4daf3bef638cb709c2e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:10 +0000 Subject: [PATCH 08/34] Output templates: the reference's columns and swatch colours, aligned map cards and a used map's square The tab lays out on the reference's columns: Presets (built-in templates with a locked file glyph, the selected one in the frame colour and bold, no accent), the outputs 10 px from both dividers, and the Input maps and Mesh/Converted maps panes keeping their width at the window's right. Output map cards are 48 px with a 6 px inset: grip, name field cut at the front while not typed in, "$", the channel swatches in the reference's colours moved onto TextureCraft's window colour with their channel's underline, then file type over bit depth on one column beside duplicate and remove. A built-in template's cards keep their full look (its lock says it is read-only). A map an output reads shows a small square of its colour; Converted maps are plain text. The drag hint is the map entries' tooltip, and the count strip reads "N output maps will be exported". --- crates/ui-egui/src/export_templates.rs | 935 ++++++++++-------- .../src/export_templates/output_card.rs | 6 + .../src/export_templates/swatch_look.rs | 4 +- crates/ui-egui/src/export_window.rs | 10 +- crates/ui-egui/src/export_window/drawn.rs | 27 +- .../ui-egui/src/export_window/export_look.rs | 7 + crates/ui-egui/tests/it/output_templates.rs | 16 +- 7 files changed, 602 insertions(+), 403 deletions(-) create mode 100644 crates/ui-egui/src/export_templates/output_card.rs diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 532d4a3c..22bdf182 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -4,7 +4,9 @@ //! Maps dragged from the Input maps, Mesh maps and Converted maps panes onto an output map's //! channel swatches fill its channels. -use egui::{Color32, RichText, Ui, vec2}; +use std::sync::LazyLock; + +use egui::{Color32, Rect, RichText, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; use texturecraft_engine::core::{BakedMap, Channel}; @@ -12,16 +14,18 @@ use texturecraft_engine::formats::export::{FILE_TOKENS, MAX_PRESET_NAME, sanitiz use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef, VirtualMap}; use crate::TextureCraftApp; +use crate::export_window::{ExportLook, GUTTER, TAB_ROW_HEIGHT, drawn}; use crate::i18n::{n_, tr, trf}; -use crate::theme::{Tokens, caption}; +use crate::theme::Tokens; use crate::unavailable::NOT_AVAILABLE; -use crate::widgets::{chip, icon_button_without_tooltip}; +use crate::widgets::chip; mod channel_target; mod map_drag; mod map_lists; mod map_preview_cache; mod map_preview_pictures; +mod output_card; mod pending_drop; mod planned_output; mod row_edit; @@ -33,61 +37,159 @@ use map_drag::MapDrag; use map_lists::{CONVERTED_MAPS, INPUT_MAPS, MESH_MAPS, MapEntry}; use map_preview_cache::MapPreviewCache; use map_preview_pictures::MapPreviewPictures; +use output_card::OutputCard; pub use pending_drop::PendingDrop; use planned_output::PlannedOutput; use row_edit::RowEdit; use source_pick::SourcePick; use swatch_look::SwatchLook; -const ICON_POINTS: f32 = 20.0; -/// Width of the Presets list -const LIST_WIDTH_POINTS: f32 = 220.0; -/// The tab's width in the reference-size window: a narrower window narrows the side panes in -/// proportion, so the output rows keep their room -const REFERENCE_TAB_WIDTH_POINTS: f32 = 1085.0; -/// The middle column's least width, and room for the separators and their spacing -const MIN_OUTPUTS_WIDTH_POINTS: f32 = 200.0; -const SEPARATOR_ALLOWANCE_POINTS: f32 = 6.0; -/// Width of the Input maps pane -const INPUTS_WIDTH_POINTS: f32 = 170.0; -/// Width of the pane with Mesh maps above Converted maps -const SIDE_MAPS_WIDTH_POINTS: f32 = 165.0; -/// Share of the side pane's height that Mesh maps take; Converted maps get the rest -const MESH_MAPS_SHARE: f32 = 0.45; const RENAME_ID: &str = "exp_rename"; /// The name "+" gives a new template, as in the reference const NEW_PRESET: &str = "new_export_preset"; -/// Height of a Presets list row, and where its icon and name start -const PRESET_ROW_HEIGHT_POINTS: f32 = 18.0; -const PRESET_ICON_INDENT_POINTS: f32 = 2.0; -const PRESET_TEXT_INDENT_POINTS: f32 = 20.0; +// Layout in points from the window content's top left corner, the side panes from its right edge, measured on the locked mock -/// Height of a map list entry, the gap between entries, and where its marker and name sit -const ENTRY_HEIGHT_POINTS: f32 = 21.0; -const ENTRY_GAP_POINTS: f32 = 2.0; -const ENTRY_TEXT_INDENT_POINTS: f32 = 22.0; -const ENTRY_TEXT_SIZE_POINTS: f32 = 12.0; -const MARKER_INDENT_POINTS: f32 = 10.0; -const MARKER_SIZE_POINTS: f32 = 10.0; +/// Width of the Presets column +const PRESETS_WIDTH: f32 = 216.2; +/// Middle of the column titles +const HEADER_Y: f32 = 73.0; +/// Centre of the Presets header's first glyph, from the column's right edge +const PRESET_ICON_FROM_RIGHT: f32 = 14.0; +/// Step between the Presets header's glyphs +const PRESET_ICON_STEP: f32 = 22.0; +/// Size of the Presets header's glyphs +const PRESET_ICON_SIZE: f32 = 13.0; +/// Top of the lists under the titles +const LIST_TOP: f32 = 88.0; +/// Height of a Presets row +const PRESET_ROW_HEIGHT: f32 = 20.0; +/// Centre of a Presets row's file glyph +const PRESET_ICON_X: f32 = 16.0; +/// Where a Presets row's name starts +const PRESET_NAME_LEFT: f32 = 26.3; +/// Size of a Presets row's file glyph +const PRESET_ROW_ICON_SIZE: f32 = 12.0; +/// The column titles' left edge, inside their column +const TITLE_INDENT: f32 = 7.5; + +/// The middle column's margin to the dividers on both sides +const MIDDLE_MARGIN: f32 = 10.0; +/// Middle of the Current preset line +const CURRENT_PRESET_Y: f32 = 69.0; +/// Gap after "Current preset:" +const NAME_GAP: f32 = 5.0; +/// From the template's name to its lock's centre +const LOCK_GAP: f32 = 12.0; +/// Middle of the Output maps row +const OUTPUT_MAPS_Y: f32 = 106.0; +/// The air around a Create button's name +const CREATE_PADDING: f32 = 22.0; +/// Gap between the Create buttons +const CREATE_GAP: f32 = 6.0; +/// Gap before "Create:" +const CREATE_LABEL_GAP: f32 = 2.0; +/// Top of the first output map card +const CARDS_TOP: f32 = 127.0; +/// The count strip's top, above the body's bottom +const COUNT_TOP_ABOVE_BOTTOM: f32 = 24.0; +/// The count strip's bottom, above the body's bottom +const COUNT_BOTTOM_ABOVE_BOTTOM: f32 = 1.0; +/// The count's indent in its strip +const COUNT_TEXT_INDENT: f32 = 6.0; + +/// Height of an output map card +const CARD_HEIGHT: f32 = 48.0; +/// Gap below a card +const CARD_GAP: f32 = 6.0; +/// Corner radius of a card +const CARD_RADIUS: u8 = 3; +/// Inset of a card's swatches from its top and bottom +const CARD_INSET: f32 = 6.0; +/// Centre of a card's grip +const GRIP_X: f32 = 10.0; +/// Width of the grip's click area +const GRIP_WIDTH: f32 = 16.0; +/// Size of the grip's glyph +const GRIP_SIZE: f32 = 14.0; +/// Where a card's file name field starts +const NAME_FIELD_LEFT: f32 = 20.0; +/// Width of the file name field +const NAME_FIELD_WIDTH: f32 = 150.0; +/// The file name field's least width in a narrow window +const MIN_NAME_FIELD_WIDTH: f32 = 60.0; +/// Gap before the "$" button +const DOLLAR_GAP: f32 = 4.0; +/// Width of the "$" button +const DOLLAR_WIDTH: f32 = 22.0; +/// Gap between "$" and the swatches +const SWATCHES_GAP: f32 = 8.0; +/// The lists' and icons' rows, above and below the card's middle +const CARD_ROW_OFFSET: f32 = 10.0; +/// Centre of a card's icons, from its right edge +const CARD_ICON_FROM_RIGHT: f32 = 14.0; +/// From the icons to the lists' chevrons +const CARD_CHEVRON_STEP: f32 = 22.0; +/// Gap between a list's value and its chevron +const CARD_VALUE_GAP: f32 = 8.0; +/// Size of a card's icons +const CARD_ICON_SIZE: f32 = 12.0; +/// Values the cards' lists line up on, so cards with shorter ones keep the same column +const CARD_VALUE_SAMPLES: [&str; 3] = ["png", "8 bits", "16 bits"]; + +/// The Input maps divider, from the window's right edge +const INPUTS_DIVIDER_FROM_RIGHT: f32 = 342.3; +/// The Mesh maps divider, from the window's right edge +const SIDE_DIVIDER_FROM_RIGHT: f32 = 161.9; +/// Where the Input maps pane starts after its divider +const PANE_FROM_DIVIDER: f32 = 2.0; +/// Where it ends before the next one +const INPUTS_END_BEFORE_DIVIDER: f32 = 3.5; +/// Where the Mesh maps pane starts after its divider +const SIDE_PANE_FROM_DIVIDER: f32 = 4.0; +/// The divider between Mesh maps and Converted maps, below the body's middle +const SIDE_SPLIT_BELOW_MIDDLE: f32 = 10.0; +/// Gap between Mesh maps' last row and that divider +const MESH_BOTTOM_GAP: f32 = 6.0; +/// Middle of Converted maps' title, below the divider +const CONVERTED_TITLE_Y: f32 = 18.0; +/// Top of Converted maps' rows, below the divider +const CONVERTED_ROWS_TOP: f32 = 33.0; +/// A map entry's inset in its pane +const ENTRY_INSET: f32 = 3.0; +/// Height of a map entry +const ENTRY_HEIGHT: f32 = 20.0; +/// Pitch of the map entries +const ENTRY_PITCH: f32 = 21.0; +/// Height of a group's name row +const GROUP_HEIGHT: f32 = 18.0; +/// Indent of the titles and group names +const GROUP_INDENT: f32 = 4.0; +/// Where a used map's square starts +const MARKER_LEFT: f32 = 9.0; +/// Side of that square +const MARKER_SIZE: f32 = 10.0; +/// Its corner radius +const MARKER_RADIUS: u8 = 1; +/// How much lighter its edge is than its fill +const MARKER_EDGE_LIGHTEN: u8 = 40; +/// Where a map entry's name starts +const ENTRY_NAME_LEFT: f32 = 25.0; /// How strongly a map TextureCraft does not have yet is dimmed const UNAVAILABLE_FADE: f32 = 0.6; -/// An output map row: padding, gap below it, grip width, file name field width, icon size -const ROW_MARGIN_POINTS: f32 = 6.0; -const ROW_GAP_POINTS: f32 = 4.0; -const GRIP_WIDTH_POINTS: f32 = 5.0; -const NAME_FIELD_WIDTH_POINTS: f32 = 150.0; -const ROW_ICON_POINTS: f32 = 16.0; -/// Width the "Output maps" title and the Create buttons need on one row -const OUTPUT_MAPS_ROW_WIDTH_POINTS: f32 = 420.0; -/// The narrowest file name field, the "$" button and the format, bit depth and icon columns at a -/// row's right end, and the gaps between a row's controls (besides the swatches') -const MIN_NAME_FIELD_WIDTH_POINTS: f32 = 60.0; -const DOLLAR_BUTTON_WIDTH_POINTS: f32 = 22.0; -const ROW_LISTS_WIDTH_POINTS: f32 = 100.0; -const ROW_GAPS: f32 = 4.0; -/// The accent frame around a drop target: its stroke and its gap to the target +/// Naming pattern's info glyph, from the window's right edge +const NAMING_INFO_FROM_RIGHT: f32 = 20.8; +/// Its dropdown's left edge, from the window's right edge +const NAMING_COMBO_LEFT_FROM_RIGHT: f32 = 182.4; +/// Its dropdown's right edge, from the window's right edge +const NAMING_COMBO_RIGHT_FROM_RIGHT: f32 = 34.0; +/// Its label's right edge, from the window's right edge +const NAMING_LABEL_FROM_RIGHT: f32 = 188.0; +/// Size of the info glyph +const INFO_SIZE: f32 = 14.0; + +/// The accent-free frame around a drop target: its stroke and its gap to the target const DROP_HIGHLIGHT_STROKE_POINTS: f32 = 1.5; const DROP_HIGHLIGHT_GAP_POINTS: f32 = 2.0; /// Side of the corner mark of an inverted swatch @@ -96,24 +198,49 @@ const INVERTED_MARK_POINTS: f32 = 8.0; const PREVIEW_FILE_WIDTH_POINTS: f32 = 150.0; const PREVIEW_CHANNEL_WIDTH_POINTS: f32 = 34.0; -/// A channel swatch: its side, the label's size and offset from the top, and the bars that show -/// which channels of the source it reads -const SWATCH_SIZE_POINTS: f32 = 32.0; -const SWATCH_TEXT_SIZE_POINTS: f32 = 11.0; -const SWATCH_TEXT_TOP_POINTS: f32 = 3.0; -const SWATCH_BAR_WIDTH_POINTS: f32 = 18.0; -const SWATCH_BAR_HEIGHT_POINTS: f32 = 2.0; -const SWATCH_BAR_BOTTOM_POINTS: f32 = 9.0; +/// Width of a channel swatch; its height is the card's less its inset +const SWATCH_WIDTH: f32 = 34.0; +/// Gap between swatches +const SWATCH_GAP: f32 = 2.0; +/// Middle of a swatch's letters, from its top +const SWATCH_LABEL_Y: f32 = 11.0; +/// A swatch's underline: its inset from the sides +const SWATCH_BAR_INSET: f32 = 6.0; +/// Its top, from the swatch's bottom +const SWATCH_BAR_BOTTOM: f32 = 10.0; +/// Its height +const SWATCH_BAR_HEIGHT: f32 = 2.0; -/// Swatch colours: one hue per map, spread by the golden ratio so neighbours differ, muted to -/// keep the white label readable -const HUE_STEP: f32 = 0.618_034; -const SWATCH_SATURATION: f32 = 0.45; -const SWATCH_VALUE_DARK: f32 = 0.42; -const SWATCH_VALUE_LIGHT: f32 = 0.62; +/// The reference's swatch colours mix channel levels 31, 71 and 111 +const SWATCH_LEVELS: [u8; 3] = [31, 71, 111]; +/// The shift from the reference's darker window to TextureCraft's window colour +const SWATCH_SHIFT: [u8; 3] = [1, 6, 16]; +/// The maps the reference shows keep its own colours +const REFERENCE_SWATCHES: [(SourceRef, [u8; 3]); 6] = [ + (SourceRef::Channel { channel: Channel::BaseColor, component: 0 }, [71, 31, 31]), + (SourceRef::Channel { channel: Channel::Opacity, component: 0 }, [71, 71, 71]), + (SourceRef::Virtual { map: VirtualMap::AoMixed, component: 0 }, [111, 71, 31]), + (SourceRef::Channel { channel: Channel::Roughness, component: 0 }, [111, 111, 71]), + (SourceRef::Channel { channel: Channel::Metallic, component: 0 }, [31, 71, 111]), + (SourceRef::Virtual { map: VirtualMap::NormalDirectX, component: 0 }, [111, 31, 111]), +]; -/// The bars of the R, G and B channels a swatch reads -const COMPONENT_COLORS: [Color32; 3] = [Color32::from_rgb(220, 70, 70), Color32::from_rgb(80, 190, 90), Color32::from_rgb(80, 120, 230)]; +/// Every mix of the swatch levels that is no grey and no reference colour, taken in turn by the other maps +static FREE_SWATCHES: LazyLock> = LazyLock::new(|| { + let levels = SWATCH_LEVELS.iter().flat_map(|&r| SWATCH_LEVELS.iter().flat_map(move |&g| SWATCH_LEVELS.iter().map(move |&b| [r, g, b]))); + levels.filter(|rgb| !(rgb[0] == rgb[1] && rgb[1] == rgb[2]) && REFERENCE_SWATCHES.iter().all(|(_, known)| known != rgb)).collect() +}); + +/// The underline of R +const BAR_RED: Color32 = Color32::from_rgb(230, 70, 70); +/// The underline of G +const BAR_GREEN: Color32 = Color32::from_rgb(80, 200, 90); +/// The underline of B +const BAR_BLUE: Color32 = Color32::from_rgb(80, 130, 240); +/// The underline of A +const BAR_ALPHA: Color32 = Color32::from_rgb(220, 220, 220); +/// The underline of RGB and gray +const BAR_WHOLE: Color32 = Color32::WHITE; /// What a cleared channel writes: black, or opaque in the alpha channel const CLEARED_VALUE: f32 = 0.0; @@ -188,8 +315,6 @@ const CONSTANT_DRAG_SPEED: f64 = 0.005; /// The naming patterns the input maps can be shown with (the reference's second one names /// another vendor's material and is left out) const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"]; -/// Width of the Naming pattern list -const NAMING_PATTERN_WIDTH_POINTS: f32 = 150.0; /// `s` reading component `k` (only 3-component sources have more than one). fn with_component(s: &SourceRef, k: u8) -> SourceRef { @@ -345,43 +470,28 @@ enum MapAction { Remove(usize), } -/// The Output templates tab: template list, the selected template's outputs, then the Input maps -/// pane and the pane with Mesh maps above Converted maps. -pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) { +/// The Output templates tab in `body`: presets, outputs, Input maps, then Mesh maps above Converted maps +pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, body: Rect, builtins: &[ExportPreset]) { sync_draft(app); - let height = ui.available_height(); + let top = body.top() - TAB_ROW_HEIGHT; let names = crate::export_window::template_groups(app, builtins).1; - let scale = (ui.available_width() / REFERENCE_TAB_WIDTH_POINTS).min(1.0); - let (list_width, inputs_width, side_width) = (LIST_WIDTH_POINTS * scale, INPUTS_WIDTH_POINTS * scale, SIDE_MAPS_WIDTH_POINTS * scale); - let mut list_action = None; - ui.vertical(|ui| { - ui.set_width(list_width); - ui.set_height(height); - list_action = preset_list(app, ui, &names); - }); - ui.separator(); - ui.vertical(|ui| { - // Leave room for the two map panes and three separators - let panes = inputs_width + side_width + 8.0 * ui.spacing().item_spacing.x + SEPARATOR_ALLOWANCE_POINTS; - ui.set_width((ui.available_width() - panes).max(MIN_OUTPUTS_WIDTH_POINTS)); - ui.set_height(height); - outputs(app, ui); - }); + let presets_right = body.left() + PRESETS_WIDTH; + let inputs_divider = body.right() - INPUTS_DIVIDER_FROM_RIGHT; + let side_divider = body.right() - SIDE_DIVIDER_FROM_RIGHT; + for x in [presets_right, inputs_divider, side_divider] { + drawn::divider(ui, Rect::from_min_max(pos2(x, body.top()), pos2(x + 1.0, body.bottom()))); + } + + let list_action = preset_list(app, ui, Rect::from_min_max(body.min, pos2(presets_right, body.bottom())), top, &names); + let middle = Rect::from_min_max(pos2(presets_right + 1.0 + MIDDLE_MARGIN, body.top()), pos2(inputs_divider - MIDDLE_MARGIN, body.bottom())); + ui.scope(|ui| outputs(app, ui, middle, top)); // The panes mark the maps the selected template's outputs read - let marked = marked_sources(app, &Tokens::get(ui.ctx())); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(inputs_width); - ui.set_height(height); - input_maps(ui, &marked); - }); - ui.separator(); - ui.vertical(|ui| { - ui.set_width(side_width); - ui.set_height(height); - mesh_and_converted_maps(ui, height, &marked); - }); + let marked = marked_sources(app); + let inputs = Rect::from_min_max(pos2(inputs_divider + PANE_FROM_DIVIDER, body.top()), pos2(side_divider - INPUTS_END_BEFORE_DIVIDER, body.bottom())); + input_maps(ui, inputs, top, &marked); + let side = Rect::from_min_max(pos2(side_divider + SIDE_PANE_FROM_DIVIDER, body.top()), body.max); + mesh_and_converted_maps(ui, side, top, &marked); if let Some(a) = list_action { apply(app, ui.ctx(), a); } @@ -397,93 +507,104 @@ pub fn select(app: &mut TextureCraftApp, name: String) { } } -/// "Naming pattern" with its info icon, at the right end of the tab row (laid out right to left) -pub(crate) fn naming_pattern(ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| { +/// "Naming pattern", its list and its info glyph at the tab row's right end +pub(crate) fn naming_pattern(ui: &mut Ui, window_right: f32, y: f32) { + let look = ExportLook::get(ui.ctx()); + let info_at = pos2(window_right - NAMING_INFO_FROM_RIGHT, y); + drawn::glyph(ui, info_at, ic::INFO, INFO_SIZE, look.text_dim); + let info = ui.interact(Rect::from_center_size(info_at, vec2(INFO_SIZE, INFO_SIZE)), ui.scope_id().with("exp_naming_info"), egui::Sense::hover()); + info.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, ic::INFO)); + info.on_hover_ui(|ui| { ui.label(tr("Choose how the input maps are named in this editor.")); ui.label(tr("The active texture set’s shader can affect the available map names.")); }); - egui::ComboBox::from_id_salt("exp_naming").width(NAMING_PATTERN_WIDTH_POINTS).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| { + let combo = drawn::control_rect(window_right - NAMING_COMBO_LEFT_FROM_RIGHT, window_right - NAMING_COMBO_RIGHT_FROM_RIGHT, y); + drawn::combo(ui, combo, "exp_naming", NAMING_PATTERNS[0], |ui| { for p in NAMING_PATTERNS { let _ = ui.selectable_label(true, p); } }); - ui.label(tr("Naming pattern")); + let label = tr("Naming pattern"); + let left = window_right - NAMING_LABEL_FROM_RIGHT - drawn::text_width(ui, label, false); + drawn::label_at(ui, left, y, label, look.text, false); } -/// The Presets list: the templates sorted by name (built-in and user); a right click offers -/// Rename, Duplicate and Remove, F2 renames -fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Option { +/// The Presets list in `column` with its header's tools; a right click offers Rename, Duplicate and Remove, F2 renames +fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32, names: &[String]) -> Option { + let look = ExportLook::get(ui.ctx()); let mut act = None; - let sel = app.ui.export.preset.clone(); + let selected_name = app.ui.export.preset.clone(); let user = app.ui.export.draft.is_some(); - ui.horizontal(|ui| { - ui.label(caption(tr("Presets"))); + drawn::label_at(ui, column.left() + TITLE_INDENT, top + HEADER_Y, tr("Presets"), look.text, true); - // Copy, "−" and "+" from left to right, without tooltips as in the reference - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icon_button_without_tooltip(ui, ic::PLUS, tr("New template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::New); - } - if ui.add_enabled_ui(user, |ui| icon_button_without_tooltip(ui, ic::MINUS, tr("Delete the selected template"), false, ICON_POINTS)).inner.clicked() - { - act = Some(ListAction::Remove(sel.clone())); - } - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate the selected template"), false, ICON_POINTS).clicked() { - act = Some(ListAction::Duplicate(sel.clone())); - } - - // TextureCraft's template files: a focusable menu, as the row's right click is pointer only - let actions = icon_button_without_tooltip(ui, ic::DOTS_THREE, tr("Template actions"), false, ICON_POINTS); - let opened_now = actions.clicked(); - egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); - }); - }); - ui.add_space(2.0); - if std::mem::take(&mut app.ui.export.rename_key) && user { - act = Some(ListAction::StartRename(sel.clone())); + // Template actions, Duplicate, "−" and "+" from left to right, without tooltips as in the reference + let icon_at = |slot_from_right: f32| pos2(column.right() - PRESET_ICON_FROM_RIGHT - slot_from_right * PRESET_ICON_STEP, top + HEADER_Y); + if drawn::icon_button(ui, icon_at(0.0), ic::PLUS, PRESET_ICON_SIZE, tr("New template"), true, false).clicked() { + act = Some(ListAction::New); } - egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { - for name in names { - let is_user = app.session.export_presets.list.iter().any(|p| p.name == *name); - match app.ui.export.renaming.as_mut().filter(|_| *name == sel) { - Some(buf) => { - let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::unique(RENAME_ID)).desired_width(f32::INFINITY)); - if r.lost_focus() { - act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) { - ListAction::Select(name.clone()) - } else { - ListAction::Rename(buf.clone()) + if drawn::icon_button(ui, icon_at(1.0), ic::MINUS, PRESET_ICON_SIZE, tr("Delete the selected template"), user, false).clicked() { + act = Some(ListAction::Remove(selected_name.clone())); + } + if drawn::icon_button(ui, icon_at(2.0), ic::COPY, PRESET_ICON_SIZE, tr("Duplicate the selected template"), true, false).clicked() { + act = Some(ListAction::Duplicate(selected_name.clone())); + } + + // TextureCraft's template files: a focusable menu, as the row's right click is pointer only + let actions = drawn::icon_button(ui, icon_at(3.0), ic::DOTS_THREE, PRESET_ICON_SIZE, tr("Template actions"), true, false); + let opened_now = actions.clicked(); + egui::Popup::menu(&actions).id(ui.make_persistent_id("exp_template_actions")).show(|ui| template_file_items(ui, &mut act, true, opened_now)); + if std::mem::take(&mut app.ui.export.rename_key) && user { + act = Some(ListAction::StartRename(selected_name.clone())); + } + + // The rows scroll, the scroll bar in its strip at the column's right + let rows = Rect::from_min_max(pos2(column.left(), top + LIST_TOP), column.max); + ui.scope_builder(egui::UiBuilder::new().max_rect(rows), |ui| { + egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + let width = rows.width() - GUTTER; + for name in names { + let is_user = app.session.export_presets.list.iter().any(|preset| preset.name == *name); + let (rect, _) = ui.allocate_exact_size(vec2(width, PRESET_ROW_HEIGHT), egui::Sense::hover()); + match app.ui.export.renaming.as_mut().filter(|_| *name == selected_name) { + Some(name_buffer) => { + let field = egui::TextEdit::singleline(name_buffer).id(egui::Id::unique(RENAME_ID)).margin(vec2(PRESET_NAME_LEFT, 0.0)); + let rename_field = ui.put(rect, field); + if rename_field.lost_focus() { + act = Some(if ui.input(|input| input.key_pressed(egui::Key::Escape)) { + ListAction::Select(name.clone()) + } else { + ListAction::Rename(name_buffer.clone()) + }); + } + } + None => { + let response = preset_row(ui, rect, name, *name == selected_name, is_user).on_hover_text(name); + if response.double_clicked() && is_user { + act = Some(ListAction::StartRename(name.clone())); + } else if response.clicked() { + act = Some(ListAction::Select(name.clone())); + } + response.context_menu(|ui| { + let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); + if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::StartRename(name.clone())); + } + if ui.button(tr("Duplicate")).clicked() { + act = Some(ListAction::Duplicate(name.clone())); + } + if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { + act = Some(ListAction::Remove(name.clone())); + } + + // TextureCraft's template files, after the reference's entries + ui.separator(); + template_file_items(ui, &mut act, *name == selected_name, false); }); } } - None => { - let r = preset_row(ui, name, *name == sel).on_hover_text(name); - if r.double_clicked() && is_user { - act = Some(ListAction::StartRename(name.clone())); - } else if r.clicked() { - act = Some(ListAction::Select(name.clone())); - } - r.context_menu(|ui| { - let read_only = tr("Built-in templates are read-only: duplicate one to edit it"); - if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::StartRename(name.clone())); - } - if ui.button(tr("Duplicate")).clicked() { - act = Some(ListAction::Duplicate(name.clone())); - } - if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() { - act = Some(ListAction::Remove(name.clone())); - } - - // TextureCraft's template files, after the reference's entries - ui.separator(); - template_file_items(ui, &mut act, *name == sel, false); - }); - } } - } + }); }); act } @@ -506,25 +627,23 @@ fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: b } } -/// A Presets list row: a document icon and the name (cut with "…" when long), the selected one in -/// the accent colour -fn preset_row(ui: &mut Ui, name: &str, selected: bool) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), PRESET_ROW_HEIGHT_POINTS), egui::Sense::click()); +/// A Presets row: a locked file glyph for a built-in template, the name cut with "…", the selected one in bold +fn preset_row(ui: &mut Ui, rect: Rect, name: &str, selected: bool, is_user: bool) -> egui::Response { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, ui.scope_id().with(("exp_preset_row", name)), egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); - let painter = ui.painter(); - if response.hovered() { - painter.rect_filled(rect, tokens.radius, tokens.row_hover); + if selected { + painter.rect_filled(rect, 0.0, look.chrome); + } else if response.hovered() { + painter.rect_filled(rect, 0.0, look.raised); } - let font = egui::TextStyle::Body.resolve(ui.style()); - painter.text(rect.left_center() + vec2(PRESET_ICON_INDENT_POINTS, 0.0), egui::Align2::LEFT_CENTER, ic::FILE_TEXT, font.clone(), tokens.text_dim); - let color = if selected { tokens.accent } else { tokens.text }; - let mut job = egui::text::LayoutJob::simple_singleline(name.to_string(), font, color); - job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width() - PRESET_TEXT_INDENT_POINTS); - let galley = painter.layout_job(job); - let top_left = egui::pos2(rect.left() + PRESET_TEXT_INDENT_POINTS, rect.center().y - galley.size().y / 2.0); - painter.galley(top_left, galley, color); + let icon = if is_user { ic::FILE_TEXT } else { ic::FILE_LOCK }; + drawn::glyph(ui, pos2(rect.left() + PRESET_ICON_X, rect.center().y), icon, PRESET_ROW_ICON_SIZE, look.text_dim); + let shown = drawn::fitted(ui, name, rect.width() - PRESET_NAME_LEFT, false, selected); + let color = if selected { look.text } else { look.list_text }; + drawn::text_at(ui, rect.left() + PRESET_NAME_LEFT, rect.center().y, &shown, color, selected); + drawn::paint_focus(ui, &response); response } @@ -760,14 +879,15 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) { let _ = (app, storage); } -/// The selected template's output maps (editable for user templates). -fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { +/// The selected template's output maps in `column`, editable for user templates +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) => { - ui.label(RichText::new(tr("Select an output template")).color(tokens.text_dim)); + drawn::label_at(ui, column.left(), top + CURRENT_PRESET_Y, tr("Select an output template"), look.text_dim, false); return; } }; @@ -778,76 +898,80 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) { } let mut edit = RowEdit::default(); - // The selected template in a strip, "Current preset:" in bold - egui::Frame::new().fill(tokens.row).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Current preset:")).strong().color(tokens.text_strong)); - ui.label(&preset.name); - if !editable { - ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); - } - }); - }); + // "Current preset:" in bold, the template's name, a lock on a built-in one + let y = top + CURRENT_PRESET_Y; + let title = tr("Current preset:"); + let name_left = column.left() + drawn::text_width(ui, title, true) + NAME_GAP; + drawn::label_at(ui, column.left(), y, title, look.text, true); + let name = drawn::label_at(ui, name_left, y, &preset.name, look.text, false); + if !editable { + let lock_at = pos2(name.rect.right() + LOCK_GAP, y); + drawn::glyph(ui, lock_at, ic::LOCK_SIMPLE, CARD_ICON_SIZE, look.text_dim); + let lock = + ui.interact(Rect::from_center_size(lock_at, vec2(CARD_ICON_SIZE, CARD_ICON_SIZE)), ui.scope_id().with("exp_preset_lock"), egui::Sense::hover()); + lock.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, ic::LOCK_SIMPLE)); + lock.on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it")); + } - // "Output maps", with the Create buttons at the right end of the same row, or of the next one - // when the column is too narrow for both - let create_buttons = |ui: &mut Ui, edit: &mut RowEdit| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_enabled_ui(editable, |ui| { - for (label, layout, split, file) in CREATE.iter().rev() { - if ui.button(tr(label)).clicked() { - edit.action = Some(MapAction::Add(*layout, *split, file)); - } - } - ui.label(RichText::new(tr("Create:")).color(tokens.text_dim)); - }); - }); - }; - if ui.available_width() >= OUTPUT_MAPS_ROW_WIDTH_POINTS { - ui.horizontal(|ui| { - ui.label(caption(tr("Output maps"))); - create_buttons(ui, &mut edit); - }); - } else { - ui.label(caption(tr("Output maps"))); - ui.horizontal(|ui| create_buttons(ui, &mut edit)); - } - if let Err(e) = &preview { - ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0)); + // A built-in template's cards and buttons keep their full look: the lock says they are read-only + ui.visuals_mut().disabled_alpha = 1.0; + let y = top + OUTPUT_MAPS_Y; + drawn::label_at(ui, column.left(), y, tr("Output maps"), look.text, true); + let mut right = column.right(); + for (label, layout, split, file) in CREATE.iter().rev() { + let width = drawn::text_width(ui, tr(label), false) + CREATE_PADDING; + if drawn::button(ui, drawn::control_rect(right - width, right, y), tr(label), false, editable).clicked() { + edit.action = Some(MapAction::Add(*layout, *split, file)); + } + right -= width + CREATE_GAP; } + let create = tr("Create:"); + drawn::label_at(ui, right - CREATE_LABEL_GAP - drawn::text_width(ui, create, false), y, create, look.text, false); + let mut changed = false; let map_count = preset.maps.len(); let mut split = app.ui.export.draft_split.clone(); split.resize(map_count, false); - // Leave room for the footer text and the framed count below - let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y + 2.0 * ROW_MARGIN_POINTS; - egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| { - ui.add_enabled_ui(editable, |ui| { - // Every row takes the column's width, not the width a wider row before it left - let row_width = ui.available_width(); - for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { - let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); - changed |= ui.allocate_ui(vec2(row_width, 0.0), |ui| output_row(ui, index, map_count, map, row_split, planned, &mut edit)).inner; - ui.add_space(ROW_GAP_POINTS); - } + // The cards scroll between the header and the count strip; their lists line up on one column + let strip = + Rect::from_min_max(pos2(column.left(), column.bottom() - COUNT_TOP_ABOVE_BOTTOM), pos2(column.right(), column.bottom() - COUNT_BOTTOM_ABOVE_BOTTOM)); + let cards = Rect::from_min_max(pos2(column.left(), top + CARDS_TOP), pos2(column.right(), strip.top() - CARD_GAP)); + let values = + preset.maps.iter().flat_map(|map| [map.format.extension().to_string(), crate::export_window::depth_label(Some(map.format), map.bit_depth, false)]); + let value_width = values.chain(CARD_VALUE_SAMPLES.map(str::to_string)).map(|value| drawn::text_width(ui, &value, false)).fold(0.0, f32::max); + ui.scope_builder(egui::UiBuilder::new().max_rect(cards), |ui| { + egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).show(ui, |ui| { + let height = map_count as f32 * (CARD_HEIGHT + CARD_GAP); + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), egui::Sense::hover()); + ui.add_enabled_ui(editable, |ui| { + for ((index, map), row_split) in preset.maps.iter_mut().enumerate().zip(split.iter_mut()) { + let planned = preview.as_ref().ok().and_then(|outputs| outputs.get(index)).and_then(Option::as_ref); + let top = area.top() + index as f32 * (CARD_HEIGHT + CARD_GAP); + let card = Rect::from_min_size(pos2(area.left(), top), vec2(area.width(), CARD_HEIGHT)); + let row = OutputCard { index, count: map_count, value_width }; + changed |= output_row(ui, card, &row, map, row_split, planned, &mut edit); + } + }); }); }); - ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim)); // The hovered output's pictures show from the next frame on if let (Some(index), Ok(params)) = (edit.hovered_output, ¶ms) { MapPreviewCache::fill(app, ui.ctx(), params, index); } - // Count only maps that have sources in the current set - if let Ok(planned) = &preview { - let exported = planned.iter().flatten().count(); - egui::Frame::new().fill(tokens.field).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(trf("{n} output maps will be exported.", &[("n", &exported)])); - }); + // Count only maps that have sources in the current set; an edit that cannot be saved says why there + ui.painter().rect_filled(strip, 0.0, look.control); + let text_left = strip.left() + COUNT_TEXT_INDENT; + match &preview { + Ok(planned) => { + let exported = planned.iter().flatten().count(); + drawn::label_at(ui, text_left, strip.center().y, &trf("{n} output maps will be exported", &[("n", &exported)]), look.text, false); + } + Err(e) => { + drawn::label_at(ui, text_left, strip.center().y, &trf("Not saved: {error}", &[("error", e)]), tokens.danger, false); + } } if !editable { return; @@ -978,71 +1102,83 @@ fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result, edit: &mut RowEdit) -> bool { - let tokens = Tokens::get(ui.ctx()); +/// One output map card: grip, file name, "$", swatches, then file type over bit depth beside duplicate and remove +fn output_row(ui: &mut Ui, card: Rect, row: &OutputCard, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { + let look = ExportLook::get(ui.ctx()); + let index = row.index; + + // The card takes a dragged row before its controls, which sit above it + let card_response = ui.interact(card, ui.scope_id().with(("exp_card", index)), egui::Sense::hover()); + ui.painter().rect_filled(card, CARD_RADIUS, look.control); + let mid = card.center().y; let mut changed = false; - let frame = egui::Frame::new().fill(tokens.row).corner_radius(tokens.radius).inner_margin(ROW_MARGIN_POINTS).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend); + grip(ui, Rect::from_center_size(pos2(card.left() + GRIP_X, mid), vec2(GRIP_WIDTH, card.height())), index, row.count, edit); - // The name field gives way in a narrow window, so the swatches and lists stay in the row - let swatches = swatch_targets(map, *split).len() as f32; - let spacing = ui.spacing().item_spacing.x; - let others = GRIP_WIDTH_POINTS + DOLLAR_BUTTON_WIDTH_POINTS + swatches * (SWATCH_SIZE_POINTS + spacing) + ROW_LISTS_WIDTH_POINTS; - let name_width = (ui.available_width() - others - ROW_GAPS * spacing).clamp(MIN_NAME_FIELD_WIDTH_POINTS, NAME_FIELD_WIDTH_POINTS); + // The name field gives way in a narrow window, so the swatches and lists keep their room + let swatches_width = swatch_targets(map, *split).len() as f32 * (SWATCH_WIDTH + SWATCH_GAP); + let lists_width = CARD_ICON_FROM_RIGHT + CARD_CHEVRON_STEP + CARD_VALUE_GAP + row.value_width + SWATCHES_GAP; + let room = card.width() - NAME_FIELD_LEFT - DOLLAR_GAP - DOLLAR_WIDTH - SWATCHES_GAP - swatches_width - lists_width; + let name_width = room.clamp(MIN_NAME_FIELD_WIDTH, NAME_FIELD_WIDTH); + let name_rect = drawn::control_rect(card.left() + NAME_FIELD_LEFT, card.left() + NAME_FIELD_LEFT + name_width, mid); + changed |= name_field(ui, name_rect, index, &mut map.file, planned); + let dollar = drawn::control_rect(name_rect.right() + DOLLAR_GAP, name_rect.right() + DOLLAR_GAP + DOLLAR_WIDTH, mid); + changed |= token_menu(ui, dollar, index, &mut map.file); + let swatches = Rect::from_min_max(pos2(dollar.right() + SWATCHES_GAP, card.top() + CARD_INSET), pos2(card.right(), card.bottom() - CARD_INSET)); + changed |= channel_swatches(ui, swatches, index, map, split, planned, edit); - grip(ui, index, count, edit); - let name = ui.add(egui::TextEdit::singleline(&mut map.file).desired_width(name_width)).on_hover_ui(|ui| { - ui.label(tr("File name without extension; variables insert names")); - ui.label(planned_text(planned)); - }); - changed |= name.changed(); - changed |= token_menu(ui, &mut map.file); - changed |= channel_swatches(ui, index, map, split, planned, edit); - - // The lists and icons at the row's right end: file format and duplicate, bit depth and remove - ui.add_space((ui.available_width() - ROW_LISTS_WIDTH_POINTS).max(0.0)); - ui.vertical(|ui| { - ui.horizontal(|ui| { - changed |= format_menu(ui, map); - if icon_button_without_tooltip(ui, ic::COPY, tr("Duplicate this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Duplicate(index)); - } - }); - ui.horizontal(|ui| { - changed |= depth_menu(ui, map); - if icon_button_without_tooltip(ui, ic::X, tr("Remove this output"), false, ROW_ICON_POINTS).clicked() { - edit.action = Some(MapAction::Remove(index)); - } - }); - }); - }); - }); - - // Another row's grip dropped here moves that row here (the type check keeps a map list drop) - let row = frame.response; - let row_dragged_over = row.dnd_hover_payload::().is_some_and(|from| from.0 != index); - if row_dragged_over { - drop_highlight(ui, row.rect, &tokens); + // The right block: file type over bit depth on one column, duplicate over remove beside them + let icon_x = card.right() - CARD_ICON_FROM_RIGHT; + let chevron_x = icon_x - CARD_CHEVRON_STEP; + let value_left = chevron_x - CARD_VALUE_GAP - row.value_width; + let (upper, lower) = (mid - CARD_ROW_OFFSET, mid + CARD_ROW_OFFSET); + changed |= format_menu(ui, (value_left, chevron_x, upper), index, map); + changed |= depth_menu(ui, (value_left, chevron_x, lower), index, map); + if drawn::icon_button(ui, pos2(icon_x, upper), ic::COPY, CARD_ICON_SIZE, tr("Duplicate this output"), ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Duplicate(index)); } - if row_dragged_over && let Some(from) = row.dnd_release_payload::() { + if drawn::icon_button(ui, pos2(icon_x, lower), ic::X, CARD_ICON_SIZE, tr("Remove this output"), ui.is_enabled(), false).clicked() { + edit.action = Some(MapAction::Remove(index)); + } + + // Another card's grip dropped here moves that card here (the type check keeps a map list drop) + let row_dragged_over = card_response.dnd_hover_payload::().is_some_and(|from| from.0 != index); + if row_dragged_over { + drop_highlight(ui, card); + } + if row_dragged_over && let Some(from) = card_response.dnd_release_payload::() { edit.action = Some(MapAction::Move { from: from.0, to: index }); } changed } -/// The grip at a row's left: drag it onto another row to move the map there; the arrow keys and -/// its right-click menu move it one place -fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { - let tokens = Tokens::get(ui.ctx()); +/// The file name field; until it is typed in it shows the name's end, cut with "…"; true when it changed +fn name_field(ui: &mut Ui, rect: Rect, index: usize, file: &mut String, planned: Option<&PlannedOutput>) -> bool { + let look = ExportLook::get(ui.ctx()); + let id = ui.scope_id().with(("exp_map_name", index)); + let typing = ui.memory(|memory| memory.has_focus(id)); + let text_color = if typing { look.text } else { Color32::TRANSPARENT }; + let field = egui::TextEdit::singleline(file).id(id).margin(vec2(drawn::VALUE_INSET, 0.0)).background_color(look.control).text_color(text_color); + let response = ui.put(rect, field).on_hover_ui(|ui| { + ui.label(tr("File name without extension; variables insert names")); + ui.label(planned_text(planned)); + }); + if !typing { + let shown = drawn::fitted(ui, file, rect.width() - 2.0 * drawn::VALUE_INSET, true, false); + let color = if drawn::looks_disabled(ui, ui.is_enabled()) { look.text_dim } else { look.text }; + drawn::text_at(ui, rect.left() + drawn::VALUE_INSET, rect.center().y, &shown, color, false); + } + response.changed() +} + +/// A card's grip: drag it onto another card, or use the arrow keys or its menu, to move the map +fn grip(ui: &mut Ui, rect: Rect, index: usize, count: usize, edit: &mut RowEdit) { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(GRIP_WIDTH_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click_and_drag()); + let response = ui.interact(rect, ui.scope_id().with(("exp_grip", index)), if enabled { egui::Sense::click_and_drag() } else { egui::Sense::hover() }); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tr("Reorder"))); - let color = if response.hovered() || response.dragged() { tokens.text } else { tokens.text_dim }; - ui.painter().rect_filled(rect, 1.0, color); + let color = if enabled && (response.hovered() || response.dragged()) { look.text } else { look.text_dim }; + drawn::glyph(ui, rect.center(), ic::DOTS_SIX_VERTICAL, GRIP_SIZE, color); + drawn::paint_focus(ui, &response); let response = response.on_hover_cursor(egui::CursorIcon::Grab); response.dnd_set_drag_payload(MapDrag(index)); @@ -1071,10 +1207,12 @@ fn grip(ui: &mut Ui, index: usize, count: usize, edit: &mut RowEdit) { } } -/// The "$" button: the file name variables in the reference's order, then $channel -fn token_menu(ui: &mut Ui, file: &mut String) -> bool { +/// The "$" button in `rect`: the file name variables in the reference's order, then $channel +fn token_menu(ui: &mut Ui, rect: Rect, index: usize, file: &mut String) -> bool { let mut changed = false; - let menu = ui.menu_button("$", |ui| { + let id = ui.scope_id().with(("exp_tokens", index)); + let button = drawn::button_with_id(ui, id, rect, "$", "$", false, ui.is_enabled()).on_hover_text(tr("Insert a variable")); + egui::Popup::menu(&button).show(|ui| { let mut add = |ui: &mut Ui, token: &str| { if ui.button(RichText::new(token).monospace()).clicked() { file.push_str(token); @@ -1093,14 +1231,15 @@ fn token_menu(ui: &mut Ui, file: &mut String) -> bool { add(ui, token); } }); - menu.response.on_hover_text(tr("Insert a variable")); changed } -/// The file type menu of an output map ("png˅") -fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The file type menu of an output map ("png ⌄") at `place`: (value's left, chevron's centre, middle) +fn format_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let mut changed = false; - let menu = ui.menu_button(RichText::new(format!("{} {}", map.format.extension(), ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_format", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, map.format.extension()).on_hover_text(tr("File format")); + egui::Popup::menu(&menu).show(|ui| { for extension in MAP_FILE_TYPES { let Some(format) = FileFormat::from_extension(extension) else { ui.add_enabled(false, egui::Button::selectable(false, extension)).on_disabled_hover_text(tr(NOT_AVAILABLE)); @@ -1118,16 +1257,17 @@ fn format_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("File format")); changed } -/// The bit depth menu of an output map ("8 bits˅"); templates do not keep dithering yet -fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { +/// The bit depth menu of an output map ("8 bits ⌄"); templates do not keep dithering yet +fn depth_menu(ui: &mut Ui, (left, chevron, y): (f32, f32, f32), index: usize, map: &mut MapSpec) -> bool { let format = map.format; let mut changed = false; let shown = crate::export_window::depth_label(Some(format), map.bit_depth, false); - let menu = ui.menu_button(RichText::new(format!("{shown} {}", ic::CARET_DOWN)), |ui| { + let id = ui.scope_id().with(("exp_map_depth", index)); + let menu = drawn::text_dropdown(ui, id, left, chevron, y, &shown).on_hover_text(tr("Bit depth")); + egui::Popup::menu(&menu).show(|ui| { for (depth, dithering) in crate::export_window::depth_options(format) { let label = crate::export_window::depth_label(Some(format), depth, dithering); if dithering { @@ -1139,7 +1279,6 @@ fn depth_menu(ui: &mut Ui, map: &mut MapSpec) -> bool { } } }); - menu.response.on_hover_text(tr("Bit depth")); changed } @@ -1280,8 +1419,8 @@ fn swatch_tooltip(map: &MapSpec, source: &SourceRef, target: ChannelTarget, inve } } -/// The colour of a map on swatches and list markers (None for constants) -fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { +/// A map's colour on swatches and list markers (None for constants), the reference's own where it has one +fn source_color(source: &SourceRef) -> Option { let channels = Channel::ALL.len(); let converted = VirtualMap::ALL.len(); let index = match source { @@ -1290,19 +1429,19 @@ fn source_color(source: &SourceRef, tokens: &Tokens) -> Option { SourceRef::Baked { map, .. } => channels + converted + BakedMap::ALL.iter().position(|m| m == map)?, SourceRef::Constant(_) => return None, }; - let hue = (index as f32 * HUE_STEP).fract(); - let value = if tokens.dark { SWATCH_VALUE_DARK } else { SWATCH_VALUE_LIGHT }; - Some(egui::ecolor::Hsva::new(hue, SWATCH_SATURATION, value, 1.0).into()) + let reference = REFERENCE_SWATCHES.iter().find(|(known, _)| same_source(known, source)).map(|(_, rgb)| *rgb); + let [r, g, b] = reference.or_else(|| FREE_SWATCHES.get(index % FREE_SWATCHES.len().max(1)).copied())?; + Some(Color32::from_rgb(r + SWATCH_SHIFT[0], g + SWATCH_SHIFT[1], b + SWATCH_SHIFT[2])) } -/// The bars under a swatch's letters: red, green and blue for a colour map's RGB, else the one -/// channel read (white for gray) -fn swatch_bars(map: &MapSpec, source: &SourceRef, target: ChannelTarget, tokens: &Tokens) -> Vec { - match source { - SourceRef::Constant(_) => Vec::new(), - _ if source.components() == 3 && target == ChannelTarget::Rgb && rgb_spread(map) => COMPONENT_COLORS.to_vec(), - _ if source.components() == 3 => COMPONENT_COLORS.get(usize::from(component_of(source))).copied().into_iter().collect(), - _ => vec![tokens.text_strong], +/// The underline of a swatch: the colour of the channel its letters name (white for RGB and gray) +fn swatch_bar(target: ChannelTarget) -> Color32 { + match target { + ChannelTarget::One(Dest::R) => BAR_RED, + ChannelTarget::One(Dest::G) => BAR_GREEN, + ChannelTarget::One(Dest::B) => BAR_BLUE, + ChannelTarget::One(Dest::A) => BAR_ALPHA, + ChannelTarget::Rgb | ChannelTarget::One(Dest::L) => BAR_WHOLE, } } @@ -1357,13 +1496,11 @@ fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { }); } -/// An output map's channel swatches: drop targets for the map lists. A click opens Clear channel -/// (and Separate R, G and B on R, G, B), a right click TextureCraft's own tools. Hovering one -/// shows the file the output writes. -fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { - let tokens = Tokens::get(ui.ctx()); +/// A card's channel swatches from `area`'s left: drop targets for the map lists, with click and right-click menus +fn channel_swatches(ui: &mut Ui, area: Rect, index: usize, map: &mut MapSpec, split: &mut bool, planned: Option<&PlannedOutput>, edit: &mut RowEdit) -> bool { let mut changed = false; let shows_split = *split || !rgb_collapsed(map); + let mut left = area.left(); for (slot, target) in swatch_targets(map, *split).into_iter().enumerate() { let Some(source) = source_of(map, target).cloned() else { continue }; @@ -1374,8 +1511,11 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo if inverted { name = trf("{swatch}, inverted", &[("swatch", &name)]); } - let look = SwatchLook { fill: source_color(&source, &tokens), bars: swatch_bars(map, &source, target, &tokens), inverted }; - let response = swatch(ui, label, &name, &look); + let constant = matches!(source, SourceRef::Constant(_)); + let look = SwatchLook { fill: source_color(&source), bar: (!constant).then(|| swatch_bar(target)), inverted }; + let rect = Rect::from_min_max(pos2(left, area.top()), pos2(left + SWATCH_WIDTH, area.bottom())); + left += SWATCH_WIDTH + SWATCH_GAP; + let response = swatch(ui, ui.scope_id().with(("exp_swatch", index, slot)), rect, label, &name, &look); if response.contains_pointer() { edit.hovered_output = Some(index); } @@ -1391,7 +1531,7 @@ fn channel_swatches(ui: &mut Ui, index: usize, map: &mut MapSpec, split: &mut bo // A map dragged over the swatch, or dropped on it; a row's grip passes through to its row let map_dragged_over = response.dnd_hover_payload::().is_some(); if map_dragged_over { - drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS), &tokens); + drop_highlight(ui, response.rect.expand(DROP_HIGHLIGHT_GAP_POINTS)); } if map_dragged_over && let Some(input) = response.dnd_release_payload::() { edit.pending = Some(PendingDrop { map: index, target, source: (*input).clone(), position: response.rect.center_bottom() }); @@ -1471,35 +1611,41 @@ fn set_constant(map: &mut MapSpec, target: ChannelTarget, value: f32) { } } -/// The accent frame around a drop target under a dragged map or row -fn drop_highlight(ui: &Ui, rect: egui::Rect, tokens: &Tokens) { - ui.painter().rect_stroke(rect, tokens.radius, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, tokens.accent), egui::StrokeKind::Outside); +/// The frame round a drop target, in the text colour: the accent is Export's alone +fn drop_highlight(ui: &Ui, rect: Rect) { + let look = ExportLook::get(ui.ctx()); + ui.painter().rect_stroke(rect, CARD_RADIUS, egui::Stroke::new(DROP_HIGHLIGHT_STROKE_POINTS, look.text), egui::StrokeKind::Outside); } -/// One channel swatch: `label` on top, filled with the source's colour, bars below for the -/// channels it reads, a corner mark when inverted -fn swatch(ui: &mut Ui, label: &str, name: &str, look: &SwatchLook) -> egui::Response { - let tokens = Tokens::get(ui.ctx()); +/// One channel swatch `id`: its letters, the source's colour, its channel's underline, a corner mark when inverted +fn swatch(ui: &mut Ui, id: egui::Id, rect: Rect, label: &str, name: &str, swatch_look: &SwatchLook) -> egui::Response { + let look = ExportLook::get(ui.ctx()); let enabled = ui.is_enabled(); - let (rect, response) = ui.allocate_exact_size(vec2(SWATCH_SIZE_POINTS, SWATCH_SIZE_POINTS), egui::Sense::click()); + let response = ui.interact(rect, id, egui::Sense::click()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, name)); + // Light lettering on the dark swatches in every theme let painter = ui.painter(); - let border = if response.hovered() { tokens.accent } else { tokens.button_border }; - painter.rect(rect, tokens.radius, look.fill.unwrap_or(tokens.button), egui::Stroke::new(1.0, border), egui::StrokeKind::Inside); - let label_font = egui::FontId::proportional(SWATCH_TEXT_SIZE_POINTS); - painter.text(rect.center_top() + vec2(0.0, SWATCH_TEXT_TOP_POINTS), egui::Align2::CENTER_TOP, label, label_font, tokens.text_strong); - let bar_width = SWATCH_BAR_WIDTH_POINTS / look.bars.len().max(1) as f32; - let left = rect.center().x - SWATCH_BAR_WIDTH_POINTS / 2.0; - for (k, color) in look.bars.iter().enumerate() { - let min = egui::pos2(left + k as f32 * bar_width, rect.bottom() - SWATCH_BAR_BOTTOM_POINTS); - painter.rect_filled(egui::Rect::from_min_size(min, vec2(bar_width, SWATCH_BAR_HEIGHT_POINTS)), 0.0, *color); + painter.rect_filled(rect, 0.0, swatch_look.fill.unwrap_or(look.raised)); + if response.hovered() { + painter.rect_stroke(rect, 0.0, egui::Stroke::new(1.0, look.text_dim), egui::StrokeKind::Inside); } - if look.inverted { + let lettering = if look.dark { look.text } else { look.window }; + painter.text(pos2(rect.center().x, rect.top() + SWATCH_LABEL_Y), egui::Align2::CENTER_CENTER, label, drawn::font(false), lettering); + if let Some(bar) = swatch_look.bar { + let bottom = rect.bottom() - SWATCH_BAR_BOTTOM; + painter.rect_filled( + Rect::from_min_max(pos2(rect.left() + SWATCH_BAR_INSET, bottom), pos2(rect.right() - SWATCH_BAR_INSET, bottom + SWATCH_BAR_HEIGHT)), + 0.0, + bar, + ); + } + if swatch_look.inverted { let corner = rect.right_top(); let mark = vec![corner, corner - vec2(INVERTED_MARK_POINTS, 0.0), corner + vec2(0.0, INVERTED_MARK_POINTS)]; - painter.add(egui::Shape::convex_polygon(mark, tokens.text_strong, egui::Stroke::NONE)); + painter.add(egui::Shape::convex_polygon(mark, lettering, egui::Stroke::NONE)); } + drawn::paint_focus(ui, &response); response } @@ -1585,79 +1731,92 @@ 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, tokens: &Tokens) -> Vec<(SourceRef, Color32)> { +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 sources = preset.maps.iter().flat_map(|map| map.channels.iter().map(|(_, source)| source)); - sources.filter_map(|source| source_color(source, tokens).map(|color| (source.clone(), color))).collect() + sources.filter_map(|source| source_color(source).map(|color| (source.clone(), color))).collect() } -/// The Input maps pane: the input maps in their groups -fn input_maps(ui: &mut Ui, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Input maps"))); - egui::ScrollArea::vertical().id_salt("exp_inputs").auto_shrink([false; 2]).show(ui, |ui| { +/// A pane's title at `left`, on the column titles' line +fn pane_title(ui: &mut Ui, left: f32, y: f32, title: &str) { + let look = ExportLook::get(ui.ctx()); + drawn::label_at(ui, left + GROUP_INDENT, y, title, look.text, true); +} + +/// A pane's entries scrolling in `area`, the scroll bar in its strip at the right +fn pane_list(ui: &mut Ui, area: Rect, id: &str, add: impl FnOnce(&mut Ui, f32)) { + ui.scope_builder(egui::UiBuilder::new().max_rect(area), |ui| { + egui::ScrollArea::vertical().id_salt(id).auto_shrink([false; 2]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + add(ui, area.width() - GUTTER); + }); + }); +} + +/// The Input maps pane in `pane`: the input maps in their groups +fn input_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + let look = ExportLook::get(ui.ctx()); + pane_title(ui, pane.left(), top + HEADER_Y, tr("Input maps")); + let list = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pane.max); + pane_list(ui, list, "exp_inputs", |ui, width| { for (group, entries) in INPUT_MAPS.iter() { - ui.label(RichText::new(tr(group)).italics()); - map_entries(ui, entries, marked, false); + let (rect, _) = ui.allocate_exact_size(vec2(width, GROUP_HEIGHT), egui::Sense::hover()); + drawn::label_at(ui, rect.left() + GROUP_INDENT, rect.center().y, tr(group), look.text_dim, false); + map_entries(ui, width, entries, marked); } }); } -/// The side pane: Mesh maps above Converted maps (in the highlight colour, as in the reference) -fn mesh_and_converted_maps(ui: &mut Ui, height: f32, marked: &[(SourceRef, Color32)]) { - ui.label(caption(tr("Mesh maps"))); - egui::ScrollArea::vertical() - .id_salt("exp_mesh_maps") - .auto_shrink([false; 2]) - .max_height(height * MESH_MAPS_SHARE) - .show(ui, |ui| map_entries(ui, &MESH_MAPS, marked, false)); - ui.separator(); - ui.label(caption(tr("Converted maps"))); - egui::ScrollArea::vertical().id_salt("exp_converted_maps").auto_shrink([false; 2]).show(ui, |ui| map_entries(ui, &CONVERTED_MAPS, marked, true)); +/// The side pane in `pane`: Mesh maps above Converted maps, a divider between them +fn mesh_and_converted_maps(ui: &mut Ui, pane: Rect, top: f32, marked: &[(SourceRef, Color32)]) { + pane_title(ui, pane.left(), top + HEADER_Y, tr("Mesh maps")); + let split = pane.center().y + SIDE_SPLIT_BELOW_MIDDLE; + let mesh = Rect::from_min_max(pos2(pane.left(), top + LIST_TOP), pos2(pane.right(), split - MESH_BOTTOM_GAP)); + pane_list(ui, mesh, "exp_mesh_maps", |ui, width| map_entries(ui, width, &MESH_MAPS, marked)); + drawn::divider(ui, Rect::from_min_max(pos2(pane.left() - 1.0, split), pos2(pane.right(), split + 1.0))); + pane_title(ui, pane.left(), split + CONVERTED_TITLE_Y, tr("Converted maps")); + let converted = Rect::from_min_max(pos2(pane.left(), split + CONVERTED_ROWS_TOP), pane.max); + pane_list(ui, converted, "exp_converted_maps", |ui, width| map_entries(ui, width, &CONVERTED_MAPS, marked)); } -fn map_entries(ui: &mut Ui, entries: &[MapEntry], marked: &[(SourceRef, Color32)], converted: bool) { - let tokens = Tokens::get(ui.ctx()); - let text_color = if converted { tokens.warning } else { tokens.text }; +fn map_entries(ui: &mut Ui, width: f32, entries: &[MapEntry], marked: &[(SourceRef, Color32)]) { for (name, source) in entries { let marker = source.as_ref().and_then(|source| marked.iter().find(|(used, _)| same_source(used, source)).map(|(_, color)| *color)); - map_entry(ui, tr(name), source.as_ref(), text_color, marker); + map_entry(ui, width, tr(name), source.as_ref(), marker); } } -/// A map list entry to drag onto an output channel, with the colour marker of an output map that -/// reads it; a map TextureCraft does not have yet is greyed and cannot be dragged -fn map_entry(ui: &mut Ui, name: &str, source: Option<&SourceRef>, text_color: Color32, marker: Option) { - let tokens = Tokens::get(ui.ctx()); +/// A map list entry to drag onto a channel; a used map shows a square of its colour, a missing one is greyed +fn map_entry(ui: &mut Ui, width: f32, name: &str, source: Option<&SourceRef>, marker: Option) { + let look = ExportLook::get(ui.ctx()); let available = source.is_some(); let sense = if available { egui::Sense::drag() } else { egui::Sense::hover() }; - let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), ENTRY_HEIGHT_POINTS), sense); + let (rect, response) = ui.allocate_exact_size(vec2(width, ENTRY_PITCH), sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, available, name)); + let row = Rect::from_min_max(pos2(rect.left() + ENTRY_INSET, rect.top()), pos2(rect.right(), rect.top() + ENTRY_HEIGHT)); let painter = ui.painter(); - let row = rect.shrink2(vec2(0.0, ENTRY_GAP_POINTS / 2.0)); - painter.rect_filled(row, 0.0, if available && response.hovered() { tokens.row_hover } else { tokens.row }); + painter.rect_filled(row, 0.0, if available && response.hovered() { look.raised } else { look.control }); if let Some(color) = marker { - painter.rect_filled( - egui::Rect::from_center_size(row.left_center() + vec2(MARKER_INDENT_POINTS, 0.0), egui::Vec2::splat(MARKER_SIZE_POINTS)), - 1.0, - color, + let square = Rect::from_min_size(pos2(rect.left() + MARKER_LEFT, row.center().y - MARKER_SIZE / 2.0), vec2(MARKER_SIZE, MARKER_SIZE)); + let edge = Color32::from_rgb( + color.r().saturating_add(MARKER_EDGE_LIGHTEN), + color.g().saturating_add(MARKER_EDGE_LIGHTEN), + color.b().saturating_add(MARKER_EDGE_LIGHTEN), ); + painter.rect(square, MARKER_RADIUS, color, egui::Stroke::new(1.0, edge), egui::StrokeKind::Inside); } - let color = if available { text_color } else { tokens.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; - painter.text( - row.left_center() + vec2(ENTRY_TEXT_INDENT_POINTS, 0.0), - egui::Align2::LEFT_CENTER, - name, - egui::FontId::proportional(ENTRY_TEXT_SIZE_POINTS), - color, - ); + let color = if available { look.text } else { look.text_dim.gamma_multiply(UNAVAILABLE_FADE) }; + let shown = drawn::fitted(ui, name, row.right() - rect.left() - ENTRY_NAME_LEFT, false, false); + drawn::text_at(ui, rect.left() + ENTRY_NAME_LEFT, row.center().y, &shown, color, false); let Some(source) = source else { response.on_hover_text(tr(NOT_AVAILABLE)); return; }; - let response = response.on_hover_cursor(egui::CursorIcon::Grab); + // How to use the entry is its tooltip, not a line under the cards + let response = response.on_hover_cursor(egui::CursorIcon::Grab).on_hover_text(tr("Drop an input map onto a channel to assign it to that output.")); response.dnd_set_drag_payload(source.clone()); if response.dragged() && let Some(at) = response.interact_pointer_pos() diff --git a/crates/ui-egui/src/export_templates/output_card.rs b/crates/ui-egui/src/export_templates/output_card.rs new file mode 100644 index 00000000..a7f1eddc --- /dev/null +++ b/crates/ui-egui/src/export_templates/output_card.rs @@ -0,0 +1,6 @@ +/// An output map card's index, the card count (for the grip's moves) and the width its lists' values line up on +pub(super) struct OutputCard { + pub(super) index: usize, + pub(super) count: usize, + pub(super) value_width: f32, +} diff --git a/crates/ui-egui/src/export_templates/swatch_look.rs b/crates/ui-egui/src/export_templates/swatch_look.rs index 99d81b19..f33e86d8 100644 --- a/crates/ui-egui/src/export_templates/swatch_look.rs +++ b/crates/ui-egui/src/export_templates/swatch_look.rs @@ -4,7 +4,7 @@ use egui::Color32; pub(super) struct SwatchLook { /// The source map's colour (None: empty or a constant). pub(super) fill: Option, - /// One bar per channel of the source the swatch reads. - pub(super) bars: Vec, + /// The underline in the colour of the channel the swatch's letters name (None: a constant) + pub(super) bar: Option, pub(super) inverted: bool, } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 86635088..04bb8243 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1758,13 +1758,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let right = window.right() - RIGHT_MARGIN; let row_y = window.top() + TAB_ROW_CONTROLS_Y; match app.ui.export.tab { - 1 => { - let strip = egui::Rect::from_min_max(egui::pos2(window.center().x, window.top()), egui::pos2(right, body.top())); - ui.scope_builder( - egui::UiBuilder::new().max_rect(strip).layout(egui::Layout::right_to_left(egui::Align::Center)), - crate::export_templates::naming_pattern, - ); - } + 1 => crate::export_templates::naming_pattern(ui, window.right(), row_y), 2 => { let width = drawn::text_width(ui, tr("Open output directory"), false) + OPEN_DIRECTORY_PADDING; let rect = drawn::control_rect(window.right() - OPEN_DIRECTORY_FROM_RIGHT - width, window.right() - OPEN_DIRECTORY_FROM_RIGHT, row_y); @@ -1800,7 +1794,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut row = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); row.set_height(body.height()); match app.ui.export.tab { - 1 => crate::export_templates::tab(app, &mut row, &presets), + 1 => crate::export_templates::tab(app, ui, body, &presets), 2 => list_tab(app, &mut row), _ => settings_tab(app, ui, window, body, &presets), } diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs index fe55c374..e6fd3a4e 100644 --- a/crates/ui-egui/src/export_window/drawn.rs +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -1,7 +1,7 @@ //! The Export textures window's own controls, drawn at the places its layout gives them: tabs, //! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`]) -use egui::{Align2, Color32, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; +use egui::{Align2, Color32, CornerRadius, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2}; use egui_phosphor::regular as ic; use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE}; @@ -34,6 +34,10 @@ const TAB_GAP: f32 = 3.0; /// How far a tab reaches under the divider, where the body's colour covers its lower corners const TAB_OVERLAP: f32 = 4.0; +/// A quiet dropdown's hover face: its padding round the value and chevron, and half its height +const TEXT_DROPDOWN_PADDING: f32 = 3.0; +const TEXT_DROPDOWN_HALF_HEIGHT: f32 = 9.0; + /// Hit area of an icon button around its glyph const ICON_HIT_SIZE: f32 = 20.0; @@ -303,3 +307,24 @@ pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name paint_focus(ui, &response); response } + +/// A card's quiet dropdown: its value from `value_left` and a chevron at `chevron_x`, no box +pub(crate) fn text_dropdown(ui: &mut Ui, id: Id, value_left: f32, chevron_x: f32, y: f32, value: &str) -> Response { + let look = ExportLook::get(ui.ctx()); + let enabled = ui.is_enabled(); + let rect = Rect::from_min_max( + pos2(value_left - TEXT_DROPDOWN_PADDING, y - TEXT_DROPDOWN_HALF_HEIGHT), + pos2(chevron_x + CHEVRON_SIZE / 2.0 + TEXT_DROPDOWN_PADDING, y + TEXT_DROPDOWN_HALF_HEIGHT), + ); + let response = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() }); + let name = format!("{value} {}", ic::CARET_DOWN); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name)); + if response.hovered() && enabled { + ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), look.raised); + } + let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text }; + text_at(ui, value_left, y, value, color, false); + glyph(ui, pos2(chevron_x, y), ic::CARET_DOWN, CHEVRON_SIZE, color); + paint_focus(ui, &response); + response +} diff --git a/crates/ui-egui/src/export_window/export_look.rs b/crates/ui-egui/src/export_window/export_look.rs index 866dad2f..ef7e04c4 100644 --- a/crates/ui-egui/src/export_window/export_look.rs +++ b/crates/ui-egui/src/export_window/export_look.rs @@ -23,6 +23,9 @@ const SCROLL_BAR_MARGIN: f32 = 4.0; /// How far the dividers sit below the frame colour, so they read on it const DIVIDER_DARKENING: f32 = 0.26; +/// How far the Presets list's names sit from the text colour towards the dim one +const LIST_TEXT_DIMMING: f32 = 0.37; + /// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter #[derive(Clone, Copy)] pub(crate) struct ExportLook { @@ -36,7 +39,9 @@ pub(crate) struct ExportLook { pub(crate) outline: Color32, pub(crate) text: Color32, pub(crate) text_dim: Color32, + pub(crate) list_text: Color32, pub(crate) accent: Color32, + pub(crate) dark: bool, } impl ExportLook { @@ -52,7 +57,9 @@ impl ExportLook { outline: tokens.button_border, text: tokens.text, text_dim: tokens.text_dim, + list_text: lerp_color(tokens.text, tokens.text_dim, LIST_TEXT_DIMMING), accent: tokens.accent, + dark: tokens.dark, } } diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index d11fe0d8..ff614407 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -95,15 +95,23 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) { fn the_tab_shows_the_preset_tools_and_map_editor() { let library = TemplateLibrary::new("layout"); let mut h = harness(&library); - for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] { + for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:"] { assert!(h.query_by_label(text).is_some(), "{text}"); } + let hint = "Drop an input map onto a channel to assign it to that output."; + assert!(h.query_by_label(hint).is_none(), "the drag hint is no line under the cards"); + let metallic = h.get_by_role_and_label(egui::Role::ListItem, "Metallic").rect().center(); + h.hover_at(metallic); + h.run_steps(30); + assert!(h.query_by_label(hint).is_some(), "a map entry's tooltip says how to use it"); + h.hover_at(egui::pos2(1.0, 1.0)); + h.run_steps(4); assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR"))); let maps = h.state().session.export_preset("Mine").unwrap().maps.len(); let ts = h.state().session.ts(); let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap(); let exported = plan.as_array().unwrap().len(); - assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some()); + assert!(h.query_by_label(&format!("{exported} output maps will be exported")).is_some()); for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] { assert!(h.query_by_label(create).is_some(), "{create}"); } @@ -262,8 +270,8 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() { assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}"); hover_name_field(&mut h, 1); assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row says so"); - assert!(h.query_by_label("1 output maps will be exported.").is_some()); - assert!(h.query_by_label("2 output maps will be exported.").is_none()); + assert!(h.query_by_label("1 output maps will be exported").is_some()); + assert!(h.query_by_label("2 output maps will be exported").is_none()); } #[test] From e2db799bece9cbbc676196422b1419ed36ad1dbd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:21:28 +0000 Subject: [PATCH 09/34] List of exports: the file tree on the frame colour beside the console MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tree sits on the frame colour, its scroll bar in a strip at its right: each set a bold name after its chevron, its files indented and the size, file type and bit depth columns placed after the longest file name, each file's path as tooltip. The fold strip (») has the window's colour with a divider before the console; the console's "Console" header sits on the window colour, its lines on the frame colour. Open output directory sits at the tab row's right, 9 px above the divider. The console's least and starting width is the reference's at TextureCraft's window width. --- crates/ui-egui/src/export_window.rs | 273 +++++++++++------- crates/ui-egui/src/export_window/tree_file.rs | 8 + crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/tests/it/export_progress.rs | 4 +- 4 files changed, 181 insertions(+), 106 deletions(-) create mode 100644 crates/ui-egui/src/export_window/tree_file.rs diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 04bb8243..10c08fce 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -12,7 +12,7 @@ use crate::TextureCraftApp; use crate::file_dialogs::{Bound, FileDialog}; use crate::i18n::{n_, tr, trf}; use crate::state::{ConsoleLine, ExportSetPlan, ExportUi, FileType, MapExport, SIZE_OF_LARGEST_SET, SetExport}; -use crate::theme::{Tokens, caption, semibold}; +use crate::theme::{Tokens, semibold}; use crate::unavailable::NOT_AVAILABLE; pub(crate) mod drawn; @@ -20,10 +20,12 @@ pub(crate) mod export_look; mod inherited_settings; mod map_row; mod page_place; +mod tree_file; pub(crate) use export_look::ExportLook; use inherited_settings::InheritedSettings; use map_row::MapRow; use page_place::PagePlace; +use tree_file::TreeFile; /// The reference window's size; a smaller screen gets a smaller window const REFERENCE_WINDOW_SIZE_POINTS: egui::Vec2 = egui::vec2(1100.0, 740.0); @@ -160,6 +162,39 @@ const MAP_FORMAT_WIDTH: f32 = 61.2; /// Width of a map's own size list const MAP_SIZE_WIDTH: f32 = 100.0; +/// The console's least width: the reference's 300 at TextureCraft's narrower window +pub(crate) const CONSOLE_WIDTH: f32 = 284.0; +/// The file tree's least width +const MIN_TREE_WIDTH: f32 = 300.0; +/// Width of the strip that folds the console +const STRIP_WIDTH: f32 = 17.9; +/// Gap between the file tree and the strip +const STRIP_GAP: f32 = 1.9; +/// Size of the strip's glyph +const STRIP_GLYPH_SIZE: f32 = 13.0; +/// The console text's indent +const CONSOLE_TEXT_INDENT: f32 = 18.0; +/// Middle of the console's header +const CONSOLE_HEADER_Y: f32 = 66.0; +/// Where the console's lines start +const CONSOLE_BODY_TOP: f32 = 89.0; +/// Air above and below the console's lines +const CONSOLE_PADDING: f32 = 6.0; +/// Air above the file tree's first row +const TREE_TOP_PADDING: f32 = 3.0; +/// Height of a file tree row +const TREE_ROW_HEIGHT: f32 = 21.0; +/// Centre of a set's chevron +const TREE_CHEVRON_X: f32 = 13.2; +/// Where a set's name starts +const TREE_NAME_INDENT: f32 = 26.3; +/// Where its files start +const TREE_FILE_INDENT: f32 = 45.1; +/// Gap after the name and size columns +const TREE_COLUMN_GAP: f32 = 28.0; +/// Gap after the file type column +const TREE_BITS_GAP: f32 = 14.0; + /// The output sizes the Size list offers, in texels per side pub(crate) const SIZES: [u32; 7] = [128, 256, 512, 1024, 2048, 4096, 8192]; @@ -1254,49 +1289,36 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, } } -/// The LIST OF EXPORTS console's and file tree's least width, as in the reference -const CONSOLE_WIDTH: f32 = 300.0; -const MIN_TREE_WIDTH: f32 = 300.0; -/// Width of the strip between the file tree and the console -const SPLITTER_WIDTH: f32 = 14.0; -/// Padding of the CONSOLE header band, about 45 points high as in the reference -const CONSOLE_HEADER_MARGIN_X: i8 = 12; -const CONSOLE_HEADER_MARGIN_Y: i8 = 14; -/// The file tree: indent of the file rows under their texture set, and the row height -const TREE_INDENT: f32 = 35.0; -const TREE_ROW_HEIGHT: f32 = 17.0; -/// Half the width of the tree's chevron -const CHEVRON_HALF_WIDTH: f32 = 4.0; - /// Green of the console's success lines fn success(tk: &Tokens) -> egui::Color32 { if tk.dark { egui::Color32::from_rgb(110, 200, 120) } else { egui::Color32::from_rgb(30, 130, 50) } } -/// The LIST OF EXPORTS tab: a tree of the files each ticked texture set exports (file, size, -/// file type, bit depth; the full path as tooltip), and the console -fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { +/// 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) { + let look = ExportLook::get(ui.ctx()); let tk = Tokens::get(ui.ctx()); let hidden = app.ui.export.console_hidden; - // Tree and console keep at least their reference width - let spacing = ui.spacing().item_spacing.x; - let room = ui.available_width() - SPLITTER_WIDTH - 2.0 * spacing; + // The console keeps at least its least width, the tree at least its own + let room = body.width() - STRIP_WIDTH - STRIP_GAP - 1.0; let console_width = app.ui.export.console_width.min(room - MIN_TREE_WIDTH).max(CONSOLE_WIDTH); - let tree_width = if hidden { room } else { room - console_width }; - ui.vertical(|ui| { - ui.set_width(tree_width); + let console_left = if hidden { body.right() + 1.0 } else { body.right() - console_width }; + let strip = egui::Rect::from_min_max(egui::pos2(console_left - 1.0 - STRIP_WIDTH, body.top() + 1.0), egui::pos2(console_left - 1.0, body.bottom())); + 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::vertical().id_salt("exp_list").auto_shrink([false; 2]).show(ui, |ui| export_tree(app, ui, &tk)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it - let (strip, response) = ui.allocate_exact_size(vec2(SPLITTER_WIDTH, ui.available_height()), egui::Sense::click_and_drag()); + drawn::divider(ui, egui::Rect::from_min_max(strip.right_top(), egui::pos2(strip.right() + 1.0, strip.bottom()))); + let response = ui.interact(strip, ui.scope_id().with("exp_console_strip"), egui::Sense::click_and_drag()); let tooltip = if hidden { tr("Show Console") } else { tr("Hide Console") }; response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); let glyph = if hidden { ic::CARET_DOUBLE_LEFT } else { ic::CARET_DOUBLE_RIGHT }; - let glyph_color = if response.hovered() { tk.text_strong } else { tk.text }; - ui.painter().rect_filled(strip, 0.0, tk.chrome); - ui.painter().text(strip.center(), egui::Align2::CENTER_CENTER, glyph, egui::TextStyle::Body.resolve(ui.style()), glyph_color); + let glyph_color = if response.hovered() { look.text } else { look.text_dim }; + drawn::glyph(ui, strip.center(), glyph, STRIP_GLYPH_SIZE, glyph_color); drawn::paint_focus(ui, &response); let response = response.on_hover_text(tooltip); if !hidden && (response.hovered() || response.dragged()) { @@ -1307,31 +1329,35 @@ fn list_tab(app: &mut TextureCraftApp, ui: &mut Ui) { } else if response.clicked() { app.ui.export.console_hidden = !hidden; } - if !hidden { - ui.vertical(|ui| { - ui.set_width(console_width); - egui::Frame::new().fill(tk.row).inner_margin(egui::Margin::symmetric(CONSOLE_HEADER_MARGIN_X, CONSOLE_HEADER_MARGIN_Y)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(caption(&tr("Console").to_uppercase()).strong()); - }); - let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); - console.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible).show(ui, |ui| { - for line in &app.ui.export.console { - match line { - ConsoleLine::Step(t) => { - ui.label(t); - } - ConsoleLine::Done(t) => { - ui.label(RichText::new(t).color(success(&tk))); - } - ConsoleLine::Set(name) => { - ui.label(set_line(ui, name, &tk)); - } + if hidden { + return; + } + + // The console: its header on the window colour, its lines on the frame colour below + let top = body.top() - TAB_ROW_HEIGHT; + let console = egui::Rect::from_min_max(egui::pos2(console_left, body.top() + 1.0), body.max); + drawn::label_at(ui, console.left() + CONSOLE_TEXT_INDENT, top + CONSOLE_HEADER_Y, tr("Console"), look.text, true); + let lines = egui::Rect::from_min_max(egui::pos2(console.left(), top + CONSOLE_BODY_TOP), console.max); + ui.painter().rect_filled(lines, 0.0, look.chrome); + let inner = lines.shrink2(vec2(0.0, CONSOLE_PADDING)).with_min_x(lines.left() + CONSOLE_TEXT_INDENT); + ui.scope_builder(egui::UiBuilder::new().max_rect(inner), |ui| { + let console = egui::ScrollArea::vertical().id_salt("exp_console").auto_shrink([false; 2]).stick_to_bottom(true); + console.show(ui, |ui| { + for line in &app.ui.export.console { + match line { + ConsoleLine::Step(t) => { + ui.label(t); + } + ConsoleLine::Done(t) => { + ui.label(RichText::new(t).color(success(&tk))); + } + ConsoleLine::Set(name) => { + ui.label(set_line(ui, name, &tk)); } } - }); + } }); - } + }); } /// "Texture set " with the name in bold @@ -1347,22 +1373,53 @@ fn set_line(ui: &Ui, name: &str, tk: &Tokens) -> egui::text::LayoutJob { job } -/// One expandable node per ticked texture set, a row per file +/// 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) { - if let Some(job) = &app.ui.export.job - && !job.preview.is_empty() - { - for (index, set) in job.preview.iter().enumerate() { - export_tree_set(ui, index, set, &job.directory, tk); + 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()), + _ => { + 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()) } - return; - } + }; + 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 columns = { + let size = TREE_FILE_INDENT + longest(|f| &f.name) + TREE_COLUMN_GAP; + let format = size + longest(|f| &f.size) + TREE_COLUMN_GAP; + [size, format, format + longest(|f| &f.format) + TREE_BITS_GAP] + }; - for ts in export_selection(app) { - let params = set_params(app, ts); - if let Some(set) = plan_set(app, ts, ¶ms) { - export_tree_set(ui, ts, &set, &app.ui.export.dir, tk); + // 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 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 }) + .sum(); + let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT), egui::Sense::hover()); + let mut y = area.top() + TREE_TOP_PADDING; + for (((index, set), files), open) in sets.iter().zip(&rows).zip(open) { + 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)); } + 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); + y += TREE_ROW_HEIGHT; + } + for file in files { + tree_file(ui, area.left(), y + TREE_ROW_HEIGHT / 2.0, columns, file); + y += TREE_ROW_HEIGHT; + } + } + y += TREE_ROW_HEIGHT; } } @@ -1374,47 +1431,59 @@ fn plan_set(app: &mut TextureCraftApp, index: usize, params: &serde_json::Value) Some(ExportSetPlan { index: Some(index), name, files }) } -fn export_tree_set(ui: &mut Ui, index: usize, set: &ExportSetPlan, directory: &str, tokens: &Tokens) { - ui.spacing_mut().indent = TREE_INDENT; - let header = egui::CollapsingHeader::new(&set.name).id_salt(("exp_tree", index)).default_open(true).icon(chevron); - header.show(ui, |ui| match &set.files { - Ok(files) => { - egui::Grid::new(("exp_tree_grid", index)).num_columns(4).min_row_height(TREE_ROW_HEIGHT).spacing(vec2(12.0, 4.0)).show(ui, |ui| { - for output in files.as_array().into_iter().flatten() { - let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); - 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 path = std::path::Path::new(directory).join(file).display().to_string(); - ui.label(file).on_hover_text(&path); - ui.label(set_size_label(size, source_size)).on_hover_text(&path); - ui.label(format.map_or("", FileFormat::name)).on_hover_text(&path); - ui.label(depth_label(format, depth, dithering)).on_hover_text(&path); - ui.end_row(); - } - }); - } - Err(error) => { - ui.label(RichText::new(error).color(tokens.danger)); - } - }); +/// 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 tree's outline chevron: pointing down when open, right (left in right-to-left) when closed -fn chevron(ui: &mut Ui, openness: f32, response: &egui::Response) { - let color = Tokens::get(ui.ctx()).text; - let center = response.rect.center(); - let half = CHEVRON_HALF_WIDTH; - let points = if openness > 0.5 { - [center + vec2(-half, -half / 2.0), center + vec2(0.0, half / 2.0), center + vec2(half, -half / 2.0)] - } else if ui.style().right_to_left { - [center + vec2(half / 2.0, -half), center + vec2(-half / 2.0, 0.0), center + vec2(half / 2.0, half)] - } else { - [center + vec2(-half / 2.0, -half), center + vec2(half / 2.0, 0.0), center + vec2(-half / 2.0, half)] +/// 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() }; + + let to_text = |output: &serde_json::Value| { + let file = output.get("file").and_then(serde_json::Value::as_str).unwrap_or_default(); + 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; + TreeFile { + name: file.to_string(), + size: set_size_label(size, source_size), + format: format.map_or("", FileFormat::name).to_string(), + bits: depth_label(format, depth, dithering), + path: std::path::Path::new(directory).join(file).display().to_string(), + } }; - ui.painter().add(egui::Shape::line(points.to_vec(), egui::Stroke::new(1.5, color))); + files.as_array().into_iter().flatten().map(to_text).collect() +} + +/// A texture set's node row: the chevron and its name in bold; true when clicked +fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { + let look = ExportLook::get(ui.ctx()); + let response = ui.interact(rect, id, egui::Sense::click()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); + let y = rect.center().y; + let chevron = if open { + ic::CARET_DOWN + } else if ui.style().right_to_left { + ic::CARET_LEFT + } else { + ic::CARET_RIGHT + }; + drawn::glyph(ui, egui::pos2(rect.left() + TREE_CHEVRON_X, y), chevron, drawn::CHEVRON_SIZE, look.text); + drawn::text_at(ui, rect.left() + TREE_NAME_INDENT, y, name, look.text, true); + drawn::paint_focus(ui, &response); + response.clicked() +} + +/// A file's row at `y`: its name, then size, file type and bit depth in `columns`, each with the whole path as tooltip +fn tree_file(ui: &mut Ui, left: f32, y: f32, columns: [f32; 3], file: &TreeFile) { + let look = ExportLook::get(ui.ctx()); + let texts = [(TREE_FILE_INDENT, &file.name), (columns[0], &file.size), (columns[1], &file.format), (columns[2], &file.bits)]; + for (x, text) in texts { + drawn::label_at(ui, left + x, y, text, look.text, false).on_hover_text(&file.path); + } } /// Show the output folder in the system's file manager (created first when missing) @@ -1791,11 +1860,9 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { let mut body_ui = ui.new_child(egui::UiBuilder::new().max_rect(body)); body_ui.shrink_clip_rect(body); let ui = &mut body_ui; - let mut row = ui.new_child(egui::UiBuilder::new().max_rect(body).layout(egui::Layout::left_to_right(egui::Align::Min))); - row.set_height(body.height()); match app.ui.export.tab { 1 => crate::export_templates::tab(app, ui, body, &presets), - 2 => list_tab(app, &mut row), + 2 => list_tab(app, ui, body), _ => settings_tab(app, ui, window, body, &presets), } }); diff --git a/crates/ui-egui/src/export_window/tree_file.rs b/crates/ui-egui/src/export_window/tree_file.rs new file mode 100644 index 00000000..8b3f64fb --- /dev/null +++ b/crates/ui-egui/src/export_window/tree_file.rs @@ -0,0 +1,8 @@ +/// A file row of LIST OF EXPORTS: the texts of its columns and its whole path +pub(super) struct TreeFile { + pub(super) name: String, + pub(super) size: String, + pub(super) format: String, + pub(super) bits: String, + pub(super) path: String, +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index fbcd6053..59900a4a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -475,7 +475,7 @@ impl Default for ExportUi { /// The LIST OF EXPORTS console's width when the window opens, as in the reference fn default_console_width() -> f32 { - 300.0 + crate::export_window::CONSOLE_WIDTH } fn default_export_dir() -> String { diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index b46b84a1..b027549b 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -128,7 +128,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some()); assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some()); assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none()); - assert!(h.query_by_label("CONSOLE").is_some()); + assert!(h.query_by_label("Console").is_some()); // A row's tooltip is the full path let preset = h.state().ui.export.preset.clone(); @@ -142,7 +142,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { // The strip at the console's edge hides it, then shows it again h.get_by_role_and_label(egui::Role::Button, "Hide Console").click(); h.run_steps(4); - assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none()); + assert!(h.state().ui.export.console_hidden && h.query_by_label("Console").is_none()); h.get_by_role_and_label(egui::Role::Button, "Show Console").click(); h.run_steps(4); assert!(!h.state().ui.export.console_hidden); From f165f47699bfb327006be3c510bfbcc90c0f4c82 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:39:59 +0000 Subject: [PATCH 10/34] Export: Unreal Engine Subsurface Profile (Packed) template, the packed Unreal maps plus a SubsurfaceMask map of the scatter weight for the material's Opacity input Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 45 ++++++++++++++++++++++++++++++ crates/formats/src/presets.rs | 10 +++++++ docs/features.md | 2 +- 4 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index ca377337..acfe2f53 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -137,6 +137,7 @@ Built-in presets (each one lists the public specification its packing follows in | OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) | | Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | +| Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 14bb5238..ab398c0f 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1740,3 +1740,48 @@ fn a_map_preview_holds_the_values_its_file_stores() { assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map"); assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); } + +/// The 8-bit value of an image position as RGBA +fn pixel(file: &ExportedFile) -> [i32; 4] { + decode(file).to_rgba8().get_pixel(3, 3).0.map(i32::from) +} + +fn byte(value: f32) -> i32 { + (value * 255.0).round() as i32 +} + +fn assert_close(actual: [i32; 4], expected: [i32; 4], what: &str) { + assert!(actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= 1), "{what}: {actual:?} instead of {expected:?}"); +} + +/// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it +fn tilt_normals(fx: &mut Fx) -> i32 { + let tilt = Vec3::new(0.3, 0.4, 0.0); + let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt()); + fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array()); + byte(tilt.y * 0.5 + 0.5) +} + +#[test] +fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps() { + let mut channels = default_channels(); + channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::ScatterWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Unreal Engine Subsurface Profile (Packed)"); + + let mask = find(&files, "_SubsurfaceMask.png"); + assert_eq!(decode(mask).color(), image::ColorType::L8, "the mask is one 8-bit channel"); + assert_close(pixel(mask), [byte(0.7), byte(0.7), byte(0.7), 255], "scatter weight in the mask"); + let [r, g, b, _] = pixel(find(&files, "_OcclusionRoughnessMetallic.png")); + assert_close([r, g, b, 0], [byte(0.6), byte(0.4), byte(0.8), 0], "R occlusion, G roughness, B metallic"); + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "opacity feeds the mask, not the base color's alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 2f2879a4..5fcf0ef0 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -219,6 +219,16 @@ pub fn builtin_presets() -> Vec { map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))), ], ), + // Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine (the Opacity input masks the scattering, so the base color has no alpha) + preset( + "Unreal Engine Subsurface Profile (Packed)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("OcclusionRoughnessMetallic", 8, orm()), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index 3da74d2d..3d0ff36a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 0d1df0580e54797c0121f0e49a3e964459df2c57 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:40:34 +0000 Subject: [PATCH 11/34] Export: glTF Specular Glossiness (archived extension) template, a specular/glossiness set's diffuse with opacity and its specular with glossiness in alpha, as Khronos' archived extension lays them out Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md Only the set's own Specular and Glossiness channels are written; converting a metallic/roughness set is left out, since no target documents that conversion. --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 21 +++++++++++++++++++++ crates/formats/src/presets.rs | 15 +++++++++++++++ docs/features.md | 2 +- 4 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index acfe2f53..1e7f3bdc 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -138,6 +138,7 @@ Built-in presets (each one lists the public specification its packing follows in | Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` | | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | +| glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index ab398c0f..05929b9e 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1785,3 +1785,24 @@ fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps let green = pixel(find(&files, "_Normal.png"))[1]; assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); } + +#[test] +fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_channels() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::Normal, Channel::Height, Channel::Opacity]); + let specular = [0.2, 0.5, 0.8]; + fx.set_all(Channel::Specular, |_, _| specular); + fx.set_all(Channel::Glossiness, |_, _| [0.3; 3]); + fx.set_all(Channel::Opacity, |_, _| [0.9; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8); + let srgb = specular.map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(specular_glossiness), [srgb[0], srgb[1], srgb[2], byte(0.3)], "sRGB specular, linear glossiness in alpha"); + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Diffuse.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB diffuse, opacity in alpha"); + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 5fcf0ef0..e1aedf9f 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -229,6 +229,21 @@ pub fn builtin_presets() -> Vec { map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))), ], ), + // Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md (diffuse with alpha, specular RGB with glossiness in A) + preset( + "glTF Specular Glossiness (archived extension)", + vec![ + map("Diffuse", 8, base_with_alpha()), + map("SpecularGlossiness", 8, { + let mut specular_glossiness = rgb(|k| ch(Channel::Specular, k)); + specular_glossiness.push((Dest::A, ch(Channel::Glossiness, 0))); + specular_glossiness + }), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index 3d0ff36a..fde5812e 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 498394a11df40ba1b603736d8babca99537e12f9 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:40:53 +0000 Subject: [PATCH 12/34] Export: Redshift Standard Material (separate maps) template, one map per Standard Material input the texture set has, normals in OpenGL as Redshift expects Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html and https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 24 ++++++++++++++++++++++++ crates/formats/src/presets.rs | 20 ++++++++++++++++++++ docs/features.md | 2 +- 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 1e7f3bdc..4817d0e8 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -139,6 +139,7 @@ Built-in presets (each one lists the public specification its packing follows in | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | +| Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 05929b9e..2b6e604e 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1806,3 +1806,27 @@ fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_ch let green = pixel(find(&files, "_Normal.png"))[1]; assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); } + +#[test] +fn the_redshift_template_writes_one_map_per_input_the_set_has() { + let mut channels = default_channels(); + channels.extend([Channel::ScatterWeight, Channel::CoatWeight]); + let mut fx = Fx::new(&channels); + fx.set_all(Channel::Roughness, |_, _| [0.4; 3]); + fx.set_all(Channel::Metallic, |_, _| [0.8; 3]); + fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]); + fx.set_all(Channel::CoatWeight, |_, _| [0.2; 3]); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Redshift Standard Material (separate maps)"); + + let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect(); + for (input, expected) in [("Metalness", 0.8), ("ReflectionRoughness", 0.4), ("SubsurfaceWeight", 0.7), ("CoatWeight", 0.2)] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); + assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index e1aedf9f..5b870db3 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -244,6 +244,26 @@ pub fn builtin_presets() -> Vec { map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))), ], ), + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html (the Standard Material inputs) + // Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html (normal maps in OpenGL format) + preset("Redshift Standard Material (separate maps)", { + let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0))); + let rgb8 = |name: &str, c: Channel| map(name, 8, rgb(|k| ch(c, k))); + vec![ + rgb8("BaseColor", Channel::BaseColor), + gray8("Metalness", Channel::Metallic), + gray8("ReflectionRoughness", Channel::Roughness), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + rgb8("EmissionColor", Channel::Emissive), + gray8("Opacity", Channel::Opacity), + gray8("SubsurfaceWeight", Channel::ScatterWeight), + gray8("CoatWeight", Channel::CoatWeight), + gray8("CoatRoughness", Channel::CoatRoughness), + gray8("SheenWeight", Channel::SheenWeight), + rgb8("SheenColor", Channel::SheenColor), + gray8("SheenRoughness", Channel::SheenRoughness), + ] + }), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index fde5812e..facc1ea0 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From ba6dcf5240ba7dfc651c5ef9a401ee1e084aedf0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:41:09 +0000 Subject: [PATCH 13/34] Export: Roblox SurfaceAppearance (separate maps) template, colour with opacity in alpha, OpenGL normal, metalness and roughness, named with the suffixes Roblox's reimport assigns Based on #258 by Aalzard. Spec: https://create.roblox.com/docs/art/modeling/surface-appearance, https://create.roblox.com/docs/art/modeling/texture-specifications and https://create.roblox.com/docs/art/modeling/reimport Roblox's MaterialVariant gets no template of its own: its docs don't say whether it reads the colour map's alpha, the only difference the old one made. --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 31 +++++++++++++++++------------- crates/formats/src/presets.rs | 12 ++++++++++++ docs/features.md | 2 +- 4 files changed, 32 insertions(+), 14 deletions(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 4817d0e8..8cd9e1cd 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -140,6 +140,7 @@ Built-in presets (each one lists the public specification its packing follows in | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | | Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | +| Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 2b6e604e..30b8f6ec 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1741,19 +1741,6 @@ fn a_map_preview_holds_the_values_its_file_stores() { assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error"); } -/// The 8-bit value of an image position as RGBA -fn pixel(file: &ExportedFile) -> [i32; 4] { - decode(file).to_rgba8().get_pixel(3, 3).0.map(i32::from) -} - -fn byte(value: f32) -> i32 { - (value * 255.0).round() as i32 -} - -fn assert_close(actual: [i32; 4], expected: [i32; 4], what: &str) { - assert!(actual.iter().zip(expected).all(|(a, e)| (a - e).abs() <= 1), "{what}: {actual:?} instead of {expected:?}"); -} - /// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it fn tilt_normals(fx: &mut Fx) -> i32 { let tilt = Vec3::new(0.3, 0.4, 0.0); @@ -1830,3 +1817,21 @@ fn the_redshift_template_writes_one_map_per_input_the_set_has() { assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}"); } + +#[test] +fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Roblox SurfaceAppearance (separate maps)"); + + let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v))); + assert_close(pixel(find(&files, "_Color.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB colour, opacity in alpha"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4)] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 5b870db3..e510a7c1 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -264,6 +264,18 @@ pub fn builtin_presets() -> Vec { gray8("SheenRoughness", Channel::SheenRoughness), ] }), + // Spec: https://create.roblox.com/docs/art/modeling/surface-appearance (ColorMap alpha is opacity) + // Spec: https://create.roblox.com/docs/art/modeling/texture-specifications (OpenGL normals only; grayscale metalness and roughness) + // Spec: https://create.roblox.com/docs/art/modeling/reimport (the file name suffix it assigns to each map) + preset( + "Roblox SurfaceAppearance (separate maps)", + vec![ + map("Color", 8, base_with_alpha()), + map("Normal", 8, normal(VirtualMap::NormalOpenGl)), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index facc1ea0..212894c6 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 3b56a8e6b3f85500df9a2bfeb2b971df4332d237 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:41:24 +0000 Subject: [PATCH 14/34] Export: Sketchfab Metalness (separate maps) template, one map per Sketchfab metalness channel with DirectX normals, Sketchfab's default Based on #258 by Aalzard. Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps, https://help.sketchfab.com/en/articles/16152634-materials-pbr and https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map The base color has no alpha: Sketchfab's docs don't say its opacity reads it. --- crates/formats/README.md | 1 + crates/formats/src/export/tests.rs | 17 +++++++++++++++++ crates/formats/src/presets.rs | 14 ++++++++++++++ docs/features.md | 2 +- 4 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/formats/README.md b/crates/formats/README.md index 8cd9e1cd..89482c00 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -141,6 +141,7 @@ Built-in presets (each one lists the public specification its packing follows in | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | | Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | | Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | +| Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` | | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 30b8f6ec..e9eb5a63 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1835,3 +1835,20 @@ fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() { let green = pixel(find(&files, "_Normal.png"))[1]; assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); } + +#[test] +fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() { + let mut fx = packing_fixture(); + let open_gl_green = tilt_normals(&mut fx); + + let files = fx.render_preset("Sketchfab Metalness (separate maps)"); + + assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "no alpha on the base color"); + for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4), ("AmbientOcclusion", 0.6)] { + let file = find(&files, &format!("_{input}.png")); + assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is linear grayscale"); + assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input); + } + let green = pixel(find(&files, "_Normal.png"))[1]; + assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); +} diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index e510a7c1..e41c4094 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -276,6 +276,20 @@ pub fn builtin_presets() -> Vec { map("Roughness", 8, gray(ch(Channel::Roughness, 0))), ], ), + // Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps (sRGB base color, linear grayscale metalness; no alpha, the docs don't say opacity reads it) + // Spec: https://help.sketchfab.com/en/articles/16152634-materials-pbr (roughness, AO and emission channels) + // Spec: https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map (DirectX normals by default) + preset( + "Sketchfab Metalness (separate maps)", + vec![ + map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))), + map("Metalness", 8, gray(ch(Channel::Metallic, 0))), + map("Roughness", 8, gray(ch(Channel::Roughness, 0))), + map("Normal", 8, normal(VirtualMap::NormalDirectX)), + map("AmbientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0))), + map("Emission", 8, rgb(|k| ch(Channel::Emissive, k))), + ], + ), preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()), preset( "Mesh maps", diff --git a/docs/features.md b/docs/features.md index 212894c6..edc6c265 100644 --- a/docs/features.md +++ b/docs/features.md @@ -163,7 +163,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, - anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, separate maps, mesh maps and document channels, in + anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. From 7d59a82e1b699cbf8d4a9801c49d7836c5292cbe Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 25 Nov 2026 22:35:31 +0000 Subject: [PATCH 15/34] Auto: Fix PSD batch exports and preserve template settings Bound retained PSD output and preserve document names, layer names, and preview channels. Keep saved presets and draft map overrides usable, report explicit grayscale J2K colour spaces, and let active picks handle Escape first. Validated with local export regressions, Clippy, layering, and WebAssembly compilation. --- crates/engine/src/file_cmds.rs | 39 ++++-- crates/engine/src/preset_cmds.rs | 109 ++++++++++++++--- crates/formats/README.md | 2 +- crates/formats/src/export/layered_psd.rs | 6 +- crates/formats/src/export/map_preview.rs | 14 ++- crates/formats/src/export/map_renderer.rs | 4 +- crates/formats/src/export/mod.rs | 97 +++++++++++++-- crates/formats/src/export/tests.rs | 126 ++++++++++++++++++++ crates/formats/src/lib.rs | 2 +- crates/formats/src/presets.rs | 9 ++ crates/ui-egui/src/export_templates.rs | 74 +++++++++--- crates/ui-egui/src/export_window.rs | 52 ++++---- crates/ui-egui/src/menus.rs | 30 +++-- crates/ui-egui/src/web_files.rs | 14 +-- crates/ui-egui/tests/it/export_settings.rs | 21 ++++ crates/ui-egui/tests/it/output_templates.rs | 19 +++ 16 files changed, 516 insertions(+), 102 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 8818c010..6b47fa94 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -288,30 +288,51 @@ impl Session { /// named like one an earlier set exports is left out, with a warning (see /// [`texturecraft_formats::skip_repeated_names`]). pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { - let mut files = self.render_export_files(sets, opts, |_, plans| plans)?; + self.export_file_jobs(sets.iter().map(|&set| (set, opts))) + } + + /// Render one in-memory batch, using each set's own export settings when supplied. + pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator) -> Result> { + let mut files = self.render_export_jobs(jobs, |_, plans| plans)?; texturecraft_formats::skip_repeated_names(&mut files); Ok(files) } + #[cfg(not(target_arch = "wasm32"))] fn render_export_files( &mut self, sets: &[usize], options: &ExportOptions, + select: impl FnMut(usize, Vec) -> Vec, + ) -> Result> { + self.render_export_jobs(sets.iter().map(|&set| (set, options)), select) + } + + fn render_export_jobs<'a>( + &mut self, + jobs: impl IntoIterator, mut select: impl FnMut(usize, Vec) -> Vec, ) -> Result> { + let project = &self.doc.project; + let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); + let mut psd_bytes = 0; + let mut pending = Vec::new(); + for (set_index, options) in jobs { + let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?; + let plans = select(set_index, plans); + if !plans.is_empty() { + let set = project.texture_set(set_index).map_err(|error| EngineError::Other(error.to_string()))?; + texturecraft_formats::export::check_psd_batch(set, options, &plans, &mut psd_bytes).map_err(fe)?; + pending.push((set_index, options, plans)); + } + } + if self.solo.is_none() { self.update(); } - let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:")); let mut out = Vec::new(); - for &set_index in sets { - let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?; - let plans = select(set_index, plans); - if plans.is_empty() { - continue; - } - + for (set_index, options, plans) in pending { let files = self.with_export_input( set_index, &mesh_name, diff --git a/crates/engine/src/preset_cmds.rs b/crates/engine/src/preset_cmds.rs index 8bae78b3..eeaea8bd 100644 --- a/crates/engine/src/preset_cmds.rs +++ b/crates/engine/src/preset_cmds.rs @@ -2,15 +2,18 @@ //! dialog's Output templates tab list, read, save and remove. On the desktop the user presets //! are mirrored as `.json` files in a library folder (see [`Session::load_export_presets`]). +use std::borrow::Cow; + use serde_json::{Value, json}; use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem}; -use texturecraft_formats::{ExportPreset, builtin_preset, builtin_preset_catalog, preset_from_json}; +use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json}; use crate::commands::{CommandSpec, always, bad, boolp, strp}; use crate::{Result, Session, cmd}; /// Most user presets kept (and read from the library folder). const MAX_USER_PRESETS: usize = 512; +const BUILTIN_PRESET_PREFIX: &str = "builtin:"; /// The user's export presets. #[derive(Clone, Debug, Default)] @@ -49,6 +52,16 @@ fn same_name(a: &str, b: &str) -> bool { a.trim().eq_ignore_ascii_case(b.trim()) } +/// A qualified selector names a built-in independently of a saved library entry. +pub fn unqualified_preset_name(name: &str) -> &str { + let mut name = name.trim(); + while name.get(..BUILTIN_PRESET_PREFIX.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(BUILTIN_PRESET_PREFIX)) { + name = &name[BUILTIN_PRESET_PREFIX.len()..]; + } + + name +} + /// Library file stem: two names with the same stem would share a file. fn file_key(name: &str) -> String { sanitize_file_stem(name.trim()).to_ascii_lowercase() @@ -61,8 +74,25 @@ impl UserPresets { /// `name` belongs to a built-in or to a user preset other than `skip` (or shares its file). fn taken(&self, name: &str, skip: Option) -> bool { - builtin_preset(name).is_some() - || self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name))) + let keeps_name = skip.and_then(|index| self.list.get(index)).is_some_and(|preset| same_name(&preset.name, name)); + (!keeps_name && builtin_preset(unqualified_preset_name(name)).is_some()) || self.user_name_taken(name, skip) + } + + fn user_name_taken(&self, name: &str, skip: Option) -> bool { + let key = file_key(name); + self.list.iter().enumerate().any(|(i, preset)| Some(i) != skip && (same_name(&preset.name, name) || file_key(&preset.name) == key)) + } + + /// Restore a saved preset under the name existing settings use. + pub fn restore(&mut self, preset: ExportPreset) -> std::result::Result<(), String> { + preset.validate().map_err(|error| error.to_string())?; + let reserved = builtin_preset(&preset.name).is_some_and(|builtin| !NEW_BUILTIN_PRESET_NAMES.contains(&builtin.name.as_str())); + if reserved || self.user_name_taken(&preset.name, None) || self.list.len() >= MAX_USER_PRESETS { + return Err(format!("preset \"{}\" exists already or the library is full", preset.name)); + } + + self.list.push(preset); + Ok(()) } /// `name`, or `name 2`, `name 3`… (shortened to fit) when taken. @@ -115,7 +145,21 @@ impl UserPresets { impl Session { /// A built-in or user export preset by name (case-insensitive). pub fn export_preset(&self, name: &str) -> Option { - builtin_preset(name).or_else(|| self.export_presets.find(name).and_then(|i| self.export_presets.list.get(i).cloned())) + self.export_presets.find(name).and_then(|index| self.export_presets.list.get(index).cloned()).or_else(|| builtin_preset(unqualified_preset_name(name))) + } + + pub fn has_user_export_preset(&self, name: &str) -> bool { + self.export_presets.find(name).is_some() + } + + /// Use the familiar built-in name unless the user's library already owns that selector. + pub fn builtin_export_preset_id<'a>(&self, name: &'a str) -> Cow<'a, str> { + let mut id = Cow::Borrowed(name); + while self.has_user_export_preset(&id) { + id = Cow::Owned(format!("{BUILTIN_PRESET_PREFIX}{id}")); + } + + id } /// Use `dir` as the user preset library: read its `*.json` presets (replacing the list) and @@ -129,10 +173,8 @@ impl Session { files.sort(); let mut lib = UserPresets { list: Vec::new(), dir: Some(dir) }; for path in files.into_iter().take(MAX_USER_PRESETS) { - match texturecraft_formats::load_preset(&path).map_err(|e| e.to_string()) { - Ok(p) if lib.taken(&p.name, None) => warnings.push(format!("{}: preset \"{}\" exists already", path.display(), p.name)), - Ok(p) => lib.list.push(p), - Err(e) => warnings.push(format!("{}: {e}", path.display())), + if let Err(error) = texturecraft_formats::load_preset(&path).map_err(|error| error.to_string()).and_then(|preset| lib.restore(preset)) { + warnings.push(format!("{}: {error}", path.display())); } } self.export_presets = lib; @@ -141,9 +183,9 @@ impl Session { } fn list(session: &mut Session, _: &Value) -> Result { - let entry = |preset: &ExportPreset, builtin: bool| json!({"name": preset.name, "maps": preset.maps.len(), "builtin": builtin}); - let builtins = builtin_preset_catalog().iter().map(|preset| entry(preset, true)); - let custom = session.export_presets.list.iter().map(|preset| entry(preset, false)); + let entry = |name: &str, maps: usize, builtin: bool| json!({"name": name, "maps": maps, "builtin": builtin}); + let builtins = builtin_preset_catalog().iter().map(|preset| entry(&session.builtin_export_preset_id(&preset.name), preset.maps.len(), true)); + let custom = session.export_presets.list.iter().map(|preset| entry(&preset.name, preset.maps.len(), false)); Ok(json!(builtins.chain(custom).collect::>())) } @@ -196,11 +238,16 @@ fn save(s: &mut Session, p: &Value) -> Result { fn remove(s: &mut Session, p: &Value) -> Result { const CMD: &str = "export.preset.remove"; let name = name_param(p, CMD)?; - if builtin_preset(name).is_some() { - return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be removed"))); - } - let i = s.export_presets.find(name).ok_or_else(|| bad(CMD, format!("no user export preset `{name}`")))?; - let removed = s.export_presets.list.remove(i); + let Some(index) = s.export_presets.find(name) else { + let message = if builtin_preset(unqualified_preset_name(name)).is_some() { + format!("\"{name}\" is a built-in preset and can't be removed") + } else { + format!("no user export preset `{name}`") + }; + return Err(bad(CMD, message)); + }; + + let removed = s.export_presets.list.remove(index); s.export_presets.delete(&removed.name); Ok(Value::Null) } @@ -316,6 +363,36 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn feedback_existing_preset_keeps_its_name_and_export_maps() { + let dir = tempfile::tempdir().unwrap(); + let name = "Roblox SurfaceAppearance (separate maps)"; + let custom = preset(name); + std::fs::write(dir.path().join(format!("{}.json", sanitize_file_stem(name))), custom.to_string()).unwrap(); + let mut s = session(); + assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4); + + let warnings = s.load_export_presets(dir.path().to_path_buf()); + + 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")); + + let listed = run(&mut s, "export.presets", json!({})).unwrap(); + let names = listed.as_array().unwrap(); + assert!(names.iter().any(|entry| entry["name"] == name && entry["builtin"] == false)); + 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); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_library_folder_mirrors_saves_renames_and_removals() { diff --git a/crates/formats/README.md b/crates/formats/README.md index 6c876997..4be58133 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -142,7 +142,7 @@ Built-in presets (each one lists the public specification its packing follows in | USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` | | Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) | | glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` | -| Redshift Standard Material (separate maps) | one map per Standard Material input the set has: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | +| Redshift Standard Material (separate maps) | separate maps for the listed inputs when the set supplies their sources: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` | | Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` | | Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` | | Separate maps | one file per channel, gray where scalar, height 16-bit | diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index a55b3d5d..f8982036 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -18,14 +18,14 @@ const ALPHA_INDEX: usize = 3; /// Budget for the pixel buffers of one PSD export, including the renderer's padding and encoder const MAX_PSD_WORKING_BYTES: u64 = 2 * 1024 * 1024 * 1024; -/// Check file limits and pixel-buffer working memory before constructing the renderer. +/// Check file and working memory limits, returning the canvas size and estimated encoded bytes. pub(super) fn preflight<'a>( set: &TextureSet, options: &ExportOptions, tile: Option, depth: u8, layers: impl Iterator + Clone, -) -> Result<(u32, u32)> { +) -> Result<((u32, u32), 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))); @@ -63,7 +63,7 @@ pub(super) fn preflight<'a>( ))); } - Ok(canvas) + Ok((canvas, file_bytes)) } /// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas. diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index eace759c..81063de3 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -63,10 +63,13 @@ impl MapPreview { } let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L); - let rgb_from_gray = - gray_source.filter(|_| file.format == FileFormat::Hdr || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))); + let psd = file.format == FileFormat::Psd; + let rgb_from_gray = gray_source + .filter(|_| psd || file.format == FileFormat::Hdr || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))); let channels = if grayscale { vec![Dest::L] + } else if psd { + vec![Dest::R, Dest::G, Dest::B, Dest::A] } else if rgb_from_gray.is_some() { [Dest::R, Dest::G, Dest::B].into_iter().chain(channel_layout.iter().skip(1).map(|(dest, _)| *dest)).collect() } else { @@ -108,13 +111,16 @@ impl MapPreview { } else if let (Some(gray), [red, green, blue, alpha @ ..]) = (rgb_from_gray, &mut *pixel) { let value = preview_sample(sample(gray), Dest::L); (*red, *green, *blue) = (value, value, value); - if let ([alpha], Some(source)) = (alpha, channel_layout.get(1)) { - *alpha = preview_sample(sample(source), Dest::A); + if let [alpha] = alpha { + *alpha = channel_layout.get(1).map_or(u8::MAX, |source| preview_sample(sample(source), Dest::A)); } } else { for (output, channel) in pixel.iter_mut().zip(&channel_layout) { *output = preview_sample(sample(channel), channel.0); } + if psd && channel_layout.len() < component_count { + pixel[component_count - 1] = u8::MAX; + } } } }); diff --git a/crates/formats/src/export/map_renderer.rs b/crates/formats/src/export/map_renderer.rs index 3b493ab4..ebfd2e29 100644 --- a/crates/formats/src/export/map_renderer.rs +++ b/crates/formats/src/export/map_renderer.rs @@ -126,8 +126,8 @@ impl<'a> MapRenderer<'a> { } let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - // A colour space the user chose is written into the colour maps (data maps have none) - let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); + // Raw J2K reports the missing tag even for a grayscale colour map + let embed = (options.color_space.is_some() && map.is_color() && (component_count >= 3 || format == FileFormat::J2k)).then_some(space); Ok(RenderedMap { data, size, component_count, srgb, embed }) } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 93c8329a..41522520 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -45,6 +45,8 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Bound retained PSD payloads before rendering, with headroom for a document's working buffers and ZIP packaging +const MAX_PSD_BATCH_BYTES: u64 = 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). @@ -651,6 +653,44 @@ fn psd_stem(mesh_name: &str, set_name: &str, set_index: usize, max_len: usize) - format!("{mesh}_{set}_{set_index}") } +/// Keep tiled names stable even when the export window plans each texture set separately. +fn untiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, atlas: bool) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, MAX_STEM); + if atlas { + return stem; + } + + let Some((base, tile)) = stem.rsplit_once('.') else { return stem }; + let Ok(number) = tile.parse::() else { return stem }; + + let suffix_len = tile.len() + 1; + let collides = number.to_string() == tile + && project.texture_sets.iter().enumerate().any(|(index, other)| { + other.uv_tiles.contains(&number) && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - suffix_len)) + }); + if !collides { + return stem; + } + + // Reserve the ordinary untiled names, including names that already end in an index + let untiled_names: BTreeSet<_> = project + .texture_sets + .iter() + .enumerate() + .filter(|(_, other)| other.uv_tiles.is_empty()) + .map(|(index, other)| psd_stem(mesh_name, &other.name, index, MAX_STEM).to_ascii_lowercase()) + .collect(); + let mut attempt = 0usize; + loop { + let suffix = if attempt == 0 { format!("_{set_index}") } else { format!("-{attempt}_{set_index}") }; + let name = format!("{}{suffix}", &stem[..stem.len().min(MAX_STEM - suffix.len())]); + if !untiled_names.contains(&name.to_ascii_lowercase()) { + return name; + } + attempt += 1; + } +} + /// [`sanitize_file_stem`] for each `/`-separated folder name and the file stem. pub fn sanitize_file_path(s: &str) -> String { s.split('/').map(sanitize_file_stem).collect::>().join("/") @@ -697,8 +737,12 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export // Integer files clamp wide-gamut linear color to 0–1 let clamps = color_map && !format.holds_float(bit_depth) && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065); - // Append `$udim` to names for separate UV tiles - let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() }; + // A PSD layer needs only explicit tile tokens because its document name already holds the tile number + let template = if format != FileFormat::Psd && tiles[0].is_some() && !map.file.contains("$udim") { + std::borrow::Cow::Owned(format!("{}.$udim", map.file)) + } else { + std::borrow::Cow::Borrowed(map.file.as_str()) + }; let expand_stem = |udim: &str| { let expanded = template .replace("$udim", udim) @@ -737,16 +781,13 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export .then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name())) }; - // The PSD's own name holds the tile number, so its layers are named without the one appended if format == FileFormat::Psd { if enabled { - let appended = tile.filter(|_| template != map.file).map(|number| format!(".{number}")); - let name = appended.as_deref().and_then(|suffix| stem.strip_suffix(suffix)).unwrap_or(&stem).to_string(); - warnings.extend(packs_colour(&name)); + warnings.extend(packs_colour(&stem)); if psd_layers.is_empty() { psd_layers.resize_with(tiles.len(), Vec::new); } - psd_layers[tile_index].push((PlannedLayer { map: map_index, name, dither }, bit_depth, warnings)); + psd_layers[tile_index].push((PlannedLayer { map: map_index, name: stem, dither }, bit_depth, warnings)); } continue; } @@ -800,7 +841,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let base = psd_stem(mesh_name, &set.name, ts, MAX_STEM - suffix.len()); (format!("{base}{suffix}"), Some(format!("{base}."))) } else { - (psd_stem(mesh_name, &set.name, ts, MAX_STEM), None) + (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) }; let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); claim_path(&mut active_files, &mut active_dirs, &name)?; @@ -870,9 +911,12 @@ fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { + let mut psd_bytes = 0; let mut files = Vec::new(); - for &set in sets { - files.extend(list_outputs(project, set, mesh_name, opts)?.into_iter().map(|file| (set, file))); + for &index in sets { + let planned = list_outputs(project, index, mesh_name, opts)?; + check_psd_batch(project.texture_set(index)?, opts, &planned, &mut psd_bytes)?; + files.extend(planned.into_iter().map(|file| (index, file))); } Ok(keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings)) @@ -1048,6 +1092,28 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result Result<()> { + let mut estimate = *total_bytes; + for file in planned.iter().filter(|file| file.format == FileFormat::Psd) { + let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; + add_psd_batch_bytes(&mut estimate, file_bytes)?; + } + + *total_bytes = estimate; + Ok(()) +} + +fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64) -> Result<()> { + let estimate = total_bytes.saturating_add(file_bytes); + if estimate > MAX_PSD_BATCH_BYTES { + return Err(FormatError::TooLarge("total PSD output would exceed 1 GiB; use a smaller export size, fewer PSD maps or separate exports".into())); + } + + *total_bytes = estimate; + Ok(()) +} + /// Render the retained plans from `list_outputs` for this input and these options. pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec) -> Result> { if planned.is_empty() { @@ -1066,10 +1132,15 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned ))); } + let mut psd_bytes = 0; for file in &planned { - let size = - (file.format == FileFormat::Psd).then(|| layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())).transpose()?; - psd_sizes.push(size); + if file.format == FileFormat::Psd { + let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; + add_psd_batch_bytes(&mut psd_bytes, file_bytes)?; + psd_sizes.push(Some(size)); + } else { + psd_sizes.push(None); + } } } diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 437fcf1e..b5d18af0 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2191,3 +2191,129 @@ fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() { assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}"); } + +#[test] +fn feedback_psd_preview_matches_layer_rgba() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + + for channels in [roughness(), gray_alpha, rgba_half_alpha()] { + let options = one_map(FileFormat::Psd, 8, channels); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let files = fx.render(&options); + let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap().rgba8().unwrap(); + + assert_eq!(preview.channels, [Dest::R, Dest::G, Dest::B, Dest::A]); + assert!(preview.pixels == layer.data, "the preview shows the layer's stored channels"); + } +} + +#[test] +fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].uv_tiles = vec![1001]; + let mut options = one_map(FileFormat::Psd, 8, roughness()); + let literal = format!("{}.1001", "a".repeat(MAX_STEM - ".1001".len())); + options.preset.maps[0].file = literal.clone(); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert_eq!(plan[0].layers[0].name, literal); + + 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"); +} + +#[test] +fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body".into(); + fx.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + for name in ["body.1001", "Body.1001_1", "Trim"] { + let mut untiled = fx.project.texture_sets[0].clone(); + untiled.name = name.into(); + untiled.uv_tiles.clear(); + fx.project.texture_sets.push(untiled); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + + let plans = list_set_outputs(&fx.project, &[1, 0, 2, 3], "sphere", &options).unwrap(); + + assert_eq!(plans.len(), 5); + assert_eq!(plans[1].1.name, "sphere_Body.1001.psd"); + assert_eq!(plans[2].1.name, "sphere_Body.1002.psd"); + 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"); +} + +#[test] +fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.padding = Padding::None; + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); + + let smaller = list_set_outputs(&fx.project, &[0], "sphere", &options).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 = list_set_outputs(&fx.project, &[0], "sphere", &options); + 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]; + let (width, height) = set.size(); + fx.comp = Composite::with_size(&default_channels(), width, height); + fx.coverage.resize((width * height) as usize, true); + let error = render_maps(&fx.input(), &options).unwrap_err(); + assert!(error.to_string().contains("total PSD"), "{error}"); + + let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + println!("PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {MAX_PSD_BATCH_BYTES}", estimated_bytes * 33); + + let mut small = fx.project.texture_sets[0].clone(); + small.uv_tiles = (1001..1006).collect(); + fx.project.texture_sets[0] = small.clone(); + small.name = "Other".into(); + fx.project.texture_sets.push(small); + assert!(list_set_outputs(&fx.project, &[0], "sphere", &options).is_ok()); + assert!(list_set_outputs(&fx.project, &[1], "sphere", &options).is_ok()); + assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_err(), "the budget includes all selected sets"); +} + +#[test] +fn feedback_j2k_warns_for_explicit_gray_and_rgb_colour_spaces() { + let fx = Fx::new(&default_channels()); + let base = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let gray = vec![(Dest::L, base(0))]; + let rgb = vec![(Dest::R, base(0)), (Dest::G, base(1)), (Dest::B, base(2))]; + + for (channels, selected, expected) in [ + (gray.clone(), Some(ColorSpace::LinearRec709), Some(ColorSpace::LinearRec709)), + (gray, Some(ColorSpace::AcesCg), Some(ColorSpace::LinearRec709)), + (rgb, Some(ColorSpace::Srgb), Some(ColorSpace::Srgb)), + (roughness(), None, None), + ] { + let mut options = one_map(FileFormat::J2k, 8, channels); + options.color_space = selected; + + let files = fx.render(&options); + let warnings: Vec<_> = files[0].warnings.iter().filter(|warning| warning.contains("J2K export does not embed")).collect(); + + assert_eq!(warnings.len(), usize::from(expected.is_some()), "warnings: {:?}", files[0].warnings); + if let Some(space) = expected { + assert!(warnings[0].ends_with(space.name())); + } + } +} diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 5baa1a7a..85356dce 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -53,7 +53,7 @@ pub use mesh_export::{ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh}; #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; -pub use presets::{DEFAULT_PRESET, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json}; +pub use presets::{DEFAULT_PRESET, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json}; pub use project_file::{ BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, RamReservation, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, set_project_open_limit_gib, diff --git a/crates/formats/src/presets.rs b/crates/formats/src/presets.rs index 8ef1fc79..0b34ceb5 100644 --- a/crates/formats/src/presets.rs +++ b/crates/formats/src/presets.rs @@ -311,6 +311,15 @@ pub const DEFAULT_PRESET: &str = "Document channels + Normal + AO (No Alpha)"; /// scripts still use it). const OLD_DEFAULT_PRESET: &str = "Document channels + Normal + AO"; +/// Names introduced with the export update, which could previously belong to saved user presets. +pub const NEW_BUILTIN_PRESET_NAMES: [&str; 5] = [ + "Unreal Engine Subsurface Profile (Packed)", + "glTF Specular Glossiness (archived extension)", + "Redshift Standard Material (separate maps)", + "Roblox SurfaceAppearance (separate maps)", + "Sketchfab Metalness (separate maps)", +]; + /// The immutable built-in templates shared by menu and command lookups. pub fn builtin_preset_catalog() -> &'static [ExportPreset] { static CATALOG: std::sync::LazyLock> = std::sync::LazyLock::new(builtin_presets); diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index a0e0802e..3832919c 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -584,7 +584,8 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32, n } } None => { - let response = preset_row(ui, rect, name, *name == selected_name, is_user).on_hover_text(name); + let label = template_label(&app.session, name); + let response = preset_row(ui, rect, name, label, *name == selected_name, is_user).on_hover_text(name); if response.double_clicked() && is_user { act = Some(ListAction::StartRename(name.clone())); } else if response.clicked() { @@ -633,11 +634,10 @@ fn template_file_items(ui: &mut Ui, act: &mut Option, with_export: b } /// A Presets row: a locked file glyph for a built-in template, the name cut with "…", the selected one in bold -fn preset_row(ui: &mut Ui, rect: Rect, name: &str, selected: bool, is_user: bool) -> egui::Response { +fn preset_row(ui: &mut Ui, rect: Rect, name: &str, label: &str, selected: bool, is_user: bool) -> egui::Response { let look = ExportLook::get(ui.ctx()); let response = ui.interact(rect, ui.scope_id().with(("exp_preset_row", name)), egui::Sense::click()); - let name = template_label(name); - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, name)); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, selected, label)); let painter = ui.painter(); if selected { painter.rect_filled(rect, 0.0, look.chrome); @@ -646,7 +646,7 @@ fn preset_row(ui: &mut Ui, rect: Rect, name: &str, selected: bool, is_user: bool } let icon = if is_user { ic::FILE_TEXT } else { ic::FILE_LOCK }; drawn::glyph(ui, pos2(rect.left() + PRESET_ICON_X, rect.center().y), icon, PRESET_ROW_ICON_SIZE, look.text_dim); - let shown = drawn::fitted(ui, name, rect.width() - PRESET_NAME_LEFT, false, selected); + let shown = drawn::fitted(ui, label, rect.width() - PRESET_NAME_LEFT, false, selected); let color = if selected { look.text } else { look.list_text }; drawn::text_at(ui, rect.left() + PRESET_NAME_LEFT, rect.center().y, &shown, color, selected); drawn::paint_focus(ui, &response); @@ -683,7 +683,7 @@ fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) { } ListAction::Duplicate(name) => { if let Some(p) = app.session.export_preset(&name) { - let name = format!("{}_copy", template_label(&p.name)).chars().take(MAX_PRESET_NAME).collect(); + let name = format!("{}_copy", template_label(&app.session, &name)).chars().take(MAX_PRESET_NAME).collect(); save_new(app, &ExportPreset { name, ..p }); } } @@ -867,9 +867,9 @@ pub fn load_library(app: &mut TextureCraftApp, storage: Option<&dyn eframe::Stor app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, skipped.into_iter().map(|w| format!("Export template skipped: {w}"))); } #[cfg(target_arch = "wasm32")] - for p in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { - if let Ok(v) = serde_json::to_value(&p) { - app.run("export.preset.save", json!({ "preset": v, "unique": true })); + for preset in storage.and_then(|s| eframe::get_value::>(s, STORAGE_KEY)).unwrap_or_default() { + if let Err(error) = app.session.export_presets.restore(preset) { + app.session.log.warnings(texturecraft_engine::log::LIBRARY_SOURCE, [format!("Export template skipped: {error}")]); } } } @@ -913,7 +913,7 @@ fn outputs(app: &mut TextureCraftApp, ui: &mut Ui, column: Rect, top: f32) { let title = tr("Current preset:"); let name_left = column.left() + drawn::text_width(ui, title, true) + NAME_GAP; drawn::label_at(ui, column.left(), y, title, look.text, true); - let name = drawn::label_at(ui, name_left, y, template_label(&preset.name), look.text, false); + let name = drawn::label_at(ui, name_left, y, template_label(&app.session, &app.ui.export.preset), look.text, false); if !editable { let lock_at = pos2(name.rect.right() + LOCK_GAP, y); drawn::glyph(ui, lock_at, ic::LOCK_SIMPLE, CARD_ICON_SIZE, look.text_dim); @@ -1069,12 +1069,23 @@ fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec Result { let mut params = crate::export_window::set_params(app, app.session.ts()); - params["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?; + let export = &app.ui.export; + let same_template = params.get("preset").and_then(Value::as_str) == Some(export.preset.as_str()); - // The set's map overrides apply only to its own template - if let Some(params) = params.as_object_mut() { + if !same_template && let Some(params) = params.as_object_mut() { params.remove("maps"); + } else if let (Some(_), Some(maps)) = (&export.draft, params.get_mut("maps").and_then(Value::as_array_mut)) { + // Draft positions have no override until they map to a saved output + maps.retain_mut(|settings| { + let Some(saved_index) = settings["map"].as_u64().and_then(|index| usize::try_from(index).ok()) else { return false }; + let Some(draft_index) = export.draft_maps.iter().position(|origin| *origin == Some(saved_index)) else { return false }; + + settings["map"] = json!(draft_index); + true + }); } + + params["preset"] = serde_json::to_value(preset).map_err(|error| error.to_string())?; Ok(params) } @@ -1503,7 +1514,8 @@ fn preview_pictures(ui: &mut Ui, map: &MapSpec, pictures: &MapPreviewPictures) { Dest::R | Dest::G | Dest::B if source_of(map, gray).is_some() => gray, _ => target, }; - let source = source_of(map, source_target).unwrap_or(&SourceRef::Constant(CLEARED_VALUE)); + let fallback = SourceRef::Constant(if *dest == Dest::A { CLEARED_ALPHA } else { CLEARED_VALUE }); + let source = source_of(map, source_target).unwrap_or(&fallback); let inverted = source_target.dests().iter().any(|dest| map.inverted.contains(dest)); ui.horizontal(|ui| { @@ -1855,6 +1867,40 @@ mod tests { SourceRef::Channel { channel, component } } + #[test] + fn feedback_preview_follows_draft_maps_to_their_saved_overrides() { + use crate::state::{MapExport, SetExport}; + use egui_kittest::Harness; + + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let app = harness.state_mut(); + let ts = app.session.ts(); + 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()]; + let resized = MapExport { size: Some(128), ..MapExport::default() }; + let disabled = MapExport { enabled: false, ..MapExport::default() }; + app.ui.export.preset = saved.name.clone(); + app.ui.export.sets.insert( + ts, + SetExport { + maps_template: saved.name, + maps: [(0, resized), (1, disabled), (2, MapExport { size: Some(512), ..MapExport::default() })].into(), + ..SetExport::default() + }, + ); + app.ui.export.draft = Some(draft.clone()); + app.ui.export.draft_maps = vec![Some(1), None, Some(0)]; + + let params = plan_params(app, &draft).unwrap(); + 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!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); + } + #[test] fn layouts_keep_sources_and_drops_fill_rgb() { let mut map = new_map(Layout::Rgb, "t"); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 9a93edad..fd2fea9a 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -335,31 +335,47 @@ fn file_type_name(format: &str) -> String { } /// The label shown for a stored template name. Custom template names pass through unchanged. -pub(super) fn template_label(name: &str) -> &str { - match name { +pub(super) fn template_label<'a>(session: &texturecraft_engine::Session, name: &'a str) -> &'a str { + use texturecraft_engine::preset_cmds::unqualified_preset_name; + + let label = match unqualified_preset_name(name) { "Unreal Engine Subsurface Profile (Packed)" => tr("Packed maps with a scattering mask"), "Redshift Standard Material (separate maps)" => tr("Separate coat, sheen and scattering maps"), "Roblox SurfaceAppearance (separate maps)" => tr("Four maps with opacity in color"), "Sketchfab Metalness (separate maps)" => tr("Six maps with a negative-Y normal"), - _ => name, - } + _ => return name, + }; + + if session.has_user_export_preset(name) { name } else { label } } /// The template list: the first group (name, whether TextureCraft has it), then the others /// (built-in and user templates) sorted by name. pub(crate) fn template_groups(app: &TextureCraftApp, builtins: &[ExportPreset]) -> (Vec<(&'static str, bool)>, Vec) { let first = FIRST_GROUP.iter().map(|name| (*name, builtins.iter().any(|p| p.name == *name))).collect(); - let mut rest: Vec = builtins.iter().map(|p| p.name.clone()).filter(|n| !FIRST_GROUP.contains(&n.as_str())).collect(); + let mut rest: Vec = builtins + .iter() + .filter(|preset| !FIRST_GROUP.contains(&preset.name.as_str())) + .map(|preset| app.session.builtin_export_preset_id(&preset.name).into_owned()) + .collect(); rest.extend(app.session.export_presets.list.iter().map(|p| p.name.clone())); - rest.sort_by(|left, right| template_label(left).cmp(template_label(right)).then_with(|| left.cmp(right))); + rest.sort_by(|left, right| template_label(&app.session, left).cmp(template_label(&app.session, right)).then_with(|| left.cmp(right))); rest.dedup(); (first, rest) } /// A template dropdown in `rect` over `first` and `rest`; true when `current` changed -fn template_combo(ui: &mut Ui, rect: egui::Rect, id: &str, current: &mut String, first: &[(&str, bool)], rest: &[String]) -> bool { +fn template_combo( + session: &texturecraft_engine::Session, + ui: &mut Ui, + rect: egui::Rect, + id: &str, + current: &mut String, + first: &[(&str, bool)], + rest: &[String], +) -> bool { let mut changed = false; - drawn::combo(ui, rect, id, template_label(current).to_owned(), |ui| { + drawn::combo(ui, rect, id, template_label(session, current).to_owned(), |ui| { for (name, have) in first { if *have { changed |= ui.selectable_value(current, (*name).to_string(), *name).on_hover_text(*name).changed(); @@ -369,7 +385,7 @@ fn template_combo(ui: &mut Ui, rect: egui::Rect, id: &str, current: &mut String, } ui.separator().on_hover_text(tr("Some templates in this list are unavailable")); for name in rest { - changed |= ui.selectable_value(current, name.clone(), template_label(name)).on_hover_text(name).changed(); + changed |= ui.selectable_value(current, name.clone(), template_label(session, name)).on_hover_text(name).changed(); } }); changed @@ -1013,7 +1029,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, place: PagePlace, builtin row_label(ui, place, y, tr("Output template")); let (first, rest) = template_groups(app, builtins); let mut picked = app.ui.export.preset.clone(); - if template_combo(ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { + if template_combo(&app.session, ui, drawn::control_rect(left, right, y), "exp_preset", &mut picked, &first, &rest) { crate::export_templates::select(app, picked); } @@ -1237,9 +1253,9 @@ fn set_page(app: &mut TextureCraftApp, ui: &mut Ui, ts: usize, place: PagePlace, let row_y = |row: usize| place.y(SET_FIRST_ROW_Y + row as f32 * SET_ROW_PITCH); let mut toggled = None; - if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), template_label(&from.preset), |ui, rect| { + if override_row(ui, place, row_y(0), tr("Output template"), overrides.preset.is_some(), template_label(&app.session, &from.preset), |ui, rect| { if let Some(preset) = &mut overrides.preset { - template_combo(ui, rect, "exp_set_preset", preset, &first, &rest); + template_combo(&app.session, ui, rect, "exp_set_preset", preset, &first, &rest); } }) { toggled = Some(0); @@ -1687,13 +1703,8 @@ fn cancel(app: &mut TextureCraftApp) { app.ui.windows.export = false; } -/// Escape closes the window as Cancel does, read in `menus::shortcuts`; an open dropdown, channel question, template rename or text field takes it first -pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState, popup_open: bool) { - let export = &app.ui.export; - if popup_open || export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some() { - return; - } - +/// Escape closes the window as Cancel does after shortcut routing checks higher-priority inputs. +pub(crate) fn keys_in(app: &mut TextureCraftApp, input: &mut egui::InputState) { if input.consume_key(egui::Modifiers::NONE, egui::Key::Escape) { app.ui.export.job = None; cancel(app); @@ -1804,7 +1815,8 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { } // Settings saved under the default template's old name - if let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) + if !app.session.has_user_export_preset(&app.ui.export.preset) + && let Some(b) = texturecraft_engine::formats::builtin_preset(&app.ui.export.preset) && b.name != app.ui.export.preset { app.ui.export.preset = b.name; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9a497ce9..53547d2f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -514,11 +514,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - // The open list or the picker window closes on this Escape itself + let export = &app.ui.export; let escape_is_free = !popup_open && !picker_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()); if confirming_reset { // Its keys were handled before the shortcuts ran - } else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if escape_is_free && export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { // The Output templates question: Escape answers it with the safe choice app.ui.export.ask = None; } else if app.ui.windows.project_config.is_some() { @@ -528,22 +531,25 @@ 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 app.ui.windows.export { - // Escape is the window's Cancel; nothing behind the window reads it - crate::export_window::keys_in(app, input, !escape_is_free); - } else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if popup_open || export_input_active { + // The open list or export input handles the key + } else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_color = None; - } else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) { cancel_point_pick = true; - } else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !escape_is_free { + // The picker window handles the key + } else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; - } else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); - } else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) { app.picking_symmetry_plane = false; - } else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if app.ui.windows.export { + crate::export_window::keys_in(app, input); + } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.cancel_path(); } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 41caad25..72227984 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -360,14 +360,14 @@ mod web { } fn export(app: &mut TextureCraftApp, jobs: &[(usize, Value)]) -> Result { - let mut files = Vec::new(); - for (set_index, params) in jobs { - let options = texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures").map_err(|e| e.to_string())?; - files.extend(app.session.export_files(&[*set_index], &options).map_err(|e| e.to_string())?); - } + let options = jobs + .iter() + .map(|(_, params)| texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures")) + .collect::, _>>() + .map_err(|error| error.to_string())?; + let jobs_with_options = jobs.iter().zip(&options).map(|((set_index, _), options)| (*set_index, options)); + let mut files = app.session.export_file_jobs(jobs_with_options).map_err(|error| error.to_string())?; - // Keep one file for each case-insensitive name in the download - texturecraft_engine::formats::skip_repeated_names(&mut files); if app.ui.export.shader_parameters { let sets: Vec = jobs.iter().map(|(set_index, _)| *set_index).collect(); match shader_parameters_sidecar(&app.session.doc.project, &sets, &files) { diff --git a/crates/ui-egui/tests/it/export_settings.rs b/crates/ui-egui/tests/it/export_settings.rs index c379b0f8..2c79474b 100644 --- a/crates/ui-egui/tests/it/export_settings.rs +++ b/crates/ui-egui/tests/it/export_settings.rs @@ -216,3 +216,24 @@ fn the_page_reset_puts_the_parameters_back() { assert_eq!((e.size, e.padding.as_str()), (0, "infinite")); assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page"); } + +#[test] +fn feedback_escape_clears_a_pick_before_cancelling_export() { + let mut h = harness(); + let pick = egui::Id::unique("export_escape_screen_color_pick"); + h.state_mut().picking_color = Some(pick); + h.state_mut().ui.export.size = 512; + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(h.state().picking_color.is_none(), "the armed pick receives Escape first"); + assert!(h.query_by_role_and_label(egui::Role::Button, "Save settings").is_some()); + assert_eq!(h.state().ui.export.size, 512); + + h.key_press(egui::Key::Escape); + h.run_steps(4); + + assert!(!h.state().ui.windows.export); + assert_eq!(h.state().ui.export.size, 0); +} diff --git a/crates/ui-egui/tests/it/output_templates.rs b/crates/ui-egui/tests/it/output_templates.rs index 12a40ace..c40deb73 100644 --- a/crates/ui-egui/tests/it/output_templates.rs +++ b/crates/ui-egui/tests/it/output_templates.rs @@ -763,3 +763,22 @@ fn leaving_output_templates_releases_pictures_from_each_hovered_map() { assert!(!h.state().ui.windows.export); assert_eq!(previews(&h), 0); } + +#[test] +fn feedback_template_preview_counts_overrides_only_for_its_own_maps() { + let library = TemplateLibrary::new("preview-map-overrides"); + let mut h = harness(&library); + let ts = h.state().session.ts(); + let plan = h.state_mut().run("export.plan", json!({"ts": ts, "preset": "Mine"})).unwrap(); + let initial = plan.as_array().unwrap().len(); + assert!(initial > 0); + let disabled = MapExport { enabled: false, ..MapExport::default() }; + h.state_mut().ui.export.sets.insert(ts, SetExport { maps_template: "Mine".into(), maps: [(0, disabled)].into(), ..SetExport::default() }); + + h.run_steps(4); + + 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()); +} From b965b750f7707c075f71a17cfa3084ee9cc8c352 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 25 Nov 2026 23:10:17 +0000 Subject: [PATCH 16/34] Auto: Fix export planning, previews, and file-list scrolling Disambiguate colliding PSD filenames and budget only the documents retained for export. Match grayscale WebP previews to the encoded channels and make wide export details reachable by scrolling. Document built-in preset selection and verify declared JPEG 2000 component precision. Focused Linux tests, affected-package Clippy, and WebAssembly checks passed. --- crates/engine/src/file_cmds.rs | 23 +++-- crates/engine/tests/it/export_file_types.rs | 22 +++++ crates/formats/README.md | 10 ++- crates/formats/src/export/map_preview.rs | 6 +- crates/formats/src/export/mod.rs | 95 +++++++++++++++------ crates/formats/src/export/tests.rs | 91 ++++++++++++++++++++ crates/ui-egui/src/export_window.rs | 20 ++++- crates/ui-egui/tests/it/export_progress.rs | 30 +++++++ 8 files changed, 255 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 6b47fa94..9940b372 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -285,17 +285,14 @@ impl Session { } /// Render every export file for texture sets `sets` (in memory; works on the web). A file - /// named like one an earlier set exports is left out, with a warning (see - /// [`texturecraft_formats::skip_repeated_names`]). + /// named like one an earlier set exports is left out, with a warning. pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result> { self.export_file_jobs(sets.iter().map(|&set| (set, opts))) } /// Render one in-memory batch, using each set's own export settings when supplied. pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator) -> Result> { - let mut files = self.render_export_jobs(jobs, |_, plans| plans)?; - texturecraft_formats::skip_repeated_names(&mut files); - Ok(files) + self.render_export_jobs(jobs, |_, plans| plans) } #[cfg(not(target_arch = "wasm32"))] @@ -315,18 +312,28 @@ impl Session { ) -> Result> { let project = &self.doc.project; let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:")); - let mut psd_bytes = 0; let mut pending = Vec::new(); for (set_index, options) in jobs { let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?; let plans = select(set_index, plans); if !plans.is_empty() { - let set = project.texture_set(set_index).map_err(|error| EngineError::Other(error.to_string()))?; - texturecraft_formats::export::check_psd_batch(set, options, &plans, &mut psd_bytes).map_err(fe)?; pending.push((set_index, options, plans)); } } + // Keep each winning plan with the options of the job that produced it + let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan))); + for (job, plan) in texturecraft_formats::export::keep_first_planned_names(plans) { + pending[job].2.push(plan); + } + pending.retain(|(_, _, plans)| !plans.is_empty()); + + let mut psd_bytes = 0; + for (set_index, options, plans) in &pending { + let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?; + texturecraft_formats::export::check_psd_batch(set, options, plans, &mut psd_bytes).map_err(fe)?; + } + if self.solo.is_none() { self.update(); } diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index e8bbe2c3..40e4816f 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -28,6 +28,28 @@ fn the_new_file_types_dithering_and_diffusion_export() { assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err()); } +#[test] +fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { + const SMALL_SIDE: u32 = 128; + let mesh = texturecraft_engine::geom::primitives::udim_plane(); + let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:udim_plane", None, SMALL_SIDE).unwrap(); + let preset = + json!({"name": "Roughness", "maps": [{"file": "rough", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]}); + let options = |size| texturecraft_engine::file_cmds::export_options(&session, &json!({"preset": preset, "size": size, "padding": "none"}), "test").unwrap(); + 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)); + let batch = session.export_file_jobs(jobs).unwrap(); + + assert_eq!(batch.len(), first.len()); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.name == original.name && kept.bytes == original.bytes)); + assert!(batch.iter().zip(&first).all(|(kept, original)| kept.warnings.len() > original.warnings.len())); + println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::()); +} + #[test] fn a_map_size_wins_over_the_export_size_in_the_plan() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); diff --git a/crates/formats/README.md b/crates/formats/README.md index 4be58133..eb04b8bf 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -148,9 +148,13 @@ Built-in presets (each one lists the public specification its packing follows in | Separate maps | one file per channel, gray where scalar, height 16-bit | | Mesh maps | every baked map (`$channel` = map id), 16-bit | -The preset column gives the stable automation and saved-setting names. The export window describes -four templates by their output. **Packed maps with a scattering mask** targets Unreal Engine's -subsurface input. **Separate coat, sheen and scattering maps** targets Redshift. +The preset column gives the stable automation and saved-setting names. When a user preset shares +a table name, that name selects the user preset so saved settings keep working. To select the +built-in through automation, pass the exact `name` from its `builtin: true` entry in +`export.presets`. + +The export window describes four templates by their output. **Packed maps with a scattering mask** +targets Unreal Engine's subsurface input. **Separate coat, sheen and scattering maps** targets Redshift. **Four maps with opacity in color** targets Roblox, and **Six maps with a negative-Y normal** targets Sketchfab. diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index 81063de3..282ec063 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -64,8 +64,10 @@ impl MapPreview { let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L); let psd = file.format == FileFormat::Psd; - let rgb_from_gray = gray_source - .filter(|_| psd || file.format == FileFormat::Hdr || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))); + let rgb_from_gray = gray_source.filter(|_| { + matches!(file.format, FileFormat::Psd | FileFormat::Hdr | FileFormat::Webp) + || (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2)) + }); let channels = if grayscale { vec![Dest::L] } else if psd { diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 41522520..7e0afcb3 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -653,40 +653,67 @@ fn psd_stem(mesh_name: &str, set_name: &str, set_index: usize, max_len: usize) - format!("{mesh}_{set}_{set_index}") } -/// Keep tiled names stable even when the export window plans each texture set separately. +/// Compare against the whole project so a separate export and a batch agree on names. fn untiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, atlas: bool) -> String { let stem = psd_stem(mesh_name, &set.name, set_index, MAX_STEM); - if atlas { - return stem; - } + let taken = |candidate: &str| { + let tile = psd_tile_suffix(candidate); + project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index).any(|(index, other)| { + if atlas || other.uv_tiles.is_empty() { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM)) + } else { + tile.is_some_and(|(base, number)| { + other.uv_tiles.contains(&number) + && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - (candidate.len() - base.len()))) + }) + } + }) + }; + if taken(&stem) { disambiguated_psd_stem(&stem, set_index, MAX_STEM, taken) } else { stem } +} - let Some((base, tile)) = stem.rsplit_once('.') else { return stem }; - let Ok(number) = tile.parse::() else { return stem }; +/// Only a canonical tile number can collide with a generated UDIM suffix. +fn psd_tile_suffix(stem: &str) -> Option<(&str, u32)> { + let (base, suffix) = stem.rsplit_once('.')?; + let number: u32 = suffix.parse().ok()?; + (number.to_string() == suffix).then_some((base, number)) +} - let suffix_len = tile.len() + 1; - let collides = number.to_string() == tile - && project.texture_sets.iter().enumerate().any(|(index, other)| { - other.uv_tiles.contains(&number) && base.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, MAX_STEM - suffix_len)) - }); +/// Keep one UDIM base for all tiles of a set when any tile's ordinary name collides. +fn tiled_psd_stem(project: &Project, mesh_name: &str, set_index: usize, set: &TextureSet, limit: usize) -> String { + let stem = psd_stem(mesh_name, &set.name, set_index, limit); + let other_sets = || project.texture_sets.iter().enumerate().filter(|(index, _)| *index != set_index); + let collides = other_sets().any(|(index, other)| { + !other.uv_tiles.is_empty() + && stem.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + && other.uv_tiles.iter().any(|tile| set.uv_tiles.contains(tile)) + }); if !collides { return stem; } - // Reserve the ordinary untiled names, including names that already end in an index - let untiled_names: BTreeSet<_> = project - .texture_sets - .iter() - .enumerate() - .filter(|(_, other)| other.uv_tiles.is_empty()) - .map(|(index, other)| psd_stem(mesh_name, &other.name, index, MAX_STEM).to_ascii_lowercase()) - .collect(); + // Reserve ordinary names so a generated suffix cannot take another document's name + disambiguated_psd_stem(&stem, set_index, limit, |candidate| { + other_sets().any(|(index, other)| { + if other.uv_tiles.is_empty() { + let untiled = psd_stem(mesh_name, &other.name, index, MAX_STEM); + psd_tile_suffix(&untiled).is_some_and(|(base, tile)| candidate.eq_ignore_ascii_case(base) && set.uv_tiles.contains(&tile)) + } else { + candidate.eq_ignore_ascii_case(&psd_stem(mesh_name, &other.name, index, limit)) + } + }) + }) +} + +fn disambiguated_psd_stem(stem: &str, set_index: usize, limit: usize, taken: impl Fn(&str) -> bool) -> String { let mut attempt = 0usize; loop { let suffix = if attempt == 0 { format!("_{set_index}") } else { format!("-{attempt}_{set_index}") }; - let name = format!("{}{suffix}", &stem[..stem.len().min(MAX_STEM - suffix.len())]); - if !untiled_names.contains(&name.to_ascii_lowercase()) { + let name = format!("{}{suffix}", &stem[..stem.len().min(limit - suffix.len())]); + if !taken(&name) { return name; } + attempt += 1; } } @@ -810,6 +837,9 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export } } + // Reuse the base across tiles with the same suffix width + let mut tiled_bases = HashMap::new(); + // Each tile's PSD maps are the layers of one file named after the texture set for (&tile, in_tile) in tiles.iter().zip(psd_layers) { let Some((first_layer, ..)) = in_tile.first() else { continue }; @@ -838,7 +868,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let ext = FileFormat::Psd.extension(); let (stem, udim_stem) = if let Some(number) = tile { let suffix = format!(".{number}"); - let base = psd_stem(mesh_name, &set.name, ts, MAX_STEM - suffix.len()); + let limit = MAX_STEM - suffix.len(); + let base = tiled_bases.entry(limit).or_insert_with(|| tiled_psd_stem(project, mesh_name, ts, set, limit)); (format!("{base}{suffix}"), Some(format!("{base}."))) } else { (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) @@ -911,15 +942,19 @@ fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { - let mut psd_bytes = 0; let mut files = Vec::new(); for &index in sets { let planned = list_outputs(project, index, mesh_name, opts)?; - check_psd_batch(project.texture_set(index)?, opts, &planned, &mut psd_bytes)?; files.extend(planned.into_iter().map(|file| (index, file))); } - Ok(keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings)) + let files = keep_first_planned_names(files); + let mut psd_bytes = 0; + for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { + check_psd_batch(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes)?; + } + + Ok(files) } // --------------------------------------------------------------------------------------------- @@ -1703,9 +1738,15 @@ pub fn skip_repeated_names(files: &mut Vec) { *files = keep_first_names(std::mem::take(files), |file| &file.name, |file| &mut file.warnings); } -fn keep_first_names(files: Vec, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { +/// Keep the first case-insensitive use of each filename and attach duplicate warnings to its plan. +pub fn keep_first_planned_names(files: impl IntoIterator) -> Vec<(T, PlannedFile)> { + keep_first_names(files, |(_, file)| &file.name, |(_, file)| &mut file.warnings) +} + +fn keep_first_names(files: impl IntoIterator, name: impl Fn(&T) -> &str, warnings: impl Fn(&mut T) -> &mut Vec) -> Vec { + let files = files.into_iter(); let mut first = HashMap::new(); - let mut kept = Vec::with_capacity(files.len()); + let mut kept = Vec::with_capacity(files.size_hint().0); for file in files { let filename = name(&file); match first.entry(filename.to_ascii_lowercase()) { diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index b5d18af0..a7e6fcb0 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1498,7 +1498,12 @@ fn jpeg2000_is_lossless_at_8_and_16_bits() { let components = usize::from(image.color().channel_count()); let expected = image.to_rgba16(); let planes = jpeg2000_planes(&file.bytes); + let info = j2k::J2kDecoder::inspect_support(&file.bytes).unwrap(); + assert_eq!(info.components.len(), components, "{}", file.name); + for (component, declared) in info.components.iter().enumerate() { + assert_eq!(declared.bit_depth, depth, "{} component {component} precision", file.name); + } assert_eq!(planes.len(), components, "{}", file.name); for (component, plane) in planes.iter().enumerate() { assert_eq!(plane.len(), expected.pixels().len(), "{} component {component}", file.name); @@ -1993,6 +1998,28 @@ fn feedback_jpeg_previews_omit_the_alpha_channel() { } } +#[test] +fn webp_preview_matches_the_exported_channels_and_samples() { + let fx = Fx::new(&default_channels()); + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.retain(|(dest, _)| *dest != Dest::A); + + for (layout, expected) in + [(roughness(), &[Dest::R, Dest::G, Dest::B][..]), (gray_alpha, &[Dest::R, Dest::G, Dest::B, Dest::A][..]), (rgb, &[Dest::R, Dest::G, Dest::B][..])] + { + let options = one_map(FileFormat::Webp, 8, layout); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + let image = decode(&fx.render(&options)[0]); + + assert_eq!(preview.channels, expected); + assert_eq!(preview.channels.len(), usize::from(image.color().channel_count())); + assert_eq!(preview.pixels, image.as_bytes()); + } +} + #[test] fn pgm_preview_shows_exported_luminance_without_alpha() { let fx = Fx::new(&default_channels()); @@ -2257,6 +2284,70 @@ fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() { assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning"); } +#[test] +fn psd_document_names_survive_sanitization_and_case_collisions() { + let mut fx = Fx::new(&default_channels()); + fx.project.texture_sets[0].name = "Body Coat".into(); + for (name, tiles) in [ + ("body_coat", vec![]), + ("Body_Coat_0", vec![]), + ("Body Coat", vec![1001, 1002]), + ("BODY_COAT", vec![1001]), + ("Trim", vec![]), + ("body_coat", vec![1011]), + ] { + let mut set = fx.project.texture_sets[0].clone(); + set.name = name.into(); + set.uv_tiles = tiles; + fx.project.texture_sets.push(set); + } + let options = one_map(FileFormat::Psd, 8, roughness()); + let indices = [6, 5, 4, 3, 2, 1, 0]; + + let batch = list_set_outputs(&fx.project, &indices, "sphere", &options).unwrap(); + let separate: Vec<_> = indices + .into_iter() + .flat_map(|index| list_outputs(&fx.project, index, "sphere", &options).unwrap().into_iter().map(move |file| (index, file.name))) + .collect(); + + assert_eq!(batch.into_iter().map(|(index, file)| (index, file.name)).collect::>(), separate); + for (index, unchanged) in [(2, "sphere_Body_Coat_0.psd"), (5, "sphere_Trim.psd"), (6, "sphere_body_coat.1011.psd")] { + 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"); + + let atlas_options = ExportOptions { atlas: true, ..options }; + let atlas = list_set_outputs(&fx.project, &indices, "sphere", &atlas_options).unwrap(); + assert_eq!(atlas.len(), indices.len(), "atlas documents also need distinct names"); +} + +#[test] +fn psd_batch_budget_counts_only_retained_documents() { + let mut fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Psd, 8, roughness()); + options.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1006).collect(); + let mut other = fx.project.texture_sets[0].clone(); + other.name = "Other".into(); + fx.project.texture_sets.push(other); + + let once = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); + let repeated = list_set_outputs(&fx.project, &[0, 0], "sphere", &options).unwrap(); + let distinct = list_set_outputs(&fx.project, &[0, 1], "sphere", &options); + let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); + + assert_eq!(once.len(), repeated.len()); + assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len())); + assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD"))); + println!( + "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {MAX_PSD_BATCH_BYTES}", + bytes_per_tile * once.len() as u64, + bytes_per_tile * (once.len() + repeated.len()) as u64 + ); +} + #[test] fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { let mut fx = Fx::new(&default_channels()); diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index fd2fea9a..9cc30594 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1350,7 +1350,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::vertical().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, &tk)); }); // The strip at the console's left edge: a click hides or shows the console, a drag resizes it @@ -1441,7 +1441,10 @@ fn export_tree(app: &mut TextureCraftApp, ui: &mut Ui, tk: &Tokens) { .zip(&open) .map(|(((_, set), files), open)| 1 + 1 + if *open { files.len().max(usize::from(set.files.is_err())) } else { 0 }) .sum(); - let (area, _) = ui.allocate_exact_size(vec2(ui.available_width(), TREE_TOP_PADDING + row_count as f32 * TREE_ROW_HEIGHT), egui::Sense::hover()); + 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) { let header = egui::Rect::from_min_max(egui::pos2(area.left(), y), egui::pos2(area.right(), y + TREE_ROW_HEIGHT)); @@ -1514,6 +1517,19 @@ fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui:: drawn::glyph(ui, egui::pos2(rect.left() + TREE_CHEVRON_X, y), chevron, drawn::CHEVRON_SIZE, look.text); drawn::text_at(ui, rect.left() + TREE_NAME_INDENT, y, name, look.text, true); drawn::paint_focus(ui, &response); + + if response.has_focus() && rect.width() > ui.clip_rect().width() { + let direction = ui.input_mut(|input| { + let start = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowLeft); + let end = input.consume_key(egui::Modifiers::NONE, egui::Key::ArrowRight); + i8::from(start) - i8::from(end) + }); + if direction != 0 { + ui.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + ui.scroll_with_delta(vec2(f32::from(direction) * ui.clip_rect().width() / 2.0, 0.0)); + } + } + response.clicked() } diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index de7e577b..f264b092 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -154,6 +154,36 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { assert!(!h.state().ui.export.console_hidden); } +#[test] +fn long_filenames_leave_the_export_details_reachable_by_scrolling() { + let (mut h, _) = harness("wide-tree"); + let name = "Wide".repeat(44); + h.state_mut().session.doc.project.texture_sets[0].name.clone_from(&name); + h.state_mut().ui.export.tab = 2; + h.run_steps(4); + let bits_label = "16 bits"; + let bits_fit = |h: &Harness<'_, TextureCraftApp>| { + h.output().shapes.iter().any(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == bits_label => clipped.clip_rect.contains_rect(text.visual_bounding_rect()), + _ => false, + }) + }; + assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport"); + h.get_by_role_and_label(egui::Role::Button, &name).focus(); + h.run_steps(3); + assert!(h.get_by_role_and_label(egui::Role::Button, &name).is_focused()); + + for _ in 0..12 { + h.key_press(egui::Key::ArrowRight); + h.run_steps(2); + } + h.run_steps(10); + + assert!(bits_fit(&h), "horizontal keyboard scrolling brings bit depth into the viewport"); + assert!(h.query_all_by_label(bits_label).next().is_some(), "bit depth has an accessibility label"); + assert!(h.query_by_label("Console").is_some()); +} + #[test] fn open_output_directory_asks_the_system_to_show_the_folder() { let (mut h, dir) = harness("open"); From f67270d6ae765ac56ad97f03298e394f7e9d8f7f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:10:02 +0000 Subject: [PATCH 17/34] Export: JPEG 2000 back to greyed; its writer moves to craft-libs The j2k/jp2 writer is a codec, so it goes to craft-image-codecs first (review on #827); the export wires it in again once craft-libs ships it. --- ATTRIBUTION.md | 8 - Cargo.lock | 69 +------ Cargo.toml | 3 - NOTICE | 5 - README.md | 2 +- crates/engine/src/file_cmds.rs | 4 +- crates/engine/tests/it/materialx.rs | 2 +- crates/engine/tests/it/usd_asset.rs | 16 -- crates/formats/Cargo.toml | 2 - crates/formats/README.md | 2 +- crates/formats/src/export/jpeg2000.rs | 67 ------- crates/formats/src/export/linear_gray.icc | Bin 460 -> 0 bytes crates/formats/src/export/map_renderer.rs | 4 +- crates/formats/src/export/mod.rs | 31 +--- crates/formats/src/export/tests.rs | 181 +------------------ crates/formats/src/mesh_export/usd.rs | 4 +- crates/ui-egui/src/export_window.rs | 4 +- crates/ui-egui/tests/it/export_file_types.rs | 23 ++- docs/control-protocol.md | 6 +- docs/features.md | 2 +- 20 files changed, 35 insertions(+), 400 deletions(-) delete mode 100644 crates/formats/src/export/jpeg2000.rs delete mode 100644 crates/formats/src/export/linear_gray.icc diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 8ec51fb8..a895078e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -27,7 +27,6 @@ licensed and keep their license file next to them. | `assets/hdr/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | [Poly Haven release](https://polyhaven.com/a/studio_small_09), [1K Radiance HDR](https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/1k/studio_small_09_1k.hdr) (MD5 `d5d7eb9d26d341d6aa4d11c1a54fd97c`) | [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/) | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | -| `crates/formats/src/export/linear_gray.icc` | TextureCraft Linear Gray (D50) | TextureCraft contributors | Original ICC v2.1 monochrome display profile generated with Little CMS 2.14 from D50 and gamma 1.0, with a fixed creation date of 2026-01-01 | MIT OR Apache-2.0 | ## Third-party assets compiled into the binary @@ -54,13 +53,6 @@ time (nothing is bundled); see [docs/localization-parity.md](docs/localization-p | `x11rb` | X11 pointer and pixel capture | https://github.com/psychon/x11rb | MIT OR Apache-2.0 | | `zbus` | Wayland desktop color-picker portal | https://github.com/z-galaxy/zbus | MIT | -## JPEG 2000 export dependencies - -| Crate | Use | Upstream | License | -|---|---|---|---| -| `j2k`, `j2k-core`, `j2k-native`, `j2k-types`, `j2k-profile`, `j2k-codec-math` 0.11.3 | JPEG 2000 codestream and JP2 export | [frames-sg contributors](https://github.com/frames-sg/j2k/tree/c708d2fda9f2672472b9e06aa2e66bf1f191dc3d) | MIT OR Apache-2.0 | -| `fearless_simd` 1.3.0 | SIMD support used by `j2k-native` | [Raph Levien and contributors](https://github.com/linebender/fearless_simd/tree/2ac6acdd13efb7689a6e80049a4933516a57ec20) | Apache-2.0 OR MIT | - ## Procedural content (no asset files) Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals diff --git a/Cargo.lock b/Cargo.lock index be50cc5f..7da98739 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1832,12 +1832,6 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97b65636e5b9ef369943878ac74335ba1c55c1cb6adbf1e2c293c624248d693" -[[package]] -name = "fearless_simd" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a7107516a8be9a4ffe92495f3dbfe04348be0ad18f17c67a1d846511f99e599" - [[package]] name = "filetime" version = "0.2.29" @@ -2400,7 +2394,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" dependencies = [ - "fearless_simd 0.4.1", + "fearless_simd", ] [[package]] @@ -2766,63 +2760,6 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" -[[package]] -name = "j2k" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5dcb93d62c580930297896f25933b034bf665534568626787dbf0f03027e7b0" -dependencies = [ - "j2k-core", - "j2k-native", - "j2k-types", - "moxcms", - "thiserror 2.0.21", -] - -[[package]] -name = "j2k-codec-math" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38b1ddbaa04c07213dba6180ed1168f0e96bfa35890542c414d872cea0c7d58" -dependencies = [ - "j2k-types", -] - -[[package]] -name = "j2k-core" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae969eb19e9b3a8d65c4342f9921717be407571cc0fbc44e4379daa0b588d01c" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "j2k-native" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "971da314ca1501363f686b6796d309ebbda7d2f88d34671c38d79132f7cb59ff" -dependencies = [ - "fearless_simd 1.3.0", - "j2k-codec-math", - "j2k-profile", - "j2k-types", - "libm", - "rayon", -] - -[[package]] -name = "j2k-profile" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c1c0cc7e85f2ab1cc85c9a6d2bad3680319c0cdf558f3be14b4ccdbd6917fca" - -[[package]] -name = "j2k-types" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "716edd556741a415294d955121f76d41b7d8d650554fb09f30d0654b15127ac9" - [[package]] name = "jni" version = "0.22.4" @@ -5282,8 +5219,6 @@ dependencies = [ "gltf", "half", "image", - "j2k", - "j2k-core", "png", "rayon", "serde", @@ -5822,7 +5757,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbb2141a2bca6e6d598e471fd4d1d7eed8e020aad6a28187edda07f091a325dd" dependencies = [ "bytemuck", - "fearless_simd 0.4.1", + "fearless_simd", "guillotiere", "log", "peniko", diff --git a/Cargo.toml b/Cargo.toml index 2f7b4610..656c9522 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,9 +44,6 @@ image = { version = "0.25", default-features = false, features = ["png", "jpeg", craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "3dff4793f1a5bd1f99a4fe3280d48f515158dff3" } half = "2" exr = { version = "1.73", default-features = false } -# JPEG 2000 writing (craft-image-codecs only reads it); j2k 0.13 needs Rust 1.99 -j2k = "0.11.3" -j2k-core = "0.11.3" eframe = { version = "0.37", default-features = false } egui = "0.37" wgpu = "30" diff --git a/NOTICE b/NOTICE index 2e3666df..25d962ff 100644 --- a/NOTICE +++ b/NOTICE @@ -24,11 +24,6 @@ Native eyedropper components: - x11rb — MIT OR Apache-2.0. Copyright 2019 x11rb contributors. - zbus — MIT. Copyright (c) 2024 Zeeshan Ali Khan and zbus contributors. -JPEG 2000 export components: -- j2k, j2k-core, j2k-native, j2k-types, j2k-profile and j2k-codec-math — MIT OR Apache-2.0. - Copyright (c) 2026 frames-sg contributors. -- fearless_simd — Apache-2.0 OR MIT. Copyright (c) 2018 Raph Levien. - Phosphor Icons (compiled in through the egui-phosphor crate) — MIT. egui default fonts (compiled in through the epaint_default_fonts crate): Ubuntu-Light — Ubuntu Font Licence 1.0; Hack — MIT and Bitstream Vera License; Noto Emoji — SIL Open Font License 1.1; diff --git a/README.md b/README.md index 29b1daea..345c32c1 100644 --- a/README.md +++ b/README.md @@ -157,7 +157,7 @@ cd apps/texturecraft-web && trunk serve # web build cargo xtask ci # fmt, clippy, tests, layering, wasm ``` -You need Rust 1.96 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). +You need Rust 1.95 or newer. The app opens with no project (**File ▸ Open sample project** loads a baked one, and **File ▸ Close** returns to the empty state). **File ▸ New project** starts from your own mesh file and a project template. TextureCraft generates UVs if the mesh has none. Japanese, Chinese, Korean and Arabic interface text uses the fonts of diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 9940b372..aa390ad0 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Export textures", ["File"], None, - "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|j2k|jp2|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", + "{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension; the maps written as psd are the layers of one _.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write .usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write _shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}", always, export_textures ), @@ -1079,7 +1079,7 @@ fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) - #[cfg(not(target_arch = "wasm32"))] fn material_format(format: FileFormat) -> bool { - !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp | FileFormat::J2k | FileFormat::Jp2) + !matches!(format, FileFormat::Psd | FileFormat::Jng | FileFormat::Pgm | FileFormat::Webp) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/tests/it/materialx.rs b/crates/engine/tests/it/materialx.rs index 504ed162..c6ee8dfe 100644 --- a/crates/engine/tests/it/materialx.rs +++ b/crates/engine/tests/it/materialx.rs @@ -187,7 +187,7 @@ fn per_map_overrides_of_the_template_do_not_reach_the_openpbr_maps() { #[test] fn a_file_type_a_material_cannot_use_falls_back_to_png() { let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); - for (format, bit_depth, ext) in [("psd", 16, "psd"), ("pgm", 8, "pgm"), ("jng", 8, "jng"), ("j2k", 8, "j2k"), ("jp2", 8, "jp2"), ("tiff", 16, "tif")] { + for (format, bit_depth, ext) in [("psd", 16, "psd"), ("pgm", 8, "pgm"), ("jng", 8, "jng"), ("tiff", 16, "tif")] { let dir = temp(format); let result = execute( diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs index 1abbb0e9..a130f813 100644 --- a/crates/engine/tests/it/usd_asset.rs +++ b/crates/engine/tests/it/usd_asset.rs @@ -421,19 +421,3 @@ fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() { 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}"); } - -#[test] -fn jpeg2000_maps_export_beside_usd_without_creating_texture_bindings() { - let mut s = ball(); - for format in ["j2k", "jp2"] { - let dir = temp(format); - - let result = export(&mut s, &dir, json!({"ts": 0, "format": format, "usdAsset": true})); - - assert!(files(&result).iter().any(|file| file.ends_with(&format!(".{format}"))), "{result}"); - let materials = read_back(&s, &dir); - - assert!(materials[material_of(&s, 0)].0.is_empty(), "{materials:?}"); - assert!(result["warnings"].to_string().contains(&format!("doesn't read {} files", format.to_uppercase())), "{result}"); - } -} diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index 43775bb6..dff3f94d 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -31,8 +31,6 @@ flate2 = { workspace = true } half = { workspace = true } zip = { workspace = true } exr = { workspace = true } -j2k = { workspace = true } -j2k-core = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } diff --git a/crates/formats/README.md b/crates/formats/README.md index eb04b8bf..b92e715f 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -106,7 +106,7 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; collisions get `_2`, `_3`, … plus a warning. - A map is written only when one of its sources has data in the texture set (channel present, map baked, …); alpha from a missing channel is dropped. -- Formats: PNG 8/16, JPEG 8 (q 95), J2K and JP2 8/16 (lossless), JNG 8 (JPEG colour, +- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. PSD writes one file per texture set or UV tile, with each output map stored as a layer. diff --git a/crates/formats/src/export/jpeg2000.rs b/crates/formats/src/export/jpeg2000.rs deleted file mode 100644 index d2142c25..00000000 --- a/crates/formats/src/export/jpeg2000.rs +++ /dev/null @@ -1,67 +0,0 @@ -//! JPEG 2000, lossless (reversible 5/3 wavelet): a raw codestream (.j2k) or one in a JP2 file (.jp2) - -use j2k::{ - J2kChannelAssociation, J2kChannelDefinition, J2kChannelType, J2kFileBoxMetadata, J2kFileColorSpec, J2kFileWrapOptions, J2kLosslessEncodeOptions, - J2kLosslessSamples, encode_j2k_lossless, wrap_j2k_codestream, -}; -use j2k_core::Colorspace; - -/// Original ICC v2 profile with a D50 white point and gamma 1.0 (ITU-T T.800, I.5.3.3) -pub(super) const LINEAR_GRAY_PROFILE: &[u8] = include_bytes!("linear_gray.icc"); - -/// Encode `bytes` (8-bit or native-endian 16-bit L, LA, RGB or RGBA samples) of a `width`×`height` image; `jp2` wraps it in a JP2 file that records `icc` -pub(super) fn write_jpeg2000( - bytes: Vec, - (width, height): (u32, u32), - component_count: usize, - depth: u8, - jp2: bool, - icc: Option<&[u8]>, -) -> Result, String> { - // Only big-endian hosts need to reverse the native 16-bit samples - #[cfg(target_endian = "big")] - let bytes = { - let mut bytes = bytes; - if depth == 16 { - for sample in bytes.as_chunks_mut::<2>().0 { - sample.swap(0, 1); - } - } - bytes - }; - - let components = u16::try_from(component_count).map_err(|_| format!("{component_count} components"))?; - let input = J2kLosslessSamples { data: &bytes, width, height, components, bit_depth: depth, signed: false }; - let codestream = encode_j2k_lossless(input, &J2kLosslessEncodeOptions::default()).map_err(|error| error.to_string())?.codestream; - drop(bytes); - if !jp2 { - return Ok(codestream); - } - - // The last component of LA and RGBA is opacity, for the whole image - let color_count = if component_count >= 3 { 3 } else { 1 }; - let definitions: Vec = (0..components) - .map(|channel_index| { - if channel_index < color_count { - J2kChannelDefinition { - channel_index, - channel_type: J2kChannelType::Color, - association: J2kChannelAssociation::Color { index: channel_index + 1 }, - } - } else { - J2kChannelDefinition { channel_index, channel_type: J2kChannelType::Opacity, association: J2kChannelAssociation::WholeImage } - } - }) - .collect(); - let mut options = J2kFileWrapOptions::jp2(); - options.color = match icc { - Some(profile) => J2kFileColorSpec::IccProfile(profile), - None if color_count == 3 => J2kFileColorSpec::Enumerated(Colorspace::SRgb), - None => J2kFileColorSpec::Enumerated(Colorspace::Grayscale), - }; - if component_count.is_multiple_of(2) { - options.metadata = J2kFileBoxMetadata { palette: None, component_mappings: &[], channel_definitions: &definitions }; - } - - wrap_j2k_codestream(&codestream, options).map_err(|error| error.to_string()) -} diff --git a/crates/formats/src/export/linear_gray.icc b/crates/formats/src/export/linear_gray.icc deleted file mode 100644 index 1b338b34097128d0de61b17293e7031fc2859e4f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 460 zcmZQzU_6tPoLkH!z`&53S5o92_s-M{+??2?GOT4v=kCUQz&JuK=<|vO|KLf$Tj%HXl?ykjWq) zl3GzxT9oQsl$chc;FFn`npmXZUX)m=py6U_pb1g}0`d$Y45 MapRenderer<'a> { } let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect(); - // Raw J2K reports the missing tag even for a grayscale colour map - let embed = (options.color_space.is_some() && map.is_color() && (component_count >= 3 || format == FileFormat::J2k)).then_some(space); + // A colour space the user chose is written into the colour maps (data maps have none) + let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space); Ok(RenderedMap { data, size, component_count, srgb, embed }) } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 7e0afcb3..03de7767 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -26,7 +26,6 @@ use texturecraft_texel::{ColorSpace, linear_to_srgb}; use crate::{FormatError, MAX_IMAGE_SIZE, Result}; mod encoding; -mod jpeg2000; mod layered_psd; mod map_override; mod map_preview; @@ -106,19 +105,15 @@ pub enum FileFormat { Pgm, /// Photoshop document: every output map of a texture set in this format as a layer of one file Psd, - /// JPEG 2000 codestream, lossless - J2k, - /// JPEG 2000 in a JP2 file, lossless - Jp2, } impl FileFormat { /// Whether the texture can be referenced by the USD asset exporter. pub fn usable_by_usd_asset(self) -> bool { - !matches!(self, Self::Psd | Self::J2k | Self::Jp2) + self != Self::Psd } - pub const ALL: [FileFormat; 13] = [ + pub const ALL: [FileFormat; 11] = [ FileFormat::Png, FileFormat::Jpeg, FileFormat::Tga, @@ -130,8 +125,6 @@ impl FileFormat { FileFormat::Jng, FileFormat::Pgm, FileFormat::Psd, - FileFormat::J2k, - FileFormat::Jp2, ]; pub fn extension(self) -> &'static str { @@ -147,8 +140,6 @@ impl FileFormat { FileFormat::Jng => "jng", FileFormat::Pgm => "pgm", FileFormat::Psd => "psd", - FileFormat::J2k => "j2k", - FileFormat::Jp2 => "jp2", } } @@ -176,7 +167,7 @@ impl FileFormat { /// float for TIFF and HDR). pub fn bit_depths(self) -> &'static [u8] { match self { - FileFormat::Png | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2 => &[8, 16], + FileFormat::Png | FileFormat::Pgm | FileFormat::Psd => &[8, 16], FileFormat::Tiff => &[8, 16, 32], FileFormat::Exr => &[16, 32], FileFormat::Hdr => &[32], @@ -1402,7 +1393,7 @@ fn encode( // Embed ICC or EXR chromaticities only where the format supports them if let Some(space) = embed - && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::J2k) + && matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng) { warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name())); } @@ -1504,20 +1495,6 @@ fn encode( FileFormat::Webp => CodecFormat::WebP, FileFormat::Pgm => CodecFormat::Pnm, FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)), - FileFormat::J2k | FileFormat::Jp2 => { - let jp2 = format == FileFormat::Jp2; - let gray = component_count <= 2; - let profile = if jp2 && !gray { - let linear_rgb = srgb.iter().take(3).all(|encoded| !encoded); - embed.or(linear_rgb.then_some(ColorSpace::LinearRec709)).and_then(crate::icc::profile) - } else { - None - }; - let linear_gray = jp2 && gray && !srgb.first().copied().unwrap_or(false); - let icc = profile.as_deref().or(linear_gray.then_some(jpeg2000::LINEAR_GRAY_PROFILE)); - - return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, icc).map_err(|error| encoding_error(&error)); - } FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")), FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")), }; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index a7e6fcb0..355b0ec9 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -366,9 +366,8 @@ fn every_format_encodes_and_decodes() { let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); preset.maps.push(gray_alpha); - // JNG, PGM, PSD and JPEG 2000 have tests of their own (the image crate reads none of them) - let own_tests = |format: &FileFormat| matches!(format, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd | FileFormat::J2k | FileFormat::Jp2); - for format in FileFormat::ALL.into_iter().filter(|format| !own_tests(format)) { + // JNG, PGM and PSD have tests of their own (the image crate reads none of them) + for format in FileFormat::ALL.into_iter().filter(|f| !matches!(f, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd)) { for &depth in format.bit_depths() { let mut opts = ExportOptions::new(preset.clone()); opts.format_override = Some(format); @@ -948,7 +947,7 @@ fn exr_carries_the_chromaticities_of_the_space() { #[test] fn formats_without_a_place_for_a_colour_space_say_so() { let data = vec![0.25f32; 4 * 4 * 3]; - for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr, FileFormat::J2k] { + for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] { let mut warnings = Vec::new(); encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}"); @@ -1456,154 +1455,6 @@ fn jng_has_jpeg_colour_and_lossless_alpha() { assert!(!gray.bytes.windows(4).any(|w| w == b"IDAT")); } -/// A JPEG 2000 file's component planes -fn jpeg2000_planes(bytes: &[u8]) -> Vec> { - let mut decoder = j2k::J2kDecoder::new(bytes).unwrap(); - let decoded = decoder.decode_native_components().unwrap(); - decoded - .planes() - .iter() - .map(|plane| match plane.bytes_per_sample() { - 1 => plane.data().iter().map(|byte| u16::from(*byte)).collect(), - _ => plane.data().chunks(2).map(|pair| u16::from_le_bytes([pair[0], pair[1]])).collect(), - }) - .collect() -} - -#[test] -fn jpeg2000_is_lossless_at_8_and_16_bits() { - let fx = Fx::new(&[Channel::BaseColor, Channel::Opacity, Channel::Roughness, Channel::Metallic, Channel::Normal]); - let preset = builtin_preset("glTF PBR Metal Roughness").unwrap(); - let jp2_signature = [0, 0, 0, 12, b'j', b'P', b' ', b' ']; - let codestream_signature = [0xFF, 0x4F, 0xFF, 0x51]; - for depth in [8u8, 16] { - let mut png_options = ExportOptions::new(preset.clone()); - png_options.bit_depth_override = Some(depth); - let png = fx.render(&png_options); - for format in [FileFormat::J2k, FileFormat::Jp2] { - let mut options = png_options.clone(); - options.format_override = Some(format); - let files = fx.render(&options); - - assert_eq!(files.len(), png.len()); - - for (file, reference) in files.iter().zip(&png) { - assert!(file.name.ends_with(format.extension()), "{}", file.name); - let signature: &[u8] = if format == FileFormat::Jp2 { &jp2_signature } else { &codestream_signature }; - - assert!(file.bytes.starts_with(signature), "{}", file.name); - - // Every sample is the PNG's, with alpha the last component - let image = decode(reference); - let components = usize::from(image.color().channel_count()); - let expected = image.to_rgba16(); - let planes = jpeg2000_planes(&file.bytes); - let info = j2k::J2kDecoder::inspect_support(&file.bytes).unwrap(); - - assert_eq!(info.components.len(), components, "{}", file.name); - for (component, declared) in info.components.iter().enumerate() { - assert_eq!(declared.bit_depth, depth, "{} component {component} precision", file.name); - } - assert_eq!(planes.len(), components, "{}", file.name); - for (component, plane) in planes.iter().enumerate() { - assert_eq!(plane.len(), expected.pixels().len(), "{} component {component}", file.name); - let source = if components <= 2 && component == 1 { 3 } else { component }; - for (texel, sample) in expected.pixels().zip(plane) { - let want = if depth == 8 { texel[source] / 257 } else { texel[source] }; - - assert_eq!(*sample, want, "{} component {component}", file.name); - } - } - } - } - } -} - -#[test] -fn jp2_declares_linear_storage_for_rgb_data_maps() { - let fx = Fx::new(&default_channels()); - let mut options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap()); - options.format_override = Some(FileFormat::Jp2); - let linear = crate::icc::profile(ColorSpace::LinearRec709).unwrap(); - - let files = fx.render(&options); - let has_linear_profile = |file: &ExportedFile| file.bytes.windows(linear.len()).any(|bytes| bytes == linear); - - assert!(has_linear_profile(find(&files, "_OcclusionRoughnessMetallic"))); - assert!(has_linear_profile(find(&files, "_Normal"))); - assert!(!has_linear_profile(find(&files, "_BaseColor"))); -} - -#[test] -fn feedback_jp2_grayscale_declares_the_transfer_applied_to_samples() { - use j2k::{J2kChannelAssociation, J2kChannelType, J2kColorSpec}; - - let fx = Fx::new(&default_channels()); - for format in [FileFormat::J2k, FileFormat::Jp2] { - for depth in [8, 16] { - for alpha in [false, true] { - for linear in [true, false] { - let channel = if linear { Channel::Roughness } else { Channel::BaseColor }; - let mut channels = vec![(Dest::L, SourceRef::Channel { channel, component: 0 })]; - if alpha { - channels.push((Dest::A, SourceRef::Constant(0.5))); - } - - let options = one_map(format, depth, channels); - let reference = fx.render(&ExportOptions { format_override: Some(FileFormat::Png), ..options.clone() }); - let samples = decode(&reference[0]).to_rgba16(); - let exported = fx.render(&options); - let planes = jpeg2000_planes(&exported[0].bytes); - - assert_eq!(planes.len(), 1 + usize::from(alpha)); - for (plane, component) in planes.iter().zip([0, 3]) { - let expected: Vec<_> = samples.pixels().map(|pixel| if depth == 8 { pixel[component] / 257 } else { pixel[component] }).collect(); - assert_eq!(plane, &expected); - } - - let info = j2k::J2kDecoder::inspect_support(&exported[0].bytes).unwrap(); - let metadata = info.file_metadata; - if format == FileFormat::J2k { - assert!(metadata.is_none()); - continue; - } - - let metadata = metadata.unwrap(); - match (&metadata.color_specs[..], linear) { - ([J2kColorSpec::IccProfile { profile }], true) => { - assert_eq!(&profile[16..24], b"GRAYXYZ "); - let word = |at| u32::from_be_bytes(profile[at..at + 4].try_into().unwrap()) as usize; - let curve_tag = (132..132 + 12 * word(128)).step_by(12).find(|&at| &profile[at..at + 4] == b"kTRC").unwrap(); - let curve = word(curve_tag + 4); - assert_eq!(&profile[curve..curve + 4], b"curv"); - assert_eq!(word(curve + 8), 1); - assert_eq!(&profile[curve + 12..curve + 14], &0x0100u16.to_be_bytes(), "gamma 1.0"); - } - ([J2kColorSpec::Enumerated { value: 17 }], false) => {} - (spec, _) => panic!("wrong grayscale colour declaration for linear={linear}: {spec:?}"), - } - if alpha { - assert!(metadata.channel_definitions.iter().any(|definition| definition.channel_index == 1 - && definition.channel_type == J2kChannelType::Opacity - && definition.association == J2kChannelAssociation::WholeImage)); - } - } - } - } - } -} - -#[test] -fn jp2_records_a_chosen_colour_space_as_an_icc_profile() { - let data = vec![0.25f32; 8 * 8 * 3]; - let profile = crate::icc::profile(ColorSpace::AcesCg).unwrap(); - let mut warnings = Vec::new(); - let bytes = - encode(Encoding { format: FileFormat::Jp2, depth: 8, dither: false }, (8, 8), 3, data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap(); - assert!(bytes.windows(profile.len()).any(|window| window == profile.as_slice()), "the profile is in the file"); - assert!(warnings.is_empty(), "{warnings:?}"); -} - #[test] fn tiff_32f_holds_linear_floats() { let fx = Fx::new(&default_channels()); @@ -2382,29 +2233,3 @@ fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { assert!(list_set_outputs(&fx.project, &[1], "sphere", &options).is_ok()); assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_err(), "the budget includes all selected sets"); } - -#[test] -fn feedback_j2k_warns_for_explicit_gray_and_rgb_colour_spaces() { - let fx = Fx::new(&default_channels()); - let base = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; - let gray = vec![(Dest::L, base(0))]; - let rgb = vec![(Dest::R, base(0)), (Dest::G, base(1)), (Dest::B, base(2))]; - - for (channels, selected, expected) in [ - (gray.clone(), Some(ColorSpace::LinearRec709), Some(ColorSpace::LinearRec709)), - (gray, Some(ColorSpace::AcesCg), Some(ColorSpace::LinearRec709)), - (rgb, Some(ColorSpace::Srgb), Some(ColorSpace::Srgb)), - (roughness(), None, None), - ] { - let mut options = one_map(FileFormat::J2k, 8, channels); - options.color_space = selected; - - let files = fx.render(&options); - let warnings: Vec<_> = files[0].warnings.iter().filter(|warning| warning.contains("J2K export does not embed")).collect(); - - assert_eq!(warnings.len(), usize::from(expected.is_some()), "warnings: {:?}", files[0].warnings); - if let Some(space) = expected { - assert!(warnings[0].ends_with(space.name())); - } - } -} diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 2a03b8f1..1ccbdb67 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -386,12 +386,12 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: /// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion, /// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has /// no data for. `project_normal` is the project's normal convention, used by normal maps that -/// follow it. Layered PSD files and JPEG 2000 files are omitted. +/// follow it. Layered PSD files are omitted. pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec { let mut out: Vec = Vec::new(); let mut seen_maps = Vec::new(); for file in files { - // PSD stores several maps and OpenUSD's default reader has no JPEG 2000 support + // PSD stores several maps in one file if !file.format.usable_by_usd_asset() { continue; } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 9cc30594..6772698d 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -229,8 +229,8 @@ pub(crate) const FILE_TYPES: [(&str, Option); 14] = [ ("tiff", Some(FileFormat::Tiff)), ("hdr", Some(FileFormat::Hdr)), ("exr", Some(FileFormat::Exr)), - ("j2k", Some(FileFormat::J2k)), - ("jp2", Some(FileFormat::Jp2)), + ("j2k", None), + ("jp2", None), ("webp", Some(FileFormat::Webp)), ("psd", Some(FileFormat::Psd)), ("sbsar", None), diff --git a/crates/ui-egui/tests/it/export_file_types.rs b/crates/ui-egui/tests/it/export_file_types.rs index 682f3625..8967fe80 100644 --- a/crates/ui-egui/tests/it/export_file_types.rs +++ b/crates/ui-egui/tests/it/export_file_types.rs @@ -46,23 +46,22 @@ fn entries(h: &Harness<'_, TextureCraftApp>, labels: &[&str]) -> Vec { const TYPES: [&str; 14] = ["bmp", "jpeg", "jng", "pgm", "png", "targa", "tiff", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"]; #[test] -fn the_file_type_list_is_the_reference_one_with_sbsar_greyed() { +fn the_file_type_list_is_the_reference_one_with_three_greyed() { let mut h = harness(); open_combo(&mut h, "Based on output template"); - assert_eq!(entries(&h, &TYPES), TYPES.map(String::from).to_vec()); - assert!(h.get_all_by_label("sbsar").last().unwrap().accesskit_node().is_disabled(), "sbsar is greyed"); - h.get_all_by_label("sbsar").last().unwrap().scroll_to_me(); - h.run_steps(6); - let at = h.get_all_by_label("sbsar").last().unwrap().rect().center(); - h.hover_at(at); - h.run_steps(30); - - assert!(h.query_by_label("Not available yet").is_some(), "sbsar at {at:?}"); - for name in ["j2k", "jp2", "psd"] { - assert!(!h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} can be picked"); + // Bottom up, so no tooltip covers the next entry + for name in ["sbsar", "jp2", "j2k"] { + assert!(h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} is greyed"); + h.get_all_by_label(name).last().unwrap().scroll_to_me(); + h.run_steps(6); + let at = h.get_all_by_label(name).last().unwrap().rect().center(); + h.hover_at(at); + h.run_steps(30); + assert!(h.query_by_label("Not available yet").is_some(), "{name} at {at:?}"); } + assert!(!h.get_all_by_label("psd").last().unwrap().accesskit_node().is_disabled()); } #[test] diff --git a/docs/control-protocol.md b/docs/control-protocol.md index faaf80c0..07f933bd 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -80,7 +80,7 @@ and names it in `warnings`. Materials omit any map with incomplete tiles or a UD shared by different sets. `format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`, -`hdr`, `exr`, `j2k`, `jp2`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for +`hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and `export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `export.preview` takes the same parameters plus `map` (an index into the template's maps) and @@ -93,8 +93,8 @@ channel defaults. `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. -Layered PSD and JPEG 2000 maps are written as requested. MaterialX uses compatible companion -maps for these formats. USD omits their texture bindings and returns a warning. +Layered PSD maps are written as requested. MaterialX uses compatible companion maps for this +format. USD omits their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus diff --git a/docs/features.md b/docs/features.md index edc6c265..a7e2f0b9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -164,7 +164,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in - PNG, JPEG, JPEG 2000, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 + PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16 bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation, infinite, or dilation + diffusion), size override and OpenGL or DirectX normals. - **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion, From 5032edca95685d46b4d7bede889432937f21d8c0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:48:11 +0000 Subject: [PATCH 18/34] Export: PSD memory budgets only in the browser; a desktop PSD renders a layer at a time An 8192 PSD of one map and a 4096 "Separate maps" PSD were refused on desktop by the 2 GiB working budget and the 1 GiB batch budget, which main never had (review on #827). Both budgets are now a browser tab's only (PsdBudget::WEB on wasm32); the 30000 px side and 2 GiB file limits stay everywhere. The merged image is no longer a floating-point canvas: it is built a row at a time from the quantized layers, so only the layer being rendered is in floating point. Peak working bytes by the code's own accounting (default infinite padding): - 8192, one map, 8-bit: 2.75 GiB (2 GiB source and layer, 512 MiB file, 256 MiB padding); before, 3.75 GiB with the 1 GiB float canvas - 4096, "Separate maps" on the default 5-channel set: 2.31 GiB at its 16-bit document depth, 1.19 GiB in 8-bit (the encoder's 3x file bytes dominate) A PSD that cannot be planned no longer stops the set's other files: list_outputs leaves it out with a warning on the set's first file, and is an error only when the PSD was the set's only output. --- crates/formats/src/export/layered_psd.rs | 97 +++++++++++++++++++----- crates/formats/src/export/mod.rs | 59 ++++++++++---- crates/formats/src/export/psd_budget.rs | 17 +++++ crates/formats/src/export/tests.rs | 71 +++++++++++++---- 4 files changed, 195 insertions(+), 49 deletions(-) create mode 100644 crates/formats/src/export/psd_budget.rs diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index f8982036..951a18ef 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -15,17 +15,34 @@ use crate::{FormatError, Result}; /// Where alpha sits in an RGBA texel const ALPHA_INDEX: usize = 3; -/// Budget for the pixel buffers of one PSD export, including the renderer's padding and encoder -const MAX_PSD_WORKING_BYTES: u64 = 2 * 1024 * 1024 * 1024; - -/// Check file and working memory limits, returning the canvas size and estimated encoded bytes. +/// Check the file limits and the working memory against `working_limit` (None: unlimited), returning the canvas size and estimated encoded bytes pub(super) fn preflight<'a>( set: &TextureSet, options: &ExportOptions, tile: Option, depth: u8, layers: impl Iterator + Clone, + working_limit: Option, ) -> Result<((u32, u32), u64)> { + let (canvas, file_bytes, working_bytes) = working_set(set, options, tile, depth, layers)?; + if working_limit.is_some_and(|limit| working_bytes >= limit) { + let (width, height) = canvas; + return Err(FormatError::Invalid(format!( + "a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format" + ))); + } + + Ok((canvas, file_bytes)) +} + +/// The canvas size, estimated encoded bytes and peak working bytes of one PSD, after checking the file limits +fn working_set<'a>( + set: &TextureSet, + options: &ExportOptions, + tile: Option, + depth: u8, + layers: impl Iterator + Clone, +) -> 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))); @@ -33,7 +50,9 @@ pub(super) fn preflight<'a>( 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 largest_layer_bytes = sizes.map(texels).max().unwrap_or(0) * float_bytes_per_texel; - let composite_bytes = texels(canvas) * float_bytes_per_texel; + + // The merged image is built a row at a time: a canvas row and a layer row in floating point + let merge_bytes = 2 * u64::from(canvas.0) * float_bytes_per_texel; // Resizing overlaps source and destination, and RGBA conversion can overlap two output buffers let mut scratch_bytes = source_bytes.saturating_add(largest_layer_bytes).max(2 * largest_layer_bytes); @@ -52,34 +71,24 @@ pub(super) fn preflight<'a>( padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::()) as u64)); } - // The encoder can hold staged pixels, planes and the output at once - let rendering = scratch_bytes.saturating_add(composite_bytes).saturating_add(file_bytes); + // 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 + 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); - if working_bytes >= MAX_PSD_WORKING_BYTES { - let (width, height) = canvas; - return Err(FormatError::Invalid(format!( - "a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format" - ))); - } - - Ok((canvas, file_bytes)) + Ok((canvas, file_bytes, working_bytes)) } /// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas. pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u32, u32)) -> Result { let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned; - // Keep only the current layer in floating point alongside the merged image - let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES]; + // Only the current layer is in floating point; the others are kept as the file stores them let mut pixels = Vec::with_capacity(layers.len()); let mut embedded = None; for layer in layers.iter().rev() { let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; embedded = map.embed.or(embedded); let rgba = to_rgba(map.data, map.component_count, &map.srgb); - over(&mut composite, size.0, &rgba, map.size.0); - let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; let layer_pixels = pixel_data(rgba, map.size.0, encoding)?; pixels.push((layer.name.as_str(), map.size, layer_pixels)); @@ -88,8 +97,7 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name())); } - let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: false }; - let composite = pixel_data(composite, size.0, encoding)?; + let composite = merged_image(size, bit_depth, &pixels)?; let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?; if bytes.len() as u64 >= PSD_MAX_FILE_BYTES { @@ -129,6 +137,53 @@ fn to_rgba(mut data: Vec, component_count: usize, srgb: &[bool]) -> Vec Result { + let row_len = width as usize * PSD_RGBA_PLANES; + let sample_count = row_len * height as usize; + let mut merged_row = vec![0.0f32; row_len]; + let mut layer_row = Vec::with_capacity(row_len); + let reserve_error = |error| FormatError::Invalid(format!("PSD merged image allocation failed: {error}")); + if depth == 16 { + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(merged_row.iter().map(|&value| quantize_u16(value))); + } + return Ok(PixelData::Rgba16(merged)); + } + + let mut merged = Vec::new(); + merged.try_reserve_exact(sample_count).map_err(reserve_error)?; + let encoding = Encoding { format: FileFormat::Psd, depth, dither: false }; + for y in 0..height as usize { + merge_row(y, width, layers, &mut merged_row, &mut layer_row); + merged.extend(quantize_integer(encoding, width, PSD_RGBA_PLANES, merged_row.iter().copied())?); + } + Ok(PixelData::Rgba8(merged)) +} + +/// Row `y` of the merged image into `merged_row`, each layer's row decoded into `layer_row` in turn +fn merge_row(y: usize, width: u32, layers: &[(&str, (u32, u32), PixelData)], merged_row: &mut [f32], layer_row: &mut Vec) { + merged_row.fill(0.0); + for (_, (layer_width, layer_height), samples) in layers { + if y >= *layer_height as usize { + continue; + } + + let span = *layer_width as usize * PSD_RGBA_PLANES; + let range = y * span..(y + 1) * span; + layer_row.clear(); + match samples { + PixelData::Rgba8(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u8::MAX))), + PixelData::Rgba16(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u16::MAX))), + _ => continue, + } + over(merged_row, width, layer_row, *layer_width); + } +} + /// Composite a straight-alpha RGBA layer at the top left of the canvas. fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) { let canvas_rows = canvas.chunks_exact_mut(canvas_width as usize * PSD_RGBA_PLANES); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 03de7767..e7eafd58 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -31,12 +31,14 @@ mod map_override; mod map_preview; mod map_renderer; mod planned_layer; +mod psd_budget; mod rendered_map; use encoding::Encoding; pub use map_override::MapOverride; pub use map_preview::{MAX_PREVIEW_SIDE, MapPreview}; use map_renderer::MapRenderer; pub use planned_layer::PlannedLayer; +use psd_budget::PsdBudget; /// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture /// width tilts the normal 45°, at any resolution. @@ -44,8 +46,6 @@ const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; const PSD_MAX_SIDE_PIXELS: u32 = 30_000; const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024; -/// Bound retained PSD payloads before rendering, with headroom for a document's working buffers and ZIP packaging -const MAX_PSD_BATCH_BYTES: u64 = 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). @@ -716,6 +716,11 @@ pub fn sanitize_file_path(s: &str) -> String { /// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_outputs(project, ts, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_outputs`] with the PSD memory limits of `budget` +fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { opts.preset.validate()?; let set = project.texture_set(ts)?; for requested_size in opts.size.iter().chain(opts.maps.values().filter_map(|own| own.size.as_ref())) { @@ -832,13 +837,12 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export let mut tiled_bases = HashMap::new(); // Each tile's PSD maps are the layers of one file named after the texture set + let mut psd_failures = Vec::new(); for (&tile, in_tile) in tiles.iter().zip(psd_layers) { let Some((first_layer, ..)) = in_tile.first() else { continue }; let first_map = first_layer.map; let bit_depth = in_tile.iter().map(|(_, depth, _)| *depth).max().unwrap_or(8); - layered_psd::preflight(set, opts, tile, bit_depth, in_tile.iter().map(|(layer, ..)| layer))?; - let mut warnings = Vec::new(); let mut layers = Vec::with_capacity(in_tile.len()); let mut dither_requested = false; @@ -866,11 +870,26 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export (untiled_psd_stem(project, mesh_name, ts, set, opts.atlas), None) }; let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings); + if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) { + psd_failures.push((name, error)); + continue; + } + claim_path(&mut active_files, &mut active_dirs, &name)?; let udim_name = udim_stem.map(|stem| format!("{stem}{renamed}.{ext}")); let dither = bit_depth == 8 && dither_requested; out.push(PlannedFile { name, map: first_map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers }); } + + // A PSD that cannot be written leaves the set's other files to export, its reason a warning on the first of them + for (name, error) in psd_failures { + let Some(first) = out.first_mut() else { return Err(error) }; + let reason = match error { + FormatError::Invalid(reason) | FormatError::TooLarge(reason) => reason, + other => other.to_string(), + }; + first.warnings.push(format!("\"{name}\" was not written: {reason}")); + } Ok(out) } @@ -933,16 +952,21 @@ fn psd_size(set: &TextureSet, tile: Option, export_size: Option) -> (u /// Plan a selection in export order, keeping only the first case-insensitive use of a name. pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result> { + plan_set_outputs(project, sets, mesh_name, opts, PsdBudget::TARGET) +} + +/// [`list_set_outputs`] with the PSD memory limits of `budget` +fn plan_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions, budget: PsdBudget) -> Result> { let mut files = Vec::new(); for &index in sets { - let planned = list_outputs(project, index, mesh_name, opts)?; + let planned = plan_outputs(project, index, mesh_name, opts, budget)?; files.extend(planned.into_iter().map(|file| (index, file))); } let files = keep_first_planned_names(files); let mut psd_bytes = 0; for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { - check_psd_batch(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes)?; + check_psd_batch_within(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes, budget)?; } Ok(files) @@ -1118,21 +1142,25 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result Result<()> { + check_psd_batch_within(set, options, planned, total_bytes, PsdBudget::TARGET) +} + +fn check_psd_batch_within(set: &TextureSet, options: &ExportOptions, planned: &[PlannedFile], total_bytes: &mut u64, budget: PsdBudget) -> Result<()> { let mut estimate = *total_bytes; for file in planned.iter().filter(|file| file.format == FileFormat::Psd) { - let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; - add_psd_batch_bytes(&mut estimate, file_bytes)?; + let (_, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut estimate, file_bytes, budget.batch_bytes)?; } *total_bytes = estimate; Ok(()) } -fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64) -> Result<()> { +fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64, limit: Option) -> Result<()> { let estimate = total_bytes.saturating_add(file_bytes); - if estimate > MAX_PSD_BATCH_BYTES { + if limit.is_some_and(|limit| estimate > limit) { return Err(FormatError::TooLarge("total PSD output would exceed 1 GiB; use a smaller export size, fewer PSD maps or separate exports".into())); } @@ -1142,6 +1170,11 @@ fn add_psd_batch_bytes(total_bytes: &mut u64, file_bytes: u64) -> Result<()> { /// Render the retained plans from `list_outputs` for this input and these options. pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec) -> Result> { + render_planned_maps_within(input, options, planned, PsdBudget::TARGET) +} + +/// [`render_planned_maps`] with the PSD memory limits of `budget` +fn render_planned_maps_within(input: &ExportInput, options: &ExportOptions, planned: Vec, budget: PsdBudget) -> Result> { if planned.is_empty() { return Ok(Vec::new()); } @@ -1161,8 +1194,8 @@ pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned let mut psd_bytes = 0; for file in &planned { if file.format == FileFormat::Psd { - let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter())?; - add_psd_batch_bytes(&mut psd_bytes, file_bytes)?; + let (size, file_bytes) = layered_psd::preflight(set, options, file.tile, file.bit_depth, file.layers.iter(), budget.working_bytes)?; + add_psd_batch_bytes(&mut psd_bytes, file_bytes, budget.batch_bytes)?; psd_sizes.push(Some(size)); } else { psd_sizes.push(None); diff --git a/crates/formats/src/export/psd_budget.rs b/crates/formats/src/export/psd_budget.rs new file mode 100644 index 00000000..e6300254 --- /dev/null +++ b/crates/formats/src/export/psd_budget.rs @@ -0,0 +1,17 @@ +/// The memory limits PSD planning holds an export to: a browser tab's address space needs them, a native export renders one layer at a time without them +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct PsdBudget { + /// Pixel buffers of one document, including the renderer's padding and encoder + pub(super) working_bytes: Option, + /// Encoded documents one batch holds in memory, with headroom for a document's working buffers and ZIP packaging + pub(super) batch_bytes: Option, +} + +impl PsdBudget { + /// A browser tab's: the export and the app share its 4 GiB address space + pub(super) const WEB: Self = Self { working_bytes: Some(2 * 1024 * 1024 * 1024), batch_bytes: Some(1024 * 1024 * 1024) }; + /// A desktop export's: the machine bounds it, as it does every other file type + pub(super) const NATIVE: Self = Self { working_bytes: None, batch_bytes: None }; + /// The budget of the platform this build runs on + pub(super) const TARGET: Self = if cfg!(target_arch = "wasm32") { Self::WEB } else { Self::NATIVE }; +} diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 355b0ec9..f6035d35 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1350,11 +1350,45 @@ fn feedback_psd_rejects_large_working_set_during_planning() { let mut options = one_map(FileFormat::Psd, 8, rgba_half_alpha()); options.size = Some(8192); - let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err(); + let error = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err(); assert!(error.to_string().contains("working memory"), "{error}"); options.size = Some(4096); - assert!(list_outputs(&fx.project, 0, "sphere", &options).is_ok()); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).is_ok()); +} + +#[test] +fn a_native_export_plans_psds_a_browser_tab_cannot_hold() { + let mut fx = Fx::new(&default_channels()); + let mut one = one_map(FileFormat::Psd, 8, rgba_half_alpha()); + one.size = Some(MAX_IMAGE_SIZE / 2); + let mut separate = ExportOptions::new(builtin_preset("Separate maps").unwrap()); + separate.format_override = Some(FileFormat::Psd); + separate.size = Some(4096); + fx.project.texture_sets[0].uv_tiles = (1001..1005).collect(); + + let plans = [list_outputs(&fx.project, 0, "sphere", &one), list_outputs(&fx.project, 0, "sphere", &separate)]; + + for plan in plans { + let plan = plan.unwrap(); + assert!(!plan.is_empty() && plan.iter().all(|file| file.format == FileFormat::Psd), "{plan:?}"); + } + assert!(list_set_outputs(&fx.project, &[0], "sphere", &separate).is_ok(), "a desktop batch holds every tile's PSD"); +} + +#[test] +fn a_psd_that_cannot_be_planned_leaves_the_sets_other_maps() { + let fx = Fx::new(&default_channels()); + 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, 16, rgba_half_alpha()); + options.preset.maps.push(psd); + options.size = Some(MAX_IMAGE_SIZE); + + let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap(); + + assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}"); + assert!(plan[0].warnings.iter().any(|warning| warning.contains(".psd") && warning.contains("2 GiB")), "{:?}", plan[0].warnings); } #[test] @@ -1397,7 +1431,7 @@ fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() { assert!(error.to_string().contains("2 GiB"), "{error}"); options.size = Some(4096); - assert!(list_outputs(&fx.project, 0, "sphere", &options).unwrap_err().to_string().contains("working memory")); + assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err().to_string().contains("working memory")); options.atlas = false; assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 3); } @@ -2184,18 +2218,19 @@ fn psd_batch_budget_counts_only_retained_documents() { other.name = "Other".into(); fx.project.texture_sets.push(other); - let once = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); - let repeated = list_set_outputs(&fx.project, &[0, 0], "sphere", &options).unwrap(); - let distinct = list_set_outputs(&fx.project, &[0, 1], "sphere", &options); + let once = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap(); + let repeated = plan_set_outputs(&fx.project, &[0, 0], "sphere", &options, PsdBudget::WEB).unwrap(); + let distinct = plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB); let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); assert_eq!(once.len(), repeated.len()); assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len())); assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD"))); println!( - "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {MAX_PSD_BATCH_BYTES}", + "PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {:?}", bytes_per_tile * once.len() as u64, - bytes_per_tile * (once.len() + repeated.len()) as u64 + bytes_per_tile * (once.len() + repeated.len()) as u64, + PsdBudget::WEB.batch_bytes ); } @@ -2207,29 +2242,35 @@ fn feedback_psd_batch_rejects_large_retained_output_before_rendering() { options.size = Some(4096); fx.project.texture_sets[0].uv_tiles = (1001..1008).collect(); - let smaller = list_set_outputs(&fx.project, &[0], "sphere", &options).unwrap(); + 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 = list_set_outputs(&fx.project, &[0], "sphere", &options); + 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]; let (width, height) = set.size(); fx.comp = Composite::with_size(&default_channels(), width, height); fx.coverage.resize((width * height) as usize, true); - let error = render_maps(&fx.input(), &options).unwrap_err(); + let planned = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap(); + let error = render_planned_maps_within(&fx.input(), &options, planned, PsdBudget::WEB).unwrap_err(); assert!(error.to_string().contains("total PSD"), "{error}"); let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap(); - println!("PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {MAX_PSD_BATCH_BYTES}", estimated_bytes * 33); + println!( + "PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {:?}", + estimated_bytes * 33, + PsdBudget::WEB.batch_bytes + ); let mut small = fx.project.texture_sets[0].clone(); small.uv_tiles = (1001..1006).collect(); fx.project.texture_sets[0] = small.clone(); small.name = "Other".into(); fx.project.texture_sets.push(small); - assert!(list_set_outputs(&fx.project, &[0], "sphere", &options).is_ok()); - assert!(list_set_outputs(&fx.project, &[1], "sphere", &options).is_ok()); - assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_err(), "the budget includes all selected sets"); + assert!(plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[1], "sphere", &options, PsdBudget::WEB).is_ok()); + assert!(plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB).is_err(), "the budget includes all selected sets"); + assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_ok(), "a desktop batch has no such budget"); } From 67ac6e65e4bacc2107e5c4ed39ae48081415d73e Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:32 +0000 Subject: [PATCH 19/34] Export: a glTF specular/glossiness file stays RGBA without a glossiness channel KHR_materials_pbrSpecularGlossiness reads glossiness from the specularGlossinessTexture's alpha, so a set with specular but no glossiness wrote an RGB file the extension can't use (review on #827). A glossiness alpha the set lacks is now written fully glossy, the extension's glossinessFactor default of 1. --- crates/formats/src/export/mod.rs | 9 ++++++++- crates/formats/src/export/tests.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index e7eafd58..5ee5768e 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -44,6 +44,8 @@ use psd_budget::PsdBudget; /// width tilts the normal 45°, at any resolution. const HEIGHT_SPAN: f32 = 16.0; const JPEG_QUALITY: u8 = 95; +/// Glossiness a set lacks: the KHR_materials_pbrSpecularGlossiness glossinessFactor default +const MISSING_GLOSSINESS: SourceRef = SourceRef::Constant(1.0); 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 @@ -584,7 +586,12 @@ pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { /// does not have is dropped. fn layout<'m>(set: &TextureSet, map: &'m MapSpec) -> Vec<(Dest, &'m SourceRef)> { let get = |d: Dest| map.channels.iter().find(|(x, _)| *x == d).map(|(_, s)| s); - let alpha = get(Dest::A).filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))); + + // A glossiness alpha stays, fully glossy, so a specular/glossiness file is RGBA without the channel too + let alpha = match get(Dest::A) { + Some(SourceRef::Channel { channel: Channel::Glossiness, .. }) if !set.has_channel(Channel::Glossiness) => Some(&MISSING_GLOSSINESS), + alpha => alpha.filter(|s| !matches!(s, SourceRef::Channel { channel, .. } if !set.has_channel(*channel))), + }; let black = &SourceRef::Constant(0.0); let mut out = match get(Dest::L) { Some(l) => vec![(Dest::L, l)], diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index f6035d35..36d120d9 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2039,6 +2039,18 @@ fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_ch assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}"); } +#[test] +fn the_gltf_specular_glossiness_file_is_rgba_and_fully_glossy_without_a_glossiness_channel() { + let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Normal]); + fx.set_all(Channel::Specular, |_, _| [0.2, 0.5, 0.8]); + + let files = fx.render_preset("glTF Specular Glossiness (archived extension)"); + + let specular_glossiness = find(&files, "_SpecularGlossiness.png"); + assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8, "the extension reads glossiness from alpha"); + assert_eq!(pixel(specular_glossiness)[3], 255, "glossinessFactor defaults to 1"); +} + #[test] fn the_redshift_template_writes_one_map_per_input_the_set_has() { let mut channels = default_channels(); From 254868413eb7add4724bc3a1c37ed25f6c14293f Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:32 +0000 Subject: [PATCH 20/34] Export: the hover preview is no larger than the map's own size MapPreview bounded its side only by the requested side and the composite, so a map with its own size (or a smaller export size) previewed larger than the file it writes (review on #827). The file's longer side, from the map's own size, else the export size, now bounds it too. --- crates/formats/src/export/map_preview.rs | 6 ++++-- crates/formats/src/export/tests.rs | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/export/map_preview.rs b/crates/formats/src/export/map_preview.rs index 282ec063..a4401503 100644 --- a/crates/formats/src/export/map_preview.rs +++ b/crates/formats/src/export/map_preview.rs @@ -50,11 +50,13 @@ impl MapPreview { return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage"))); } + // 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 source_side = composite_width.max(height); - let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(source_side); + 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 tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1); let sampler = Sampler::new(input, options, set, tile_res, uncovered); let mut channel_layout = layout(set, spec); let grayscale = file.format == FileFormat::Pgm; diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 36d120d9..0a252f7f 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -1836,6 +1836,24 @@ fn map_preview_bounds_the_longer_side_of_a_tall_atlas() { assert_eq!(preview.pixels.len(), (preview.width * preview.height) as usize); } +#[test] +fn a_map_preview_is_no_larger_than_the_maps_own_size() { + let fx = Fx::new(&default_channels()); + let mut options = one_map(FileFormat::Png, 8, roughness()); + let own = RES / 4; + options.maps.insert(0, MapOverride { size: Some(own), ..MapOverride::default() }); + let file = decode(&fx.render(&options)[0]); + + let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert_eq!((preview.width, preview.height), file.dimensions(), "the preview shows the file at its own size"); + options.size = Some(RES / 2); + options.maps.clear(); + let export_sized = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap(); + + assert!(export_sized.width > preview.width && export_sized.width < RES, "the export size bounds a map without its own"); +} + #[test] fn a_map_preview_holds_the_values_its_file_stores() { let mut fx = Fx::new(&default_channels()); From abe73ab18035c8ac497cf003ef76b2cd577d21dd Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:32 +0000 Subject: [PATCH 21/34] Export: each greyed bit depth list has its own id disabled_combo took its id from the label alone, so two Output maps rows with a one-depth file type (BMP, JPEG) clashed and shared one accessibility node (review on #827). It is now salted with the row's own id, as the enabled bit depth list is. --- crates/ui-egui/src/export_window.rs | 2 +- crates/ui-egui/src/export_window/drawn.rs | 6 +++--- .../ui-egui/tests/it/export_map_overrides.rs | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 6772698d..3230c7cc 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -298,7 +298,7 @@ fn file_type_lists( let options = parsed.map(depth_options).unwrap_or_default(); let shown = if parsed.is_some() { depth_label(parsed, *bit_depth, *dithering) } else { String::new() }; if options.len() < 2 { - drawn::disabled_combo(ui, rects[1], &shown, tr("Bit depth")); + drawn::disabled_combo(ui, rects[1], ("bits", id), &shown, tr("Bit depth")); return; } diff --git a/crates/ui-egui/src/export_window/drawn.rs b/crates/ui-egui/src/export_window/drawn.rs index ad2604f9..9f92508f 100644 --- a/crates/ui-egui/src/export_window/drawn.rs +++ b/crates/ui-egui/src/export_window/drawn.rs @@ -235,10 +235,10 @@ pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Respo response } -/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim -pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, shown: &str, name: &str) -> Response { +/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim; `id` tells it from the rows' other ones +pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, name: &str) -> Response { let look = ExportLook::get(ui.ctx()); - let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", name)), Sense::hover()); + let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", id)), Sense::hover()); response.widget_info(|| { let mut info = WidgetInfo::labeled(Role::ComboBox, false, name); info.current_text_value = Some(shown.to_owned()); diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 594c2916..2df31472 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -278,3 +278,22 @@ fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() { assert_eq!(image::image_dimensions(&path).unwrap(), (side, side), "{}", path.display()); } } + +#[test] +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() }; + for map in &rows { + o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "bmp".into(), bit_depth: 8, dithering: false }), size: None }); + } + h.state_mut().ui.export.sets.insert(0, o); + h.run_steps(4); + + let greyed: Vec<_> = h.get_all_by_role_and_label(egui::Role::ComboBox, "Bit depth").map(|node| node.accesskit_node().id()).collect(); + + assert_eq!(rows.len(), 2); + assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node"); + assert_ne!(greyed[0], greyed[1]); +} From 2a79b229bbab4c717e2d78adafa0f99c5b35b21b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:33 +0000 Subject: [PATCH 22/34] Export: the desktop shader settings file runs the same name check as the web and headless ones file.exportTextures wrote _shaders.json without checking it against the export's texture paths, which the web download and the headless export do (review on #827). The check is one shared helper, check_shader_parameters_name, run here against this command's files and the earlier commands' reservedNames, so a clash is a warning and the file is not written. --- crates/engine/src/file_cmds.rs | 9 +++++++-- crates/engine/src/shader_parameters.rs | 13 ++++++++++--- crates/engine/tests/it/export_file_types.rs | 20 ++++++++++++++++++++ 3 files changed, 37 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index aa390ad0..13324de1 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -825,11 +825,16 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { written.extend(write_usd_asset(session, dir, exports, &mut warnings)); } if let Some(shader_sets) = shader_sets { - let path = dir.join(crate::shader_parameters::shader_parameters_file(&session.doc.project.name)); + let name = crate::shader_parameters::shader_parameters_file(&session.doc.project.name); + let path = dir.join(&name); let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets); + // Check the name against this command's files and the earlier commands' `reservedNames`, as the web download and headless export do + let roots = written.iter().filter_map(|written| written.strip_prefix(dir).ok()?.components().next()?.as_os_str().to_str()); + let checked = crate::shader_parameters::check_shader_parameters_name(&name, roots.chain(taken_names.keys().map(String::as_str))); + // The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is - let text = serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string()); + let text = checked.and_then(|()| serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string())); match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) { Ok(()) => written.push(path), Err(error) => warnings.push(format!("The shader settings file was not written: {error}")), diff --git a/crates/engine/src/shader_parameters.rs b/crates/engine/src/shader_parameters.rs index 428615b2..12a04674 100644 --- a/crates/engine/src/shader_parameters.rs +++ b/crates/engine/src/shader_parameters.rs @@ -34,12 +34,19 @@ pub fn shader_parameters_file(name: &str) -> String { format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name)) } +/// Refuse the file name `name` when one of the export's texture paths (`/`-separated, relative to the export folder) is that file or lies in a folder of that name, ignoring case +pub fn check_shader_parameters_name<'a>(name: &str, texture_paths: impl IntoIterator) -> std::result::Result<(), String> { + if texture_paths.into_iter().any(|path| path.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(name))) { + return Err(format!("\"{name}\" is already used by a texture file or folder")); + } + + Ok(()) +} + /// Build the download or headless sidecar after checking its name against every texture path. pub fn shader_parameters_sidecar(project: &Project, sets: &[usize], textures: &[ExportedFile]) -> std::result::Result { let name = shader_parameters_file(&project.name); - if textures.iter().any(|texture| texture.name.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(&name))) { - return Err(format!("\"{name}\" is already used by a texture file or folder")); - } + check_shader_parameters_name(&name, textures.iter().map(|texture| texture.name.as_str()))?; let bytes = serde_json::to_vec_pretty(&shader_parameters(project, sets)).map_err(|error| error.to_string())?; Ok(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() }) diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 40e4816f..2240954f 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -96,3 +96,23 @@ fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() { assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{result}"); } + +#[test] +fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let name = texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name); + let reserved = format!("{}/Color.png", name.to_uppercase()); + + let result = execute( + &mut session, + "file.exportTextures", + &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true, "reservedNames": [reserved]}), + ) + .unwrap(); + + assert!(!dir.path().join(&name).exists(), "{result}"); + let warnings = result["warnings"].as_array().unwrap(); + + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}"); +} From 00238575c878ea5dc1a69dfeeaf497e67aa47495 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:42 +0000 Subject: [PATCH 23/34] Export: document PSD file names, layer names and limits A PSD export writes one _.psd per UV tile, and the template's file names become its layer names instead of file names (review on #827). docs/control-protocol.md says so, with the size limits and the browser-only memory budgets. --- docs/control-protocol.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 07f933bd..31d23fd5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -93,8 +93,13 @@ channel defaults. `padding: "diffusion"` dilates by `dilation` texels and fills the remaining space with a smooth blend of the island colours. -Layered PSD maps are written as requested. MaterialX uses compatible companion maps for this -format. USD omits their texture bindings and returns a warning. +Layered PSD: the maps written as `psd` are the layers of one `_.psd` per +texture set and UV tile (`_..psd` for a tiled set), so the template's file +names don't name the file: they become the layer names, a `/` in one making layer groups. A PSD +that would pass 30000 pixels a side or 2 GiB is left out with a warning on the set's first other +file (an error when it is the set's only file); in the browser a PSD's working memory and a batch's +PSD output are also bounded. MaterialX uses compatible companion maps for this format. USD omits +their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus From 982a17c10f2bb6c3616107666f363bfc2ce7b640 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:21:32 +0000 Subject: [PATCH 24/34] Export: the greyed bit depth test uses a one-depth file type and finds the lists by value BMP and JPEG list 8 bits and 8 bits + dithering, so their bit depth list is enabled; the greyed one is HDR's (32f bits only), whose rows clashed. The greyed lists expose their value, not a label, to the accessibility tree, so the test now counts two HDR rows' "32f bits" lists. --- crates/ui-egui/tests/it/export_map_overrides.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 2df31472..497acf60 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -286,12 +286,13 @@ fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() { let template = h.state().ui.export.preset.clone(); let mut o = SetExport { maps_template: template, ..SetExport::default() }; for map in &rows { - o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "bmp".into(), bit_depth: 8, dithering: false }), size: None }); + o.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.run_steps(4); - let greyed: Vec<_> = h.get_all_by_role_and_label(egui::Role::ComboBox, "Bit depth").map(|node| node.accesskit_node().id()).collect(); + let greyed: Vec<_> = + h.get_all_by_role(egui::Role::ComboBox).filter(|node| node.value().as_deref() == Some("32f bits")).map(|node| node.accesskit_node().id()).collect(); assert_eq!(rows.len(), 2); assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node"); From 61c601e040bbbfe089329c5a035203adff619f82 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:33:55 +0000 Subject: [PATCH 25/34] Export: a PSD planning warning outlives the file that carried it when reserved or repeated names drop that file --- crates/engine/src/file_cmds.rs | 22 +++++++++++++------- crates/engine/tests/it/export_file_types.rs | 23 +++++++++++++++++++++ crates/formats/src/export/mod.rs | 17 ++++++++++++--- 3 files changed, 51 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 13324de1..ae004bcf 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -967,8 +967,20 @@ fn reserve_export_names( let mut blocked_maps = HashSet::new(); plans.retain(|plan| { let name = plan.name.to_ascii_lowercase(); - if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) { - blocked_maps.extend(plan.maps()); + let reserved = reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)); + if !reserved && let Entry::Vacant(entry) = taken_names.entry(name) { + entry.insert(Some(set_index)); + return true; + } + + // A set warning outlives the file that carried it + for warning in plan.warnings.iter().filter(|warning| texturecraft_formats::export::is_set_warning(warning)) { + if !warnings.contains(warning) { + warnings.push(warning.clone()); + } + } + blocked_maps.extend(plan.maps()); + if reserved { warnings.push(format!( "\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names", plan.name @@ -976,12 +988,6 @@ fn reserve_export_names( return false; } - if let Entry::Vacant(entry) = taken_names.entry(name) { - entry.insert(Some(set_index)); - return true; - } - - blocked_maps.extend(plan.maps()); if fallback { warnings.push(format!( "MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names", diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 2240954f..d4e16341 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -116,3 +116,26 @@ fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() { assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}"); } + +#[test] +fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]); + let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]); + let preset = json!({"name": "Two and a PSD", "maps": [ + {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, + {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, + {"file": "layered", "format": "Psd", "bit_depth": 16, "channels": colour}, + ]}); + let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": [{"map": 2, "size": 16384}], "reservedNames": reserved}); + let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap(); + let first = plan[0]["file"].as_str().unwrap().to_owned(); + let second = plan[1]["file"].as_str().unwrap().to_owned(); + + let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap(); + + let warnings = result["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))), "{result}"); + assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}"); +} diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 5ee5768e..42328c95 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -895,11 +895,19 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti FormatError::Invalid(reason) | FormatError::TooLarge(reason) => reason, other => other.to_string(), }; - first.warnings.push(format!("\"{name}\" was not written: {reason}")); + first.warnings.push(format!("\"{name}\" {PSD_NOT_WRITTEN}{reason}")); } Ok(out) } +/// What a set's PSD planning failure says after the file name +const PSD_NOT_WRITTEN: &str = "was not written: "; + +/// Whether `warning` is about a PSD of the set that was not planned rather than the file carrying it, so it outlives that file +pub fn is_set_warning(warning: &str) -> bool { + warning.split_once(".psd\" ").is_some_and(|(name, rest)| name.starts_with('"') && rest.starts_with(PSD_NOT_WRITTEN)) +} + /// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added fn unique_name(used: &mut BTreeSet, stem: &str, ext: &str, warnings: &mut Vec) -> (String, String) { let mut name = format!("{stem}.{ext}"); @@ -1764,11 +1772,14 @@ fn keep_first_names(files: impl IntoIterator, name: impl Fn(&T) -> let files = files.into_iter(); let mut first = HashMap::new(); let mut kept = Vec::with_capacity(files.size_hint().0); - for file in files { - let filename = name(&file); + for mut file in files { + let filename = name(&file).to_owned(); match first.entry(filename.to_ascii_lowercase()) { Entry::Occupied(previous) => { + // The later file's set warnings stay with the export + let moved: Vec<_> = warnings(&mut file).extract_if(.., |warning| is_set_warning(warning)).collect(); if let Some(winner) = kept.get_mut(*previous.get()) { + warnings(winner).extend(moved); warnings(winner).push(format!( "\"{}\" of a later texture set has the name of a file an earlier texture set exports, so it was not written; add $textureSet to the template's file names or rename a texture set", filename From 7a41c2c03c1aedc1a75ffa2dd0e7bab99309fb30 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:33:55 +0000 Subject: [PATCH 26/34] Export: say PSD names can be sanitized or disambiguated and point clients to export.plan --- docs/control-protocol.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 31d23fd5..48b63c45 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -95,11 +95,13 @@ channel defaults. Layered PSD: the maps written as `psd` are the layers of one `_.psd` per texture set and UV tile (`_..psd` for a tiled set), so the template's file -names don't name the file: they become the layer names, a `/` in one making layer groups. A PSD -that would pass 30000 pixels a side or 2 GiB is left out with a warning on the set's first other -file (an error when it is the set's only file); in the browser a PSD's working memory and a batch's -PSD output are also bounded. MaterialX uses compatible companion maps for this format. USD omits -their texture bindings and returns a warning. +names don't name the file: they become the layer names, a `/` in one making layer groups. The +document name is sanitized like other file names and can be shortened or disambiguated (a +texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read +the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left +out with a warning on the set's first other file (an error when it is the set's only file); in the +browser a PSD's working memory and a batch's PSD output are also bounded. MaterialX uses +compatible companion maps for this format. USD omits their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus From f304cea242c4485b7ed909b41e74925005362604 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:34:00 +0000 Subject: [PATCH 27/34] Export: describe the browser PSD limits as estimates of PSD buffers and output, not a total memory bound --- docs/control-protocol.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 48b63c45..34f65fec 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -99,9 +99,10 @@ names don't name the file: they become the layer names, a `/` in one making laye document name is sanitized like other file names and can be shortened or disambiguated (a texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left -out with a warning on the set's first other file (an error when it is the set's only file); in the -browser a PSD's working memory and a batch's PSD output are also bounded. MaterialX uses -compatible companion maps for this format. USD omits their texture bindings and returns a warning. +out with a warning on the set's first other file (an error when it is the set's only file). In the +browser, estimates of a PSD's working buffers and of a batch's encoded PSD output are also bounded; +they don't bound the tab's total memory, as raster outputs and ZIP packaging use memory outside +them. MaterialX uses compatible companion maps for this format. USD omits their texture bindings and returns a warning. `effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its stack position, blend, opacity and visibility. Replacement filters start from defaults plus From 6aa412db625925ea20384f134709ab5bed44dada Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:42:53 +0000 Subject: [PATCH 28/34] Export: the PSD warning test plans a too-large PSD within the export size limit --- crates/engine/tests/it/export_file_types.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index d4e16341..341e196c 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -123,19 +123,25 @@ fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { let dir = tempfile::tempdir().unwrap(); let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]); let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]); - let preset = json!({"name": "Two and a PSD", "maps": [ + let mut preset = json!({"name": "Two and a PSD", "maps": [ {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, - {"file": "layered", "format": "Psd", "bit_depth": 16, "channels": colour}, ]}); - let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": [{"map": 2, "size": 16384}], "reservedNames": reserved}); + // Four 16-bit RGBA layers at 8192 pixels and the merged image pass the 2 GiB PSD limit + for layer in 0..4 { + preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour})); + } + let sizes: Vec<_> = (2..6).map(|map| json!({"map": map, "size": 8192})).collect(); + let params = |reserved: Vec| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": sizes, "reservedNames": reserved}); let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap(); let first = plan[0]["file"].as_str().unwrap().to_owned(); let second = plan[1]["file"].as_str().unwrap().to_owned(); + let psd_warning = + |warnings: &serde_json::Value| warnings.as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))); + assert!(plan.as_array().unwrap().len() == 2 && psd_warning(&plan[0]["warnings"]), "{plan}"); let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap(); - let warnings = result["warnings"].as_array().unwrap(); - assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written"))), "{result}"); + assert!(psd_warning(&result["warnings"]), "{result}"); assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}"); } From 48dc4832155fa4344f2e549ceb2f14db7e0ebcbe Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:50:04 +0000 Subject: [PATCH 29/34] Export: a PSD layer is quantized to RGBA as it widens, without a floating-point RGBA copy --- crates/formats/src/export/layered_psd.rs | 63 ++++++++++-------------- crates/formats/src/export/tests.rs | 36 ++++++++++++++ 2 files changed, 62 insertions(+), 37 deletions(-) diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index 951a18ef..af95e664 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -88,9 +88,8 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 for layer in layers.iter().rev() { let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?; embedded = map.embed.or(embedded); - let rgba = to_rgba(map.data, map.component_count, &map.srgb); let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; - let layer_pixels = pixel_data(rgba, map.size.0, encoding)?; + let layer_pixels = rgba_pixel_data(map.data, map.component_count, &map.srgb, map.size.0, encoding)?; pixels.push((layer.name.as_str(), map.size, layer_pixels)); } if let Some(space) = embedded { @@ -107,36 +106,6 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings }) } -/// L, LA, RGB or RGBA samples as RGBA (gray repeated, opaque without alpha), sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 -fn to_rgba(mut data: Vec, component_count: usize, srgb: &[bool]) -> Vec { - let encode = |component: usize, value: f32| if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) }; - - if component_count == PSD_RGBA_PLANES { - for texel in data.as_chunks_mut::().0 { - for (component, value) in texel.iter_mut().enumerate() { - *value = encode(component, *value); - } - } - - return data; - } - - data.chunks_exact(component_count.max(1)) - .flat_map(|texel| { - let encoded = |component| encode(component, texel.get(component).copied().unwrap_or(0.0)); - match component_count { - 1 | 2 => { - let gray = encoded(0); - let alpha = if component_count == 2 { encoded(1) } else { 1.0 }; - [gray, gray, gray, alpha] - } - 3 => [encoded(0), encoded(1), encoded(2), 1.0], - _ => [encoded(0), encoded(1), encoded(2), encoded(3)], - } - }) - .collect() -} - /// The merged image of `layers` (bottom first, as the file stores them), one row at a time fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u32), PixelData)]) -> Result { let row_len = width as usize * PSD_RGBA_PLANES; @@ -206,16 +175,36 @@ fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) } } -/// Quantize directly into the sample type the PSD builder accepts. -fn pixel_data(samples: Vec, width: u32, encoding: Encoding) -> Result { +/// L, LA, RGB or RGBA samples quantized as the RGBA the PSD builder accepts: gray repeated, opaque without alpha, sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn rgba_pixel_data(mut data: Vec, component_count: usize, srgb: &[bool], width: u32, encoding: Encoding) -> Result { + let component_count = component_count.max(1); + for texel in data.chunks_exact_mut(component_count) { + for (component, value) in texel.iter_mut().enumerate() { + *value = if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }; + } + } + + // Widen each texel while quantizing, so no floating-point RGBA copy of the layer is made + let texel_count = data.len() / component_count; + let rgba = (0..texel_count * PSD_RGBA_PLANES).map(|index| { + let (texel, component) = (index / PSD_RGBA_PLANES, index % PSD_RGBA_PLANES); + let source = match component_count { + 1 | 2 if component < ALPHA_INDEX => Some(0), + 1 | 3 if component == ALPHA_INDEX => None, + 2 => Some(1), + _ => Some(component), + }; + source.map_or(1.0, |source| data.get(texel * component_count + source).copied().unwrap_or(0.0)) + }); + if encoding.depth == 16 { let mut pixels = Vec::new(); - pixels.try_reserve_exact(samples.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; - pixels.extend(samples.into_iter().map(quantize_u16)); + pixels.try_reserve_exact(rgba.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; + pixels.extend(rgba.map(quantize_u16)); return Ok(PixelData::Rgba16(pixels)); } - quantize_integer(encoding, width, PSD_RGBA_PLANES, samples.into_iter()).map(PixelData::Rgba8) + quantize_integer(encoding, width, PSD_RGBA_PLANES, rgba).map(PixelData::Rgba8) } /// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 0a252f7f..64fd5115 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2153,6 +2153,42 @@ fn feedback_psd_preview_matches_layer_rgba() { } } +#[test] +fn psd_layers_hold_the_samples_of_the_same_png_at_every_layout_and_depth() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let base_colour = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.pop(); + let layouts = [roughness(), vec![(Dest::L, base_colour(0))], gray_alpha, rgb, rgba_half_alpha()]; + + for channels in layouts { + for (depth, dither) in [(8, false), (8, true), (16, false)] { + let mut png_options = one_map(FileFormat::Png, depth, channels.clone()); + png_options.dither = dither; + let mut psd_options = png_options.clone(); + psd_options.format_override = Some(FileFormat::Psd); + + let png = decode(&fx.render(&png_options)[0]); + let psd = craft_psd::PsdFile::from_bytes(&fx.render(&psd_options)[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap(); + + let context = format!("{channels:?} at {depth} bits, dithering {dither}"); + if depth == 16 { + // Planes of big-endian samples: red, green, blue, then transparency + let planes: Vec> = [0, 1, 2, -1].into_iter().map(|id| layer.channel_bytes(id).unwrap()).collect(); + let texel_count = planes[0].len() / 2; + let samples: Vec = + (0..texel_count).flat_map(|texel| planes.iter().map(move |plane| u16::from_be_bytes([plane[2 * texel], plane[2 * texel + 1]]))).collect(); + assert!(samples == png.to_rgba16().into_raw(), "{context}"); + } else { + assert!(layer.rgba8().unwrap().data == png.to_rgba8().into_raw(), "{context}"); + } + } + } +} + #[test] fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { let mut fx = Fx::new(&default_channels()); From c58fd595471b095e8b5fc92625158df0e633e7cc Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:56:38 +0000 Subject: [PATCH 30/34] Export: a tiled map's UDIM name pattern is expanded once per map, not once per tile --- crates/formats/src/export/mod.rs | 11 +++++++---- crates/formats/src/export/tests.rs | 3 +++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 42328c95..7fe9b6be 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -784,8 +784,11 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti sanitize_file_path(&expanded) }; + // A tiled raster's name with a placeholder for its tile, the same for every tile + let udim_template = (format != FileFormat::Psd && tiles[0].is_some()).then(|| expand_stem("UDIMTOKEN")); for (tile_index, &tile) in tiles.iter().enumerate() { - let stem = expand_stem(&tile.unwrap_or(1001).to_string()); + let tile_number = tile.unwrap_or(1001).to_string(); + let stem = expand_stem(&tile_number); let ext = format.extension(); let mut warnings = Vec::new(); if color_map @@ -832,9 +835,9 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti // Use a UDIM name only when substituting its tile recovers the output name // Truncation or literal placeholder text can make that substitution ambiguous - let udim_name = tile - .map(|_| expand_stem("UDIMTOKEN")) - .filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)) + let udim_name = udim_template + .as_deref() + .filter(|t| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &tile_number) == stem) .map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "")); out.push(PlannedFile { name, map: map_index, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() }); } diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 64fd5115..3fe0e174 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -759,6 +759,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() { // A folder stays in the placeholder name assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_.png".to_string()), Some("Base/Body_.png".to_string())]); + + // A name without the token gets the tile as a suffix, and so does its placeholder + assert_eq!(udim_names("$textureSet".into()), [Some("Body..png".to_string()), Some("Body..png".to_string())]); } #[test] From 758474a9124bc672d2456cee94cd54faea09b5d0 Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 08:42:41 +0000 Subject: [PATCH 31/34] Export: the export tests install the framework runtime, as main's tests do since #800 --- crates/ui-egui/src/export_templates.rs | 2 +- crates/ui-egui/tests/it/export_shader_parameters.rs | 5 ++++- crates/ui-egui/tests/ui_snapshots.rs | 8 ++++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index a7ece23a..70f708b4 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1875,7 +1875,7 @@ mod tests { use egui_kittest::Harness; let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut harness = Harness::builder().build_eframe(|cc| TextureCraftApp::new(cc, session)); + 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(); let saved = app.session.export_preset("Unreal Engine (Packed)").unwrap(); diff --git a/crates/ui-egui/tests/it/export_shader_parameters.rs b/crates/ui-egui/tests/it/export_shader_parameters.rs index 07c1b479..7480cd63 100644 --- a/crates/ui-egui/tests/it/export_shader_parameters.rs +++ b/crates/ui-egui/tests/it/export_shader_parameters.rs @@ -10,7 +10,10 @@ use super::temp_dir::TempDir; #[test] fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut h = Harness::builder() + .with_size(egui::vec2(1600.0, 960.0)) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .build_eframe(|cc| TextureCraftApp::new(cc, session)); h.state_mut().ui.prefs.language = "en".into(); h.run_steps(4); let dir = TempDir::new("export-shader-parameters"); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 367fccb8..c9f43e43 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -3230,8 +3230,12 @@ fn export_window_snapshots() { set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1); session.doc.project.texture_sets.push(set); } - let mut harness = - Harness::builder().with_size(egui::vec2(1112.0, 662.0)).with_pixels_per_point(2.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + let mut harness = Harness::builder() + .with_size(egui::vec2(1112.0, 662.0)) + .with_pixels_per_point(2.0) + .with_context_setup(texturecraft_ui_egui::framework::install_headless) + .wgpu() + .build_eframe(|cc| TextureCraftApp::new(cc, session)); harness.state_mut().ui.prefs.language = "en".into(); harness.state_mut().ui.prefs.brightness = brightness; harness.set_render_cursor(false); From 948f6446aabcc9630f8b7d20672deb7cb603757b Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:09:40 +0000 Subject: [PATCH 32/34] List of exports: a texture set's folding header reports itself as a disclosure triangle, as egui's CollapsingHeader does --- crates/ui-egui/src/export_window.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index 3230c7cc..a3f6661b 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -1505,7 +1505,8 @@ fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { let look = ExportLook::get(ui.ctx()); let response = ui.interact(rect, id, egui::Sense::click()); - response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name)); + // A folding header, as egui's CollapsingHeader reports one + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); let y = rect.center().y; let chevron = if open { ic::CARET_DOWN From 06614b74e0431528a5ff12f7ff046e7df2aa05b1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:36:51 +0700 Subject: [PATCH 33/34] Export: the long-filename tree test looks up the set by its disclosure-triangle role 948f6446 made a texture set's folding header report itself as a DisclosureTriangle, as CollapsingHeader does. The tree-node test was updated to match; long_filenames_leave_the_export_details_reachable_by_scrolling still queried Role::Button and failed on Ubuntu (run 45798885802). --- crates/ui-egui/tests/it/export_progress.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 06d3f913..8a756d8a 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -174,9 +174,9 @@ 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::Button, &name).focus(); + h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus(); h.run_steps(3); - assert!(h.get_by_role_and_label(egui::Role::Button, &name).is_focused()); + assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused()); for _ in 0..12 { h.key_press(egui::Key::ArrowRight); From 091869033ab9e12c3c0357ad2d54519df771c3f0 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 28 Nov 2026 00:21:21 +0000 Subject: [PATCH 34/34] Auto: Preflight export paths and label tiled atlas previews Reject selections that use one output path as both a file and a folder before rendering or starting a desktop export. Expose tile metadata in export.plan and use it to label atlas previews, including ambiguous filenames. Write quantized 8-bit PSD rows directly into the merged-image buffer. Cover path conflicts in both orders, partial desktop writes, and visible atlas captions with regression tests. --- crates/engine/src/file_cmds.rs | 11 ++- crates/engine/tests/it/export_file_types.rs | 42 ++++++++- crates/formats/README.md | 3 +- crates/formats/src/export/layered_psd.rs | 6 +- crates/formats/src/export/mod.rs | 23 ++++- crates/ui-egui/src/export_templates.rs | 86 +++++++++++++++---- .../src/export_templates/planned_output.rs | 2 + crates/ui-egui/src/export_window.rs | 9 +- .../ui-egui/tests/it/export_map_overrides.rs | 6 +- crates/ui-egui/tests/it/export_progress.rs | 34 ++++++++ docs/control-protocol.md | 15 ++-- 11 files changed, 199 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index daee5a0e..ac846ba5 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -103,7 +103,7 @@ pub fn specs() -> Vec { "List export outputs", [], None, - "{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name and warns about later duplicates)", + "{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)", always, plan ), @@ -401,7 +401,12 @@ impl Session { // Keep each winning plan with the options of the job that produced it let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan))); - for (job, plan) in texturecraft_formats::export::keep_first_planned_names(plans) { + let plans = texturecraft_formats::export::keep_first_planned_names(plans); + if pending.len() > 1 { + texturecraft_formats::export::validate_export_paths(plans.iter().map(|(_, plan)| plan.name.as_str())).map_err(fe)?; + } + + for (job, plan) in plans { pending[job].2.push(plan); } pending.retain(|(_, _, plans)| !plans.is_empty()); @@ -630,6 +635,8 @@ fn plan(session: &mut Session, params: &Value) -> Result { "ts": set_index, "map": output.map, "file": output.name, + "tile": output.tile, + "udimPattern": output.udim_name, "format": output.format.extension(), "bitDepth": output.bit_depth, "dithering": output.dither, diff --git a/crates/engine/tests/it/export_file_types.rs b/crates/engine/tests/it/export_file_types.rs index 341e196c..dca3a215 100644 --- a/crates/engine/tests/it/export_file_types.rs +++ b/crates/engine/tests/it/export_file_types.rs @@ -50,6 +50,45 @@ fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() { println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::()); } +#[test] +fn a_psd_file_and_another_sets_folder_conflict_during_planning() { + use texturecraft_engine::core::Channel; + use texturecraft_engine::file_cmds::export_options; + + let mut session = texturecraft_engine::sample_session(128, 32).unwrap(); + let sets = &mut session.doc.project.texture_sets; + sets[0].name = "Body".into(); + sets[0].channels.retain(|(channel, _)| *channel != Channel::Metallic); + sets[1].name = "Trim".into(); + let preset = json!({"name": "Conflicting outputs", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}, + {"file": "$mesh_Body.psd/detail", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Metallic"}}]]} + ]}); + let dir = tempfile::tempdir().unwrap(); + let mut params = json!({"preset": preset, "padding": "none", "dir": dir.path()}); + + params["ts"] = json!(0); + let body = execute(&mut session, "export.plan", ¶ms).unwrap(); + params["ts"] = json!(1); + let trim = execute(&mut session, "export.plan", ¶ms).unwrap(); + let file = body[0]["file"].as_str().unwrap(); + let nested_file = trim.as_array().unwrap().iter().find_map(|file| file["file"].as_str().filter(|name| name.contains('/'))).unwrap(); + assert_eq!(nested_file.split('/').next(), Some(file), "separate plans collide when combined"); + + for order in [[0, 1], [1, 0]] { + params["ts"] = json!(order); + let plan_error = execute(&mut session, "export.plan", ¶ms).unwrap_err(); + let options = export_options(&session, ¶ms, "export.plan").unwrap(); + let render_error = session.export_files(&order, &options).unwrap_err(); + let write_error = execute(&mut session, "file.exportTextures", ¶ms).unwrap_err(); + + for error in [plan_error, render_error, write_error] { + assert!(error.to_string().contains("folder"), "{error}"); + } + assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none()); + } +} + #[test] fn a_map_size_wins_over_the_export_size_in_the_plan() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -127,7 +166,8 @@ fn a_psd_warning_outlives_a_reserved_file_that_carried_it() { {"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness}, {"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness}, ]}); - // Four 16-bit RGBA layers at 8192 pixels and the merged image pass the 2 GiB PSD limit + + // Four 16-bit RGBA layers at 8192 pixels exceed the 2 GiB PSD limit for layer in 0..4 { preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour})); } diff --git a/crates/formats/README.md b/crates/formats/README.md index 5f60e6ef..f32292cb 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -110,7 +110,8 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result; deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. PSD writes one file per texture set or UV tile, with each output map stored as a layer. - Smaller maps keep their sizes and align to the top left of the canvas. A `/` in a map + For tiled sets, `ExportOptions::atlas` writes one document for the whole set. Smaller maps + keep their sizes and align to the top left of the canvas. A `/` in a map name creates a layer group inside the PSD. 8-bit files can be dithered (`ExportOptions::dither`, an 8×8 ordered pattern). When `ExportOptions::color_space` is unset, color maps default to sRGB in integer files and linear Rec.709 in float files. An explicit diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index af95e664..f7be380c 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -8,7 +8,7 @@ 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, - quantize_integer, quantize_u16, + quantize_integer, quantize_u8, quantize_u16, }; use crate::{FormatError, Result}; @@ -125,11 +125,11 @@ fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u let mut merged = Vec::new(); merged.try_reserve_exact(sample_count).map_err(reserve_error)?; - let encoding = Encoding { format: FileFormat::Psd, depth, dither: false }; for y in 0..height as usize { merge_row(y, width, layers, &mut merged_row, &mut layer_row); - merged.extend(quantize_integer(encoding, width, PSD_RGBA_PLANES, merged_row.iter().copied())?); + merged.extend(merged_row.iter().copied().map(quantize_u8)); } + Ok(PixelData::Rgba8(merged)) } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 3ded1c05..8ca37c57 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -939,7 +939,7 @@ fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: & let mut prefix = lower.as_str(); while let Some((folder, _)) = prefix.rsplit_once('/') { if files.contains(folder) { - return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file"))); + return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another output exports that file"))); } dirs.insert(folder.to_owned()); @@ -949,6 +949,17 @@ fn claim_path(files: &mut BTreeSet, dirs: &mut BTreeSet, name: & Ok(()) } +/// Reject file and folder conflicts across a selection's retained output paths, ignoring case. +pub fn validate_export_paths<'a>(names: impl IntoIterator) -> Result<()> { + let mut files = BTreeSet::new(); + let mut folders = BTreeSet::new(); + for name in names { + claim_path(&mut files, &mut folders, name)?; + } + + 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(); @@ -982,6 +993,10 @@ fn plan_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &E } let files = keep_first_planned_names(files); + if sets.len() > 1 { + validate_export_paths(files.iter().map(|(_, file)| file.name.as_str()))?; + } + let mut psd_bytes = 0; for (index, file) in files.iter().filter(|(_, file)| file.format == FileFormat::Psd) { check_psd_batch_within(project.texture_set(*index)?, opts, std::slice::from_ref(file), &mut psd_bytes, budget)?; @@ -1565,6 +1580,10 @@ fn encode( write_raster(&image, codec_format).map_err(|error| encoding_error(&error)) } +fn quantize_u8(value: f32) -> u8 { + (value * f32::from(u8::MAX) + 0.5) as u8 +} + fn quantize_u16(value: f32) -> u16 { (value * f32::from(u16::MAX) + 0.5) as u16 } @@ -1593,7 +1612,7 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp if dither { bytes.extend(samples.enumerate().map(|(index, value)| (value * max_sample + threshold(index)).floor().clamp(0.0, max_sample) as u8)); } else { - bytes.extend(samples.map(|value| (value * max_sample + 0.5) as u8)); + bytes.extend(samples.map(quantize_u8)); } } diff --git a/crates/ui-egui/src/export_templates.rs b/crates/ui-egui/src/export_templates.rs index 70f708b4..aa7f223d 100644 --- a/crates/ui-egui/src/export_templates.rs +++ b/crates/ui-egui/src/export_templates.rs @@ -1095,33 +1095,46 @@ fn planned_outputs(app: &mut TextureCraftApp, params: &Value) -> Result> = vec![None; map_count]; + let tile_files = tr("UV tile files"); for file in plan.as_array().into_iter().flatten() { let Some(name) = file.get("file").and_then(Value::as_str) else { continue }; - let output = PlannedOutput { - file: name.to_string(), - size: file.get("size").and_then(Value::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), + let tiled = file["tile"].is_number(); + let display_name = if tiled { file["udimPattern"].as_str().unwrap_or(tile_files) } else { name }; + let mut remember = |entry: &Value, layer_name: Option<&str>| { + let Some(slot) = index(entry).and_then(|index| outputs.get_mut(index)) else { return }; + + if let Some(previous) = slot { + // Some disambiguated or truncated paths have no common tile pattern + if tiled && previous.file != display_name && previous.file != tile_files { + previous.file = tile_files.into(); + } + return; + } + + *slot = Some(PlannedOutput { + file: match layer_name { + Some(layer_name) if !tiled => format!("{name} › {layer_name}"), + _ => display_name.to_owned(), + }, + tiled, + size: file.get("size").and_then(Value::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), + }); }; match file.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty()) { Some(layers) => { for layer in layers { - let layer_name = layer.get("name").and_then(Value::as_str).unwrap_or_default(); - if let Some(slot) = index(layer).and_then(|i| outputs.get_mut(i)) { - *slot = Some(PlannedOutput { file: format!("{name} › {layer_name}"), ..output.clone() }); - } - } - } - None => { - if let Some(slot) = index(file).and_then(|i| outputs.get_mut(i)) { - *slot = Some(output); + remember(layer, layer.get("name").and_then(Value::as_str)); } } + None => remember(file, None), } } + Ok(outputs) } @@ -1487,13 +1500,16 @@ fn output_preview(ui: &mut Ui, index: usize, map: &MapSpec, planned: Option<&Pla return; }; - ui.label(RichText::new(&planned.file).color(tokens.text_strong)); + let title = if planned.tiled { trf("Atlas preview: {file}", &[("file", &planned.file)]) } else { planned.file.clone() }; + ui.label(RichText::new(title).color(tokens.text_strong)); if let Some(Some(pictures)) = MapPreviewCache::get(ui.ctx(), index) { preview_pictures(ui, map, &pictures); } + let file_type = planned.format.map_or("", FileFormat::extension); let depth = crate::export_window::depth_label(planned.format, planned.bit_depth, planned.dithering); - ui.label(RichText::new(format!("{size} x {size} · {file_type} {depth}", size = planned.size)).color(tokens.text_dim)); + let details = if planned.tiled { format!("{file_type} {depth}") } else { format!("{size} x {size} · {file_type} {depth}", size = planned.size) }; + ui.label(RichText::new(details).color(tokens.text_dim)); } /// The file's picture with each channel's grey picture, letter and source beside it @@ -1903,6 +1919,40 @@ mod tests { assert_eq!(params["maps"].as_array().unwrap().len(), 2, "the new map and the removed map get no override"); } + #[test] + fn tiled_raster_and_psd_previews_describe_the_whole_atlas() { + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable as _; + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives::udim_plane; + + let session = Session::new_project("Tiles", udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + 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 mut preset = app.session.export_preset("Separate maps").unwrap(); + preset.maps.truncate(2); + preset.maps[0].file = "Raster".into(); + preset.maps[0].format = FileFormat::Png; + preset.maps[1].file = "Group/Layer.$udim".into(); + preset.maps[1].format = FileFormat::Psd; + let mut ambiguous = preset.maps[0].clone(); + ambiguous.file = "Literal_UDIMTOKEN.$udim".into(); + preset.maps.push(ambiguous); + let params = json!({"ts": 0, "preset": preset}); + + let outputs = planned_outputs(app, ¶ms).unwrap(); + let preview = Harness::builder().with_context_setup(crate::framework::install_headless).build_ui(|ui| { + for (index, map) in preset.maps.iter().enumerate() { + output_preview(ui, index, map, outputs[index].as_ref()); + } + }); + + assert!(preview.query_by_label("Atlas preview: Raster..png").is_some()); + assert!(preview.query_by_label_contains(".psd").is_some()); + assert!(preview.query_by_label("Atlas preview: UV tile files").is_some()); + assert!(preview.query_by_label_contains("128 x 128").is_none(), "the tile size must not describe the whole atlas"); + } + #[test] fn layouts_keep_sources_and_drops_fill_rgb() { let mut map = new_map(Layout::Rgb, "t"); diff --git a/crates/ui-egui/src/export_templates/planned_output.rs b/crates/ui-egui/src/export_templates/planned_output.rs index e81666d4..6c5bcf37 100644 --- a/crates/ui-egui/src/export_templates/planned_output.rs +++ b/crates/ui-egui/src/export_templates/planned_output.rs @@ -4,6 +4,8 @@ use texturecraft_engine::formats::FileFormat; #[derive(Clone)] 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, pub(super) format: Option, diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index a3f6661b..c346d033 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -443,7 +443,10 @@ fn start_export(app: &mut TextureCraftApp) { .collect(); let preview: Vec<_> = pending.iter().filter_map(|(index, params)| plan_set(app, *index, params)).collect(); - let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)); + let error = preview.iter().find_map(|plan| plan.files.as_ref().err().cloned()).or_else(|| name_clash(&preview)).or_else(|| { + let paths = preview.iter().filter_map(|plan| plan.files.as_ref().ok()).flat_map(planned_names); + 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; @@ -1505,8 +1508,10 @@ fn tree_files(set: &ExportSetPlan, directory: &str) -> Vec { fn tree_header(ui: &mut Ui, rect: egui::Rect, name: &str, open: bool, id: egui::Id) -> bool { let look = ExportLook::get(ui.ctx()); let response = ui.interact(rect, id, egui::Sense::click()); - // A folding header, as egui's CollapsingHeader reports one + + // Expose the hand-drawn header as a disclosure control response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::DisclosureTriangle, true, name)); + let y = rect.center().y; let chevron = if open { ic::CARET_DOWN diff --git a/crates/ui-egui/tests/it/export_map_overrides.rs b/crates/ui-egui/tests/it/export_map_overrides.rs index 15b326b3..d2edee62 100644 --- a/crates/ui-egui/tests/it/export_map_overrides.rs +++ b/crates/ui-egui/tests/it/export_map_overrides.rs @@ -163,8 +163,7 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() { fn export_writes_a_map_with_its_own_file_type() { let mut h = harness(); let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize; - let dir = std::env::temp_dir().join(format!("tc-export-map-overrides-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + 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 }); @@ -184,10 +183,9 @@ fn export_writes_a_map_with_its_own_file_type() { h.run_steps(1); } h.run_steps(2); - let names: Vec = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); + let names: Vec = std::fs::read_dir(&*dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(); assert_eq!(names.iter().filter(|n| n.ends_with(".tga")).count(), 1, "{names:?}"); - let _ = std::fs::remove_dir_all(&dir); } #[test] diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index 8a756d8a..ec4bf518 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -255,6 +255,40 @@ fn texture_sets_writing_the_same_file_name_do_not_start_an_export() { let _ = std::fs::remove_dir_all(&library); } +#[test] +fn a_texture_set_cannot_export_into_another_sets_psd_file() { + use texturecraft_ui_egui::state::SetExport; + + let (mut h, _) = harness("psd-folder-clash"); + let scratch = tempfile::tempdir().unwrap(); + let dir = scratch.path().join("textures"); + let library = tempfile::tempdir().unwrap(); + let app = h.state_mut(); + app.ui.export.dir = dir.display().to_string(); + app.session.load_export_presets(library.path().to_path_buf()); + let psd = json!({"name": "Layered", "maps": [ + {"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": psd})).unwrap(); + let plan = app.run("export.plan", json!({"preset": "Layered", "ts": 0})).unwrap(); + let file_name = plan[0]["file"].as_str().unwrap(); + let nested = json!({"name": "Nested", "maps": [ + {"file": format!("{file_name}/detail"), "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]} + ]}); + app.run("export.preset.save", json!({"preset": nested})).unwrap(); + app.ui.export.preset = "Layered".into(); + app.ui.export.sets.insert(1, SetExport { preset: Some("Nested".into()), ..Default::default() }); + h.run_steps(4); + + click(&mut h, "Export"); + finish(&mut h); + + assert!(h.state().ui.export.job.is_none()); + assert_eq!(exports(&h), 0, "the full selection must be checked before starting"); + assert!(!dir.exists()); + assert!(console(&h).iter().any(|line| line.contains("folder")), "{:?}", console(&h)); +} + #[test] fn opening_another_project_stops_the_export() { let (mut h, dir) = harness("project"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3ae31541..27a60c1d 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -44,9 +44,11 @@ grayscale image (the whole tile atlas for a UV-tiled set). `file.exportTextures`, `export.plan`, the automation `textures.export` method and the MCP `textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?, size?}]`. Each entry overrides that map's export settings. The `map` field is its index in the selected -template. A map’s `size` in pixels overrides the export size. `enabled: false` suppresses that file while reserving its name. When several texture -sets produce the same name (ignoring case), programmatic and browser exports keep the first file -and warn about later duplicates. The desktop export window reports the collision before writing. +template. A map's `size` in pixels overrides the export size. `enabled: false` leaves out a PSD layer +or suppresses a raster file while reserving its name. When several texture sets produce the same +name (ignoring case), programmatic and browser exports keep the first file and warn about later +duplicates. The desktop export window reports the collision before writing. Texture planning +rejects a selection that uses the same path as both a file and a folder before rendering. `shaderParameters: true` writes `_shaders.json` beside the textures with the shader model, its settings and the names of the exported texture sets. An array of texture set @@ -84,11 +86,14 @@ shared by different sets. `hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and `export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). +Tiled files include their UV tile number in `tile` and, when available, their filename template +with a `` placeholder in `udimPattern`. These fields are null when they do not apply. `export.preview` takes the same parameters plus `map` (an index into the template's maps) and `side` (the maximum width or height, in pixels, capped at 512). It returns `{width, height, channels, pixels}` for the first texture set named by `ts`, or null when the -set writes no file for that map. HDR previews list RGB without alpha. TIFF previews list RGB -or RGBA when the encoder stores luminance in three channels. The preview uses 8-bit values, +set writes no file for that map. For a UV-tiled set the picture shows the atlas. HDR previews +list RGB without alpha. TIFF and WebP previews list RGB or RGBA when the encoder stores +luminance in three channels. PSD previews show the output layer's RGBA channels. The preview uses 8-bit values, with sRGB colour channels and linear data channels. Texels outside the UV islands use the channel defaults. `padding: "diffusion"` dilates by