mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-24 00:10:45 +01:00
Keep the files of earlier texture sets of an export when writing the MaterialX maps
This commit is contained in:
1 parent
927fedf313
commit
c9640bae07
6 files changed
+213
-10
No files matched your search
@@ -55,7 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}",
|
||||
"{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] (files an earlier command of the same export wrote, compared ignoring case: this command leaves out its own files and OpenPBR maps of these names and says so in `warnings`; the export window passes it), materialX?: bool (also write a .mtlx OpenPBR material per texture set; a preset without OpenPBR file names gets the maps of the \"OpenPBR (separate maps)\" preset written beside its own files, without the per-map `maps` overrides)}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -641,21 +641,29 @@ fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let opts = export_options(s, p, "file.exportTextures")?;
|
||||
let sets = sets_param(s, p, "file.exportTextures")?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?;
|
||||
let reserved = reserved_names(p)?;
|
||||
let files = s.export_files(&sets, &opts)?;
|
||||
|
||||
// A file an earlier command of the same export wrote keeps its name: the export window runs
|
||||
// one command per texture set, and a later set's file must not replace an earlier one (which an
|
||||
// earlier .mtlx may refer to)
|
||||
let (files, skipped): (Vec<_>, Vec<_>) = files.into_iter().partition(|f| !reserved.contains(&f.name.to_ascii_lowercase()));
|
||||
let mut warnings: Vec<String> = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect();
|
||||
warnings.extend(skipped.iter().map(|f| format!("\"{}\" was not written: an earlier file of this export has the same name", f.name)));
|
||||
let mut written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?;
|
||||
|
||||
// The rendered files are not needed after this; only their names are
|
||||
let mut taken: std::collections::HashSet<String> = files.iter().map(|f| f.name.to_ascii_lowercase()).collect();
|
||||
let own: std::collections::HashSet<String> = files.iter().map(|f| f.name.to_ascii_lowercase()).collect();
|
||||
drop(files);
|
||||
drop(skipped);
|
||||
let mut taken = reserved;
|
||||
if p.get("materialX").and_then(Value::as_bool).unwrap_or(false) {
|
||||
// The material reads OpenPBR maps whatever template was chosen: a template without
|
||||
// their file names gets an extra pass of the built-in OpenPBR template beside its own files
|
||||
let extra = openpbr_options(&opts);
|
||||
let material_opts = extra.as_ref().unwrap_or(&opts);
|
||||
if extra.is_none() {
|
||||
taken.clear();
|
||||
} else {
|
||||
if extra.is_some() {
|
||||
taken.extend(own);
|
||||
let mut maps = s.export_files(&sets, material_opts)?;
|
||||
for file in &maps {
|
||||
for warning in &file.warnings {
|
||||
@@ -665,12 +673,12 @@ fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
// A file of the chosen template is never replaced; the material leaves out the map it would have used
|
||||
// A file of the chosen template, or of an earlier command of this export, is never replaced; the material leaves out the map it would have used
|
||||
let before = maps.len();
|
||||
maps.retain(|f| !taken.contains(&f.name.to_ascii_lowercase()));
|
||||
if maps.len() < before {
|
||||
warnings
|
||||
.push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template, so the material does not use it".into());
|
||||
.push("MaterialX: a map of the OpenPBR template has the file name of a map of the chosen template or of an earlier file of this export, so the material does not use it".into());
|
||||
}
|
||||
written.extend(texturecraft_formats::write_files(&maps, std::path::Path::new(&dir)).map_err(fe)?);
|
||||
}
|
||||
@@ -680,6 +688,19 @@ fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(), "warnings": warnings }))
|
||||
}
|
||||
|
||||
/// `reservedNames`: the names of files earlier commands of the same export wrote (lower-cased).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn reserved_names(p: &Value) -> Result<std::collections::HashSet<String>> {
|
||||
match p.get("reservedNames") {
|
||||
None | Some(Value::Null) => Ok(Default::default()),
|
||||
Some(Value::Array(names)) => names
|
||||
.iter()
|
||||
.map(|name| name.as_str().map(str::to_ascii_lowercase).ok_or_else(|| bad("file.exportTextures", "`reservedNames` must be a list of file names")))
|
||||
.collect(),
|
||||
Some(_) => Err(bad("file.exportTextures", "`reservedNames` must be a list of file names")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The options of the extra pass that writes the maps a MaterialX reads, or None when `opts`'
|
||||
/// template already has a map with an OpenPBR file name (`texturecraft_formats::materialx`).
|
||||
/// The pass uses the built-in "OpenPBR (separate maps)" template with the export's size,
|
||||
@@ -730,6 +751,7 @@ fn write_materialx(
|
||||
let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
let mut out = Vec::new();
|
||||
let mut stems = std::collections::HashSet::new();
|
||||
let reserved = taken.clone();
|
||||
let mut written_names = taken;
|
||||
let mut normal_map_written = false;
|
||||
let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065);
|
||||
@@ -780,7 +802,16 @@ fn write_materialx(
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = dir.join(format!("{stem}.mtlx"));
|
||||
let file_name = format!("{stem}.mtlx");
|
||||
if reserved.contains(&file_name.to_ascii_lowercase()) {
|
||||
warnings.push(format!(
|
||||
"MaterialX: texture set \"{}\" exports as \"{file_name}\" like an earlier file of this export, so its .mtlx was not written",
|
||||
set.name
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = dir.join(file_name);
|
||||
texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?;
|
||||
aces2065_written |=
|
||||
textures.iter().any(|texture| texture.colorspace == aces2065_tag && materialx::INPUTS.contains(&(texture.input.as_str(), materialx::Kind::Color)));
|
||||
|
||||
@@ -249,6 +249,96 @@ fn a_file_of_the_template_is_never_replaced_by_an_openpbr_map() {
|
||||
assert!(!referenced(&first).contains(&"material_ball_a_base_color.png".to_string()), "{first}");
|
||||
}
|
||||
|
||||
/// A template with one map, the base colour, named `$mesh_$textureSet` (no input suffix)
|
||||
fn base_colour_template() -> texturecraft_engine::formats::ExportPreset {
|
||||
use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef};
|
||||
let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component };
|
||||
ExportPreset {
|
||||
name: "base colour only".into(),
|
||||
maps: vec![MapSpec {
|
||||
file: "$mesh_$textureSet".into(),
|
||||
format: FileFormat::Png,
|
||||
bit_depth: 8,
|
||||
channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))],
|
||||
inverted: Vec::new(),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// One `file.exportTextures` command of texture set `ts`, as the export window sends them: the
|
||||
/// names of the files the earlier commands wrote are passed as `reservedNames`
|
||||
fn export_set(s: &mut Session, dir: &std::path::Path, ts: usize, earlier: &[String]) -> Value {
|
||||
let params = json!({"dir": dir.display().to_string(), "preset": base_colour_template(), "ts": ts, "materialX": true, "reservedNames": earlier});
|
||||
execute(s, "file.exportTextures", ¶ms).unwrap()
|
||||
}
|
||||
|
||||
fn warned(r: &Value, text: &str) -> bool {
|
||||
r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains(text))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_openpbr_map_never_replaces_a_file_an_earlier_command_of_the_export_wrote() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
// Set 0's own file is named like the base colour map set 1 gets from the OpenPBR template
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a_base_color"})).unwrap();
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a"})).unwrap();
|
||||
let dir = temp("later-extra");
|
||||
let first = export_set(&mut s, &dir, 0, &[]);
|
||||
let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap();
|
||||
let second = export_set(&mut s, &dir, 1, &names(&first));
|
||||
assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched");
|
||||
assert!(warned(&second, "has the file name of a map of the chosen template or of an earlier file of this export"), "{second}");
|
||||
let material = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap();
|
||||
assert!(!referenced(&material).contains(&"material_ball_a_base_color.png".to_string()), "{material}");
|
||||
for file in referenced(&material) {
|
||||
assert!(dir.join(&file).is_file(), "{file}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_of_the_template_never_replaces_an_openpbr_map_an_earlier_command_wrote() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
// Set 0's OpenPBR base colour has the name set 1's own file gets from the template
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap();
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "a_base_color"})).unwrap();
|
||||
let dir = temp("later-own");
|
||||
let first = export_set(&mut s, &dir, 0, &[]);
|
||||
let kept = std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap();
|
||||
let second = export_set(&mut s, &dir, 1, &names(&first));
|
||||
assert_eq!(std::fs::read(dir.join("material_ball_a_base_color.png")).unwrap(), kept, "the earlier file is untouched");
|
||||
assert!(warned(&second, "\"material_ball_a_base_color.png\" was not written"), "{second}");
|
||||
|
||||
// The earlier material still points at the file it was written with
|
||||
let earlier = std::fs::read_to_string(dir.join("material_ball_a.mtlx")).unwrap();
|
||||
assert!(referenced(&earlier).contains(&"material_ball_a_base_color.png".to_string()), "{earlier}");
|
||||
let later = std::fs::read_to_string(dir.join("material_ball_a_base_color.mtlx")).unwrap();
|
||||
assert!(!referenced(&later).contains(&"material_ball_a_base_color.png".to_string()), "{later}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_material_is_not_written_over_a_file_an_earlier_command_wrote() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "a"})).unwrap();
|
||||
let dir = temp("mtlx-name");
|
||||
let r = export_set(&mut s, &dir, 0, &["MATERIAL_BALL_A.MTLX".to_string()]);
|
||||
assert!(!files(&r).iter().any(|f| f.ends_with(".mtlx")), "{r}");
|
||||
assert!(warned(&r, "exports as \"material_ball_a.mtlx\" like an earlier file of this export"), "{r}");
|
||||
let r = export_set(&mut s, &dir, 0, &["unrelated.mtlx".to_string()]);
|
||||
assert!(files(&r).iter().any(|f| f.ends_with("material_ball_a.mtlx")), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_names_must_be_a_list_of_names() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let dir = temp("bad-reserved");
|
||||
for bad in [json!("a.png"), json!([1])] {
|
||||
let params = json!({"dir": dir.display().to_string(), "preset": OPENPBR, "reservedNames": bad});
|
||||
assert!(execute(&mut s, "file.exportTextures", ¶ms).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_colour_maps_are_tagged_linear() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
@@ -326,6 +326,10 @@ fn export_step(app: &mut TextureCraftApp, frame: u64) {
|
||||
let set = || ConsoleLine::Set(name.clone());
|
||||
app.ui.export.console.extend([set(), set(), ConsoleLine::Step(tr("Rendering the selected maps").into())]);
|
||||
|
||||
// The files of the earlier texture sets keep their names, the material's extra maps and .mtlx files included
|
||||
if let Some(job) = app.ui.export.job.as_ref().filter(|job| !job.written.is_empty()) {
|
||||
params["reservedNames"] = json!(job.written);
|
||||
}
|
||||
let Some(response) = app.run("file.exportTextures", params) else {
|
||||
app.ui.export.job = None;
|
||||
return;
|
||||
|
||||
@@ -149,3 +149,75 @@ fn a_warning_every_texture_set_raises_shows_once_in_the_console_and_the_log() {
|
||||
assert_eq!(h.state().session.log.iter().filter(|line| line.contains(DIRECTX_WARNING)).count(), 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A template with one map, the base colour, named `$mesh_$textureSet` (no input suffix)
|
||||
fn base_colour_template() -> texturecraft_engine::formats::ExportPreset {
|
||||
use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef};
|
||||
let source = |component| SourceRef::Channel { channel: texturecraft_engine::core::Channel::BaseColor, component };
|
||||
ExportPreset {
|
||||
name: "base colour only".into(),
|
||||
maps: vec![MapSpec {
|
||||
file: "$mesh_$textureSet".into(),
|
||||
format: FileFormat::Png,
|
||||
bit_depth: 8,
|
||||
channels: vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))],
|
||||
inverted: Vec::new(),
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// The base colour of texture set `ts` as the template writes it, from a plain export
|
||||
fn expected(h: &mut Harness<'static, TextureCraftApp>, ts: usize, preset: &str, file: &str, tag: &str) -> Vec<u8> {
|
||||
let dir = std::env::temp_dir().join(format!("tc-export-materialx-expected-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let params = serde_json::json!({"dir": dir.display().to_string(), "preset": preset, "ts": ts});
|
||||
texturecraft_engine::execute(&mut h.state_mut().session, "file.exportTextures", ¶ms).unwrap();
|
||||
let bytes = std::fs::read(dir.join(file)).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_sets_of_one_export_never_overwrite_each_others_files() {
|
||||
const SHARED: &str = "material_ball_a_base_color.png";
|
||||
|
||||
// (names of set 0 and set 1, the template whose export of set 0 must be what SHARED holds,
|
||||
// the material that refers to SHARED)
|
||||
let cases = [
|
||||
// Set 0's own file has the name set 1's OpenPBR base colour would get
|
||||
("a_base_color", "a", "base colour only", None),
|
||||
// Set 0's OpenPBR base colour has the name set 1's own file would get
|
||||
("a", "a_base_color", "OpenPBR (separate maps)", Some("material_ball_a.mtlx")),
|
||||
];
|
||||
for (index, (first, second, template_of_set_0, referred_by)) in cases.into_iter().enumerate() {
|
||||
let (mut h, dir) = harness(&format!("overwrite-{index}"));
|
||||
let project = &mut h.state_mut().session.doc.project;
|
||||
project.texture_sets[0].name = first.into();
|
||||
project.texture_sets[1].name = second.into();
|
||||
let template = base_colour_template();
|
||||
let name = template.name.clone();
|
||||
h.state_mut().session.export_presets.list.push(template);
|
||||
h.state_mut().ui.export.preset = name;
|
||||
h.run_steps(3);
|
||||
checkbox(&h).click();
|
||||
h.run_steps(3);
|
||||
export(&mut h);
|
||||
|
||||
let want = expected(&mut h, 0, template_of_set_0, SHARED, &index.to_string());
|
||||
assert_eq!(std::fs::read(dir.join(SHARED)).unwrap(), want, "case {index}: the earlier texture set's file was replaced");
|
||||
|
||||
// A material only points at files that exist, and only the earlier set's material at SHARED
|
||||
let materials = mtlx_files(&dir);
|
||||
assert_eq!(materials.len(), 2, "{materials:?}");
|
||||
for material in materials {
|
||||
let text = std::fs::read_to_string(&material).unwrap();
|
||||
let file_name = material.file_name().unwrap().to_string_lossy().into_owned();
|
||||
for reference in text.split("name=\"file\" type=\"filename\" value=\"").skip(1) {
|
||||
let name = reference.split('"').next().unwrap();
|
||||
assert!(dir.join(name).is_file(), "case {index}: {name} is missing");
|
||||
assert!(name != SHARED || referred_by == Some(file_name.as_str()), "case {index}: {file_name} refers to {name}");
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,11 @@ and warn about later duplicates. The desktop export window reports the collision
|
||||
`file.exportTextures` with `materialX: true` also writes a `.mtlx` OpenPBR material per texture set.
|
||||
A template without OpenPBR file names gets the maps of the "OpenPBR (separate maps)" template written
|
||||
beside its own files for it; the `maps` overrides above do not reach those maps.
|
||||
`reservedNames: [file names]` lists the files earlier `file.exportTextures` commands of the same
|
||||
export wrote (the export window runs one command per texture set and passes it). The command
|
||||
compares them ignoring case, does not write a file, an OpenPBR map or a `.mtlx` of such a name,
|
||||
and names it in `warnings`; a material leaves out the input of a map it did not write. Without it
|
||||
nothing is reserved.
|
||||
|
||||
`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
|
||||
|
||||
+3
-2
@@ -183,8 +183,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
template is selected: a template without OpenPBR file names gets the maps of *OpenPBR (separate
|
||||
maps)* written beside its own files, with the export's size, padding, colour space, file type
|
||||
and bit depth (PNG when that file type has no use in a material) and always an OpenGL normal
|
||||
map. Not covered yet: MaterialX standard_surface, Coat Normal, Specular Level, Anisotropy
|
||||
Angle and constants such as IOR. In the browser the option is greyed.
|
||||
map. A file of one texture set never replaces a file of an earlier one in the same export, the
|
||||
material's maps included. Not covered yet: MaterialX standard_surface, Coat Normal, Specular
|
||||
Level, Anisotropy Angle and constants such as IOR. In the browser the option is greyed.
|
||||
- **Mesh export** to OBJ with an MTL material library and its maps (PBR extension keys for
|
||||
roughness, metallic, normal and coat; UV-tiled sets keep their UDIM UVs and export their maps
|
||||
through Export textures), textured GLB (with clear coat and sheen) and USD (with clear coat).
|
||||
|
||||
Reference in new issue
Block a user