diff --git a/Cargo.lock b/Cargo.lock index 84a1a752..fdb30672 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5173,6 +5173,7 @@ name = "texturecraft-engine" version = "0.6.1" dependencies = [ "chrono", + "craft-usd", "epaint_default_fonts", "image", "processkit", @@ -5292,7 +5293,9 @@ dependencies = [ "craft-quit", "craft-ui", "craft-update", + "craft-usd", "craft-window", + "craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83)", "eframe", "egui", "egui-phosphor", @@ -7079,9 +7082,9 @@ dependencies = [ [[package]] name = "zip" -version = "9.8.1" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9534624d547e3f516ecde0ed9a70d37788f01d340efcfdd03bf3ea8e163c1d0" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ "constant_time_eq", "crc32fast", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b6082f63..52b37891 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -37,5 +37,6 @@ tokio = { workspace = true } rustix = { workspace = true } [dev-dependencies] +craft-usd.workspace = true image = { workspace = true } zip = { workspace = true } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index b006b38b..006bb979 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)} → {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), 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?}", always, export_textures ), @@ -662,12 +662,13 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { let mut taken_names = reserved_names(params)?; 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 mut warnings = Vec::new(); let mut udim_patterns = Vec::new(); std::fs::create_dir_all(dir).map_err(|error| bad("file.exportTextures", format!("cannot create {}: {error}", dir.display())))?; - let written = if material { + let mut written = if material { let (fallback, selected_inputs, fallback_inputs) = material_map_options(&options, session.doc.project.normal_format)?; let mut textures = BTreeMap::new(); @@ -718,6 +719,10 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { texturecraft_formats::write_files(&files, dir).map_err(fe)? }; + if let Some(exports) = &usd_asset { + written.extend(write_usd_asset(session, dir, exports, &mut warnings)); + } + 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 }); if !udim_patterns.is_empty() { @@ -727,6 +732,85 @@ fn export_textures(session: &mut Session, params: &Value) -> Result { Ok(response) } +/// What the warning of a USD asset that could not be written starts with (`file.exportTextures`). +pub const USD_ASSET_FAILED: &str = "The USD asset was not written"; + +/// The texture sets, options and `reservedNames` of one export a USD asset refers to. +#[cfg(not(target_arch = "wasm32"))] +type UsdAssetExport = (Vec, ExportOptions, HashMap>); + +/// What `usdAsset` asks for: the texture sets, options and `reservedNames` of each export whose +/// textures the USD asset refers to. `true` is this command's own; a list gives every entry's. +#[cfg(not(target_arch = "wasm32"))] +fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, sets: &[usize]) -> Result>> { + match params.get("usdAsset") { + None | Some(Value::Null | Value::Bool(false)) => Ok(None), + Some(Value::Bool(true)) => Ok(Some(vec![(sets.to_vec(), options.clone(), reserved_names(params)?)])), + Some(Value::Array(exports)) if !exports.is_empty() && exports.iter().all(Value::is_object) => exports + .iter() + .map(|export| { + Ok((sets_param(session, export, "file.exportTextures")?, export_options(session, export, "file.exportTextures")?, reserved_names(export)?)) + }) + .collect::>>() + .map(Some), + Some(_) => Err(bad("file.exportTextures", "`usdAsset` must be true, false or a non-empty list of export param objects")), + } +} + +/// `.usd` (binary USD) next to the textures: the whole mesh (every texture set, not only the sets of this +/// command) with a UsdPreviewSurface material per texture set that reads the files `exports` +/// wrote (see `texturecraft_formats::usd_texture_bindings`). A failure to build or write it is a +/// 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) { + Ok(path) => Some(path), + Err(error) => { + warnings.push(format!("{USD_ASSET_FAILED}: {error}")); + None + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> 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:")); + + // Keep the files each export kept, by the rule `file.exportTextures` applies to its reserved and earlier names + let mut taken_names = HashMap::new(); + let mut by_set = HashMap::new(); + for (sets, options, reserved) in exports { + for name in reserved.keys() { + taken_names.entry(name.clone()).or_insert(None); + } + let reserved_patterns: Vec<_> = reserved.keys().filter(|name| name.contains("")).cloned().collect(); + + for &set in sets { + let texture_set = project.texture_set(set).map_err(|error| EngineError::Other(error.to_string()))?; + let mut kept = list_outputs(project, set, &mesh_name, options).map_err(fe)?; + let skipped_maps = reserve_export_names(set, &mut kept, &mut taken_names, &reserved_patterns, &mut Vec::new(), false); + + // 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)); + by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept)); + } + } + + // A mesh without materials has one implicit material (and texture set) + let mut mesh = session.source_mesh(); + if mesh.materials.is_empty() { + mesh.materials.push("default".into()); + } + let bindings: Vec<_> = + (0..mesh.materials.len()).map(|material| session.texture_set_of_material(material).and_then(|set| by_set.remove(&set)).unwrap_or_default()).collect(); + let layer = usd_layer_with_textures(&mesh, &project.name, &bindings).map_err(fe)?; + let path = dir.join(format!("{}.usd", texturecraft_formats::export::sanitize_file_stem(&mesh_name))); + texturecraft_formats::write_atomic(&path, &layer).map_err(fe)?; + Ok(path) +} + /// Reserve paths and UDIM patterns from earlier commands without assigning them to a current set. #[cfg(not(target_arch = "wasm32"))] fn reserved_names(params: &Value) -> Result>> { diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c38e850b..ce9f1614 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -66,5 +66,6 @@ mod tool_availability; mod tool_settings; mod tools; mod udim; +mod usd_asset; mod user_smart_mask; mod uv_strokes; diff --git a/crates/engine/tests/it/usd_asset.rs b/crates/engine/tests/it/usd_asset.rs new file mode 100644 index 00000000..e6ef7bd9 --- /dev/null +++ b/crates/engine/tests/it/usd_asset.rs @@ -0,0 +1,409 @@ +//! `file.exportTextures` with `usdAsset`: `.usd` next to the textures, the whole mesh with +//! a material per texture set that reads the textures the export wrote. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::{Session, execute}; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn temp(tag: &str) -> Scratch { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("tc_usd_asset_{tag}_{}_{seq}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + Scratch(dir) +} + +fn ball() -> Session { + Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap() +} + +fn files(r: &Value) -> Vec { + r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap().to_string()).collect() +} + +fn export(s: &mut Session, dir: &std::path::Path, params: Value) -> Value { + let mut params = params; + params["dir"] = json!(dir.display().to_string()); + execute(s, "file.exportTextures", ¶ms).unwrap() +} + +/// What a UsdPreviewSurface input reads +#[derive(Debug, PartialEq, Clone)] +struct Read { + file: String, + output: String, + colour_space: String, + /// The texture shader flips green (a DirectX normal map) + flips_green: bool, +} + +/// The prim name the exporter gives a mesh material +fn identifier(name: &str) -> String { + let mut id: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect(); + if !id.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') { + id.insert(0, '_'); + } + id +} + +/// The binary USD file read back: per mesh material, the inputs of its UsdPreviewSurface that read a texture, and the number of texture shaders +fn materials(bytes: &[u8], mesh_materials: &[String]) -> Vec<(BTreeMap, usize)> { + use craft_usd::scene::Val; + let layer = craft_usd::scene::read_layer(bytes).unwrap(); + let prim = |path: &str| layer.prims.iter().find(|p| p.path == path).unwrap_or_else(|| panic!("no prim {path}")); + let first = |prop: Option<&craft_usd::scene::Prop>| match prop.and_then(|p| p.value.as_ref()) { + Some(Val::Tok(values)) => values.first().cloned().unwrap_or_default(), + other => panic!("not a token or an asset: {other:?}"), + }; + mesh_materials + .iter() + .map(|name| { + let id = identifier(name); + let material = layer.prims.iter().find(|p| p.type_name == "Material" && p.name == id).unwrap_or_else(|| panic!("no material {id}")); + let pbr = prim(&format!("{}/PBR", material.path)); + let mut inputs = BTreeMap::new(); + for (key, prop) in &pbr.props { + let (Some(input), Some(source)) = (key.strip_prefix("inputs:"), &prop.connect) else { continue }; + let (shader, output) = source.rsplit_once('/').unwrap().1.split_once(".outputs:").unwrap(); + let texture = prim(&format!("{}/{shader}", material.path)); + let flips_green = match texture.props.get("inputs:scale").and_then(|p| p.value.as_ref()) { + Some(Val::Num(scale)) => scale.get(1).is_some_and(|green| *green < 0.0), + _ => false, + }; + let read = Read { + file: first(texture.props.get("inputs:file")).trim_start_matches("./").to_string(), + output: output.into(), + colour_space: first(texture.props.get("inputs:sourceColorSpace")), + flips_green, + }; + inputs.insert(input.to_string(), read); + } + let prefix = format!("{}/", material.path); + (inputs, layer.prims.iter().filter(|p| p.path.starts_with(&prefix) && p.props.contains_key("inputs:file")).count()) + }) + .collect() +} + +/// The materials of `/material_ball.usd`, indexed by mesh material +fn read_back(s: &Session, dir: &std::path::Path) -> Vec<(BTreeMap, usize)> { + let materials = materials(&std::fs::read(dir.join("material_ball.usd")).unwrap(), &s.mesh.materials); + assert_eq!(materials.len(), s.set_count()); + materials +} + +fn material_of(s: &Session, set: usize) -> usize { + s.doc.project.texture_sets[set].material +} + +#[test] +fn it_writes_the_mesh_with_materials_that_read_the_exported_textures() { + let mut s = ball(); + assert!(s.set_count() > 1, "the test needs several texture sets"); + let dir = temp("default"); + let r = export(&mut s, &dir, json!({"usdAsset": true})); + assert!(files(&r).iter().any(|f| f.ends_with("material_ball.usd")), "the asset is listed: {r}"); + + let materials = read_back(&s, &dir); + for set in 0..s.set_count() { + let name = &texturecraft_formats::export::sanitize_file_stem(&s.doc.project.texture_sets[set].name); + let inputs = &materials[material_of(&s, set)].0; + let read = |input: &str| inputs.get(input).unwrap_or_else(|| panic!("{input} of {name}: {inputs:?}")).clone(); + for (input, output, space) in [("diffuseColor", "rgb", "sRGB"), ("roughness", "r", "raw"), ("metallic", "r", "raw"), ("normal", "rgb", "raw")] { + let read = read(input); + assert_eq!((read.output.as_str(), read.colour_space.as_str()), (output, space), "{input} of {name}"); + assert!(read.file.starts_with(&format!("material_ball_{name}_")), "{input} reads a file of its own texture set: {}", read.file); + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + assert!(!read.flips_green, "the project's normals are OpenGL"); + } + assert!(!inputs.contains_key("opacity") && !inputs.contains_key("clearcoat"), "channels the set does not have stay unbound: {inputs:?}"); + } +} + +#[test] +fn a_packed_template_reads_different_outputs_of_one_file() { + let mut s = ball(); + let dir = temp("packed"); + export(&mut s, &dir, json!({"preset": "Unreal Engine (Packed)", "usdAsset": true})); + + for (inputs, shaders) in read_back(&s, &dir) { + assert_eq!(shaders, 3, "four inputs read three files: {inputs:?}"); + let (roughness, metallic) = (&inputs["roughness"], &inputs["metallic"]); + assert_eq!(roughness.file, metallic.file, "{inputs:?}"); + assert!(roughness.file.contains("OcclusionRoughnessMetallic"), "{}", roughness.file); + assert_eq!((roughness.output.as_str(), metallic.output.as_str()), ("g", "b")); + assert_ne!(inputs["diffuseColor"].file, roughness.file); + + // The template writes DirectX normals + assert!(inputs["normal"].flips_green, "{inputs:?}"); + assert!(!inputs.contains_key("opacity"), "the base colour file has no alpha without an opacity channel"); + } +} + +#[test] +fn the_normal_convention_of_the_files_decides_whether_green_is_flipped() { + let mut s = ball(); + let (open_gl, direct_x) = (temp("normal-gl"), temp("normal-dx")); + export(&mut s, &open_gl, json!({"usdAsset": true, "normalFormat": "openGl"})); + export(&mut s, &direct_x, json!({"usdAsset": true, "normalFormat": "directX"})); + for (inputs, _) in read_back(&s, &open_gl) { + assert!(!inputs["normal"].flips_green); + } + for (inputs, _) in read_back(&s, &direct_x) { + assert!(inputs["normal"].flips_green); + } +} + +#[test] +fn a_texture_set_outside_the_export_has_no_textures() { + let mut s = ball(); + let dir = temp("subset"); + export(&mut s, &dir, json!({"ts": 0, "usdAsset": true})); + + let materials = read_back(&s, &dir); + assert!(!materials[material_of(&s, 0)].0.is_empty()); + assert!(materials[material_of(&s, 1)].0.is_empty(), "{:?}", materials[material_of(&s, 1)]); + let name = texturecraft_formats::export::sanitize_file_stem(&s.doc.project.texture_sets[1].name); + assert!(!std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.file_name().to_string_lossy().contains(&format!("_{name}_"))), "set 1 was not written"); +} + +#[test] +fn a_list_gives_each_texture_set_its_own_options() { + let mut s = ball(); + let dir = temp("list"); + export(&mut s, &dir, json!({"ts": 0})); + let list = json!([{"ts": 0}, {"ts": 1, "preset": "Unreal Engine (Packed)"}]); + export(&mut s, &dir, json!({"ts": 1, "preset": "Unreal Engine (Packed)", "usdAsset": list})); + + let materials = read_back(&s, &dir); + let first = &materials[material_of(&s, 0)].0; + let second = &materials[material_of(&s, 1)].0; + assert_eq!(first["roughness"].output, "r", "{first:?}"); + assert_eq!(second["roughness"].output, "g", "{second:?}"); + for read in first.values().chain(second.values()) { + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + } +} + +#[test] +fn it_is_not_written_unless_asked_for() { + let mut s = ball(); + let dir = temp("off"); + let off = export(&mut s, &dir, json!({})); + let explicit = export(&mut s, &dir, json!({"usdAsset": false})); + for r in [off, explicit] { + assert!(!files(&r).is_empty(), "the textures are written"); + assert!(!files(&r).iter().any(|f| f.ends_with(".usd")), "{r}"); + } + assert!(!dir.join("material_ball.usd").exists()); +} + +#[test] +fn a_failure_to_write_it_is_a_warning_and_the_textures_are_still_reported() { + let mut s = ball(); + let dir = temp("blocked"); + + // A folder where the file belongs: the asset cannot be written there + std::fs::create_dir_all(dir.join("material_ball.usd")).unwrap(); + let r = export(&mut s, &dir, json!({"usdAsset": true})); + + assert!(!files(&r).iter().any(|f| f.ends_with(".usd")), "{r}"); + assert!(files(&r).iter().any(|f| f.ends_with(".png")), "the textures are reported: {r}"); + let warnings = r["warnings"].as_array().unwrap(); + assert!(warnings.iter().any(|w| w.as_str().unwrap().starts_with("The USD asset was not written")), "{r}"); + assert!(dir.join("material_ball.usd").is_dir()); +} + +#[test] +fn the_asset_opens_again_with_its_textures_from_the_folder() { + let mut s = ball(); + let dir = temp("roundtrip"); + export(&mut s, &dir, json!({"usdAsset": true})); + + // The importer reads only the texture of the base colour, but every input the file binds reads a file of the folder + for (inputs, _) in read_back(&s, &dir) { + assert!(inputs.len() >= 4, "{inputs:?}"); + for read in inputs.values() { + assert!(dir.join(&read.file).is_file(), "{} is in the folder", read.file); + } + } + + let file = texturecraft_formats::read_mesh_file(&dir.join("material_ball.usd")).unwrap(); + assert!(file.warnings.is_empty(), "every texture it names is in the folder: {:?}", file.warnings); + assert!(file.name.ends_with(".usdz"), "the base colour texture is found and packaged: {}", file.name); + let package = zip::ZipArchive::new(std::io::Cursor::new(&file.bytes)).unwrap(); + assert!(package.file_names().any(|name| name.is_ok_and(|name| name.ends_with(".png")))); + + let back = texturecraft_formats::import_mesh_bytes(&file.name, &file.bytes).unwrap(); + assert_eq!(back.mesh.triangle_count(), s.mesh.triangle_count()); + assert_eq!(back.mesh.materials.len(), s.set_count()); +} + +#[test] +fn a_bad_usd_asset_value_is_an_error_before_anything_is_written() { + let mut s = ball(); + for value in [json!("x"), json!([]), json!([1]), json!([{"ts": 0}, "x"]), json!([{"ts": 99}]), json!({"ts": 0})] { + let dir = temp("bad"); + let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "usdAsset": value})); + assert!(r.is_err(), "{value}"); + assert!(!dir.exists(), "nothing was written for {value}"); + } +} + +#[test] +fn the_tiles_of_a_uv_tiled_set_are_read_through_one_udim_name() { + let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + let dir = temp("udim"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials); + let colour = &materials[0].0["diffuseColor"]; + assert!(colour.file.ends_with("..png"), "{}", colour.file); + for tile in ["1001", "1002"] { + assert!(dir.join(colour.file.replace("", tile)).is_file(), "tile {tile} was written"); + } +} + +/// A template with one map, the base colour, whose name does not tell texture sets apart +fn shared_name_template() -> Value { + let rgb: Vec = (0..3) + .map(|k| { + let dest = ["R", "G", "B"][k]; + json!([dest, {"Channel": {"channel": "BaseColor", "component": k}}]) + }) + .collect(); + json!({"name": "shared", "maps": [{"file": "colour", "format": "Png", "bit_depth": 8, "channels": rgb}]}) +} + +#[test] +fn a_file_name_an_earlier_export_of_the_job_has_is_not_read_by_a_later_one() { + let mut s = ball(); + let dir = temp("same-name"); + let list = json!([{"ts": 0, "preset": shared_name_template()}, {"ts": 1, "preset": shared_name_template()}]); + export(&mut s, &dir, json!({"ts": 1, "preset": shared_name_template(), "usdAsset": list})); + + let materials = read_back(&s, &dir); + assert_eq!(materials[material_of(&s, 0)].0["diffuseColor"].file, "colour.png"); + assert!(materials[material_of(&s, 1)].0.is_empty(), "the later set's file would have replaced the earlier one: {:?}", materials[material_of(&s, 1)]); +} + +#[test] +fn a_material_without_a_texture_set_has_no_textures() { + let mut s = ball(); + + // Both texture sets paint the first material (which the first set stands for): the second has none + s.doc.project.texture_sets[1].material = 0; + let dir = temp("no-set"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = read_back(&s, &dir); + assert!(!materials[0].0.is_empty()); + assert!(materials[1].0.is_empty(), "{:?}", materials[1]); +} + +/// Two two-tile planes, a material each: the first covers tiles 1001 and 1002, the second starts `shift_tiles` tiles to the right +fn two_udim_sets(shift_tiles: f32) -> Session { + let mut mesh = primitives::udim_plane(); + let mut second = primitives::udim_plane(); + second.materials[0] = "Other".into(); + for uv in &mut second.uvs { + uv.x += shift_tiles; + } + mesh.append(&second); + Session::new_project("t", mesh, "builtin:udim_plane", None, 128).unwrap() +} + +/// A material per half of a two-tile plane: the first material covers tiles 1001 and 1002, the second 1002 and 1003 +fn overlapping_tiles() -> Session { + let s = two_udim_sets(1.0); + assert_eq!(s.doc.project.texture_sets[0].uv_tiles, [1001, 1002]); + assert_eq!(s.doc.project.texture_sets[1].uv_tiles, [1002, 1003]); + s +} + +/// The shared colour map plus a roughness map whose names tell the texture sets apart +fn colour_and_own_roughness_template() -> Value { + let gray = json!([["L", {"Channel": {"channel": "Roughness", "component": 0}}]]); + let mut preset = shared_name_template(); + preset["maps"].as_array_mut().unwrap().push(json!({"file": "rough_$textureSet", "format": "Png", "bit_depth": 8, "channels": gray})); + preset +} + +#[test] +fn a_udim_map_that_lost_a_tile_to_a_name_clash_is_not_bound_but_the_other_maps_are() { + let mut s = overlapping_tiles(); + let dir = temp("udim-clash"); + + // The colour map's names do not tell the sets apart, so tile 1002 of the second set is not written; + // the roughness map's names do. + export(&mut s, &dir, json!({"ts": [0, 1], "preset": colour_and_own_roughness_template(), "usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &s.mesh.materials); + let (first, second) = (&materials[material_of(&s, 0)].0, &materials[material_of(&s, 1)].0); + assert_eq!(first["diffuseColor"].file, "colour..png", "{first:?}"); + assert!(first["roughness"].file.starts_with("rough_") && first["roughness"].file.contains(""), "{first:?}"); + assert!(!second.contains_key("diffuseColor"), "tile 1002 would read the first set's file: {second:?}"); + assert!(second["roughness"].file.starts_with("rough_") && second["roughness"].file.contains(""), "{second:?}"); + assert_ne!(first["roughness"].file, second["roughness"].file); +} + +#[test] +fn a_udim_map_whose_tiles_the_window_reserved_for_an_earlier_command_is_not_bound() { + let mut session = two_udim_sets(2.0); + assert_eq!(session.doc.project.texture_sets[1].uv_tiles, [1003, 1004]); + let dir = temp("reserved"); + let first = json!({"ts": 0, "preset": colour_and_own_roughness_template()}); + let written = export(&mut session, &dir, first.clone()); + + // The window reserves the earlier files and the UDIM patterns of earlier MaterialX documents + let mut reserved: Vec = files(&written).iter().map(|file| json!(std::path::Path::new(file).file_name().unwrap().to_str().unwrap())).collect(); + reserved.push(json!("colour..png")); + let second = json!({"ts": 1, "preset": colour_and_own_roughness_template(), "reservedNames": reserved}); + let mut last = second.clone(); + last["usdAsset"] = json!([first, second]); + export(&mut session, &dir, last); + + let materials = materials(&std::fs::read(dir.join("udim_plane.usd")).unwrap(), &session.mesh.materials); + let (first, second) = (&materials[material_of(&session, 0)].0, &materials[material_of(&session, 1)].0); + assert_eq!(first["diffuseColor"].file, "colour..png", "{first:?}"); + assert!(!dir.join("colour.1003.png").exists(), "the texture export skipped the reserved pattern"); + assert!(!second.contains_key("diffuseColor"), "the second set's colour tiles were not written: {second:?}"); + assert!(second["roughness"].file.starts_with("rough_") && second["roughness"].file.contains(""), "{second:?}"); + assert!(dir.join(second["roughness"].file.replace("", "1003")).is_file()); +} + +#[test] +fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() { + let mut mesh = primitives::plane(2.0, 4); + mesh.materials.clear(); + mesh.submeshes.clear(); + let mut s = Session::new_project("t", mesh, "builtin:plane", None, 128).unwrap(); + assert_eq!(s.set_count(), 1); + let dir = temp("no-materials"); + export(&mut s, &dir, json!({"usdAsset": true})); + + let materials = materials(&std::fs::read(dir.join("plane.usd")).unwrap(), &["default".to_string()]); + let inputs = &materials[0].0; + assert!(["diffuseColor", "roughness", "metallic", "normal"].iter().all(|input| inputs.contains_key(*input)), "{inputs:?}"); + for read in inputs.values() { + assert!(read.file.starts_with("plane_Default_"), "reads the Default texture set's files: {}", read.file); + assert!(dir.join(&read.file).is_file(), "{} was written", read.file); + } +} diff --git a/crates/formats/README.md b/crates/formats/README.md index 4033b1be..f56dbc36 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -52,6 +52,9 @@ pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format pub fn usd_export_options() -> ExportOptions; // render each material's textures with these pub enum UsdFormat { Usda, Usdc, Usdz } pub struct UsdExport { pub bytes: Vec, pub textures: Vec<(String, Vec)> } // textures: usda/usdc only +pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec; // which UsdPreviewSurface input reads which output of which exported file +pub fn usd_layer_with_textures(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result>; // binary `.usd` (Crate) only; material m reads bindings[m] as ./ +pub struct UsdTextureBinding { /* opaque */ } ``` OBJ export propagates shared writer validation and limit errors rather than returning empty bytes. @@ -65,6 +68,11 @@ emissive maps dropped, and both clear coat maps when the coat is black). Meters, `.usdc` is a Crate 0.8.0 file; `.usdz` is that layer first plus the PNGs, stored uncompressed at 64-byte aligned offsets; `.usda` / `.usdc` reference `__.png` next to the layer. +`usd_layer_with_textures` writes the same scene as a binary `.usd` (Crate) whose materials read texture files the +caller already wrote (the Export textures window's USD asset): `usd_texture_bindings` binds base +color, roughness, metallic, normal (scale/bias for the file's green convention), emissive color, +opacity, clear coat and clear coat roughness by what each map of the template holds, each reading +the `rgb`, `r`, `g`, `b` or `a` output of its file; one texture shader per file, so packed maps work. GLB: one primitive per submesh, one metallic-roughness material per mesh material with its textures embedded in the binary chunk (base color sRGB, `alphaMode: BLEND` when it has alpha; diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index 8c56e0e2..a76a46b0 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -514,7 +514,7 @@ fn normal_present(set: &TextureSet) -> bool { } /// A source with real data in this texture set (constants never count). -fn source_present(set: &TextureSet, s: &SourceRef) -> bool { +pub(crate) fn source_present(set: &TextureSet, s: &SourceRef) -> bool { match s { SourceRef::Channel { channel: Channel::Normal, .. } => normal_present(set), SourceRef::Channel { channel, .. } => set.has_channel(*channel), diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 3fd12036..8dc7d67e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -46,7 +46,10 @@ pub use export::{ 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::{GlbTextures, NamedFiles, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options}; +pub use mesh_export::{ + GlbTextures, NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options, + usd_layer_with_textures, usd_texture_bindings, +}; 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; diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index d35156a9..4cc3b24e 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -15,7 +15,7 @@ use crate::export::sanitize_file_stem; use crate::presets::{GLTF_BASE_COLOR, GLTF_CLEARCOAT, GLTF_EMISSIVE, GLTF_NORMAL, GLTF_ORM, GLTF_SHEEN, gltf_pbr_maps}; use crate::{ExportOptions, ExportPreset, ExportedFile, FileFormat, FormatError, Result}; -pub use usd::{NamedFiles, UsdExport, UsdFormat, usd_bytes, usd_export_options}; +pub use usd::{NamedFiles, UsdExport, UsdFormat, UsdTextureBinding, usd_bytes, usd_export_options, usd_layer_with_textures, usd_texture_bindings}; /// The mesh as OBJ text (UV v flipped back to OBJ's bottom-up convention). /// Invalid mesh data or shared writer limits return an error, never an empty successful export. diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index ee1a7166..49125502 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -6,11 +6,15 @@ //! UsdUVTexture shaders. Meters, Y up. use craft_usd::scene::{SceneError, UsdAttr, UsdLayer, UsdPrim, UsdValue, write_usda, write_usdc}; -use texturecraft_core::{Channel, NormalFormat}; +use texturecraft_core::{Channel, NormalFormat, TextureSet}; use texturecraft_geom::Mesh; +use texturecraft_texel::ColorSpace; + use super::{is_black, parts}; -use crate::export::{ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, VirtualMap, sanitize_file_stem}; +use crate::export::{ + Dest, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, PlannedFile, SourceRef, VirtualMap, sanitize_file_stem, source_present, +}; use crate::presets::{ch, gray, rgb, virt}; use crate::{FormatError, Result}; @@ -103,9 +107,9 @@ fn identifier(s: &str, taken: &mut Vec) -> String { id } -/// The export scene: `/` with the `Mesh` and `Materials`. `files[m]` are the texture -/// file names (by slot) of material `m`. -fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result { +/// The export scene: `/` with the `Mesh` and `Materials`. `material(m, path, id)` makes the +/// Material prim `id` at `path` for mesh material `m`. +fn scene(mesh: &Mesh, name: &str, material: impl Fn(usize, &str, &str) -> UsdPrim) -> Result { let vertex_count = mesh.positions.len(); if vertex_count == 0 || mesh.indices.len() < 3 { return Err(FormatError::Invalid("the mesh is empty".into())); @@ -177,7 +181,7 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result UsdPrim { pub fn usd_bytes(mesh: &Mesh, name: &str, textures: &[Vec], format: UsdFormat) -> Result { let stem = sanitize_file_stem(name); let (names, files) = material_maps(mesh, &stem, textures); - let layer = scene(mesh, name, &names)?; + let layer = scene(mesh, name, |m, path, id| material(path, id, names.get(m).map_or(&[][..], Vec::as_slice)))?; Ok(match format { UsdFormat::Usda => UsdExport { bytes: write_usda(&layer).into_bytes(), textures: files }, UsdFormat::Usdc => UsdExport { bytes: write_usdc(&layer).map_err(map_scene_err)?, textures: files }, @@ -291,6 +295,222 @@ pub(crate) fn usdz(layer_name: &str, layer: &[u8], files: &[(String, Vec)]) zip.finish().map_err(err) } +/// A UsdPreviewSurface input that reads a texture file the export wrote. +#[derive(Clone, Debug, PartialEq)] +pub struct UsdTextureBinding { + /// The input, as an index into the table of UsdPreviewSurface inputs (`SLOTS`). + slot: usize, + /// The file name, `` for a UV-tiled set's tiles. + file: String, + /// The texture output the input reads: `r`, `g`, `b`, `a` or `rgb`. + output: &'static str, + /// The file holds sRGB-encoded colour. + srgb: bool, + /// A normal map: the green convention of its file. + normal: Option, +} + +/// Whether `source` is what UsdPreviewSurface input `slot` (an index into [`SLOTS`]) reads. +fn feeds_slot(slot: usize, source: &SourceRef) -> bool { + let channel = match (slot, source) { + (1, SourceRef::Virtual { map: VirtualMap::Roughness, .. }) => return true, + (3, SourceRef::Virtual { map: VirtualMap::NormalOpenGl | VirtualMap::NormalDirectX, .. }) => return true, + (_, SourceRef::Channel { channel, .. }) => *channel, + _ => return false, + }; + let wanted = match slot { + 0 => Channel::BaseColor, + 1 => Channel::Roughness, + 2 => Channel::Metallic, + 3 => Channel::Normal, + 4 => Channel::Emissive, + 5 => Channel::Opacity, + 6 => Channel::CoatWeight, + _ => Channel::CoatRoughness, + }; + channel == wanted +} + +fn component_of(source: &SourceRef) -> u8 { + match source { + SourceRef::Channel { component, .. } | SourceRef::Virtual { component, .. } | SourceRef::Baked { component, .. } => *component, + SourceRef::Constant(_) => 0, + } +} + +/// The texture output of `map` that input `slot` reads, and the source it takes: a colour or +/// normal input needs the three components in R, G and B (the source is the green one's), a scalar +/// input reads the destination that holds it. None when the map does not hold the input, when `set` has no data for it (the +/// file then holds a default), when it is written inverted, or when `format` cannot keep it: JPEG +/// and HDR files drop alpha, a PGM file holds one gray channel (a colour map becomes its +/// luminance), which only a map written as L can bind. +fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format: FileFormat) -> Option<(&'static str, &'m SourceRef)> { + let holds = |dest: Dest, component: Option| { + map.channels + .iter() + .find(|(d, source)| { + *d == dest + && feeds_slot(slot, source) + && source_present(set, source) + && component.is_none_or(|k| component_of(source) == k) + && !map.inverted.contains(d) + }) + .map(|(_, source)| source) + }; + if SLOTS[slot].2 == "float" { + return [(Dest::R, "r"), (Dest::L, "r"), (Dest::G, "g"), (Dest::B, "b"), (Dest::A, "a")] + .into_iter() + .filter(|(dest, _)| match format { + FileFormat::Pgm => *dest == Dest::L, + FileFormat::Jpeg | FileFormat::Hdr => *dest != Dest::A, + _ => true, + }) + .find_map(|(dest, output)| holds(dest, None).map(|source| (output, source))); + } + + if format == FileFormat::Pgm { + return None; + } + + holds(Dest::R, Some(0))?; + let green = holds(Dest::G, Some(1))?; + holds(Dest::B, Some(2))?; + + // The green source is returned: only the green channel differs between the OpenGL and DirectX + // normal conventions + Some(("rgb", green)) +} + +/// The UsdPreviewSurface inputs the exported `files` of texture set `set` (planned with `opts`) +/// can feed, by what each map holds: base colour, roughness, metallic, normal, emissive colour, +/// 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. +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 { + // The first tile stands for all the tiles of a map + if seen_maps.contains(&file.map) { + continue; + } + + seen_maps.push(file.map); + let Some(map) = opts.preset.maps.get(file.map) else { continue }; + + // A tile whose name has no `` token cannot stand for the others + let name = match (&file.udim_name, file.tile) { + (Some(udim), _) => udim.clone(), + (None, None) => file.name.clone(), + (None, Some(_)) => continue, + }; + let srgb = opts.space_for_map(map, file.format, file.bit_depth) == ColorSpace::Srgb; + for slot in 0..SLOTS.len() { + if out.iter().any(|binding| binding.slot == slot) { + continue; + } + + let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue }; + let normal = (slot == 3).then(|| { + opts.normal_format.unwrap_or(match source { + SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl, + SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX, + _ => project_normal, + }) + }); + out.push(UsdTextureBinding { slot, file: name.clone(), output, srgb, normal }); + } + } + out +} + +/// The mesh as a layer named `name` whose material `m` reads the textures of `bindings[m]`, by +/// relative file name (`./`). +fn textured_layer(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result { + scene(mesh, name, |m, path, id| textured_material(path, id, bindings.get(m).map_or(&[][..], Vec::as_slice))) +} + +/// The mesh as a binary USD (Crate) file named `name` whose material `m` reads the textures of +/// `bindings[m]`, by relative file name (`./`): the textures are not part of the result. +pub fn usd_layer_with_textures(mesh: &Mesh, name: &str, bindings: &[Vec]) -> Result> { + write_usdc(&textured_layer(mesh, name, bindings)?).map_err(map_scene_err) +} + +/// A UsdPreviewSurface material at `path` whose inputs read `bindings`. One texture shader reads +/// each file (once per colour space and normal convention), so inputs packed into one file read +/// different outputs of it. +fn textured_material(path: &str, id: &str, bindings: &[UsdTextureBinding]) -> UsdPrim { + let mut mat = UsdPrim::new(id, "Material"); + mat.attrs.push(UsdAttr::connected("outputs:surface", "token", format!("{path}/PBR.outputs:surface"))); + let mut pbr = UsdPrim::new("PBR", "Shader"); + pbr.attrs.push(UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPreviewSurface".into()))).uniform()); + + // (shader name, a binding that has its file, colour space and normal convention, outputs read) + let mut taken = vec!["PBR".to_string(), "st".to_string()]; + let mut shaders: Vec<(String, &UsdTextureBinding, Vec<&'static str>)> = Vec::new(); + for binding in bindings { + let Some(&(_, input, input_type, ..)) = SLOTS.get(binding.slot) else { continue }; + let at = match shaders.iter().position(|(_, key, _)| (&key.file, key.srgb, key.normal) == (&binding.file, binding.srgb, binding.normal)) { + Some(at) => at, + None => { + let stem = binding.file.rsplit_once('.').map_or(binding.file.as_str(), |(stem, _)| stem); + shaders.push((identifier(stem, &mut taken), binding, Vec::new())); + shaders.len() - 1 + } + }; + let (shader, _, outputs) = &mut shaders[at]; + if !outputs.contains(&binding.output) { + outputs.push(binding.output); + } + + pbr.attrs.push(UsdAttr::connected(&format!("inputs:{input}"), input_type, format!("{path}/{shader}.outputs:{}", binding.output))); + } + + let mut textures = Vec::new(); + for (shader, binding, outputs) in shaders { + let mut tex = UsdPrim::new(&shader, "Shader"); + let token = |s: &str| Some(UsdValue::Token(s.into())); + tex.attrs = vec![ + UsdAttr::new("info:id", "token", token("UsdUVTexture")).uniform(), + UsdAttr::new("inputs:file", "asset", Some(UsdValue::Asset(format!("./{}", binding.file)))), + UsdAttr::connected("inputs:st", "float2", format!("{path}/st.outputs:result")), + UsdAttr::new("inputs:sourceColorSpace", "token", token(if binding.srgb { "sRGB" } else { "raw" })), + UsdAttr::new("inputs:wrapS", "token", token("repeat")), + UsdAttr::new("inputs:wrapT", "token", token("repeat")), + ]; + + // Unpack 0..1 texels to -1..1 vectors; a DirectX file also flips green to the OpenGL convention + if let Some(format) = binding.normal { + let (scale, bias) = match format { + NormalFormat::OpenGl => ([2.0, 2.0, 2.0, 1.0], [-1.0, -1.0, -1.0, 0.0]), + NormalFormat::DirectX => ([2.0, -2.0, 2.0, 1.0], [-1.0, 1.0, -1.0, 0.0]), + }; + tex.attrs.push(UsdAttr::new("inputs:scale", "float4", Some(UsdValue::Float4(scale)))); + tex.attrs.push(UsdAttr::new("inputs:bias", "float4", Some(UsdValue::Float4(bias)))); + } + for output in outputs { + tex.attrs.push(UsdAttr::new(&format!("outputs:{output}"), if output == "rgb" { "float3" } else { "float" }, None)); + } + textures.push(tex); + } + pbr.attrs.push(UsdAttr::new("inputs:useSpecularWorkflow", "int", Some(UsdValue::Int(0)))); + pbr.attrs.push(UsdAttr::new("outputs:surface", "token", None)); + mat.children.push(pbr); + if !textures.is_empty() { + let mut st = UsdPrim::new("st", "Shader"); + st.attrs = vec![ + UsdAttr::new("info:id", "token", Some(UsdValue::Token("UsdPrimvarReader_float2".into()))).uniform(), + // A string, not a token: usdchecker's ARKit profile refuses a token here. + UsdAttr::new("inputs:varname", "string", Some(UsdValue::Str("st".into()))), + UsdAttr::new("outputs:result", "float2", None), + ]; + mat.children.push(st); + mat.children.extend(textures); + } + mat +} + #[cfg(test)] mod aligned_package_tests { use super::*; @@ -328,3 +548,228 @@ mod aligned_package_tests { assert!(matches!(err, FormatError::Invalid(ref why) if why.starts_with("usdz package:"))); } } + +#[cfg(test)] +mod texture_binding_tests { + use super::*; + use texturecraft_core::ChannelFormat; + + const BASE_COLOR: usize = 0; + const ROUGHNESS: usize = 1; + const METALLIC: usize = 2; + const NORMAL: usize = 3; + const OPACITY: usize = 5; + + fn set_with(extra: &[Channel]) -> TextureSet { + let mut set = TextureSet::new("Body", 0, 128); + set.channels.extend(extra.iter().map(|c| (*c, ChannelFormat::default_for(*c)))); + set + } + + fn map(file: &str, format: FileFormat, channels: Vec<(Dest, SourceRef)>) -> MapSpec { + MapSpec { file: file.into(), format, bit_depth: 8, channels, inverted: Vec::new() } + } + + fn options(maps: Vec) -> ExportOptions { + ExportOptions::new(ExportPreset { name: "test".into(), maps }) + } + + fn planned(opts: &ExportOptions, index: usize) -> PlannedFile { + let map = &opts.preset.maps[index]; + PlannedFile { + name: format!("{}.{}", map.file, map.format.extension()), + map: index, + format: map.format, + bit_depth: map.bit_depth, + dither: false, + tile: None, + udim_name: None, + warnings: Vec::new(), + } + } + + fn bind(set: &TextureSet, opts: &ExportOptions, normal: NormalFormat) -> Vec { + let files: Vec = (0..opts.preset.maps.len()).map(|i| planned(opts, i)).collect(); + usd_texture_bindings(set, opts, normal, &files) + } + + fn slot(bindings: &[UsdTextureBinding], slot: usize) -> Option<&UsdTextureBinding> { + bindings.iter().find(|b| b.slot == slot) + } + + fn rgba() -> Vec<(Dest, SourceRef)> { + vec![ + (Dest::R, ch(Channel::BaseColor, 0)), + (Dest::G, ch(Channel::BaseColor, 1)), + (Dest::B, ch(Channel::BaseColor, 2)), + (Dest::A, ch(Channel::Opacity, 0)), + ] + } + + #[test] + fn colour_and_opacity_of_one_file_are_read_by_one_texture_shader() { + let opts = options(vec![map("albedo", FileFormat::Png, rgba())]); + let bindings = bind(&set_with(&[Channel::Opacity]), &opts, NormalFormat::OpenGl); + assert_eq!(slot(&bindings, BASE_COLOR).map(|b| b.output), Some("rgb")); + assert_eq!(slot(&bindings, OPACITY).map(|b| (b.output, b.file.as_str())), Some(("a", "albedo.png"))); + + // PBR, the st reader and a single texture shader + assert_eq!(textured_material("/m", "M", &bindings).children.len(), 3); + + // A set without opacity has no alpha in the file + let bindings = bind(&set_with(&[]), &opts, NormalFormat::OpenGl); + assert!(slot(&bindings, OPACITY).is_none()); + assert!(slot(&bindings, BASE_COLOR).is_some()); + } + + #[test] + fn the_layer_reads_each_file_with_its_output_and_colour_space() { + let opts = options(vec![ + map("albedo", FileFormat::Png, rgba()), + map("orm", FileFormat::Png, vec![(Dest::G, ch(Channel::Roughness, 0)), (Dest::B, ch(Channel::Metallic, 0))]), + ]); + let bindings = vec![bind(&set_with(&[Channel::Opacity]), &opts, NormalFormat::OpenGl), Vec::new()]; + let mesh = texturecraft_geom::primitives::material_ball(); + assert_eq!(mesh.materials.len(), 2); + + let text = write_usda(&textured_layer(&mesh, "ball", &bindings).unwrap()); + for expected in [ + "asset inputs:file = @./albedo.png@", + "asset inputs:file = @./orm.png@", + "color3f inputs:diffuseColor.connect = ") && text.contains("/orm.outputs:b>") && text.contains("/albedo.outputs:a>"), "{text}"); + assert!(text.contains("token inputs:sourceColorSpace = \"sRGB\"") && text.contains("token inputs:sourceColorSpace = \"raw\""), "{text}"); + assert_eq!(text.matches("\"UsdUVTexture\"").count(), 2, "one texture shader per file: {text}"); + + // The binary file holds the same layer + let bytes = usd_layer_with_textures(&mesh, "ball", &bindings).unwrap(); + assert!(bytes.starts_with(b"PXR-USDC")); + } + + #[test] + fn an_inverted_destination_is_not_bound() { + let mut inverted = map("rough", FileFormat::Png, vec![(Dest::L, ch(Channel::Roughness, 0))]); + inverted.inverted = vec![Dest::L]; + let plain = map("rough", FileFormat::Png, vec![(Dest::L, ch(Channel::Roughness, 0))]); + let set = set_with(&[]); + assert!(slot(&bind(&set, &options(vec![inverted]), NormalFormat::OpenGl), ROUGHNESS).is_none()); + assert!(slot(&bind(&set, &options(vec![plain]), NormalFormat::OpenGl), ROUGHNESS).is_some()); + } + + #[test] + fn the_tiles_of_a_uv_tiled_set_are_read_through_the_udim_name() { + let opts = options(vec![map("color.$udim", FileFormat::Png, rgba())]); + let set = set_with(&[]); + let mut tile = planned(&opts, 0); + tile.name = "color.1001.png".into(); + tile.tile = Some(1001); + let mut second = tile.clone(); + second.name = "color.1002.png".into(); + second.tile = Some(1002); + + // Tiles without a `` name cannot stand for the others + assert!(usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[tile.clone(), second.clone()]).is_empty()); + + tile.udim_name = Some("color..png".into()); + second.udim_name = tile.udim_name.clone(); + let bindings = usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[tile, second]); + assert_eq!(slot(&bindings, BASE_COLOR).map(|b| b.file.as_str()), Some("color..png")); + assert_eq!(bindings.len(), 1, "the tiles of one map make one binding"); + } + + #[test] + fn only_colour_maps_in_integer_srgb_files_are_tagged_srgb() { + let colour = || vec![(Dest::R, ch(Channel::BaseColor, 0)), (Dest::G, ch(Channel::BaseColor, 1)), (Dest::B, ch(Channel::BaseColor, 2))]; + let set = set_with(&[]); + let tag = |format: FileFormat, depth: u8, space: Option| { + let mut spec = map("c", format, colour()); + spec.bit_depth = depth; + let mut opts = options(vec![spec]); + opts.color_space = space; + let file = planned(&opts, 0); + let expected = opts.space_for_map(&opts.preset.maps[0], file.format, file.bit_depth) == ColorSpace::Srgb; + let bindings = usd_texture_bindings(&set, &opts, NormalFormat::OpenGl, &[PlannedFile { bit_depth: depth, ..file }]); + let srgb = slot(&bindings, BASE_COLOR).unwrap().srgb; + assert_eq!(srgb, expected); + srgb + }; + assert!(tag(FileFormat::Png, 8, None)); + assert!(tag(FileFormat::Png, 16, None)); + assert!(!tag(FileFormat::Exr, 16, None), "float files hold linear colour"); + assert!(!tag(FileFormat::Png, 8, Some(ColorSpace::AcesCg)), "UsdPreviewSurface knows only sRGB and raw"); + + // Data maps are raw + let data = options(vec![map("m", FileFormat::Png, vec![(Dest::L, ch(Channel::Metallic, 0))])]); + assert!(!slot(&bind(&set, &data, NormalFormat::OpenGl), METALLIC).unwrap().srgb); + } + + #[test] + fn roughness_from_glossiness_is_bound_only_for_a_set_with_glossiness() { + let from_glossiness = options(vec![map("r", FileFormat::Png, vec![(Dest::L, virt(VirtualMap::Roughness, 0))])]); + assert!(slot(&bind(&set_with(&[Channel::Glossiness]), &from_glossiness, NormalFormat::OpenGl), ROUGHNESS).is_some()); + assert!(slot(&bind(&set_with(&[]), &from_glossiness, NormalFormat::OpenGl), ROUGHNESS).is_none()); + + // Glossiness itself is the opposite of roughness + let glossiness = options(vec![map("g", FileFormat::Png, vec![(Dest::L, virt(VirtualMap::Glossiness, 0))])]); + assert!(bind(&set_with(&[]), &glossiness, NormalFormat::OpenGl).is_empty()); + } + + #[test] + fn a_file_that_cannot_hold_alpha_or_colour_is_not_bound_for_them() { + let set = set_with(&[Channel::Opacity]); + for format in [FileFormat::Jpeg, FileFormat::Hdr] { + let bindings = bind(&set, &options(vec![map("albedo", format, rgba())]), NormalFormat::OpenGl); + assert!(slot(&bindings, BASE_COLOR).is_some(), "{format:?} keeps the colour"); + assert!(slot(&bindings, OPACITY).is_none(), "{format:?} drops alpha"); + } + assert!(slot(&bind(&set, &options(vec![map("albedo", FileFormat::Png, rgba())]), NormalFormat::OpenGl), OPACITY).is_some()); + + // PGM is one gray channel: colour becomes luminance, and only a map written as L is bound + let pgm = options(vec![ + map("albedo", FileFormat::Pgm, rgba()), + map("orm", FileFormat::Pgm, vec![(Dest::G, ch(Channel::Roughness, 0)), (Dest::B, ch(Channel::Metallic, 0))]), + map("metal", FileFormat::Pgm, vec![(Dest::L, ch(Channel::Metallic, 0))]), + ]); + let bindings = bind(&set, &pgm, NormalFormat::OpenGl); + assert!(slot(&bindings, BASE_COLOR).is_none()); + assert!(slot(&bindings, ROUGHNESS).is_none()); + assert_eq!(slot(&bindings, METALLIC).map(|b| (b.output, b.file.as_str())), Some(("r", "metal.pgm"))); + } + + #[test] + fn a_normal_map_unpacks_with_the_convention_of_its_file() { + let set = set_with(&[]); + let normal = |source: fn(u8) -> SourceRef| { + options(vec![map("n", FileFormat::Png, (0..3).map(|k| ([Dest::R, Dest::G, Dest::B][k as usize], source(k))).collect())]) + }; + let convention = |opts: &ExportOptions| slot(&bind(&set, opts, NormalFormat::DirectX), NORMAL).unwrap().normal; + assert_eq!(convention(&normal(|k| ch(Channel::Normal, k))), Some(NormalFormat::DirectX), "follows the project"); + assert_eq!(convention(&normal(|k| virt(VirtualMap::NormalOpenGl, k))), Some(NormalFormat::OpenGl)); + + let mut forced = normal(|k| virt(VirtualMap::NormalOpenGl, k)); + forced.normal_format = Some(NormalFormat::DirectX); + assert_eq!(convention(&forced), Some(NormalFormat::DirectX), "the export's normal format wins"); + } + + #[test] + fn a_normal_map_takes_its_convention_from_the_green_channel() { + let set = set_with(&[]); + // Red and blue are the same in both conventions; green decides + let mixed = |green: VirtualMap| { + options(vec![map( + "n", + FileFormat::Png, + vec![(Dest::R, virt(VirtualMap::NormalOpenGl, 0)), (Dest::G, virt(green, 1)), (Dest::B, virt(VirtualMap::NormalOpenGl, 2))], + )]) + }; + let convention = |opts: &ExportOptions| slot(&bind(&set, opts, NormalFormat::OpenGl), NORMAL).unwrap().normal; + assert_eq!(convention(&mixed(VirtualMap::NormalDirectX)), Some(NormalFormat::DirectX)); + assert_eq!(convention(&mixed(VirtualMap::NormalOpenGl)), Some(NormalFormat::OpenGl)); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 5b3ed2d3..9abb472c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -27,7 +27,6 @@ log = { workspace = true } base64 = "0.22" image = { workspace = true } craft-image-codecs = { workspace = true } -zip = { workspace = true } # The OS UI language for the first run (MIT OR Apache-2.0; the browser asks `navigator.language`). [target.'cfg(not(target_arch = "wasm32"))'.dependencies] @@ -62,14 +61,20 @@ skrifa = { version = "0.48", default-features = false, features = ["std"] } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] +craft-zip = { workspace = true } rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "CssStyleDeclaration", "Navigator"] } +[dev-dependencies] +craft-zip = { workspace = true } +zip = { workspace = true } + # winit needs a window system on Linux, so the crate's own tests build with X11. [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] +craft-usd.workspace = true eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } diff --git a/crates/ui-egui/src/export_window.rs b/crates/ui-egui/src/export_window.rs index c02948b1..177d5288 100644 --- a/crates/ui-egui/src/export_window.rs +++ b/crates/ui-egui/src/export_window.rs @@ -274,7 +274,7 @@ fn start_export(app: &mut TextureCraftApp) { return; } - e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, ..Default::default() }); + e.job = Some(crate::state::ExportJob { total: pending.len(), pending, preview, directory: dir, usd_asset: e.usd_asset, ..Default::default() }); } /// Two texture sets that would write a file of the same name (ignoring case, as Windows and macOS @@ -365,16 +365,31 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) { params["reservedNames"] = job.written.iter().chain(&job.material_udim_patterns).map(|name| json!(name)).collect(); } + // The last command writes the USD asset from the params of every command, so a canceled or failed export writes none + if let Some(job) = app.ui.export.job.as_mut().filter(|job| job.usd_asset) { + job.sent.push(params.clone()); + if job.pending.is_empty() { + params["usdAsset"] = json!(job.sent); + } + } + let Some(response) = app.run("file.exportTextures", params) else { app.ui.export.job = None; return; }; + // A USD asset that could not be written also shows as an error toast + let usd_failure = response_strings(&response, "warnings").find(|warning| warning.starts_with(texturecraft_engine::file_cmds::USD_ASSET_FAILED)); + if let Some(warning) = usd_failure { + app.toast(warning.to_string(), true); + } + let files: Vec = response_strings(&response, "files") .map(|file| std::path::Path::new(file).file_name().map_or_else(|| file.to_string(), |n| n.to_string_lossy().into_owned())) .collect(); - let mut lines = vec![set(), ConsoleLine::Step(tr("Preparing textures writing").into())]; - for file in &files { + 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")) { let stem = file.rsplit_once('.').map_or(file.as_str(), |(stem, _)| stem); lines.push(set()); lines.push(ConsoleLine::Step(trf("Writing {file} texture on disk", &[("file", &stem)]))); @@ -740,6 +755,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] settings.dilation, settings.normal_format, settings.color_space, + settings.usd_asset, settings.materialx, ) = ( defaults.dir, @@ -751,6 +767,7 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] defaults.dilation, defaults.normal_format, defaults.color_space, + defaults.usd_asset, defaults.materialx, ); crate::export_templates::select(app, defaults.preset); @@ -796,19 +813,20 @@ fn global_page(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset] ui.end_row(); }); - // Unavailable export controls stay disabled - unavailable_checkbox( - ui, - tr("Export USD asset"), - tr("Export USD files hierarchy with material and textures. References the original mesh if possible, exports the mesh otherwise"), - ); + // 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("Package the mesh, materials and textures together as USD")); + #[cfg(target_arch = "wasm32")] + unavailable_checkbox(ui, tr("Export USD asset"), tr("Package the mesh, materials and textures together as USD")); // 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")); - unavailable_checkbox(ui, tr("Export shaders parameters"), tr("Exports a JSON file with the settings for all shader instances")); + + // 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.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; @@ -1279,6 +1297,17 @@ fn follow_texture_sets(app: &mut TextureCraftApp) { set.index = set.index.and_then(moved); } + // The sets already written follow too (the USD asset reads their params); a removed one leaves + job.sent = std::mem::take(&mut job.sent) + .into_iter() + .filter_map(|mut params| { + let Some(index) = params.get("ts").and_then(serde_json::Value::as_u64) else { return Some(params) }; + let index = moved(usize::try_from(index).ok()?)?; + params["ts"] = json!(index); + Some(params) + }) + .collect(); + // Removed sets leave the count too, so the bar keeps its pace job.total -= queued - job.pending.len(); } else { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 5acd63cf..ce308b37 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -357,6 +357,10 @@ pub struct ExportUi { /// "" (by file format: sRGB, or linear for float files), or a colour space name. #[serde(default)] pub color_space: String, + /// Also write `.usd`: the mesh and a material per texture set that reads the exported + /// textures (`usdAsset` of `file.exportTextures`). + #[serde(default)] + pub usd_asset: bool, /// Also write an OpenPBR MaterialX (`.mtlx`) file per texture set (`materialX` of /// `file.exportTextures`). #[serde(default)] @@ -433,6 +437,7 @@ impl Default for ExportUi { size: 0, normal_format: String::new(), color_space: String::new(), + usd_asset: false, materialx: false, skip: Vec::new(), sets: Default::default(), diff --git a/crates/ui-egui/src/state/export_job.rs b/crates/ui-egui/src/state/export_job.rs index 4668df27..cf4a87de 100644 --- a/crates/ui-egui/src/state/export_job.rs +++ b/crates/ui-egui/src/state/export_job.rs @@ -17,6 +17,11 @@ pub struct ExportJob { pub material_udim_patterns: Vec, /// The frame that wrote the last texture set (a frame's second pass writes none). pub frame: u64, + /// 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, + /// The params of the texture sets written so far, for the USD asset. + pub sent: Vec, /// Warning messages already shown in this export. pub shown_warnings: Vec, } diff --git a/crates/ui-egui/src/web_files.rs b/crates/ui-egui/src/web_files.rs index 048d7a97..accc612e 100644 --- a/crates/ui-egui/src/web_files.rs +++ b/crates/ui-egui/src/web_files.rs @@ -9,6 +9,7 @@ use std::sync::{Mutex, PoisonError}; use texturecraft_engine::Session; use texturecraft_engine::core::PROJECT_EXT; +#[cfg(any(target_arch = "wasm32", test))] use texturecraft_engine::formats::ExportedFile; use texturecraft_engine::formats::export::sanitize_file_stem; use texturecraft_engine::formats::mesh_import::MESH_EXTENSIONS; @@ -228,16 +229,14 @@ pub fn project_file_name(app: &TextureCraftApp) -> String { } /// Pack exported textures into one zip archive. -#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))] +#[cfg(any(target_arch = "wasm32", test))] fn zip_files(files: Vec) -> Result, String> { - use std::io::Write as _; - let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); - let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).large_file(true); + let mut zip = craft_zip::Writer::new(); for f in files { - zip.start_file(f.name.as_str(), opts).map_err(|e| e.to_string())?; - zip.write_all(&f.bytes).map_err(|e| e.to_string())?; + // add_with reserves ZIP64 headers up front, even for small entries. + zip.add_with(&f.name, craft_zip::Compression::Deflated, |out| out.write_all(&f.bytes)).map_err(|e| e.to_string())?; } - Ok(zip.finish().map_err(|e| e.to_string())?.into_inner()) + zip.finish().map_err(|e| e.to_string()) } #[cfg(target_arch = "wasm32")] @@ -525,16 +524,23 @@ mod tests { fn zip_round_trips_every_export_file() { let file = |name: &str, bytes: &[u8]| ExportedFile { name: name.into(), bytes: bytes.to_vec(), width: 1, height: 1, warnings: Vec::new() }; let normal = [7u8; 4096]; - let expected = [("a_BaseColor.png", b"one".as_slice()), ("a_Normal.png", normal.as_slice())]; + let expected = [("z_BaseColor.png", b"one".as_slice()), ("a_Normal.png", normal.as_slice())]; let files = expected.iter().map(|(name, bytes)| file(name, bytes)).collect(); let bytes = zip_files(files).unwrap(); - let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap(); assert_eq!(zip.len(), expected.len()); - for (name, expected_bytes) in expected { + for (index, (name, expected_bytes)) in expected.into_iter().enumerate() { + let mut entry = zip.by_index(index).unwrap(); + assert_eq!(entry.name().unwrap(), name); + assert_eq!(entry.compression(), zip::CompressionMethod::Deflated); + let header = entry.header_start() as usize; + let name_len = u16::from_le_bytes(bytes[header + 26..header + 28].try_into().unwrap()) as usize; + let extra = header + 30 + name_len; + assert_eq!(&bytes[extra..extra + 4], &[1, 0, 16, 0], "expected a ZIP64 size extra field"); let mut out = Vec::new(); - std::io::Read::read_to_end(&mut zip.by_name(name).unwrap(), &mut out).unwrap(); + std::io::Read::read_to_end(&mut entry, &mut out).unwrap(); assert_eq!(out, expected_bytes); } } diff --git a/crates/ui-egui/tests/it/export_usd_asset.rs b/crates/ui-egui/tests/it/export_usd_asset.rs new file mode 100644 index 00000000..68f310df --- /dev/null +++ b/crates/ui-egui/tests/it/export_usd_asset.rs @@ -0,0 +1,277 @@ +//! Export textures › SETTINGS: the Export USD asset option. It writes `.usd` (the mesh and a +//! material per texture set that reads the exported textures) next to the textures, with the +//! export's last texture set. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT as _, Queryable as _}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::{ConsoleLine, ExportJob}; + +/// A scratch folder that is removed when it goes out of scope, so a failing test leaves nothing behind. +struct Scratch(std::path::PathBuf); + +impl std::ops::Deref for Scratch { + type Target = std::path::Path; + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The Export textures window writing into a scratch folder of its own for `name` +fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, Scratch) { + 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-usd-asset-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let dir = Scratch(dir); + h.state_mut().ui.export.dir = dir.display().to_string(); + h.state_mut().ui.windows.export = true; + h.run_steps(4); + (h, dir) +} + +fn checkbox<'a>(h: &'a Harness<'static, TextureCraftApp>) -> egui_kittest::Node<'a> { + h.get_by_role_and_label(egui::Role::CheckBox, "Export USD asset") +} + +/// Click Export and run frames until the export ends +fn export(h: &mut Harness<'static, TextureCraftApp>) { + 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); +} + +/// The texture files `/material_ball.usd` refers to +fn referenced_files(dir: &std::path::Path) -> Vec { + let bytes = std::fs::read(dir.join("material_ball.usd")).expect("material_ball.usd"); + let layer = craft_usd::scene::read_layer(&bytes).unwrap(); + layer + .prims + .iter() + .filter_map(|prim| match prim.props.get("inputs:file")?.value.as_ref()? { + craft_usd::scene::Val::Tok(values) => values.first().map(|file| file.trim_start_matches("./").to_string()), + _ => None, + }) + .collect() +} + +#[test] +fn the_window_offers_export_usd_asset_off_by_default() { + let (h, _dir) = harness("offer"); + assert!(!checkbox(&h).accesskit_node().is_disabled()); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn ticking_export_usd_asset_writes_one_file_that_refers_to_the_exported_textures() { + let (mut h, dir) = harness("on"); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.usd_asset); + export(&mut h); + + let files = referenced_files(&dir); + assert!(h.state().session.set_count() >= 2, "one file has to cover several texture sets"); + assert!(files.len() >= h.state().session.set_count(), "every material reads textures: {files:?}"); + for file in &files { + assert!(dir.join(file).is_file(), "{file} was written"); + } + let usd = std::fs::read_dir(&*dir).unwrap().flatten().filter(|e| e.path().extension().is_some_and(|x| x == "usd")).count(); + assert_eq!(usd, 1, "one file for the whole export, not one per texture set"); +} + +#[test] +fn the_file_refers_to_the_textures_each_texture_set_was_exported_with() { + let (mut h, dir) = harness("overrides"); + h.state_mut().ui.export.sets.entry(1).or_default().preset = Some("Unreal Engine (Packed)".into()); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let files = referenced_files(&dir); + assert!(files.iter().any(|f| f.ends_with("_OcclusionRoughnessMetallic.png")), "the second texture set's template: {files:?}"); + assert!(files.iter().any(|f| f.ends_with("_roughness.png")), "the first texture set's template: {files:?}"); + for file in &files { + assert!(dir.join(file).is_file(), "{file} was written"); + } +} + +#[test] +fn only_the_exported_texture_sets_have_textures() { + let (mut h, dir) = harness("subset"); + h.state_mut().ui.export.skip = vec![0]; + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let first = texturecraft_engine::formats::export::sanitize_file_stem(&h.state().session.doc.project.texture_sets[0].name); + let files = referenced_files(&dir); + assert!(!files.is_empty()); + assert!(files.iter().all(|f| !f.starts_with(&format!("material_ball_{first}_"))), "the skipped texture set has none: {files:?}"); +} + +#[test] +fn the_console_lists_the_asset_as_a_file_but_not_as_a_saved_texture() { + let (mut h, _dir) = harness("console"); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let console = &h.state().ui.export.console; + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Done(file) if file == "material_ball.usd")), "{console:?}"); + assert!(!console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text == "Saved texture material_ball")), "{console:?}"); + assert!(console.iter().any(|line| matches!(line, ConsoleLine::Step(text) if text.starts_with("Saved texture "))), "the textures are still listed"); +} + +#[test] +fn a_canceled_export_writes_no_asset() { + let (mut h, dir) = harness("cancel"); + + // A long export, as the window starts it with the option ticked + let sets = h.state().session.set_count(); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending: Vec<(usize, serde_json::Value)> = (0..sets).cycle().take(sets * 8).map(|ts| (ts, params.clone())).collect(); + let e = &mut h.state_mut().ui.export; + e.tab = 2; + e.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, ..ExportJob::default() }); + h.run_steps(2); + h.get_all_by_label("Cancel Export").last().unwrap().click(); + h.run_steps(3); + assert!(h.state().ui.export.job.is_none()); + assert!(!dir.join("material_ball.usd").exists()); + + // The same job run to its end writes it + let pending: Vec<(usize, serde_json::Value)> = (0..sets).map(|ts| (ts, params.clone())).collect(); + h.state_mut().ui.export.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, ..ExportJob::default() }); + for _ in 0..64 { + if h.state().ui.export.job.is_none() { + break; + } + h.run_steps(1); + } + assert!(dir.join("material_ball.usd").is_file()); +} + +#[test] +fn no_asset_is_written_when_the_option_is_off() { + let (mut h, dir) = harness("off"); + export(&mut h); + assert!(std::fs::read_dir(&*dir).unwrap().next().is_some(), "the textures were written"); + assert!(!dir.join("material_ball.usd").exists()); +} + +#[test] +fn restoring_the_default_parameters_unticks_export_usd_asset() { + let (mut h, _dir) = harness("reset"); + checkbox(&h).click(); + h.run_steps(3); + assert!(h.state().ui.export.usd_asset); + h.get_by_label("Restore the default export parameters").click(); + h.run_steps(3); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn reset_all_unticks_export_usd_asset() { + let (mut h, _dir) = harness("reset-all"); + checkbox(&h).click(); + h.run_steps(3); + h.get_by_label("Reset all").click(); + h.run_steps(3); + assert!(!h.state().ui.export.usd_asset); +} + +#[test] +fn an_asset_that_cannot_be_written_shows_an_error_toast_and_the_textures_stay() { + let (mut h, dir) = harness("blocked"); + + // A folder where the file belongs: the asset cannot be written there + std::fs::create_dir_all(dir.join("material_ball.usd")).unwrap(); + checkbox(&h).click(); + h.run_steps(3); + export(&mut h); + + let toast = h.state().toasts.iter().find(|toast| toast.text.starts_with("The USD asset was not written")).expect("a toast names the failure"); + assert!(toast.error); + assert!(h.state().ui.export.job.is_none(), "the export ran to its end"); + assert!(std::fs::read_dir(&*dir).unwrap().flatten().any(|e| e.path().extension().is_some_and(|x| x == "png")), "the textures were written"); +} + +/// A running USD export that has already written texture sets 0 and 1 (the `tag` of each sent command tells them apart) +fn running_with_two_sent(h: &mut Harness<'static, TextureCraftApp>, dir: &std::path::Path) { + let sets = h.state().session.set_count(); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending: Vec<(usize, serde_json::Value)> = (0..sets).cycle().take(sets * 8).map(|ts| (ts, params.clone())).collect(); + let sent = (0..2).map(|ts| serde_json::json!({"dir": dir.display().to_string(), "ts": ts, "tag": ts})).collect(); + let e = &mut h.state_mut().ui.export; + e.tab = 2; + e.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, sent, ..ExportJob::default() }); +} + +/// The `ts` of the sent commands that carry `tag` +fn sent_ts(h: &Harness<'static, TextureCraftApp>, tag: u64) -> Vec { + let job = h.state().ui.export.job.as_ref().expect("the export is still running"); + job.sent.iter().filter(|params| params["tag"] == tag).map(|params| params["ts"].as_u64().unwrap()).collect() +} + +#[test] +fn the_sent_commands_of_a_running_export_follow_their_texture_sets_when_they_move() { + let (mut h, dir) = harness("sent-move"); + running_with_two_sent(&mut h, &dir); + h.run_steps(1); + assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![0], vec![1])); + + // The two texture sets trade places (names), as a reorder does + let names: Vec = h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect(); + for (ts, name) in [(0, "swap"), (1, names[0].as_str()), (0, names[1].as_str())] { + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.rename", &serde_json::json!({"ts": ts, "name": name})).unwrap(); + } + h.run_steps(1); + assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![1], vec![0]), "each command stays with its texture set"); +} + +#[test] +fn the_sent_command_of_a_texture_set_that_leaves_the_export_is_dropped() { + let (mut h, dir) = harness("sent-drop"); + running_with_two_sent(&mut h, &dir); + h.run_steps(1); + + // A rename the export cannot follow takes the texture set out of it + texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.rename", &serde_json::json!({"ts": 1, "name": "renamed"})).unwrap(); + h.run_steps(1); + assert_eq!((sent_ts(&h, 0), sent_ts(&h, 1)), (vec![0], vec![])); +} + +#[test] +fn each_sent_command_keeps_the_names_it_reserved_for_the_asset() { + let (mut app_harness, dir) = harness("sent-reserved"); + let params = serde_json::json!({"dir": dir.display().to_string()}); + let pending = vec![(0, params.clone()), (1, params)]; + let settings = &mut app_harness.state_mut().ui.export; + settings.tab = 2; + settings.job = Some(ExportJob { total: pending.len(), pending, usd_asset: true, written: vec!["earlier.png".into()], ..ExportJob::default() }); + + for _ in 0..8 { + app_harness.run_steps(1); + if app_harness.state().ui.export.job.as_ref().is_none_or(|job| !job.sent.is_empty()) { + break; + } + } + + let job = app_harness.state().ui.export.job.as_ref().expect("the export is still running"); + let reserved = job.sent.first().and_then(|params| params["reservedNames"].as_array()).expect("the sent command carries its reserved names"); + assert!(reserved.iter().any(|name| name == "earlier.png"), "the asset skips what the texture export skipped: {reserved:?}"); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index a4bbd233..756fd42a 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -28,6 +28,7 @@ mod export_progress; mod export_reference_texts; mod export_settings; mod export_template_guards; +mod export_usd_asset; mod file_dialogs; mod fill_channel_image; mod fill_material_rows; diff --git a/crates/ui-egui/tests/it/side_panels.rs b/crates/ui-egui/tests/it/side_panels.rs index 052068a6..aab7c36d 100644 --- a/crates/ui-egui/tests/it/side_panels.rs +++ b/crates/ui-egui/tests/it/side_panels.rs @@ -118,7 +118,8 @@ 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 USD asset")); + assert!(says_not_available(&mut harness, "Export shader settings")); harness.get_by_label("Save settings").click(); harness.run_steps(SETTLE_FRAMES); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ecb5cdbf..7d1a1f33 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -47,6 +47,19 @@ template. `enabled: false` suppresses that file while reserving its name. When s 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. +`file.exportTextures` with `usdAsset` also writes `.usd` (binary USD, Crate) next to the textures: the whole mesh +(every texture set, whatever `ts` selects) with one UsdPreviewSurface material per texture set. A +material's inputs read the texture files the export planned for that set with its output template +(`usdAsset: true`: the sets, options and `reservedNames` of this command; a list of export params such as +`[{"ts": 0, "preset": "..."}, {"ts": 1}]`, not empty, every entry an object: each entry's sets, options and `reservedNames`, the way the export window, +which runs one command per texture set, passes the params of all its commands with the last one). +Bound inputs: `diffuseColor`, `roughness`, `metallic`, `normal`, `emissiveColor`, `opacity`, +`clearcoat` and `clearcoatRoughness`, each reading the `rgb`, `r`, `g`, `b` or `a` output of the +file that holds it; other maps (ambient occlusion, height, specular...) are not bound, a UDIM map that lost a tile to an earlier +set's file name or to an entry's `reservedNames` is not bound, a mesh with no materials gets one implicit `default` material bound to the Default set, and a texture set outside the export has +no textures. A file name is relative to the file (`./`, with `` for UV tiles). A failure +to build or write it is named in `warnings` and the command still succeeds. The file is in `files`. + `file.exportTextures` with `materialX: true` also writes an OpenPBR `.mtlx` beside each texture set's maps. It reuses compatible maps with OpenPBR names and writes dedicated maps for remaining inputs with data. A named OpenPBR map explicitly disabled in `maps` stays disabled. Dedicated maps diff --git a/docs/features.md b/docs/features.md index 14e1be68..04702ee9 100644 --- a/docs/features.md +++ b/docs/features.md @@ -177,6 +177,22 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA file type, size or padding, and each output map's file type and bit depth, or leaves a map out; Export shows the progress, a console of its steps, the written files and the export's warnings (each once), and can be canceled between texture sets). +- **USD asset export:** the *Export USD asset* checkbox on the Export textures window's Global + settings (off by default, remembered with the other settings) also writes `.usd` (binary USD) next to + the exported textures when the last selected texture set is written. It holds the whole mesh with + one UsdPreviewSurface material per texture set; each material refers to the textures that texture + set was exported with (its own output template, file type, size and normal format) by relative + file name. Base colour, roughness, metallic, normal, emissive colour, opacity, clear coat and clear + coat roughness are bound; a packed template (ORM, mask map) binds several inputs to different + channels of one file. A UDIM map that lost a tile to an earlier texture set's file name or to a + UDIM pattern an earlier MaterialX document of the export uses gets no binding, and a mesh with no materials gets one implicit "default" material bound to the Default + texture set. Ambient occlusion, height and specular are not bound (the material has occlusion, + displacement and specularColor inputs, but TextureCraft does not fill them), nor are glossiness + (no matching input) and baked maps; sheen, anisotropy, transmission, scatter and coat normal have no + UsdPreviewSurface input. Colour maps written as sRGB are tagged sRGB, other maps raw; a DirectX normal map is + flipped back in the material. A texture set outside the export has no textures in the file. A + canceled export writes none, and a failure to write it is a warning. In the browser the option is + greyed. - **MaterialX export:** the *Export MaterialX* checkbox on the Export textures window's Global settings (off by default, remembered with the other settings) writes an OpenPBR `.mtlx` for each selected texture set with usable maps. Materials reference textures beside the document. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 2c04591e..1d52846a 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -67,11 +67,12 @@ that closes it back onto the bar; the float is saved with the UI state. is left out, [#789](https://github.com/storytold/texturecraft/issues/789)). EXPORT has *Export Mesh...* (the *Mesh Export Options* prompt, then the file choice) and *Export Textures...* (the Export textures window: *Global settings* above the texture sets, *General Export Parameters*, *Export USD asset* - and *Export shaders parameters* greyed, *Include all*, *Save settings* and "N textures selected - for export"). *Export MaterialX* below *Export USD asset* is a TextureCraft addition: it adds `materialX: true` - to the export. The prompt's *With displacement/tessellation* choice and both option checkboxes are - greyed; TextureCraft exports the mesh as it is. The two (i) icons carry the reference's - tooltips. + (off by default; it adds `usdAsset` to the last texture set's export, which writes `.usd` + with materials that refer to the exported textures; greyed in the browser), *Export shaders + parameters* greyed, *Include all*, *Save settings* and "N textures selected for export"). + *Export MaterialX* beside them is a TextureCraft addition: it adds `materialX: true` to the + export. The prompt's *With displacement/tessellation* choice and both option checkboxes are + greyed; TextureCraft exports the mesh as it is. - **Window menu:** Views lists *Renderer Settings* (a panel of its own: the tracer in use, the samples so far and a note; it floats when first opened and is not opened by itself in Rendering mode), *Properties - Paint* while a project is open (other tools read "Properties - ",