mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-21 20:08:15 +00:00
Auto: Integrate texture export and preserve browser log sources
Keep per-set export settings and case-insensitive filename deduplication. Route browser warnings and completion counts through MapExporter, and retain both the 2D view and texture export parity sections.
This commit is contained in:
Generated
+12
@@ -952,6 +952,17 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-psd"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=b130ac1fa44f923c3024884ab8ceb5ccdb88f15f#b130ac1fa44f923c3024884ab8ceb5ccdb88f15f"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"rayon",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-quit"
|
||||
version = "0.1.0"
|
||||
@@ -4685,6 +4696,7 @@ dependencies = [
|
||||
"craft-materialx",
|
||||
"craft-mcmat",
|
||||
"craft-mesh",
|
||||
"craft-psd",
|
||||
"craft-tcraft",
|
||||
"craft-usd",
|
||||
"craft-zip 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5631e99fe126cffb74c673eb458db04299f2bb9b)",
|
||||
|
||||
@@ -28,7 +28,7 @@ USAGE:
|
||||
texturecraft-cli bake <input> [-o <out.tcraft>] [--resolution <px>] [--maps <id,id,...>]
|
||||
Bake mesh maps for every texture set (a project is saved in place without -o).
|
||||
texturecraft-cli export <input> <dir> [--preset <name>] [--format <ext>] [--padding <mode>] [--size <px>]
|
||||
Export textures (default preset: Document channels + Normal + AO).
|
||||
Export textures (default preset: Document channels + Normal + AO (No Alpha)).
|
||||
texturecraft-cli render <input> <out.png> [--size <W>x<H>] [--view 3d|2d] [--camera <name>] [--yaw <deg>]
|
||||
[--pitch <deg>] [--samples <n>] [--bounces <n>] [--cpu]
|
||||
Render the viewport to PNG (needs a GPU or software adapter); --camera looks through a
|
||||
|
||||
@@ -464,6 +464,25 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&brush_dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_does_not_let_a_later_texture_set_replace_an_earlier_ones_file() {
|
||||
let dir = std::env::temp_dir().join(format!("tc-headless-same-name-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let session = texturecraft_engine::sample_session(128, 64).unwrap();
|
||||
let mut client = Headless::new_with_brush_dir(session, Filesystem::TrustedLocal, dir.join("brushes"));
|
||||
let sets = client.session.set_count();
|
||||
assert!(sets >= 2);
|
||||
|
||||
// A template without $textureSet gives every set the same file name
|
||||
let preset =
|
||||
json!({"name": "same", "maps": [{"file": "same", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]});
|
||||
let r = client.export(&json!({"dir": dir.join("tex").display().to_string(), "preset": preset, "ts": "all"})).unwrap();
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 1, "only the first set's file is written: {r}");
|
||||
let warned = r["warnings"].as_array().unwrap().iter().filter(|w| w.as_str().unwrap().contains("so it was not written")).count();
|
||||
assert_eq!(warned, sets - 1, "{r}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn untrusted_headless_keeps_brushes_in_memory_only() {
|
||||
let brush_dir = std::env::temp_dir().join(format!("tc-headless-denied-{}", std::process::id()));
|
||||
|
||||
@@ -18,6 +18,10 @@ use crate::security::MAX_BATCH_STEPS;
|
||||
use crate::workspace::authorize_command;
|
||||
use crate::{AutomationError, BridgeClient, Headless, bad};
|
||||
|
||||
mod export_map_params;
|
||||
|
||||
pub use export_map_params::ExportMapParams;
|
||||
|
||||
/// Where tools run.
|
||||
pub enum Backend {
|
||||
/// An in-process session.
|
||||
@@ -152,12 +156,24 @@ pub struct ExportParams {
|
||||
/// File format override: png, jpg, tga, tif, exr, …
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
/// none | dilation | dilationDefault | infinite
|
||||
/// Bit depth override (8, 16 or 32, depending on the format).
|
||||
#[serde(default, rename = "bitDepth", skip_serializing_if = "Option::is_none")]
|
||||
pub bit_depth: Option<u8>,
|
||||
/// Apply ordered dithering to 8-bit outputs.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dithering: Option<bool>,
|
||||
/// none | dilation | dilationDefault | diffusion | infinite.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub padding: Option<String>,
|
||||
/// Padding width in texels for dilation and diffusion.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dilation: Option<u32>,
|
||||
/// Output size in pixels (power of two).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
/// Settings for individual maps in the selected template.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub maps: Option<Vec<ExportMapParams>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Overrides for one output map.
|
||||
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExportMapParams {
|
||||
/// Index of the map in the preset.
|
||||
pub map: usize,
|
||||
/// False leaves this map out of the export.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub enabled: Option<bool>,
|
||||
/// File format override, such as png, pgm or tiff.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format: Option<String>,
|
||||
/// Bit depth override (8, 16 or 32, depending on the format).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub bit_depth: Option<u8>,
|
||||
/// Override dithering for this map's 8-bit outputs.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dithering: Option<bool>,
|
||||
}
|
||||
@@ -86,6 +86,29 @@ async fn inspect(c: &Conn) -> Value {
|
||||
tool(c, "session_inspect", json!({})).await
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn textures_export_accepts_per_map_settings() {
|
||||
let dir = tmp("map-options");
|
||||
let (client, server) = connect(workspace(&dir)).await;
|
||||
|
||||
let result = tool(
|
||||
&client,
|
||||
"textures_export",
|
||||
json!({"dir": "textures", "preset": "glTF PBR Metal Roughness", "maps": [
|
||||
{"map": 0, "format": "pgm", "bitDepth": 16},
|
||||
{"map": 1, "enabled": false}
|
||||
]}),
|
||||
)
|
||||
.await;
|
||||
|
||||
let files = result["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2, "{result}");
|
||||
let graymap = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".pgm")).unwrap();
|
||||
assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n128 128\n65535\n"));
|
||||
shutdown(client, server).await;
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
fn top(s: &Value) -> &Value {
|
||||
&s["layers"][0]
|
||||
}
|
||||
|
||||
+111
-39
@@ -9,7 +9,7 @@ use serde_json::{Value, json};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use texturecraft_core::{NormalFormat, PROJECT_EXT};
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile};
|
||||
use texturecraft_geom::{Mesh, primitives};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
|
||||
@@ -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?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, 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 and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
|
||||
"{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; needs the \"OpenPBR (separate maps)\" preset)}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List export outputs",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, size?, colorSpace?} → [{ts, map, file, format, bitDepth, warnings}]",
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)",
|
||||
always,
|
||||
plan
|
||||
),
|
||||
@@ -265,7 +265,9 @@ impl Session {
|
||||
reservation.save_bytes(&self.project_snapshot()).map_err(fe)
|
||||
}
|
||||
|
||||
/// Render every export file for texture sets `sets` (in memory; works on the web).
|
||||
/// Render every export file for texture sets `sets` (in memory; works on the web). A file
|
||||
/// named like one an earlier set exports is left out, with a warning (see
|
||||
/// [`texturecraft_formats::skip_repeated_names`]).
|
||||
pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result<Vec<ExportedFile>> {
|
||||
if self.solo.is_none() {
|
||||
self.update();
|
||||
@@ -288,6 +290,9 @@ impl Session {
|
||||
};
|
||||
out.extend(texturecraft_formats::render_maps(&input, opts).map_err(fe)?);
|
||||
}
|
||||
|
||||
// A later set's file would replace an earlier set's of the same name
|
||||
texturecraft_formats::skip_repeated_names(&mut out);
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
@@ -303,40 +308,43 @@ fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> {
|
||||
|
||||
/// Export options from command params; `preset` is a built-in or user preset name, or an inline
|
||||
/// preset object (validated).
|
||||
pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions> {
|
||||
let preset = match p.get("preset") {
|
||||
None | Some(Value::Null) => s.export_preset("Document channels + Normal + AO"),
|
||||
Some(Value::String(name)) => s.export_preset(name),
|
||||
pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result<ExportOptions> {
|
||||
let preset = match params.get("preset") {
|
||||
None | Some(Value::Null) => session.export_preset(texturecraft_formats::DEFAULT_PRESET),
|
||||
Some(Value::String(name)) => session.export_preset(name),
|
||||
Some(v @ Value::Object(_)) => Some(crate::preset_cmds::preset_param(v, cmd)?),
|
||||
Some(_) => return Err(bad(cmd, "`preset` must be a preset name or a preset object")),
|
||||
};
|
||||
|
||||
let preset = preset.ok_or_else(|| bad(cmd, format!("unknown export preset {}", p.get("preset").unwrap_or(&Value::Null))))?;
|
||||
let mut o = ExportOptions::new(preset);
|
||||
if let Some(f) = strp(p, "format") {
|
||||
o.format_override = Some(FileFormat::from_extension(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}`")))?);
|
||||
let preset = preset.ok_or_else(|| bad(cmd, format!("unknown export preset {}", params.get("preset").unwrap_or(&Value::Null))))?;
|
||||
let mut options = ExportOptions::new(preset);
|
||||
if let Some(f) = strp(params, "format") {
|
||||
options.format_override = Some(FileFormat::from_extension(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}`")))?);
|
||||
}
|
||||
if let Some(b) = u64p(p, "bitDepth") {
|
||||
o.bit_depth_override = Some(b.min(32) as u8);
|
||||
if let Some(depth) = u64p(params, "bitDepth") {
|
||||
options.bit_depth_override = Some(depth.min(32) as u8);
|
||||
}
|
||||
let px = u64p(p, "dilation").map(|v| v.min(256) as u32).unwrap_or(16);
|
||||
if let Some(pad) = strp(p, "padding") {
|
||||
o.padding = match pad {
|
||||
options.dither = params.get("dithering").and_then(Value::as_bool).unwrap_or(false);
|
||||
let dilation_pixels = u64p(params, "dilation").map(|v| v.min(256) as u32).unwrap_or(16);
|
||||
if let Some(pad) = strp(params, "padding") {
|
||||
options.padding = match pad {
|
||||
"none" => Padding::None,
|
||||
"dilation" => Padding::Dilation(px),
|
||||
"dilationDefault" => Padding::DilationDefault(px),
|
||||
"dilation" => Padding::Dilation(dilation_pixels),
|
||||
"dilationDefault" => Padding::DilationDefault(dilation_pixels),
|
||||
"diffusion" => Padding::DilationDiffusion(dilation_pixels),
|
||||
"infinite" => Padding::Infinite,
|
||||
other => return Err(bad(cmd, format!("unknown padding `{other}`"))),
|
||||
};
|
||||
}
|
||||
if let Some(sz) = u64p(p, "size") {
|
||||
o.size = Some(crate::session::check_resolution(u32::try_from(sz).unwrap_or(0))?);
|
||||
if let Some(size) = u64p(params, "size") {
|
||||
options.size = Some(crate::session::check_resolution(u32::try_from(size).unwrap_or(0))?);
|
||||
}
|
||||
o.normal_format = normal_format_param(cmd, p)?;
|
||||
match p.get("colorSpace") {
|
||||
options.normal_format = normal_format_param(cmd, params)?;
|
||||
options.maps = map_overrides(params, options.preset.maps.len(), cmd)?;
|
||||
match params.get("colorSpace") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(Value::String(name)) => {
|
||||
o.color_space = Some(
|
||||
options.color_space = Some(
|
||||
texturecraft_texel::ColorSpace::from_name(name)
|
||||
.ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?,
|
||||
);
|
||||
@@ -345,7 +353,38 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
|
||||
// A value of the wrong type is an error, not the format's default space
|
||||
Some(other) => return Err(bad(cmd, format!("`colorSpace` is a name (sRGB, Linear Rec.709, ACEScg or ACES2065-1), not {other}"))),
|
||||
}
|
||||
Ok(o)
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// `maps`: per map `{map: index into the preset's maps, enabled?, format?, bitDepth?, dithering?}`.
|
||||
fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result<std::collections::BTreeMap<usize, MapOverride>> {
|
||||
let mut overrides = std::collections::BTreeMap::new();
|
||||
let Some(list) = params.get("maps").filter(|value| !value.is_null()) else { return Ok(overrides) };
|
||||
|
||||
let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?}"))?;
|
||||
for settings in list {
|
||||
let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count);
|
||||
let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?;
|
||||
let mut options = MapOverride::default();
|
||||
if let Some(enabled) = settings.get("enabled") {
|
||||
options.enabled = enabled.as_bool().ok_or_else(|| bad(cmd, "`maps`: `enabled` must be true or false"))?;
|
||||
}
|
||||
if let Some(format) = settings.get("format").filter(|value| !value.is_null()) {
|
||||
let name = format.as_str().ok_or_else(|| bad(cmd, "`maps`: `format` must be a file type name"))?;
|
||||
options.format = Some(FileFormat::from_extension(name).ok_or_else(|| bad(cmd, format!("unknown format `{name}`")))?);
|
||||
}
|
||||
if let Some(depth) = settings.get("bitDepth").filter(|value| !value.is_null()) {
|
||||
let depth = depth.as_u64().ok_or_else(|| bad(cmd, "`maps`: `bitDepth` must be a nonnegative integer"))?;
|
||||
options.bit_depth = Some(depth.min(32) as u8);
|
||||
}
|
||||
if let Some(dithering) = settings.get("dithering").filter(|value| !value.is_null()) {
|
||||
options.dither = Some(dithering.as_bool().ok_or_else(|| bad(cmd, "`maps`: `dithering` must be true or false"))?);
|
||||
}
|
||||
|
||||
overrides.insert(index, options);
|
||||
}
|
||||
|
||||
Ok(overrides)
|
||||
}
|
||||
|
||||
fn sets_param(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
|
||||
@@ -371,19 +410,33 @@ fn set_index(s: &Session, v: &Value, cmd: &str) -> Result<usize> {
|
||||
}
|
||||
|
||||
fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
use texturecraft_formats::export::{list_set_outputs, scale_export_side};
|
||||
|
||||
let options = export_options(session, params, "export.plan")?;
|
||||
let project = &session.doc.project;
|
||||
let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:"));
|
||||
let sets = sets_param(session, params, "export.plan")?;
|
||||
let outputs = list_set_outputs(project, &sets, &mesh_name, &options).map_err(fe)?;
|
||||
|
||||
let mut files = Vec::with_capacity(outputs.len());
|
||||
for set_outputs in outputs.chunk_by(|(left, _), (right, _)| left == right) {
|
||||
let Some((set_index, _)) = set_outputs.first() else { continue };
|
||||
|
||||
let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?;
|
||||
let block_size = set.block_resolution();
|
||||
for (_, output) in set_outputs {
|
||||
let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile));
|
||||
let size = scale_export_side(source_size, block_size, options.size);
|
||||
|
||||
let mut files = Vec::new();
|
||||
for set_index in sets_param(session, params, "export.plan")? {
|
||||
for output in texturecraft_formats::list_outputs(project, set_index, &mesh_name, &options).map_err(fe)? {
|
||||
files.push(json!({
|
||||
"ts": set_index,
|
||||
"map": output.map,
|
||||
"file": output.name,
|
||||
"format": output.format.extension(),
|
||||
"bitDepth": output.bit_depth,
|
||||
"dithering": output.dither,
|
||||
"size": size,
|
||||
"sourceSize": source_size,
|
||||
"warnings": output.warnings,
|
||||
}));
|
||||
}
|
||||
@@ -606,23 +659,35 @@ fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std::path::Path, warnings: &mut Vec<String>) -> Result<Vec<std::path::PathBuf>> {
|
||||
use texturecraft_formats::materialx::{self, Texture};
|
||||
let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
if opts.color_space == Some(texturecraft_texel::ColorSpace::Aces2065) {
|
||||
warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut stems = std::collections::HashSet::new();
|
||||
let mut written_names = std::collections::HashSet::new();
|
||||
let mut normal_map_written = false;
|
||||
let aces2065_tag = materialx::colorspace_name(texturecraft_texel::ColorSpace::Aces2065);
|
||||
let mut aces2065_written = false;
|
||||
for &ts in sets {
|
||||
let set = s.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let mut textures: Vec<Texture> = Vec::new();
|
||||
for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? {
|
||||
let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue };
|
||||
let files = texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)?;
|
||||
|
||||
// The first tile stands for all of them: its number is written as <UDIM>
|
||||
let file = f.udim_name.clone().unwrap_or_else(|| f.name.clone());
|
||||
let colorspace = materialx::colorspace_name(opts.space_for(f.format));
|
||||
if !textures.iter().any(|t| t.input == input) {
|
||||
textures.push(Texture { input: input.to_owned(), file, colorspace });
|
||||
// If any tile of a map was skipped, its UDIM reference could pick up another set's pixels
|
||||
let mut skipped_maps = std::collections::HashSet::new();
|
||||
for file in &files {
|
||||
if !written_names.insert(file.name.to_ascii_lowercase()) {
|
||||
skipped_maps.insert(file.map);
|
||||
}
|
||||
}
|
||||
|
||||
let mut textures: Vec<Texture> = Vec::new();
|
||||
for file in files.into_iter().filter(|file| !skipped_maps.contains(&file.map)) {
|
||||
let Some(map) = opts.preset.maps.get(file.map) else { continue };
|
||||
let Some(input) = materialx::input_of_template(&map.file) else { continue };
|
||||
|
||||
// The first tile stands for all the tiles with the same naming pattern
|
||||
let filename = file.udim_name.unwrap_or(file.name);
|
||||
let space = opts.space_for_map(map, file.format, file.bit_depth);
|
||||
let colorspace = materialx::colorspace_name(space);
|
||||
if !textures.iter().any(|texture| texture.input == input) {
|
||||
textures.push(Texture { input: input.to_owned(), file: filename, colorspace });
|
||||
}
|
||||
}
|
||||
normal_map_written |= textures.iter().any(|t| t.input == "geometry_normal");
|
||||
@@ -641,11 +706,18 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
let path = dir.join(format!("{stem}.mtlx"));
|
||||
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)));
|
||||
out.push(path);
|
||||
}
|
||||
|
||||
if aces2065_written {
|
||||
warnings.push("MaterialX: version 1.39 has no ACES2065-1 colour space; the colour maps are tagged lin_ap0_scene, its name in later versions, which older readers may not know".into());
|
||||
}
|
||||
|
||||
// The normalmap node only exists in a material that has a normal map
|
||||
if normal_map_written && opts.normal_format == Some(NormalFormat::DirectX) {
|
||||
warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into());
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
//! `file.exportTextures` writes jng, pgm and psd, dithers 8-bit files on request and pads with
|
||||
//! diffusion (texturecraft #672).
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::execute;
|
||||
|
||||
#[test]
|
||||
fn the_new_file_types_dithering_and_diffusion_export() {
|
||||
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("tc_export_file_types_{}", std::process::id()));
|
||||
for (format, depth) in [("jng", 8), ("pgm", 16), ("psd", 16), ("tiff", 32)] {
|
||||
let r = execute(
|
||||
&mut s,
|
||||
"file.exportTextures",
|
||||
&json!({"dir": dir.display().to_string(), "ts": 0, "format": format, "bitDepth": depth, "padding": "diffusion", "dilation": 4}),
|
||||
)
|
||||
.unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
let ext = if format == "tiff" { "tif" } else { format };
|
||||
assert!(!files.is_empty() && files.iter().all(|f| f.as_str().unwrap().ends_with(&format!(".{ext}"))), "{format}: {files:?}");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
let plan = execute(&mut s, "export.plan", &json!({"ts": 0, "format": "png", "bitDepth": 8, "dithering": true})).unwrap();
|
||||
assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == true), "{plan}");
|
||||
let plan = execute(&mut s, "export.plan", &json!({"ts": 0, "format": "exr", "dithering": true})).unwrap();
|
||||
assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == false), "float files are never dithered");
|
||||
assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err());
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! `file.exportTextures` / `export.plan` `maps`: per map file type, bit depth and leaving a map out
|
||||
//! (texturecraft #670).
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::execute;
|
||||
|
||||
fn session() -> texturecraft_engine::Session {
|
||||
texturecraft_engine::sample_session(128, 64).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_gets_its_own_file_type_and_bit_depth_and_can_be_left_out() {
|
||||
let mut s = session();
|
||||
let plan = execute(&mut s, "export.plan", &json!({"ts": 0})).unwrap();
|
||||
let plan = plan.as_array().unwrap();
|
||||
assert!(plan.len() >= 3, "{plan:?}");
|
||||
let first = plan[0]["map"].as_u64().unwrap();
|
||||
let second = plan[1]["map"].as_u64().unwrap();
|
||||
let names: Vec<String> = plan.iter().map(|f| f["file"].as_str().unwrap().to_string()).collect();
|
||||
|
||||
let maps = json!([{"map": first, "format": "targa", "bitDepth": 8}, {"map": second, "enabled": false}]);
|
||||
let changed = execute(&mut s, "export.plan", &json!({"ts": 0, "format": "png", "bitDepth": 16, "maps": maps})).unwrap();
|
||||
let changed = changed.as_array().unwrap();
|
||||
assert_eq!(changed.len(), plan.len() - 1, "the left-out map writes nothing");
|
||||
assert_eq!(changed[0]["format"], "tga");
|
||||
assert_eq!(changed[0]["bitDepth"], 8, "the map's own depth beats the export's");
|
||||
assert!(changed[1..].iter().all(|f| f["format"] == "png" && f["bitDepth"] == 16), "the others follow the export: {changed:?}");
|
||||
assert!(!changed.iter().any(|f| f["file"] == names[1].as_str()));
|
||||
assert_eq!(changed[1]["file"], names[2].as_str(), "the other maps keep their names");
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("tc_export_maps_{}", std::process::id()));
|
||||
let r = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "ts": 0, "maps": maps})).unwrap();
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect();
|
||||
assert_eq!(files.len(), plan.len() - 1);
|
||||
assert!(files.iter().any(|f| f.ends_with(".tga")), "{files:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_index_outside_the_preset_is_refused() {
|
||||
let mut s = session();
|
||||
let e = execute(&mut s, "export.plan", &json!({"maps": [{"map": 999}]})).unwrap_err();
|
||||
assert!(e.to_string().contains("`map` must be the index"), "{e}");
|
||||
for (field, value) in [("format", json!("nope")), ("format", json!(8)), ("bitDepth", json!("16")), ("dithering", json!("true"))] {
|
||||
let mut map = json!({"map": 0});
|
||||
map[field] = value;
|
||||
assert!(execute(&mut s, "export.plan", &json!({"maps": [map]})).is_err(), "{map}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn planned_uv_tile_sizes_match_the_written_files() {
|
||||
let mut session =
|
||||
texturecraft_engine::Session::new_project("Export", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
|
||||
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
|
||||
let directory = std::env::temp_dir().join(format!("tc-export-tile-sizes-{}", std::process::id()));
|
||||
let params = json!({"dir": directory, "format": "png", "size": 128, "ts": 0});
|
||||
|
||||
let plan = execute(&mut session, "export.plan", ¶ms).unwrap();
|
||||
let plan = plan.as_array().unwrap();
|
||||
assert!(plan.iter().any(|file| file["size"] == 64));
|
||||
assert!(plan.iter().any(|file| file["size"] == 128));
|
||||
execute(&mut session, "file.exportTextures", ¶ms).unwrap();
|
||||
|
||||
for file in plan {
|
||||
let bytes = std::fs::read(directory.join(file["file"].as_str().unwrap())).unwrap();
|
||||
let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap());
|
||||
assert_eq!(file["size"], width, "{file}");
|
||||
}
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() {
|
||||
let mut s = session();
|
||||
assert!(s.set_count() >= 2);
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 0, "name": "SAME"})).unwrap();
|
||||
execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "same"})).unwrap();
|
||||
|
||||
let preset = json!({"name": "same", "maps": [
|
||||
{"file": "$textureSet", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]},
|
||||
{"file": "$textureSet", "format": "Tga", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]},
|
||||
{"file": "other", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}
|
||||
]});
|
||||
let single = execute(&mut s, "export.plan", &json!({"preset": preset, "ts": 1})).unwrap();
|
||||
let plan = execute(&mut s, "export.plan", &json!({"preset": preset, "ts": [1, 0]})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("tc_export_same_name_{}", std::process::id()));
|
||||
let result = execute(&mut s, "file.exportTextures", &json!({"dir": dir.display().to_string(), "preset": preset, "ts": [1, 0]})).unwrap();
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
|
||||
let names = ["same.png", "same.tga", "other.png"];
|
||||
let single = single.as_array().unwrap();
|
||||
let plan = plan.as_array().unwrap();
|
||||
assert_eq!(single.len(), names.len());
|
||||
assert_eq!(plan.len(), names.len(), "{plan:?}");
|
||||
for (index, name) in names.into_iter().enumerate() {
|
||||
assert_eq!(single[index]["file"], name);
|
||||
assert_eq!(single[index]["warnings"], json!([]));
|
||||
assert_eq!(plan[index]["file"], name);
|
||||
assert_eq!(plan[index]["ts"], 1);
|
||||
let warning = plan[index]["warnings"][0].as_str().unwrap();
|
||||
assert!(warning.contains("an earlier texture set exports"), "{warning}");
|
||||
assert_eq!(result["warnings"][index], warning);
|
||||
assert_eq!(std::path::Path::new(result["files"][index].as_str().unwrap()).file_name().unwrap(), name);
|
||||
}
|
||||
assert_eq!(result["files"].as_array().unwrap().len(), names.len());
|
||||
}
|
||||
@@ -11,6 +11,8 @@ mod closed_session;
|
||||
mod color_selection;
|
||||
mod content_effects;
|
||||
mod export_colour_space;
|
||||
mod export_file_types;
|
||||
mod export_maps;
|
||||
mod filter_swap;
|
||||
mod filters;
|
||||
mod frame_selection;
|
||||
|
||||
@@ -101,6 +101,68 @@ fn colour_maps_are_tagged_with_the_export_colour_space() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pgm_colour_maps_are_tagged_with_the_written_luminance_space() {
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
for (space, tag) in [(None, "srgb_texture"), (Some("ACEScg"), "lin_rec709"), (Some("ACES2065-1"), "lin_rec709")] {
|
||||
let directory = temp(tag);
|
||||
let result = execute(
|
||||
&mut session,
|
||||
"file.exportTextures",
|
||||
&json!({"dir": directory.display().to_string(), "preset": OPENPBR, "format": "pgm", "colorSpace": space, "materialX": true}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let material = files(&result).into_iter().find(|path| path.ends_with(".mtlx")).unwrap();
|
||||
let text = std::fs::read_to_string(material).unwrap();
|
||||
assert!(text.contains(&format!("_base_color.pgm\" colorspace=\"{tag}\"")), "{space:?}: {text}");
|
||||
assert!(!result["warnings"].to_string().contains("lin_ap0_scene"), "{result}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_srgb_float_tiff_tags_match_gray_and_rgb_samples() {
|
||||
use texturecraft_engine::formats::{Dest, ExportPreset, FileFormat, MapSpec, SourceRef};
|
||||
use texturecraft_engine::{core::Channel, texel::linear_to_srgb};
|
||||
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
execute(&mut session, "layer.add.fill", &json!({})).unwrap();
|
||||
execute(&mut session, "layer.fill.set", &json!({"channel": "baseColor", "color": [0.25, 0.5, 0.75]})).unwrap();
|
||||
let source = |component| SourceRef::Channel { channel: Channel::BaseColor, component };
|
||||
let mut linear_sample = None;
|
||||
for (channels, tag) in
|
||||
[(vec![(Dest::L, source(0))], "lin_rec709"), (vec![(Dest::R, source(0)), (Dest::G, source(1)), (Dest::B, source(2))], "srgb_texture")]
|
||||
{
|
||||
let directory = temp(tag);
|
||||
let preset = ExportPreset {
|
||||
name: "TIFF base colour".into(),
|
||||
maps: vec![MapSpec { file: "$mesh_$textureSet_base_color".into(), format: FileFormat::Tiff, bit_depth: 32, channels, inverted: Vec::new() }],
|
||||
};
|
||||
let result = execute(
|
||||
&mut session,
|
||||
"file.exportTextures",
|
||||
&json!({"dir": directory.display().to_string(), "preset": preset, "ts": 0, "colorSpace": "sRGB", "materialX": true}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let paths = files(&result);
|
||||
let texture = paths.iter().find(|file| file.ends_with(".tif")).unwrap();
|
||||
let material = std::fs::read_to_string(paths.iter().find(|file| file.ends_with(".mtlx")).unwrap()).unwrap();
|
||||
let warned = result["warnings"].to_string().contains("written in linear Rec.709");
|
||||
let samples = image::open(texture).unwrap().to_rgb32f();
|
||||
assert!(material.contains(&format!("_base_color.tif\" colorspace=\"{tag}\"")), "{material}");
|
||||
assert_eq!(warned, tag == "lin_rec709", "{result}");
|
||||
if let Some(expected) = linear_sample {
|
||||
let (x, y, red) = expected;
|
||||
assert!((samples.get_pixel(x, y)[0] - linear_to_srgb(red)).abs() < 1e-5);
|
||||
} else {
|
||||
let (x, y, pixel) = samples.enumerate_pixels().find(|(_, _, pixel)| (0.01..0.99).contains(&pixel[0])).unwrap();
|
||||
assert_eq!(pixel.0, [pixel[0]; 3]);
|
||||
linear_sample = Some((x, y, pixel[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sets_with_the_same_file_name_warn_instead_of_overwriting() {
|
||||
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
@@ -113,6 +175,25 @@ fn sets_with_the_same_file_name_warn_instead_of_overwriting() {
|
||||
assert!(r["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("\"A_B\"")), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_material_never_points_at_a_texture_kept_for_another_set() {
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
// The first set's name expands to the same base-colour filename as the second
|
||||
execute(&mut session, "textureSet.rename", &json!({"ts": 0, "name": "$channel"})).unwrap();
|
||||
execute(&mut session, "textureSet.rename", &json!({"ts": 1, "name": "baseColor"})).unwrap();
|
||||
let directory = temp("shared-map");
|
||||
|
||||
let result = export(&mut session, &directory, OPENPBR, true);
|
||||
|
||||
let materials: Vec<_> = files(&result).into_iter().filter(|path| path.ends_with(".mtlx")).collect();
|
||||
assert!(materials.len() >= 2, "{result}");
|
||||
assert!(std::fs::read_to_string(&materials[0]).unwrap().contains("material_ball_baseColor_base_color.png"));
|
||||
for material in materials.iter().skip(1) {
|
||||
assert!(!std::fs::read_to_string(material).unwrap().contains("material_ball_baseColor_base_color.png"), "{material}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udim_sets_use_the_udim_token() {
|
||||
let mut s = Session::new_project("t", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
|
||||
|
||||
@@ -26,6 +26,7 @@ image = { workspace = true }
|
||||
png = "0.18"
|
||||
bytemuck = { workspace = true, features = ["extern_crate_alloc"] }
|
||||
craft-image-codecs = { workspace = true }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "b130ac1fa44f923c3024884ab8ceb5ccdb88f15f" }
|
||||
gltf = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
lz4_flex = { workspace = true }
|
||||
|
||||
@@ -85,17 +85,23 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result<String>;
|
||||
normal format), `Virtual { map, component }` (`NormalOpenGl`, `NormalDirectX`, `Glossiness` =
|
||||
1 − roughness, `AoMixed` = baked AO × AO channel, `F0` = 0.08 × specular level),
|
||||
`Baked { map, component }`, `Constant(f32)`.
|
||||
- `ExportOptions { preset, format_override, bit_depth_override, padding, size, normal_format }`;
|
||||
`Padding::{None, Dilation(n), DilationDefault(n), Infinite}`; `size` must be a power of two
|
||||
- `ExportOptions::new(preset)` accepts format and bit-depth overrides, per-map settings in
|
||||
`maps`, dithering, padding, size and normal format.
|
||||
`Padding::{None, Dilation(n), DilationDefault(n), DilationDiffusion(n), Infinite}`; `size` must be a power of two
|
||||
(box filter down, bilinear up).
|
||||
- File templates: `$project`, `$mesh`, `$textureSet`, `$channel`, `$colorSpace`; names are
|
||||
sanitized to `[A-Za-z0-9_.-]` (reserved device names get a `_` prefix); case-insensitive
|
||||
collisions get `_2`, `_3`, … plus a warning.
|
||||
- A map is written only when one of its sources has data in the texture set (channel present,
|
||||
map baked, …); alpha from a missing channel is dropped.
|
||||
- Formats: PNG 8/16, JPEG 8 (q 95), TGA 8, TIFF 8/16, BMP 8, WebP 8 (lossless), EXR 16f/32f
|
||||
(`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. Color maps are sRGB in 8/16-bit and linear in float
|
||||
formats; data maps are linear; height is stored as `h · 0.5 + 0.5`.
|
||||
- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour, deflate alpha), PGM 8/16 (gray; colour
|
||||
becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8, WebP 8 (lossless), PSD 8/16 (merged image, no
|
||||
layers; alpha is an extra alpha channel, not transparency), EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f. 8-bit files can be dithered
|
||||
(`ExportOptions::dither`, an 8×8 ordered pattern). When `ExportOptions::color_space` is unset,
|
||||
color maps default to sRGB in integer files and linear Rec.709 in float files. An explicit
|
||||
override can select another supported space. PGM writes sRGB or linear Rec.709 luminance and
|
||||
falls back to linear Rec.709 when an ACES space is requested. Data maps are linear, and height
|
||||
is stored as `h · 0.5 + 0.5`.
|
||||
- Final normal: Sobel normal from the height channel (strength = `height_strength`; with 1, a
|
||||
height change of 1 over 1/16 of the texture width tilts 45°; `+Y` up the image), combined with
|
||||
the normal channel, then with the baked normal map, by Reoriented Normal Mapping. DirectX
|
||||
@@ -105,7 +111,7 @@ Built-in presets:
|
||||
|
||||
| Preset | Files (`$mesh_$textureSet_…`) |
|
||||
|---|---|
|
||||
| Document channels + Normal + AO | one per document channel (`$channel`), plus `normal` and `ambientOcclusion` (mixed) |
|
||||
| Document channels + Normal + AO (No Alpha) | one per document channel (`$channel`), plus `normal` and `ambientOcclusion` (mixed) |
|
||||
| glTF PBR Metal Roughness | `BaseColor` (sRGB, A = opacity), `OcclusionRoughnessMetallic`, `Normal` (OpenGL), `Emissive` (if present) |
|
||||
| Unreal Engine (Packed) | `BaseColor`, `OcclusionRoughnessMetallic`, `Normal` (DirectX) |
|
||||
| Unity HDRP (Mask Map) | `BaseMap`, `MaskMap` (R metal, G AO, B detail = 0, A smoothness), `Normal` (OpenGL) |
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
use super::FileFormat;
|
||||
|
||||
/// How a file is written.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Encoding {
|
||||
pub(super) format: FileFormat,
|
||||
pub(super) depth: u8,
|
||||
/// Ordered dithering before 8-bit quantization.
|
||||
pub(super) dither: bool,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::FileFormat;
|
||||
|
||||
/// One preset map's own export settings.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MapOverride {
|
||||
/// False leaves the map out (its file name is still reserved, so the others keep theirs).
|
||||
pub enabled: bool,
|
||||
/// Instead of the preset's and the export's file type.
|
||||
pub format: Option<FileFormat>,
|
||||
/// Instead of the preset's and the export's bit depth.
|
||||
pub bit_depth: Option<u8>,
|
||||
/// Instead of the export's dithering of 8-bit files.
|
||||
#[serde(default)]
|
||||
pub dither: Option<bool>,
|
||||
}
|
||||
|
||||
impl Default for MapOverride {
|
||||
fn default() -> Self {
|
||||
MapOverride { enabled: true, format: None, bit_depth: None, dither: None }
|
||||
}
|
||||
}
|
||||
+688
-125
File diff suppressed because it is too large
Load Diff
@@ -321,7 +321,9 @@ fn every_format_encodes_and_decodes() {
|
||||
};
|
||||
let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
|
||||
preset.maps.push(gray_alpha);
|
||||
for format in FileFormat::ALL {
|
||||
|
||||
// JNG, PGM and PSD have tests of their own (the image crate reads none of them)
|
||||
for format in FileFormat::ALL.into_iter().filter(|f| !matches!(f, FileFormat::Jng | FileFormat::Pgm | FileFormat::Psd)) {
|
||||
for &depth in format.bit_depths() {
|
||||
let mut opts = ExportOptions::new(preset.clone());
|
||||
opts.format_override = Some(format);
|
||||
@@ -530,8 +532,42 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() {
|
||||
let opts = ExportOptions { size: Some(32), ..ExportOptions::new(named) };
|
||||
let small = render_maps(&input, &opts).unwrap();
|
||||
assert_eq!((small[1].name.as_str(), small[1].width, small[1].height), ("1002_Body_Set.png", 32, 32));
|
||||
let atlas = render_maps(&input, &ExportOptions { atlas: true, ..ExportOptions::new(preset) }).unwrap();
|
||||
let atlas = render_maps(&input, &ExportOptions { atlas: true, ..ExportOptions::new(preset.clone()) }).unwrap();
|
||||
assert_eq!((atlas.len(), atlas[0].name.as_str(), atlas[0].width, atlas[0].height), (1, "Body_Set_color.png", 2 * RES, RES));
|
||||
|
||||
// Diffusion stays inside each tile of the atlas too: tile 1001's gap takes only its red
|
||||
let diffused = render_maps(&input, &ExportOptions { atlas: true, padding: Padding::DilationDiffusion(2), ..ExportOptions::new(preset) }).unwrap();
|
||||
let img = decode(&diffused[0]).to_rgb8();
|
||||
for x in [20, 40, RES - 1] {
|
||||
assert_eq!(img.get_pixel(x, 10).0, [255, 0, 0], "({x},10)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_export_size_keeps_each_nonempty_udim_tile_one_pixel_or_larger() {
|
||||
let mut project = Project::new("p", "builtin:udim_plane");
|
||||
let mut set = TextureSet::new("body", 0, 512);
|
||||
set.uv_tiles = vec![1001, 1002];
|
||||
set.tile_resolutions.insert(1002, 128);
|
||||
project.texture_sets.push(set);
|
||||
let composite = Composite::with_size(&[Channel::Roughness], 1024, 512);
|
||||
let coverage = vec![true; 1024 * 512];
|
||||
let input = ExportInput { project: &project, ts: 0, composite: &composite, baked: &BakedMaps::default(), coverage: &coverage, mesh_name: "m" };
|
||||
|
||||
for format in [FileFormat::Png, FileFormat::Psd] {
|
||||
let opts = ExportOptions { size: Some(2), padding: Padding::None, ..one_map(format, 8, roughness()) };
|
||||
let planned = list_outputs(&project, 0, "m", &opts).unwrap();
|
||||
let exported = render_maps(&input, &opts).unwrap();
|
||||
|
||||
assert_eq!(planned.iter().map(|file| file.tile).collect::<Vec<_>>(), [Some(1001), Some(1002)]);
|
||||
assert_eq!(exported.iter().map(|file| (file.width, file.height)).collect::<Vec<_>>(), [(2, 2), (1, 1)]);
|
||||
for (plan, file) in planned.iter().zip(&exported) {
|
||||
assert_eq!(plan.name, file.name);
|
||||
}
|
||||
if format == FileFormat::Png {
|
||||
assert_eq!(decode(&exported[1]).dimensions(), (1, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -700,13 +736,13 @@ fn a_chosen_colour_space_is_embedded_as_an_icc_profile() {
|
||||
|
||||
for space in ColorSpace::ALL {
|
||||
let mut warnings = Vec::new();
|
||||
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], Some(space), &mut warnings).unwrap();
|
||||
let bytes = encode(Encoding { format, depth, dither: false }, (8, 8), 3, data.clone(), &[false; 3], Some(space), &mut warnings).unwrap();
|
||||
assert_eq!(embedded_icc(format, &bytes), crate::icc::profile(space), "{format:?} {depth}-bit {space:?}");
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
// No colour space chosen (a data map, or the default): nothing is embedded
|
||||
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap();
|
||||
let bytes = encode(Encoding { format, depth, dither: false }, (8, 8), 3, data.clone(), &[false; 3], None, &mut Vec::new()).unwrap();
|
||||
assert_eq!(embedded_icc(format, &bytes), None, "{format:?} {depth}-bit");
|
||||
}
|
||||
}
|
||||
@@ -719,9 +755,16 @@ fn exr_carries_the_chromaticities_of_the_space() {
|
||||
let meta = exr::meta::MetaData::read_from_buffered(Cursor::new(bytes), false).unwrap();
|
||||
meta.headers[0].shared_attributes.chromaticities
|
||||
};
|
||||
assert!(read(&encode(FileFormat::Exr, 16, (4, 4), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap()).is_none());
|
||||
assert!(
|
||||
read(&encode(Encoding { format: FileFormat::Exr, depth: 16, dither: false }, (4, 4), 3, data.clone(), &[false; 3], None, &mut Vec::new()).unwrap())
|
||||
.is_none()
|
||||
);
|
||||
for space in ColorSpace::ALL {
|
||||
let c = read(&encode(FileFormat::Exr, 32, (4, 4), 3, &data, &[false; 3], Some(space), &mut Vec::new()).unwrap()).unwrap_or_else(|| panic!("{space:?}"));
|
||||
let c = read(
|
||||
&encode(Encoding { format: FileFormat::Exr, depth: 32, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(space), &mut Vec::new())
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap_or_else(|| panic!("{space:?}"));
|
||||
let [r, g, b, w] = space.chromaticities();
|
||||
for (got, want) in [(c.red, r), (c.green, g), (c.blue, b), (c.white, w)] {
|
||||
assert!((f64::from(got.0) - want[0]).abs() < 1e-5 && (f64::from(got.1) - want[1]).abs() < 1e-5, "{space:?}: {got:?} vs {want:?}");
|
||||
@@ -734,10 +777,10 @@ fn formats_without_a_place_for_a_colour_space_say_so() {
|
||||
let data = vec![0.25f32; 4 * 4 * 3];
|
||||
for format in [FileFormat::Tga, FileFormat::Bmp, FileFormat::Hdr] {
|
||||
let mut warnings = Vec::new();
|
||||
encode(format, 8, (4, 4), 3, &data, &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap();
|
||||
encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], Some(ColorSpace::AcesCg), &mut warnings).unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains("colour space") && w.contains("ACEScg")), "{format:?}: {warnings:?}");
|
||||
let mut quiet = Vec::new();
|
||||
encode(format, 8, (4, 4), 3, &data, &[false; 3], None, &mut quiet).unwrap();
|
||||
encode(Encoding { format, depth: 8, dither: false }, (4, 4), 3, data.clone(), &[false; 3], None, &mut quiet).unwrap();
|
||||
assert!(quiet.is_empty(), "{format:?}: nothing to say without a chosen space: {quiet:?}");
|
||||
}
|
||||
}
|
||||
@@ -854,3 +897,296 @@ fn inverting_a_colour_channel_inverts_the_linear_value_before_encoding() {
|
||||
assert_eq!(half.width(), RES / 2);
|
||||
assert!(half.get_pixel(0, 5)[0] >= 250, "{}", half.get_pixel(0, 5)[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_template_keeps_its_old_name_and_file_types_their_listed_names() {
|
||||
let old = builtin_preset("Document channels + Normal + AO").unwrap();
|
||||
assert_eq!(old.name, crate::DEFAULT_PRESET, "settings saved under the old name still find the template");
|
||||
assert_eq!(builtin_preset(crate::DEFAULT_PRESET).unwrap(), old);
|
||||
for f in FileFormat::ALL {
|
||||
assert_eq!(FileFormat::from_extension(f.name()), Some(f), "{} reads back", f.name());
|
||||
}
|
||||
assert_eq!(FileFormat::Tga.name(), "targa");
|
||||
assert_eq!(FileFormat::Jpeg.name(), "jpeg");
|
||||
}
|
||||
|
||||
/// One-map preset: `channels` written as `format` at `depth`
|
||||
fn one_map(format: FileFormat, depth: u8, channels: Vec<(Dest, SourceRef)>) -> ExportOptions {
|
||||
ExportOptions::new(ExportPreset { name: "t".into(), maps: vec![MapSpec { file: "out".into(), format, bit_depth: depth, channels, inverted: Vec::new() }] })
|
||||
}
|
||||
|
||||
fn rgba_half_alpha() -> Vec<(Dest, SourceRef)> {
|
||||
let c = |k| SourceRef::Channel { channel: Channel::BaseColor, component: k };
|
||||
vec![(Dest::R, c(0)), (Dest::G, c(1)), (Dest::B, c(2)), (Dest::A, SourceRef::Constant(0.5))]
|
||||
}
|
||||
|
||||
fn roughness() -> Vec<(Dest, SourceRef)> {
|
||||
vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 })]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_file_types_have_the_reference_bit_depths() {
|
||||
assert_eq!(FileFormat::Tiff.bit_depths(), &[8, 16, 32]);
|
||||
for f in [FileFormat::Png, FileFormat::Pgm, FileFormat::Psd] {
|
||||
assert_eq!(f.bit_depths(), &[8, 16], "{f:?}");
|
||||
}
|
||||
for f in [FileFormat::Bmp, FileFormat::Jpeg, FileFormat::Jng, FileFormat::Tga, FileFormat::Webp] {
|
||||
assert_eq!(f.bit_depths(), &[8], "{f:?}");
|
||||
}
|
||||
assert_eq!((FileFormat::Exr.default_depth(), FileFormat::Hdr.default_depth(), FileFormat::Psd.default_depth()), (32, 32, 8));
|
||||
assert!(FileFormat::Tiff.holds_float(32) && !FileFormat::Tiff.holds_float(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pgm_is_a_binary_graymap() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let files = fx.render(&one_map(FileFormat::Pgm, 16, roughness()));
|
||||
let f = find(&files, "out.pgm");
|
||||
let header = b"P5\n64 64\n65535\n";
|
||||
assert!(f.bytes.starts_with(header));
|
||||
assert_eq!(f.bytes.len(), header.len() + 64 * 64 * 2);
|
||||
let first = u16::from_be_bytes([f.bytes[header.len()], f.bytes[header.len() + 1]]);
|
||||
assert!((i32::from(first) - 16384).abs() <= 2, "roughness 0.25: {first}");
|
||||
|
||||
// Colour becomes its luminance, weighted in linear light, with a warning
|
||||
let mut color = one_map(FileFormat::Pgm, 8, rgba_half_alpha());
|
||||
color.preset.maps[0].file = "out_$colorSpace".into();
|
||||
let files = fx.render(&color);
|
||||
let f = find(&files, "out_sRGB.pgm");
|
||||
let header = b"P5\n64 64\n255\n";
|
||||
assert!(f.bytes.starts_with(header) && f.warnings.iter().any(|w| w.contains("luminance")), "{:?}", f.warnings);
|
||||
let [r, g, b] = fx.comp.value(Channel::BaseColor, 63, 0);
|
||||
let want = (linear_to_srgb(0.2126 * r + 0.7152 * g + 0.0722 * b) * 255.0).round();
|
||||
assert!((f32::from(f.bytes[header.len() + 63]) - want).abs() <= 1.0, "{} vs {want}", f.bytes[header.len() + 63]);
|
||||
|
||||
// In another colour space the luminance is still that of the colour, not of its converted primaries
|
||||
color.preset.maps[0].bit_depth = 16;
|
||||
let opts = ExportOptions { color_space: Some(ColorSpace::AcesCg), ..color };
|
||||
let files = fx.render(&opts);
|
||||
let f = find(&files, "out_linear.pgm");
|
||||
assert!(f.warnings.iter().any(|warning| warning.contains("ACEScg") && warning.contains("cannot")), "{:?}", f.warnings);
|
||||
assert!(!f.warnings.iter().any(|warning| warning.contains("clamped")), "{:?}", f.warnings);
|
||||
let header = b"P5\n64 64\n65535\n";
|
||||
let at = header.len() + 63 * 2;
|
||||
let got = f32::from(u16::from_be_bytes([f.bytes[at], f.bytes[at + 1]])) / 65535.0;
|
||||
let want = 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
assert!((got - want).abs() < 1e-3, "ACEScg luminance {got} vs {want}");
|
||||
|
||||
// Gray + alpha only loses the alpha
|
||||
let la = vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 }), (Dest::A, SourceRef::Constant(0.5))];
|
||||
let f = &fx.render(&one_map(FileFormat::Pgm, 8, la))[0];
|
||||
assert!(f.warnings.iter().any(|w| w.contains("alpha")) && !f.warnings.iter().any(|w| w.contains("luminance")), "{:?}", f.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_holds_the_merged_image_planar() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let f = &fx.render(&one_map(FileFormat::Psd, 8, rgba_half_alpha()))[0];
|
||||
let b = &f.bytes;
|
||||
assert_eq!(&b[0..4], b"8BPS");
|
||||
assert_eq!(u16::from_be_bytes([b[12], b[13]]), 4, "channels");
|
||||
assert_eq!((u32::from_be_bytes(b[14..18].try_into().unwrap()), u32::from_be_bytes(b[18..22].try_into().unwrap())), (64, 64));
|
||||
assert_eq!((u16::from_be_bytes([b[22], b[23]]), u16::from_be_bytes([b[24], b[25]])), (8, 3), "8-bit RGB");
|
||||
let parsed = craft_psd::PsdFile::from_bytes(b).unwrap();
|
||||
assert!(!parsed.merged_has_alpha());
|
||||
assert_eq!(parsed.alpha_channel_names(), ["Alpha"]);
|
||||
let samples = parsed.decode_merged().unwrap();
|
||||
assert_eq!(samples.len(), 4 * 64 * 64);
|
||||
let plane = |c: usize| &samples[c * 64 * 64..(c + 1) * 64 * 64];
|
||||
assert!(plane(3).iter().all(|a| *a == 128), "alpha plane");
|
||||
let png = decode(&fx.render(&one_map(FileFormat::Png, 8, rgba_half_alpha()))[0]).to_rgba8();
|
||||
assert_eq!(plane(0)[64 * 10 + 40], png.get_pixel(40, 10)[0], "the red plane holds the same values as a PNG");
|
||||
|
||||
let f16 = &fx.render(&one_map(FileFormat::Psd, 16, roughness()))[0];
|
||||
assert_eq!((u16::from_be_bytes([f16.bytes[12], f16.bytes[13]]), u16::from_be_bytes([f16.bytes[22], f16.bytes[23]])), (1, 16));
|
||||
assert_eq!(f16.bytes.len(), 26 + 12 + 2 + 2 * 64 * 64);
|
||||
|
||||
let mut gray_alpha = roughness();
|
||||
gray_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
let f16 = &fx.render(&one_map(FileFormat::Psd, 16, gray_alpha))[0];
|
||||
let parsed = craft_psd::PsdFile::from_bytes(&f16.bytes).unwrap();
|
||||
assert!(!parsed.merged_has_alpha());
|
||||
assert_eq!(parsed.alpha_channel_names(), ["Alpha"]);
|
||||
let samples = parsed.decode_merged().unwrap();
|
||||
assert_eq!(samples.len(), 2 * 2 * 64 * 64);
|
||||
assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1002];
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
options.size = Some(16_384);
|
||||
options.atlas = true;
|
||||
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("PSD") && error.to_string().contains("32768"));
|
||||
options.atlas = false;
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha());
|
||||
options.size = Some(16_384);
|
||||
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("PSD") && error.to_string().contains("2 GiB"), "{error}");
|
||||
options.bit_depth_override = Some(8);
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1);
|
||||
options.bit_depth_override = None;
|
||||
options.preset.maps[0].channels.pop();
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() {
|
||||
// These RGBA16 planes are 32 bytes below 2 GiB before headers and the alpha name
|
||||
let (width, height) = (10_924, 24_573);
|
||||
assert!(check_psd_size((width, height), 4, 16).is_err());
|
||||
assert!(check_psd_size((width, height - 1), 4, 16).is_ok());
|
||||
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011];
|
||||
let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha());
|
||||
options.size = Some(8192);
|
||||
options.atlas = true;
|
||||
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("2 GiB"), "{error}");
|
||||
options.atlas = false;
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jng_has_jpeg_colour_and_lossless_alpha() {
|
||||
use std::io::Read;
|
||||
let fx = Fx::new(&default_channels());
|
||||
let f = &fx.render(&one_map(FileFormat::Jng, 8, rgba_half_alpha()))[0];
|
||||
assert!(f.name.ends_with(".jng"));
|
||||
let b = &f.bytes;
|
||||
assert_eq!(&b[0..8], &[0x8B, b'J', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]);
|
||||
|
||||
// Walk the chunks, checking each CRC
|
||||
let mut at = 8;
|
||||
let mut chunks = Vec::new();
|
||||
while at < b.len() {
|
||||
let len = u32::from_be_bytes(b[at..at + 4].try_into().unwrap()) as usize;
|
||||
let kind = &b[at + 4..at + 8];
|
||||
let data = &b[at + 8..at + 8 + len];
|
||||
let mut crc = flate2::Crc::new();
|
||||
crc.update(kind);
|
||||
crc.update(data);
|
||||
assert_eq!(crc.sum(), u32::from_be_bytes(b[at + 8 + len..at + 12 + len].try_into().unwrap()), "{}", String::from_utf8_lossy(kind));
|
||||
chunks.push((String::from_utf8_lossy(kind).into_owned(), data.to_vec()));
|
||||
at += 12 + len;
|
||||
}
|
||||
let names: Vec<&str> = chunks.iter().map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(names, ["JHDR", "IDAT", "JDAT", "IEND"]);
|
||||
let jhdr = &chunks[0].1;
|
||||
assert_eq!(&jhdr[8..], &[14, 8, 8, 0, 8, 0, 0, 0], "colour + alpha, 8-bit JPEG, 8-bit deflate alpha");
|
||||
let jpeg = image::load_from_memory_with_format(&chunks[2].1, ImageFormat::Jpeg).unwrap();
|
||||
assert_eq!(jpeg.dimensions(), (64, 64));
|
||||
let mut alpha = Vec::new();
|
||||
flate2::read::ZlibDecoder::new(&chunks[1].1[..]).read_to_end(&mut alpha).unwrap();
|
||||
assert_eq!(alpha.len(), 64 * 65);
|
||||
assert!(alpha.chunks(65).all(|row| row[0] == 0 && row[1..].iter().all(|a| *a == 128)));
|
||||
|
||||
// Gray without alpha: no alpha chunk
|
||||
let gray = &fx.render(&one_map(FileFormat::Jng, 8, roughness()))[0];
|
||||
assert_eq!(gray.bytes[8 + 8 + 8], 8, "gray colour type");
|
||||
assert!(!gray.bytes.windows(4).any(|w| w == b"IDAT"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tiff_32f_holds_linear_floats() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let f = &fx.render(&one_map(FileFormat::Tiff, 32, roughness()))[0];
|
||||
let img = decode(f).to_rgb32f();
|
||||
assert!((img.get_pixel(5, 5)[0] - 0.25).abs() < 1e-3, "{:?}", img.get_pixel(5, 5));
|
||||
let colour = &fx.render(&one_map(FileFormat::Tiff, 32, rgba_half_alpha()))[0];
|
||||
let img = decode(colour).to_rgba32f();
|
||||
let v = fx.comp.value(Channel::BaseColor, 40, 10);
|
||||
assert!((img.get_pixel(40, 10)[0] - v[0]).abs() < 1e-3, "colour stays linear: {:?} vs {v:?}", img.get_pixel(40, 10));
|
||||
assert_eq!(img.get_pixel(40, 10)[3], 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_tiff_marks_straight_alpha_and_preserves_the_color_profile() {
|
||||
use craft_image_codecs::{ExtraSampleKind, tiff_info};
|
||||
|
||||
let fx = Fx::new(&default_channels());
|
||||
let options = ExportOptions { color_space: Some(ColorSpace::Srgb), ..one_map(FileFormat::Tiff, 32, rgba_half_alpha()) };
|
||||
let files = fx.render(&options);
|
||||
let bytes = &files[0].bytes;
|
||||
|
||||
assert_eq!(tiff_info(bytes).unwrap().pages[0].extra_samples, [ExtraSampleKind::UnassociatedAlpha]);
|
||||
assert_eq!(embedded_icc(FileFormat::Tiff, bytes), crate::icc::profile(ColorSpace::Srgb));
|
||||
let pixel = decode(&files[0]).to_rgba32f().get_pixel(40, 10).0;
|
||||
assert!((pixel[0] - linear_to_srgb(fx.comp.value(Channel::BaseColor, 40, 10)[0])).abs() < 1e-3);
|
||||
assert_eq!(pixel[3], 0.5);
|
||||
|
||||
let mut gray_alpha = roughness();
|
||||
gray_alpha.push((Dest::A, SourceRef::Constant(0.75)));
|
||||
let files = fx.render(&one_map(FileFormat::Tiff, 32, gray_alpha));
|
||||
let file = &files[0];
|
||||
|
||||
assert_eq!(tiff_info(&file.bytes).unwrap().pages[0].extra_samples, [ExtraSampleKind::UnassociatedAlpha]);
|
||||
assert_eq!(embedded_icc(FileFormat::Tiff, &file.bytes), None);
|
||||
let pixel = decode(file).to_rgba32f().get_pixel(5, 5).0;
|
||||
assert!((pixel[0] - 0.25).abs() < 1e-3);
|
||||
assert_eq!(pixel, [pixel[0], pixel[0], pixel[0], 0.75]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dithering_is_ordered_and_keeps_the_average() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let plain = one_map(FileFormat::Png, 8, rgba_half_alpha());
|
||||
let dithered = ExportOptions { dither: true, ..plain.clone() };
|
||||
let a = decode(&fx.render(&plain)[0]).to_rgba8();
|
||||
let b = decode(&fx.render(&dithered)[0]).to_rgba8();
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(b, decode(&fx.render(&dithered)[0]).to_rgba8(), "the same pattern on every export");
|
||||
let mean = |img: &image::RgbaImage| img.pixels().map(|p| f64::from(p[0])).sum::<f64>() / 4096.0;
|
||||
assert!((mean(&a) - mean(&b)).abs() < 0.6, "{} vs {}", mean(&a), mean(&b));
|
||||
|
||||
// A map's own setting wins, and 16-bit files are never dithered
|
||||
let mut own = dithered.clone();
|
||||
own.maps.insert(0, MapOverride { dither: Some(false), ..MapOverride::default() });
|
||||
assert_eq!(decode(&fx.render(&own)[0]).to_rgba8(), a);
|
||||
let wide = ExportOptions { bit_depth_override: Some(16), ..dithered.clone() };
|
||||
assert!(list_outputs(&fx.project, 0, "sphere", &wide).unwrap().iter().all(|p| !p.dither));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diffusion_padding_fills_beyond_the_dilation_smoothly() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.set_all(Channel::Roughness, |_, y| [if y < RES / 2 { 0.2 } else { 0.8 }; 3]);
|
||||
fx.coverage = (0..RES * RES).map(|i| i % RES < 16).collect();
|
||||
let mut dil = one_map(FileFormat::Png, 16, roughness());
|
||||
dil.padding = Padding::Dilation(2);
|
||||
let mut dif = dil.clone();
|
||||
dif.padding = Padding::DilationDiffusion(2);
|
||||
let a = decode(&fx.render(&dil)[0]).to_luma16();
|
||||
let b = decode(&fx.render(&dif)[0]).to_luma16();
|
||||
for y in [0, 20, 40, 63] {
|
||||
for x in 0..18 {
|
||||
assert_eq!(a.get_pixel(x, y), b.get_pixel(x, y), "islands and the dilated ring are unchanged at ({x},{y})");
|
||||
}
|
||||
assert_eq!(a.get_pixel(40, y)[0], 0, "plain dilation leaves the rest empty");
|
||||
}
|
||||
|
||||
// Near the island the fill favours its row colour and blends farther away
|
||||
let v = |x, y| f32::from(b.get_pixel(x, y)[0]) / 65535.0;
|
||||
assert!(v(19, 2) < 0.35 && v(19, 61) > 0.65, "{} {}", v(19, 2), v(19, 61));
|
||||
for y in 0..64 {
|
||||
for x in 18..64 {
|
||||
assert!((0.19..=0.81).contains(&v(x, y)), "({x},{y}) {}", v(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! Decoding imported image resources (fills, alphas, stencils).
|
||||
|
||||
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, PngCompression, SampleType};
|
||||
|
||||
use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result};
|
||||
|
||||
/// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay
|
||||
@@ -77,32 +79,38 @@ fn decode_image_with_limits(bytes: &[u8], max_texels: u64, limits: image::Limits
|
||||
/// PNG bytes of an `rgb` (sRGB) image whose alpha is `coverage` (`width × height`, top row first):
|
||||
/// drawn text as an image resource.
|
||||
pub fn coverage_png(width: u32, height: u32, coverage: &[u8], rgb: [u8; 3]) -> Result<Vec<u8>> {
|
||||
let rgba: Vec<u8> = coverage.iter().flat_map(|a| [rgb[0], rgb[1], rgb[2], *a]).collect();
|
||||
let image = image::RgbaImage::from_raw(width, height, rgba)
|
||||
// Resource callers may supply a larger coverage buffer. Encode just the given extent.
|
||||
let coverage = usize::try_from(u64::from(width) * u64::from(height))
|
||||
.ok()
|
||||
.and_then(|count| coverage.get(..count))
|
||||
.ok_or_else(|| FormatError::Invalid(format!("{} coverage values for {width}x{height}", coverage.len())))?;
|
||||
let mut png = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| FormatError::Invalid(e.to_string()))?;
|
||||
Ok(png)
|
||||
let bytes = coverage.len().checked_mul(4).ok_or_else(|| FormatError::Invalid(format!("RGBA buffer does not fit {width}x{height}")))?;
|
||||
let mut rgba = Vec::new();
|
||||
rgba.try_reserve_exact(bytes).map_err(|error| FormatError::Invalid(error.to_string()))?;
|
||||
rgba.extend(coverage.iter().flat_map(|&alpha| [rgb[0], rgb[1], rgb[2], alpha]));
|
||||
let image = Image::from_u8(width, height, ChannelLayout::Rgba, rgba).map_err(|error| FormatError::Invalid(error.to_string()))?;
|
||||
encode_resource_png(&image)
|
||||
}
|
||||
|
||||
/// 16-bit single-channel PNG bytes of `values` (0..1, `width × height`, top row first): one map
|
||||
/// split out of a packed image, or an inverted one.
|
||||
pub fn gray16_png(width: u32, height: u32, values: impl Iterator<Item = f32>) -> Result<Vec<u8>> {
|
||||
let image = gray16_image(width, height, values)?;
|
||||
|
||||
encode_gray16(&image)
|
||||
encode_resource_png(&gray16_image(width, height, values)?)
|
||||
}
|
||||
|
||||
/// A single-channel PNG and its decoded pixels, quantized identically to a saved/reloaded image.
|
||||
pub fn gray16_resource(width: u32, height: u32, values: impl Iterator<Item = f32>) -> Result<(Vec<u8>, DecodedImage)> {
|
||||
let image = gray16_image(width, height, values)?;
|
||||
let png = encode_gray16(&image)?;
|
||||
let png = encode_resource_png(&image)?;
|
||||
let rgba = image
|
||||
.pixels()
|
||||
.map(|pixel| {
|
||||
.data()
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|bytes| {
|
||||
// Match image's integer-to-float expansion so reload is bit-identical
|
||||
const GRAY16_TO_FLOAT: f32 = 1.0 / u16::MAX as f32;
|
||||
let value = f32::from(pixel.0[0]) * GRAY16_TO_FLOAT;
|
||||
let value = f32::from(u16::from_ne_bytes(*bytes)) * GRAY16_TO_FLOAT;
|
||||
[value, value, value, 1.0]
|
||||
})
|
||||
.collect();
|
||||
@@ -110,28 +118,28 @@ pub fn gray16_resource(width: u32, height: u32, values: impl Iterator<Item = f32
|
||||
Ok((png, DecodedImage { width, height, rgba, srgb: true }))
|
||||
}
|
||||
|
||||
fn encode_gray16(image: &image::ImageBuffer<image::Luma<u16>, Vec<u16>>) -> Result<Vec<u8>> {
|
||||
let mut png = Vec::new();
|
||||
image.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|error| FormatError::Invalid(error.to_string()))?;
|
||||
|
||||
Ok(png)
|
||||
fn encode_resource_png(image: &Image) -> Result<Vec<u8>> {
|
||||
let options = EncodeOptions { png_compression: PngCompression::Fast, ..EncodeOptions::default() };
|
||||
craft_image_codecs::encode(image, Format::Png, &options).map_err(|error| FormatError::Invalid(error.to_string()))
|
||||
}
|
||||
|
||||
fn gray16_image(width: u32, height: u32, values: impl Iterator<Item = f32>) -> Result<image::ImageBuffer<image::Luma<u16>, Vec<u16>>> {
|
||||
fn gray16_image(width: u32, height: u32, values: impl Iterator<Item = f32>) -> Result<Image> {
|
||||
let texels = u64::from(width) * u64::from(height);
|
||||
if width == 0 || height == 0 || width > MAX_IMAGE_SIZE || height > MAX_IMAGE_SIZE || texels > MAX_RESOURCE_TEXELS {
|
||||
return Err(FormatError::TooLarge(format!("image is {width}x{height} (limit {MAX_RESOURCE_TEXELS} texels)")));
|
||||
}
|
||||
|
||||
let expected = usize::try_from(texels).map_err(|_| FormatError::TooLarge(format!("image is {width}x{height}")))?;
|
||||
let data: Vec<u16> = values.take(expected + 1).map(|v| if v.is_finite() { (v.clamp(0.0, 1.0) * f32::from(u16::MAX)).round() as u16 } else { 0 }).collect();
|
||||
if data.len() != expected {
|
||||
return Err(FormatError::Invalid(format!("pixel count does not match {width}x{height}")));
|
||||
}
|
||||
|
||||
let image = image::ImageBuffer::<image::Luma<u16>, Vec<u16>>::from_raw(width, height, data)
|
||||
.ok_or_else(|| FormatError::Invalid(format!("pixel count does not match {width}x{height}")))?;
|
||||
Ok(image)
|
||||
// Build the shared image's native-endian buffer directly to avoid a second copy of the samples.
|
||||
let data = values
|
||||
.take(expected + 1)
|
||||
.flat_map(|value| {
|
||||
let sample = if value.is_finite() { (value.clamp(0.0, 1.0) * f32::from(u16::MAX)).round() as u16 } else { 0 };
|
||||
sample.to_ne_bytes()
|
||||
})
|
||||
.collect();
|
||||
Image::from_raw(width, height, ChannelLayout::Gray, SampleType::U16, data)
|
||||
.map_err(|_| FormatError::Invalid(format!("pixel count does not match {width}x{height}")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -158,6 +166,49 @@ mod tests {
|
||||
assert!(coverage_png(2, 2, &[0], [255; 3]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_png_preserves_rgba8_samples_and_ignores_excess_coverage() {
|
||||
let coverage = [0, 17, 128, 255, 231];
|
||||
let png = coverage_png(2, 2, &coverage, [19, 83, 207]).unwrap();
|
||||
let decoded = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap();
|
||||
|
||||
assert_eq!(decoded.color(), image::ColorType::Rgba8);
|
||||
let rgba = decoded.as_rgba8().unwrap();
|
||||
assert_eq!(rgba.dimensions(), (2, 2));
|
||||
assert_eq!(rgba.as_raw(), &[19, 83, 207, 0, 19, 83, 207, 17, 19, 83, 207, 128, 19, 83, 207, 255]);
|
||||
assert!(matches!(coverage_png(2, 2, &coverage[..3], [19, 83, 207]), Err(FormatError::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray16_png_preserves_asymmetric_samples_in_row_order() {
|
||||
let samples = [0x0001u16, 0x0100, 0x1234, 0xabcd, 0xff00, 0xffff];
|
||||
let values = samples.into_iter().map(|value| f32::from(value) / f32::from(u16::MAX));
|
||||
let png = gray16_png(3, 2, values).unwrap();
|
||||
let decoded = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap();
|
||||
|
||||
assert_eq!(decoded.color(), image::ColorType::L16);
|
||||
let gray = decoded.as_luma16().unwrap();
|
||||
assert_eq!(gray.dimensions(), (3, 2));
|
||||
assert_eq!(gray.as_raw(), &samples);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_png_preserves_samples_above_four_mebibytes() {
|
||||
let (width, height) = (1024u32, 1025u32);
|
||||
let coverage: Vec<u8> = (0..width * height).map(|index| ((index * 37 + index / width) % 256) as u8).collect();
|
||||
// Exercise the shared encoder's parallel path, selected by raw image byte count.
|
||||
assert!(coverage.len() * 4 > 4 << 20);
|
||||
let png = coverage_png(width, height, &coverage, [23, 97, 211]).unwrap();
|
||||
let decoded = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap();
|
||||
|
||||
assert_eq!(decoded.color(), image::ColorType::Rgba8);
|
||||
let rgba = decoded.as_rgba8().unwrap();
|
||||
assert_eq!(rgba.dimensions(), (width, height));
|
||||
for (index, (pixel, alpha)) in rgba.pixels().zip(&coverage).enumerate() {
|
||||
assert_eq!(pixel.0, [23, 97, 211, *alpha], "pixel {index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray16_round_trips_and_rejects_a_wrong_count() {
|
||||
let png = gray16_png(2, 1, [0.0, 1.0].into_iter()).unwrap();
|
||||
|
||||
@@ -42,14 +42,15 @@ pub mod project_file;
|
||||
pub mod zip_read;
|
||||
|
||||
pub use export::{
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs, render_maps,
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs,
|
||||
render_maps, skip_repeated_names,
|
||||
};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource};
|
||||
pub use mesh_export::{GlbTextures, NamedFiles, UsdExport, UsdFormat, glb_bytes, glb_export_options, obj_bytes, obj_with_mtl, usd_bytes, usd_export_options};
|
||||
pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use presets::load_preset;
|
||||
pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json};
|
||||
pub use presets::{DEFAULT_PRESET, builtin_preset, builtin_presets, preset_from_json, preset_to_json};
|
||||
pub use project_file::{
|
||||
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, RamReservation, load_project_bytes, project_open_limit_gib,
|
||||
sanitize_resource_name, save_project_bytes, set_project_open_limit_gib,
|
||||
|
||||
@@ -85,7 +85,7 @@ pub(crate) fn gltf_pbr_maps(file: impl Fn(&str) -> String) -> Vec<MapSpec> {
|
||||
pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
let preset = |name: &str, maps: Vec<MapSpec>| ExportPreset { name: name.into(), maps };
|
||||
vec![
|
||||
preset("Document channels + Normal + AO", {
|
||||
preset(DEFAULT_PRESET, {
|
||||
let mut maps: Vec<MapSpec> =
|
||||
Channel::ALL.into_iter().filter(|c| !matches!(c, Channel::Normal | Channel::AmbientOcclusion)).map(channel_map).collect();
|
||||
maps.push(map("normal", 8, rgb(|k| ch(Channel::Normal, k))));
|
||||
@@ -107,7 +107,7 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
vec![
|
||||
(Dest::R, ch(Channel::Metallic, 0)),
|
||||
(Dest::G, virt(VirtualMap::AoMixed, 0)),
|
||||
// Detail mask: none.
|
||||
// The preset has no detail mask
|
||||
(Dest::B, SourceRef::Constant(0.0)),
|
||||
(Dest::A, virt(VirtualMap::Glossiness, 0)),
|
||||
],
|
||||
@@ -154,7 +154,7 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
map("emission", 8, rgb(|k| ch(Channel::Emissive, k))),
|
||||
],
|
||||
),
|
||||
// OpenPBR Surface inputs, one map each (maps of channels a set lacks are skipped).
|
||||
// One map per OpenPBR input present in the texture set
|
||||
preset("OpenPBR (separate maps)", {
|
||||
let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0)));
|
||||
let rgb8 = |name: &str, c: Channel| map(name, 8, rgb(|k| ch(c, k)));
|
||||
@@ -190,9 +190,18 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The default export template.
|
||||
pub const DEFAULT_PRESET: &str = "Document channels + Normal + AO (No Alpha)";
|
||||
|
||||
/// The default template's name before it took the reference's "(No Alpha)" (saved settings and
|
||||
/// scripts still use it).
|
||||
const OLD_DEFAULT_PRESET: &str = "Document channels + Normal + AO";
|
||||
|
||||
/// A built-in preset by name (case-insensitive).
|
||||
pub fn builtin_preset(name: &str) -> Option<ExportPreset> {
|
||||
builtin_presets().into_iter().find(|p| p.name.eq_ignore_ascii_case(name.trim()))
|
||||
let name = name.trim();
|
||||
let name = if name.eq_ignore_ascii_case(OLD_DEFAULT_PRESET) { DEFAULT_PRESET } else { name };
|
||||
builtin_presets().into_iter().find(|p| p.name.eq_ignore_ascii_case(name))
|
||||
}
|
||||
|
||||
/// Parse and validate a user preset.
|
||||
|
||||
@@ -20,6 +20,8 @@ const ICON: f32 = 20.0;
|
||||
const LIST_WIDTH: f32 = 190.0;
|
||||
const INPUTS_WIDTH: f32 = 170.0;
|
||||
const RENAME_ID: &str = "exp_rename";
|
||||
/// The name "+" gives a new template, as in the reference
|
||||
const NEW_PRESET: &str = "new_export_preset";
|
||||
const RGB: [&str; 3] = ["R", "G", "B"];
|
||||
|
||||
/// An output file's channel layout.
|
||||
@@ -63,6 +65,15 @@ impl Layout {
|
||||
}
|
||||
}
|
||||
|
||||
/// The reference's Create buttons: (label, the layout the new output map gets). The split ones
|
||||
/// ("R+G+B", "R+G+B+A") make the same map; each channel can take its own source in either.
|
||||
const CREATE: [(&str, Layout); 5] =
|
||||
[(n_("Gray"), Layout::Gray), ("RGB", Layout::Rgb), ("R+G+B", Layout::Rgb), ("RGB+A", Layout::Rgba), ("R+G+B+A", Layout::Rgba)];
|
||||
|
||||
/// The naming patterns the input maps can be shown with (the reference's second one names
|
||||
/// another vendor's material and is left out)
|
||||
const NAMING_PATTERNS: [&str; 1] = ["OpenPBR"];
|
||||
|
||||
/// The input maps palette: (group, [(label, source)]).
|
||||
type Palette = [(&'static str, Vec<(&'static str, SourceRef)>); 4];
|
||||
|
||||
@@ -170,10 +181,32 @@ fn selected(app: &TextureCraftApp) -> Option<ExportPreset> {
|
||||
fn sync_draft(app: &mut TextureCraftApp) {
|
||||
let e = &mut app.ui.export;
|
||||
match app.session.export_presets.list.iter().find(|p| p.name == e.preset) {
|
||||
None => e.draft = None,
|
||||
None => {
|
||||
e.draft = None;
|
||||
e.draft_maps.clear();
|
||||
e.draft_base = None;
|
||||
}
|
||||
Some(saved) => {
|
||||
if e.draft.as_ref().is_none_or(|d| d.name != saved.name || (d != saved && d.validate().is_ok())) {
|
||||
e.draft = Some(saved.clone());
|
||||
e.draft_maps = (0..saved.maps.len()).map(Some).collect();
|
||||
e.draft_base = Some(saved.clone());
|
||||
} else if e.draft_base.as_ref() != Some(saved) {
|
||||
// Match only unambiguous maps from the previous saved order
|
||||
for origin in &mut e.draft_maps {
|
||||
*origin = origin
|
||||
.and_then(|index| {
|
||||
let previous_maps = &e.draft_base.as_ref()?.maps;
|
||||
let previous = previous_maps.get(index)?;
|
||||
previous_maps.iter().filter(|map| *map == previous).nth(1).is_none().then_some(previous)
|
||||
})
|
||||
.and_then(|previous| {
|
||||
let mut matches = saved.maps.iter().enumerate().filter(|(_, map)| *map == previous);
|
||||
let (index, _) = matches.next()?;
|
||||
matches.next().is_none().then_some(index)
|
||||
});
|
||||
}
|
||||
e.draft_base = Some(saved.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,11 +226,12 @@ enum MapAction {
|
||||
pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) {
|
||||
sync_draft(app);
|
||||
let height = ui.available_height();
|
||||
let names = crate::export_window::template_groups(app, builtins).1;
|
||||
let mut list_action = None;
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(LIST_WIDTH);
|
||||
ui.set_height(height);
|
||||
list_action = preset_list(app, ui, builtins);
|
||||
list_action = preset_list(app, ui, &names);
|
||||
});
|
||||
ui.separator();
|
||||
ui.vertical(|ui| {
|
||||
@@ -210,6 +244,7 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(INPUTS_WIDTH);
|
||||
ui.set_height(height);
|
||||
naming_pattern(ui);
|
||||
input_maps(ui);
|
||||
});
|
||||
if let Some(a) = list_action {
|
||||
@@ -227,24 +262,43 @@ pub fn select(app: &mut TextureCraftApp, name: String) {
|
||||
}
|
||||
}
|
||||
|
||||
fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) -> Option<ListAction> {
|
||||
/// "Naming pattern" with its info icon
|
||||
fn naming_pattern(ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Naming pattern"));
|
||||
egui::ComboBox::from_id_salt("exp_naming").width(90.0).selected_text(NAMING_PATTERNS[0]).show_ui(ui, |ui| {
|
||||
for p in NAMING_PATTERNS {
|
||||
let _ = ui.selectable_label(true, p);
|
||||
}
|
||||
});
|
||||
ui.label(RichText::new(ic::INFO).color(tk.text_dim)).on_hover_ui(|ui| {
|
||||
ui.label(tr("Choose how the input maps are named in this editor."));
|
||||
ui.label(tr("The active texture set’s shader can affect the available map names."));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The Presets list: the templates sorted by name (built-in and user); a right click offers
|
||||
/// Rename, Duplicate and Remove, F2 renames
|
||||
fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, names: &[String]) -> Option<ListAction> {
|
||||
let mut act = None;
|
||||
let sel = app.ui.export.preset.clone();
|
||||
let user = app.ui.export.draft.is_some();
|
||||
ui.label(caption(tr("Output templates")));
|
||||
ui.label(caption(tr("Presets")));
|
||||
ui.horizontal(|ui| {
|
||||
let tool = |ui: &mut Ui, enabled: bool, icon: &str, tip: &str| ui.add_enabled_ui(enabled, |ui| icon_button(ui, icon, tip, false, ICON)).inner.clicked();
|
||||
if tool(ui, true, ic::PLUS, tr("New template")) {
|
||||
act = Some(ListAction::New);
|
||||
}
|
||||
if tool(ui, true, ic::COPY, tr("Duplicate the selected template")) {
|
||||
act = Some(ListAction::Duplicate);
|
||||
act = Some(ListAction::Duplicate(sel.clone()));
|
||||
}
|
||||
if tool(ui, user, ic::PENCIL_SIMPLE, tr("Rename the selected template")) {
|
||||
act = Some(ListAction::StartRename(sel.clone()));
|
||||
}
|
||||
if tool(ui, user, ic::TRASH, tr("Delete the selected template")) {
|
||||
act = Some(ListAction::Remove);
|
||||
act = Some(ListAction::Remove(sel.clone()));
|
||||
}
|
||||
ui.separator();
|
||||
if tool(ui, true, ic::DOWNLOAD_SIMPLE, tr("Import a template (.json)")) {
|
||||
@@ -255,33 +309,42 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]
|
||||
}
|
||||
});
|
||||
ui.add_space(2.0);
|
||||
let names: Vec<String> = app.session.export_presets.list.iter().map(|p| p.name.clone()).collect();
|
||||
if std::mem::take(&mut app.ui.export.rename_key) && user {
|
||||
act = Some(ListAction::StartRename(sel.clone()));
|
||||
}
|
||||
egui::ScrollArea::vertical().id_salt("exp_presets").auto_shrink([false; 2]).show(ui, |ui| {
|
||||
for p in builtins {
|
||||
let r =
|
||||
ui.selectable_label(p.name == sel, format!("{} {}", ic::LOCK_SIMPLE, p.name)).on_hover_text(tr("Built-in (read-only): duplicate it to edit"));
|
||||
if r.clicked() {
|
||||
act = Some(ListAction::Select(p.name.clone()));
|
||||
}
|
||||
}
|
||||
if !names.is_empty() {
|
||||
ui.separator();
|
||||
}
|
||||
for name in names {
|
||||
match app.ui.export.renaming.as_mut().filter(|_| name == sel) {
|
||||
let is_user = app.session.export_presets.list.iter().any(|p| p.name == *name);
|
||||
match app.ui.export.renaming.as_mut().filter(|_| *name == sel) {
|
||||
Some(buf) => {
|
||||
let r = ui.add(egui::TextEdit::singleline(buf).id(egui::Id::unique(RENAME_ID)).desired_width(f32::INFINITY));
|
||||
if r.lost_focus() {
|
||||
act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) { ListAction::Select(name) } else { ListAction::Rename(buf.clone()) });
|
||||
act = Some(if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
|
||||
ListAction::Select(name.clone())
|
||||
} else {
|
||||
ListAction::Rename(buf.clone())
|
||||
});
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let r = ui.selectable_label(name == sel, format!("{} {name}", ic::USER)).on_hover_text(tr("Double-click to rename"));
|
||||
if r.double_clicked() {
|
||||
act = Some(ListAction::StartRename(name));
|
||||
let r = ui.selectable_label(*name == sel, name).on_hover_text(name);
|
||||
if r.double_clicked() && is_user {
|
||||
act = Some(ListAction::StartRename(name.clone()));
|
||||
} else if r.clicked() {
|
||||
act = Some(ListAction::Select(name));
|
||||
act = Some(ListAction::Select(name.clone()));
|
||||
}
|
||||
r.context_menu(|ui| {
|
||||
let read_only = tr("Built-in templates are read-only: duplicate one to edit it");
|
||||
if ui.add_enabled(is_user, egui::Button::new(tr("Rename"))).on_disabled_hover_text(read_only).clicked() {
|
||||
act = Some(ListAction::StartRename(name.clone()));
|
||||
}
|
||||
if ui.button(tr("Duplicate")).clicked() {
|
||||
act = Some(ListAction::Duplicate(name.clone()));
|
||||
}
|
||||
if ui.add_enabled(is_user, egui::Button::new(tr("Remove"))).on_disabled_hover_text(read_only).clicked() {
|
||||
act = Some(ListAction::Remove(name.clone()));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -298,11 +361,11 @@ fn unfinished(app: &TextureCraftApp) -> Option<String> {
|
||||
fn apply(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
|
||||
let leaves = match &act {
|
||||
ListAction::Select(name) | ListAction::StartRename(name) => *name != app.ui.export.preset,
|
||||
ListAction::New | ListAction::Duplicate | ListAction::Imported(_) => true,
|
||||
ListAction::New | ListAction::Duplicate(_) | ListAction::Imported(_) => true,
|
||||
_ => false,
|
||||
};
|
||||
if act == ListAction::Remove {
|
||||
app.ui.export.ask = Some(Ask::Delete(app.ui.export.preset.clone()));
|
||||
if let ListAction::Remove(name) = &act {
|
||||
app.ui.export.ask = Some(Ask::Delete(name.clone()));
|
||||
} else if leaves && unfinished(app).is_some() {
|
||||
app.ui.export.ask = Some(Ask::Leave(act));
|
||||
} else {
|
||||
@@ -315,11 +378,11 @@ fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
|
||||
match act {
|
||||
ListAction::Select(name) => app.ui.export.preset = name,
|
||||
ListAction::New => {
|
||||
save_new(app, &ExportPreset { name: tr("New template").into(), maps: Vec::new() });
|
||||
save_new(app, &ExportPreset { name: NEW_PRESET.into(), maps: Vec::new() });
|
||||
}
|
||||
ListAction::Duplicate => {
|
||||
if let Some(p) = selected(app) {
|
||||
let name = trf("{name} copy", &[("name", &p.name)]).chars().take(MAX_PRESET_NAME).collect();
|
||||
ListAction::Duplicate(name) => {
|
||||
if let Some(p) = app.session.export_preset(&name) {
|
||||
let name = format!("{}_copy", p.name).chars().take(MAX_PRESET_NAME).collect();
|
||||
save_new(app, &ExportPreset { name, ..p });
|
||||
}
|
||||
}
|
||||
@@ -329,7 +392,7 @@ fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
|
||||
ctx.memory_mut(|m| m.request_focus(egui::Id::unique(RENAME_ID)));
|
||||
}
|
||||
ListAction::Rename(name) => rename(app, name.trim()),
|
||||
ListAction::Remove => remove(app, app.ui.export.preset.clone()),
|
||||
ListAction::Remove(name) => remove(app, name),
|
||||
ListAction::Import => import_file(app, ctx),
|
||||
ListAction::Imported(p) => add_imported(app, &p),
|
||||
ListAction::Export => export_file(app),
|
||||
@@ -341,6 +404,7 @@ fn remove(app: &mut TextureCraftApp, name: String) {
|
||||
if app.ui.export.preset == name {
|
||||
app.ui.export.preset = crate::state::ExportUi::default().preset;
|
||||
}
|
||||
crate::export_window::template_renamed(&mut app.ui.export, &name, None);
|
||||
app.toast(trf("Deleted template \"{name}\"", &[("name", &name)]), false);
|
||||
}
|
||||
}
|
||||
@@ -413,12 +477,14 @@ fn rename(app: &mut TextureCraftApp, name: &str) {
|
||||
if name.is_empty() || name == p.name {
|
||||
return;
|
||||
}
|
||||
|
||||
let old = std::mem::replace(&mut p.name, name.to_string());
|
||||
let Ok(v) = serde_json::to_value(&p) else { return };
|
||||
if let Some(r) = app.run("export.preset.save", json!({ "preset": v, "rename": old }))
|
||||
&& let Some(n) = r.get("name").and_then(Value::as_str)
|
||||
{
|
||||
app.ui.export.preset = n.to_string();
|
||||
crate::export_window::template_renamed(&mut app.ui.export, &old, Some(n));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,83 +591,120 @@ pub fn save_library(app: &TextureCraftApp, storage: &mut dyn eframe::Storage) {
|
||||
|
||||
/// The selected template's output maps (editable for user templates).
|
||||
fn outputs(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let (mut preset, editable) = match (&app.ui.export.draft, selected(app)) {
|
||||
(Some(d), _) => (d.clone(), true),
|
||||
(None, Some(b)) => (b, false),
|
||||
(None, None) => {
|
||||
ui.label(RichText::new(tr("Select an output template")).color(tk.text_dim));
|
||||
ui.label(RichText::new(tr("Select an output template")).color(tokens.text_dim));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let preview = preview_names(app, &preset);
|
||||
let mut action = None;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(&preset.name).strong().color(tk.text_strong));
|
||||
ui.label(RichText::new(tr("Current preset:")).color(tokens.text_dim));
|
||||
ui.label(RichText::new(&preset.name).strong().color(tokens.text_strong));
|
||||
if !editable {
|
||||
ui.label(RichText::new(ic::LOCK_SIMPLE).color(tk.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it"));
|
||||
ui.label(RichText::new(ic::LOCK_SIMPLE).color(tokens.text_dim)).on_hover_text(tr("Built-in templates are read-only: duplicate one to edit it"));
|
||||
}
|
||||
});
|
||||
ui.label(caption(tr("Output maps")));
|
||||
ui.add_enabled_ui(editable, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(tr("Add output")).color(tk.text_dim));
|
||||
for l in Layout::ALL {
|
||||
if ui.small_button(format!("{} {}", ic::PLUS, tr(l.label()))).clicked() {
|
||||
action = Some(MapAction::Add(l));
|
||||
ui.label(RichText::new(tr("Create:")).color(tokens.text_dim));
|
||||
for (label, layout) in CREATE {
|
||||
if ui.small_button(tr(label)).clicked() {
|
||||
action = Some(MapAction::Add(layout));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Err(e) = &preview {
|
||||
ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tk.danger).size(11.0));
|
||||
ui.label(RichText::new(trf("Not saved: {error}", &[("error", e)])).color(tokens.danger).size(11.0));
|
||||
}
|
||||
let mut changed = false;
|
||||
let n = preset.maps.len();
|
||||
egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).show(ui, |ui| {
|
||||
if n == 0 {
|
||||
let map_count = preset.maps.len();
|
||||
|
||||
// Leave room for the footer below
|
||||
let footer = 2.0 * ui.text_style_height(&egui::TextStyle::Body) + 3.0 * ui.spacing().item_spacing.y;
|
||||
egui::ScrollArea::vertical().id_salt("exp_outputs").auto_shrink([false; 2]).max_height((ui.available_height() - footer).max(60.0)).show(ui, |ui| {
|
||||
if map_count == 0 {
|
||||
ui.add_space(8.0);
|
||||
ui.label(RichText::new(tr("No outputs yet: add one above, then drag input maps onto its channels.")).color(tk.text_dim));
|
||||
ui.label(RichText::new(tr("No outputs yet: add one above, then drag input maps onto its channels.")).color(tokens.text_dim));
|
||||
}
|
||||
ui.add_enabled_ui(editable, |ui| {
|
||||
for (mi, map) in preset.maps.iter_mut().enumerate() {
|
||||
let file = preview.as_ref().ok().and_then(|v| v.get(mi).cloned().flatten());
|
||||
changed |= output_card(ui, mi, n, map, file.as_deref(), &mut action);
|
||||
for (map_index, map) in preset.maps.iter_mut().enumerate() {
|
||||
let file = preview.as_ref().ok().and_then(|names| names.get(map_index).cloned().flatten());
|
||||
changed |= output_card(ui, map_index, map_count, map, file.as_deref(), &mut action);
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.label(RichText::new(tr("Drop an input map onto a channel to assign it to that output.")).color(tokens.text_dim));
|
||||
|
||||
// Count only maps that have sources in the current set
|
||||
if let Ok(names) = &preview {
|
||||
let exported = names.iter().flatten().count();
|
||||
ui.label(trf("{n} output maps will be exported.", &[("n", &exported)]));
|
||||
}
|
||||
if !editable {
|
||||
return;
|
||||
}
|
||||
|
||||
// Where each map came from in the saved template, moved along with the maps
|
||||
let mut origin = app.ui.export.draft_maps.clone();
|
||||
if origin.len() != map_count {
|
||||
origin = (0..map_count).map(Some).collect();
|
||||
}
|
||||
match action {
|
||||
Some(MapAction::Add(l)) => preset.maps.push(new_map(l)),
|
||||
Some(MapAction::Up(i)) if i > 0 && i < n => preset.maps.swap(i, i - 1),
|
||||
Some(MapAction::Down(i)) if i + 1 < n => preset.maps.swap(i, i + 1),
|
||||
Some(MapAction::Remove(i)) if i < n => {
|
||||
preset.maps.remove(i);
|
||||
Some(MapAction::Add(layout)) => {
|
||||
preset.maps.push(new_map(layout));
|
||||
origin.push(None);
|
||||
}
|
||||
Some(MapAction::Up(index)) if index > 0 && index < map_count => {
|
||||
preset.maps.swap(index, index - 1);
|
||||
origin.swap(index, index - 1);
|
||||
}
|
||||
Some(MapAction::Down(index)) if index + 1 < map_count => {
|
||||
preset.maps.swap(index, index + 1);
|
||||
origin.swap(index, index + 1);
|
||||
}
|
||||
Some(MapAction::Remove(index)) if index < map_count => {
|
||||
preset.maps.remove(index);
|
||||
origin.remove(index);
|
||||
}
|
||||
_ if !changed => return,
|
||||
_ => {}
|
||||
}
|
||||
commit(app, preset);
|
||||
commit(app, preset, origin);
|
||||
}
|
||||
|
||||
/// Keep the edited draft; save it when valid.
|
||||
fn commit(app: &mut TextureCraftApp, preset: ExportPreset) {
|
||||
/// Keep the edited draft; save it when valid. `origin` gives each map's index in the saved
|
||||
/// template: once saved, the texture set overrides of the maps follow them.
|
||||
fn commit(app: &mut TextureCraftApp, preset: ExportPreset, mut origin: Vec<Option<usize>>) {
|
||||
if preset.validate().is_ok()
|
||||
&& let Ok(v) = serde_json::to_value(&preset)
|
||||
&& app.run("export.preset.save", json!({ "preset": v })).is_some()
|
||||
{
|
||||
app.run("export.preset.save", json!({ "preset": v }));
|
||||
crate::export_window::template_maps_moved(&mut app.ui.export, &preset.name, &origin);
|
||||
origin = (0..preset.maps.len()).map(Some).collect();
|
||||
app.ui.export.draft_base = app.session.export_preset(&preset.name);
|
||||
}
|
||||
app.ui.export.draft = Some(preset);
|
||||
app.ui.export.draft_maps = origin;
|
||||
}
|
||||
|
||||
/// The file each map produces for the current texture set with the dialog's settings (None:
|
||||
/// the set has none of the map's sources), via `export.plan`.
|
||||
fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result<Vec<Option<String>>, String> {
|
||||
let mut p = crate::windows::export_params(app);
|
||||
let mut p = crate::export_window::set_params(app, app.session.ts());
|
||||
p["preset"] = serde_json::to_value(preset).map_err(|e| e.to_string())?;
|
||||
p["ts"] = json!(app.session.ts());
|
||||
|
||||
// The set's map overrides apply only to its own template
|
||||
if let Some(p) = p.as_object_mut() {
|
||||
p.remove("maps");
|
||||
}
|
||||
let plan = texturecraft_engine::execute(&mut app.session, "export.plan", &p).map_err(|e| e.to_string())?;
|
||||
let mut names = vec![None; preset.maps.len()];
|
||||
for f in plan.as_array().into_iter().flatten() {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
use texturecraft_engine::formats::FileFormat;
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::state::{FileType, SIZE_OF_LARGEST_SET};
|
||||
|
||||
use super::{file_type_name, largest_set};
|
||||
|
||||
/// Starting values for a texture set override.
|
||||
pub(super) struct InheritedSettings {
|
||||
pub(super) preset: String,
|
||||
pub(super) file_type: FileType,
|
||||
pub(super) size: u32,
|
||||
pub(super) padding: (String, u32),
|
||||
}
|
||||
|
||||
impl InheritedSettings {
|
||||
pub(super) fn for_texture_set(app: &TextureCraftApp, native_size: u32) -> Self {
|
||||
let e = &app.ui.export;
|
||||
let format = if e.format.is_empty() { FileFormat::Png.name().to_string() } else { file_type_name(&e.format) };
|
||||
let (bit_depth, dithering) = match FileFormat::from_extension(&format) {
|
||||
Some(f) if e.bit_depth > 0 => (f.depth(e.bit_depth), e.dithering),
|
||||
Some(f) => (f.default_depth(), false),
|
||||
None => (8, false),
|
||||
};
|
||||
let size = match e.size {
|
||||
0 => native_size,
|
||||
SIZE_OF_LARGEST_SET => largest_set(app),
|
||||
n => n,
|
||||
};
|
||||
Self { preset: e.preset.clone(), file_type: FileType { format, bit_depth, dithering }, size, padding: (e.padding.clone(), e.dilation) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use crate::state::FileType;
|
||||
|
||||
/// One Output maps row: the map, its file name pattern and what it is written as without its
|
||||
/// own override
|
||||
pub(super) struct MapRow {
|
||||
pub(super) map: usize,
|
||||
pub(super) pattern: String,
|
||||
pub(super) inherited: FileType,
|
||||
}
|
||||
@@ -49,12 +49,19 @@ pub struct FileDialogs {
|
||||
asked: Vec<AskKey>,
|
||||
/// The app has no native window (the test harness): a native dialog must never open.
|
||||
headless: bool,
|
||||
/// Folders an app without a window was asked to show (instead of a file manager).
|
||||
shown_folders: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl FileDialogs {
|
||||
/// The dialogs of the app whose context is `ctx`: an answer wakes its event loop.
|
||||
pub fn new(ctx: egui::Context) -> FileDialogs {
|
||||
FileDialogs { dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())), asked: Vec::new(), headless: false }
|
||||
FileDialogs {
|
||||
dialogs: craft_dialogs::Dialogs::new(Arc::new(move || ctx.request_repaint())),
|
||||
asked: Vec::new(),
|
||||
headless: false,
|
||||
shown_folders: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers every request with `answer_with` instead of a native dialog (tests).
|
||||
@@ -71,6 +78,42 @@ impl FileDialogs {
|
||||
self.set_override(None);
|
||||
}
|
||||
|
||||
/// Shows `dir` in the system's file manager. An app without a window (the test harness)
|
||||
/// only records it, see [`FileDialogs::shown_folders`].
|
||||
pub(crate) fn show_folder(&mut self, dir: &std::path::Path) -> std::io::Result<()> {
|
||||
if self.headless {
|
||||
self.shown_folders.push(dir.to_path_buf());
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let opener = if cfg!(target_os = "windows") {
|
||||
"explorer"
|
||||
} else if cfg!(target_os = "macos") {
|
||||
"open"
|
||||
} else {
|
||||
"xdg-open"
|
||||
};
|
||||
let directory = dir.to_path_buf();
|
||||
let (started, result) = std::sync::mpsc::sync_channel(1);
|
||||
|
||||
// Start the reaper first so a thread creation failure leaves no child behind
|
||||
std::thread::Builder::new().spawn(move || match std::process::Command::new(opener).arg(directory).spawn() {
|
||||
Ok(mut child) => {
|
||||
let _ = started.send(Ok(()));
|
||||
let _ = child.wait();
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = started.send(Err(error));
|
||||
}
|
||||
})?;
|
||||
result.recv().map_err(std::io::Error::other)?
|
||||
}
|
||||
|
||||
/// The folders an app without a window was asked to show.
|
||||
pub fn shown_folders(&self) -> &[PathBuf] {
|
||||
&self.shown_folders
|
||||
}
|
||||
|
||||
/// Requests that have not been answered yet.
|
||||
pub fn pending(&self) -> usize {
|
||||
self.asked.len()
|
||||
|
||||
@@ -25,6 +25,7 @@ pub mod docking;
|
||||
mod environment_picker;
|
||||
mod export_panel;
|
||||
pub mod export_templates;
|
||||
mod export_window;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod file_dialogs;
|
||||
mod fill_source_slot;
|
||||
|
||||
@@ -5,10 +5,12 @@ use texturecraft_engine::formats::ExportPreset;
|
||||
pub enum ListAction {
|
||||
Select(String),
|
||||
New,
|
||||
Duplicate,
|
||||
/// Copy this template, select the copy
|
||||
Duplicate(String),
|
||||
StartRename(String),
|
||||
Rename(String),
|
||||
Remove,
|
||||
/// Delete this template (after asking)
|
||||
Remove(String),
|
||||
Import,
|
||||
/// A template read from a file, added and selected
|
||||
Imported(ExportPreset),
|
||||
|
||||
@@ -490,6 +490,11 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if confirming_reset && !popup_open {
|
||||
crate::windows::reset_ui_keys(app, input, no_widget_focused);
|
||||
}
|
||||
|
||||
// F2 renames the selected template on Output templates, before its 3D view binding
|
||||
if app.ui.windows.export && app.ui.export.tab == 1 && app.ui.export.ask.is_none() && input.consume_key(Modifiers::NONE, Key::F2) {
|
||||
app.ui.export.rename_key = true;
|
||||
}
|
||||
let commands = app.bindings.dispatch(input);
|
||||
for copy in copies {
|
||||
if !input.events.contains(©) {
|
||||
|
||||
@@ -20,6 +20,19 @@ pub use library_location::LibraryLocation;
|
||||
pub use project_config::ProjectConfig;
|
||||
pub use resource_usage::ResourceUsage;
|
||||
|
||||
mod console_line;
|
||||
mod export_job;
|
||||
mod export_set_plan;
|
||||
mod file_type;
|
||||
mod map_export;
|
||||
mod set_export;
|
||||
pub use console_line::ConsoleLine;
|
||||
pub use export_job::ExportJob;
|
||||
pub use export_set_plan::ExportSetPlan;
|
||||
pub use file_type::FileType;
|
||||
pub use map_export::MapExport;
|
||||
pub use set_export::SetExport;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum Mode {
|
||||
#[default]
|
||||
@@ -319,6 +332,9 @@ impl Default for NewProject {
|
||||
}
|
||||
}
|
||||
|
||||
/// `ExportUi::size` for "Maximum size for all Texture Sets".
|
||||
pub const SIZE_OF_LARGEST_SET: u32 = u32::MAX;
|
||||
|
||||
/// The export dialog's settings (remembered between sessions).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ExportUi {
|
||||
@@ -328,10 +344,13 @@ pub struct ExportUi {
|
||||
pub format: String,
|
||||
/// Bit depth override (0 = the preset's).
|
||||
pub bit_depth: u8,
|
||||
/// none | dilation | dilationDefault | infinite
|
||||
/// Dither the 8-bit files of the file type override.
|
||||
#[serde(default)]
|
||||
pub dithering: bool,
|
||||
/// none | dilation | dilationDefault | diffusion | infinite
|
||||
pub padding: String,
|
||||
pub dilation: u32,
|
||||
/// Output size override (0 = each texture set's size).
|
||||
/// Output size override (0 = each texture set's size, [`SIZE_OF_LARGEST_SET`] = the largest set's).
|
||||
pub size: u32,
|
||||
/// "" (project), openGl or directX.
|
||||
pub normal_format: String,
|
||||
@@ -340,35 +359,81 @@ pub struct ExportUi {
|
||||
pub color_space: String,
|
||||
/// Texture sets excluded from export.
|
||||
pub skip: Vec<usize>,
|
||||
/// Per texture set (by index) overrides of the settings above.
|
||||
#[serde(default)]
|
||||
pub sets: std::collections::BTreeMap<usize, SetExport>,
|
||||
/// Whose `skip` and `sets` these are: the project name, then its texture set names in order.
|
||||
/// Another project drops them; texture sets that moved take theirs along, removed ones lose them.
|
||||
#[serde(default)]
|
||||
pub owner: Vec<String>,
|
||||
/// The session's project id `owner` was taken in (None after a restart: the name decides).
|
||||
#[serde(skip)]
|
||||
pub owner_id: Option<u64>,
|
||||
pub tab: u8,
|
||||
/// SETTINGS tab: the texture set whose page shows (None: Global settings).
|
||||
#[serde(skip)]
|
||||
pub page: Option<usize>,
|
||||
/// Output templates tab: the selected user preset being edited (saved whenever it is valid).
|
||||
#[serde(skip)]
|
||||
pub draft: Option<texturecraft_engine::formats::ExportPreset>,
|
||||
/// Output templates tab: for each map of `draft`, its index in the saved template (None: added
|
||||
/// since), so the texture set overrides of a map follow it when the draft is saved.
|
||||
#[serde(skip)]
|
||||
pub draft_maps: Vec<Option<usize>>,
|
||||
/// Output templates tab: the saved template `draft_maps` counts from.
|
||||
#[serde(skip)]
|
||||
pub draft_base: Option<texturecraft_engine::formats::ExportPreset>,
|
||||
/// Output templates tab: the new name while renaming the selected preset.
|
||||
#[serde(skip)]
|
||||
pub renaming: Option<String>,
|
||||
/// Output templates tab: F2 asked to rename the selected preset.
|
||||
#[serde(skip)]
|
||||
pub rename_key: bool,
|
||||
/// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit).
|
||||
#[serde(skip)]
|
||||
pub ask: Option<crate::export_templates::Ask>,
|
||||
/// The settings when the window opened: Cancel goes back to them.
|
||||
#[serde(skip)]
|
||||
pub opened_with: Option<Box<ExportUi>>,
|
||||
/// The export running in the window.
|
||||
#[serde(skip)]
|
||||
pub job: Option<ExportJob>,
|
||||
/// LIST OF EXPORTS: the console's lines and whether it is hidden.
|
||||
#[serde(skip)]
|
||||
pub console: Vec<ConsoleLine>,
|
||||
#[serde(skip)]
|
||||
pub console_hidden: bool,
|
||||
}
|
||||
|
||||
impl Default for ExportUi {
|
||||
fn default() -> Self {
|
||||
ExportUi {
|
||||
dir: default_export_dir(),
|
||||
preset: "Document channels + Normal + AO".into(),
|
||||
preset: texturecraft_engine::formats::DEFAULT_PRESET.into(),
|
||||
format: String::new(),
|
||||
bit_depth: 0,
|
||||
dithering: false,
|
||||
padding: "infinite".into(),
|
||||
dilation: 16,
|
||||
size: 0,
|
||||
normal_format: String::new(),
|
||||
color_space: String::new(),
|
||||
skip: Vec::new(),
|
||||
sets: Default::default(),
|
||||
owner: Vec::new(),
|
||||
owner_id: None,
|
||||
tab: 0,
|
||||
page: None,
|
||||
draft: None,
|
||||
draft_maps: Vec::new(),
|
||||
draft_base: None,
|
||||
renaming: None,
|
||||
rename_key: false,
|
||||
ask: None,
|
||||
opened_with: None,
|
||||
job: None,
|
||||
console: Vec::new(),
|
||||
console_hidden: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/// A line of the Export textures window's console.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ConsoleLine {
|
||||
Step(String),
|
||||
/// "Texture set <name>" with the name in bold.
|
||||
Set(String),
|
||||
/// A success line, in green.
|
||||
Done(String),
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use super::ExportSetPlan;
|
||||
|
||||
/// A running texture export: the texture sets still to write, one per frame.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ExportJob {
|
||||
/// Each texture set still to write with its `file.exportTextures` parameters (output folder
|
||||
/// included), taken when Export was clicked: later edits of the settings do not reach them.
|
||||
pub pending: Vec<(usize, serde_json::Value)>,
|
||||
pub total: usize,
|
||||
/// The original selection and the file names shown while the job runs.
|
||||
pub preview: Vec<ExportSetPlan>,
|
||||
/// Destination shown by the preview and Open output directory.
|
||||
pub directory: String,
|
||||
/// File names written so far.
|
||||
pub written: Vec<String>,
|
||||
/// The frame that wrote the last texture set (a frame's second pass writes none).
|
||||
pub frame: u64,
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/// The selected set and its planned files for the export window.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ExportSetPlan {
|
||||
/// The current index, or none if the set left the project.
|
||||
pub index: Option<usize>,
|
||||
pub name: String,
|
||||
pub files: Result<serde_json::Value, String>,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A file type with its bit depth (an export override).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FileType {
|
||||
/// The listed name ("png", "targa", ...).
|
||||
pub format: String,
|
||||
pub bit_depth: u8,
|
||||
/// "8 bits + dithering".
|
||||
#[serde(default)]
|
||||
pub dithering: bool,
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::FileType;
|
||||
|
||||
/// One output map's export settings on a texture set's page.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MapExport {
|
||||
/// False leaves the map out of the export.
|
||||
#[serde(default = "enabled_by_default")]
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub file_type: Option<FileType>,
|
||||
}
|
||||
|
||||
fn enabled_by_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
impl Default for MapExport {
|
||||
fn default() -> Self {
|
||||
MapExport { enabled: true, file_type: None }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{FileType, MapExport};
|
||||
|
||||
/// One texture set's export overrides (None: the global setting).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SetExport {
|
||||
#[serde(default)]
|
||||
pub preset: Option<String>,
|
||||
#[serde(default)]
|
||||
pub file_type: Option<FileType>,
|
||||
/// Texels per side.
|
||||
#[serde(default)]
|
||||
pub size: Option<u32>,
|
||||
/// Padding type and dilation width.
|
||||
#[serde(default)]
|
||||
pub padding: Option<(String, u32)>,
|
||||
/// The template `maps` belong to: they are dropped when the set's template changes.
|
||||
#[serde(default)]
|
||||
pub maps_template: String,
|
||||
/// Per output map (by index into the template's maps) settings.
|
||||
#[serde(default)]
|
||||
pub maps: std::collections::BTreeMap<usize, MapExport>,
|
||||
}
|
||||
|
||||
impl SetExport {
|
||||
/// Whether anything is overridden (the set is marked "*").
|
||||
pub fn any(&self) -> bool {
|
||||
self.preset.is_some() || self.file_type.is_some() || self.size.is_some() || self.padding.is_some() || self.maps.values().any(|m| m.file_type.is_some())
|
||||
}
|
||||
|
||||
/// Whether the set exports as the global settings say (no override, every map ticked).
|
||||
pub fn is_default(&self) -> bool {
|
||||
!self.any() && self.maps.values().all(|m| m.enabled)
|
||||
}
|
||||
}
|
||||
@@ -229,7 +229,7 @@ pub fn project_file_name(app: &TextureCraftApp) -> String {
|
||||
|
||||
/// Pack exported textures into one zip archive.
|
||||
#[cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
|
||||
fn zip_files(files: &[ExportedFile]) -> Result<Vec<u8>, String> {
|
||||
fn zip_files(files: Vec<ExportedFile>) -> Result<Vec<u8>, 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);
|
||||
@@ -342,19 +342,27 @@ mod web {
|
||||
}
|
||||
}
|
||||
|
||||
/// Export texture sets `sets` with `file.exportTextures` params (minus `dir` and `ts`): one
|
||||
/// file downloads as is, several as `<project>_textures.zip`.
|
||||
pub fn export_textures(app: &mut TextureCraftApp, params: &Value, sets: &[usize]) {
|
||||
match export(app, params, sets) {
|
||||
/// Export each texture set with its own `file.exportTextures` params (minus `dir`): one file
|
||||
/// downloads as is, several as `<project>_textures.zip`.
|
||||
pub fn export_textures(app: &mut TextureCraftApp, jobs: &[(usize, Value)]) {
|
||||
match export(app, jobs) {
|
||||
Ok(name) => app.toast(trf("Downloaded {name}", &[("name", &name)]), false),
|
||||
Err(e) => app.toast(trf("Couldn't export textures: {error}", &[("error", &e)]), true),
|
||||
}
|
||||
}
|
||||
|
||||
fn export(app: &mut TextureCraftApp, params: &Value, sets: &[usize]) -> Result<String, String> {
|
||||
let opts = texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures").map_err(|e| e.to_string())?;
|
||||
let files = app.session.export_files(sets, &opts).map_err(|e| e.to_string())?;
|
||||
app.session.log.warnings("MapExporter", files.iter().flat_map(|f| f.warnings.iter().cloned()));
|
||||
fn export(app: &mut TextureCraftApp, jobs: &[(usize, Value)]) -> Result<String, String> {
|
||||
let mut files = Vec::new();
|
||||
for (set_index, params) in jobs {
|
||||
let options = texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures").map_err(|e| e.to_string())?;
|
||||
files.extend(app.session.export_files(&[*set_index], &options).map_err(|e| e.to_string())?);
|
||||
}
|
||||
|
||||
// Keep one file for each case-insensitive name in the download
|
||||
texturecraft_engine::formats::skip_repeated_names(&mut files);
|
||||
app.session.log.warnings("MapExporter", files.iter().flat_map(|file| file.warnings.iter().cloned()));
|
||||
let file_count = files.len();
|
||||
|
||||
let name = match files.as_slice() {
|
||||
[] => return Err("the preset produced no files".into()),
|
||||
[f] => {
|
||||
@@ -363,11 +371,12 @@ mod web {
|
||||
}
|
||||
_ => {
|
||||
let name = format!("{}_textures.zip", sanitize_file_stem(&app.session.doc.project.name));
|
||||
download(&name, &zip_files(&files)?)?;
|
||||
download(&name, &zip_files(files)?)?;
|
||||
name
|
||||
}
|
||||
};
|
||||
app.session.log.info("MapExporter", format!("Exported {} textures ({name})", files.len()));
|
||||
|
||||
app.session.log.info("MapExporter", format!("Exported {file_count} textures ({name})"));
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
@@ -380,19 +389,35 @@ mod web {
|
||||
let opts = web_sys::BlobPropertyBag::new();
|
||||
opts.set_type(if name.ends_with(".zip") { "application/zip" } else { "application/octet-stream" });
|
||||
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
|
||||
let anchor: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
|
||||
anchor.set_download(name);
|
||||
anchor.style().set_property("display", "none").map_err(js)?;
|
||||
let body = document.body().ok_or("no body")?;
|
||||
|
||||
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
|
||||
let a: web_sys::HtmlAnchorElement = document.create_element("a").map_err(js)?.dyn_into().map_err(|_| "not an anchor")?;
|
||||
a.set_href(&url);
|
||||
a.set_download(name);
|
||||
a.style().set_property("display", "none").map_err(js)?;
|
||||
document.body().ok_or("no body")?.append_child(&a).map_err(js)?;
|
||||
a.click();
|
||||
a.remove();
|
||||
// Revoke once the click has been dispatched; the download keeps its own reference.
|
||||
let revoke = wasm_bindgen::closure::Closure::once_into_js(move || {
|
||||
web_sys::Url::revoke_object_url(&url).ok();
|
||||
anchor.set_href(&url);
|
||||
if let Err(error) = body.append_with_node_1(&anchor) {
|
||||
let _ = web_sys::Url::revoke_object_url(&url);
|
||||
return Err(js(error));
|
||||
}
|
||||
|
||||
let download_url = url.clone();
|
||||
let revoke = wasm_bindgen::closure::Closure::once(move || {
|
||||
let _ = web_sys::Url::revoke_object_url(&download_url);
|
||||
});
|
||||
window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?;
|
||||
|
||||
// The download keeps its own reference once the click dispatches
|
||||
const DOWNLOAD_URL_LIFETIME_MS: i32 = 10_000;
|
||||
if let Err(error) = window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.as_ref().unchecked_ref(), DOWNLOAD_URL_LIFETIME_MS) {
|
||||
anchor.remove();
|
||||
let _ = web_sys::Url::revoke_object_url(&url);
|
||||
return Err(js(error));
|
||||
}
|
||||
|
||||
// The timer owns the callback now, so release its Wasm reference slot
|
||||
drop(revoke.into_js_value());
|
||||
anchor.click();
|
||||
anchor.remove();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -499,14 +524,18 @@ mod tests {
|
||||
#[test]
|
||||
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 files = [file("a_BaseColor.png", b"one"), file("a_Normal.png", &[7u8; 4096])];
|
||||
let bytes = zip_files(&files).unwrap();
|
||||
let normal = [7u8; 4096];
|
||||
let expected = [("a_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();
|
||||
assert_eq!(zip.len(), 2);
|
||||
for f in &files {
|
||||
|
||||
assert_eq!(zip.len(), expected.len());
|
||||
for (name, expected_bytes) in expected {
|
||||
let mut out = Vec::new();
|
||||
std::io::Read::read_to_end(&mut zip.by_name(&f.name).unwrap(), &mut out).unwrap();
|
||||
assert_eq!(out, f.bytes);
|
||||
std::io::Read::read_to_end(&mut zip.by_name(name).unwrap(), &mut out).unwrap();
|
||||
assert_eq!(out, expected_bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::file_dialogs::{Bound, FileDialog};
|
||||
use crate::i18n::{tr, tr_history, trf};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::state::Mode;
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::theme::Tokens;
|
||||
use crate::widgets::primary_button;
|
||||
|
||||
pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
@@ -23,7 +23,7 @@ pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
crate::import_resources::show(app, ctx);
|
||||
}
|
||||
crate::keymap::window(app, ctx);
|
||||
crate::windows::export(app, ctx);
|
||||
crate::export_window::show(app, ctx);
|
||||
crate::mesh_export_options::show(app, ctx);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
export_mesh(app, ctx);
|
||||
@@ -272,7 +272,7 @@ fn export_mesh(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut picked = None;
|
||||
dialog("export_mesh", tr("Export mesh"), &mut open).show(ctx, |ui| {
|
||||
ui.label(caption(tr("Download as")));
|
||||
ui.label(crate::theme::caption(tr("Download as")));
|
||||
for (extension, label, hint) in formats {
|
||||
if ui.add_sized(vec2(220.0, ui.spacing().interact_size.y), egui::Button::new(label)).on_hover_text(hint).clicked() {
|
||||
picked = Some(extension);
|
||||
@@ -632,299 +632,6 @@ pub fn file_action(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) ->
|
||||
true
|
||||
}
|
||||
|
||||
/// Texture sets ticked in the export dialog.
|
||||
fn export_selection(app: &TextureCraftApp) -> Vec<usize> {
|
||||
(0..app.session.set_count()).filter(|i| !app.ui.export.skip.contains(i)).collect()
|
||||
}
|
||||
|
||||
/// Export the selected texture sets; false when a command failed (its error is already shown).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn export_sets(app: &mut TextureCraftApp) -> bool {
|
||||
let mut written = 0usize;
|
||||
for ts in export_selection(app) {
|
||||
let mut p = export_params(app);
|
||||
p["dir"] = json!(app.ui.export.dir);
|
||||
p["ts"] = json!(ts);
|
||||
match app.run("file.exportTextures", p) {
|
||||
Some(r) => written += r.get("files").and_then(|f| f.as_array()).map(Vec::len).unwrap_or(0),
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
app.toast(trf("Exported {n} textures to {folder}", &[("n", &written), ("folder", &app.ui.export.dir)]), false);
|
||||
true
|
||||
}
|
||||
|
||||
/// In the browser the textures download (one zip for several files).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn export_sets(app: &mut TextureCraftApp) -> bool {
|
||||
let sets = export_selection(app);
|
||||
crate::web_files::export_textures(app, &export_params(app), &sets);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn export_params(app: &TextureCraftApp) -> serde_json::Value {
|
||||
let e = &app.ui.export;
|
||||
let mut p = json!({"preset": e.preset, "padding": e.padding, "dilation": e.dilation});
|
||||
if !e.format.is_empty() {
|
||||
p["format"] = json!(e.format);
|
||||
}
|
||||
if e.bit_depth > 0 {
|
||||
p["bitDepth"] = json!(e.bit_depth);
|
||||
}
|
||||
if e.size > 0 {
|
||||
p["size"] = json!(e.size);
|
||||
}
|
||||
if !e.normal_format.is_empty() {
|
||||
p["normalFormat"] = json!(e.normal_format);
|
||||
}
|
||||
if !e.color_space.is_empty() {
|
||||
p["colorSpace"] = json!(e.color_space);
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn export_settings_tab(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(caption(tr("General Export Parameters")));
|
||||
egui::Grid::new("exp_grid").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| {
|
||||
// The browser downloads the files instead
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
ui.label(tr("Output directory"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::TextEdit::singleline(&mut app.ui.export.dir).desired_width(360.0));
|
||||
if ui.button("...").clicked() {
|
||||
app.ask_file(FileDialog::folder().directory(app.ui.export.dir.clone()), Bound::App, |app, paths| {
|
||||
if let Some(d) = paths.first() {
|
||||
app.ui.export.dir = d.display().to_string();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
ui.label(tr("Output template"));
|
||||
let before = app.ui.export.preset.clone();
|
||||
egui::ComboBox::from_id_salt("exp_preset").width(360.0).selected_text(app.ui.export.preset.clone()).show_ui(ui, |ui| {
|
||||
for preset in texturecraft_engine::formats::builtin_presets() {
|
||||
ui.selectable_value(&mut app.ui.export.preset, preset.name.clone(), preset.name);
|
||||
}
|
||||
if !app.session.export_presets.list.is_empty() {
|
||||
ui.separator();
|
||||
}
|
||||
for p in &app.session.export_presets.list {
|
||||
ui.selectable_value(&mut app.ui.export.preset, p.name.clone(), &p.name);
|
||||
}
|
||||
});
|
||||
if app.ui.export.preset != before {
|
||||
let picked = std::mem::replace(&mut app.ui.export.preset, before);
|
||||
crate::export_templates::select(app, picked);
|
||||
}
|
||||
ui.end_row();
|
||||
ui.label(tr("File type"));
|
||||
ui.horizontal(|ui| {
|
||||
let label = if app.ui.export.format.is_empty() { tr("From template").to_string() } else { app.ui.export.format.clone() };
|
||||
egui::ComboBox::from_id_salt("exp_fmt").selected_text(label).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut app.ui.export.format, String::new(), tr("From template"));
|
||||
for f in ["png", "jpeg", "tga", "tiff", "bmp", "webp", "exr", "hdr"] {
|
||||
ui.selectable_value(&mut app.ui.export.format, f.to_string(), f);
|
||||
}
|
||||
});
|
||||
let bd = if app.ui.export.bit_depth == 0 { tr("Default").to_string() } else { trf("{n} bits", &[("n", &app.ui.export.bit_depth)]) };
|
||||
egui::ComboBox::from_id_salt("exp_bits").selected_text(bd).show_ui(ui, |ui| {
|
||||
for (v, l) in [
|
||||
(0u8, tr("Default").to_string()),
|
||||
(8, trf("{n} bits", &[("n", &8)])),
|
||||
(16, trf("{n} bits", &[("n", &16)])),
|
||||
(32, tr("32 bits (float)").to_string()),
|
||||
] {
|
||||
ui.selectable_value(&mut app.ui.export.bit_depth, v, l);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Size"));
|
||||
let sz = if app.ui.export.size == 0 { tr("Based on each Texture Set's size").to_string() } else { format!("{0} x {0}", app.ui.export.size) };
|
||||
egui::ComboBox::from_id_salt("exp_size").width(360.0).selected_text(sz).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut app.ui.export.size, 0, tr("Based on each Texture Set's size"));
|
||||
for r in [256u32, 512, 1024, 2048, 4096, 8192] {
|
||||
ui.selectable_value(&mut app.ui.export.size, r, format!("{r} x {r}"));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Padding"));
|
||||
ui.horizontal(|ui| {
|
||||
let label = match app.ui.export.padding.as_str() {
|
||||
"none" => tr("No padding (passthrough)"),
|
||||
"dilation" => tr("Dilation + transparent"),
|
||||
"dilationDefault" => tr("Dilation + default background color"),
|
||||
_ => tr("Dilation infinite"),
|
||||
};
|
||||
egui::ComboBox::from_id_salt("exp_pad").width(260.0).selected_text(label).show_ui(ui, |ui| {
|
||||
for (v, l) in [
|
||||
("infinite", tr("Dilation infinite")),
|
||||
("dilation", tr("Dilation + transparent")),
|
||||
("dilationDefault", tr("Dilation + default background color")),
|
||||
("none", tr("No padding (passthrough)")),
|
||||
] {
|
||||
ui.selectable_value(&mut app.ui.export.padding, v.to_string(), l);
|
||||
}
|
||||
});
|
||||
if app.ui.export.padding.starts_with("dilation") {
|
||||
ui.add(egui::DragValue::new(&mut app.ui.export.dilation).range(0..=256).suffix(" px"));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
|
||||
// The reference's two switches; TextureCraft's own normal map and colour space overrides follow them
|
||||
crate::unavailable::checkbox(ui, false, tr("Export USD asset"));
|
||||
crate::unavailable::checkbox(ui, false, tr("Export shaders parameters"));
|
||||
ui.add_space(8.0);
|
||||
egui::Grid::new("exp_grid_more").num_columns(2).spacing(vec2(12.0, 8.0)).show(ui, |ui| {
|
||||
ui.label(tr("Normal map format"));
|
||||
let nf = match app.ui.export.normal_format.as_str() {
|
||||
"openGl" => "OpenGL",
|
||||
"directX" => "DirectX",
|
||||
_ => tr("From template / project"),
|
||||
};
|
||||
egui::ComboBox::from_id_salt("exp_nf").selected_text(nf).show_ui(ui, |ui| {
|
||||
for (v, l) in [("", tr("From template / project")), ("openGl", "OpenGL"), ("directX", "DirectX")] {
|
||||
ui.selectable_value(&mut app.ui.export.normal_format, v.to_string(), l);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Color space"));
|
||||
let shown = if app.ui.export.color_space.is_empty() { tr("Default") } else { app.ui.export.color_space.as_str() };
|
||||
egui::ComboBox::from_id_salt("exp_cs").selected_text(shown).show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut app.ui.export.color_space, String::new(), tr("Default"));
|
||||
for name in ["sRGB", "Linear Rec.709", "ACEScg", "ACES2065-1"] {
|
||||
ui.selectable_value(&mut app.ui.export.color_space, name.to_string(), name);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
}
|
||||
|
||||
/// Height of the Export textures window's tab body, above its buttons
|
||||
const EXPORT_BODY_HEIGHT: f32 = 440.0;
|
||||
|
||||
/// Plan only the files for the checked texture sets.
|
||||
fn selected_export_plan(app: &mut TextureCraftApp) -> texturecraft_engine::Result<serde_json::Value> {
|
||||
let mut params = export_params(app);
|
||||
params["ts"] = json!(export_selection(app));
|
||||
texturecraft_engine::execute(&mut app.session, "export.plan", ¶ms)
|
||||
}
|
||||
|
||||
pub fn export(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if !app.ui.windows.export {
|
||||
app.ui.export.ask = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let tokens = Tokens::get(ctx);
|
||||
let mut open = true;
|
||||
let mut do_export = false;
|
||||
dialog("export_textures", tr("Export textures"), &mut open).fixed_size(vec2(900.0, 520.0)).show(ctx, |ui| {
|
||||
// Nothing to export without a project
|
||||
if !app.session.project_open {
|
||||
ui.label(tr("No project is open"));
|
||||
return;
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
for (index, title) in [tr("Settings"), tr("Output templates"), tr("List of exports")].iter().enumerate() {
|
||||
if ui.selectable_label(app.ui.export.tab == index as u8, caption(&title.to_uppercase())).clicked() {
|
||||
app.ui.export.tab = index as u8;
|
||||
}
|
||||
}
|
||||
|
||||
// Tick every texture set again
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button(tr("Include all")).clicked() {
|
||||
app.ui.export.skip.clear();
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
let mut selected_count = None;
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), EXPORT_BODY_HEIGHT), egui::Layout::left_to_right(egui::Align::Min), |ui| {
|
||||
ui.set_height(EXPORT_BODY_HEIGHT);
|
||||
if app.ui.export.tab == 1 {
|
||||
crate::export_templates::tab(app, ui, &texturecraft_engine::formats::builtin_presets());
|
||||
return;
|
||||
}
|
||||
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(180.0);
|
||||
|
||||
// The settings apply to every texture set; there are no per-set settings yet
|
||||
let header = ui.selectable_label(true, RichText::new(tr("Global settings")).strong());
|
||||
let list_height = EXPORT_BODY_HEIGHT - header.rect.height() - ui.spacing().item_spacing.y;
|
||||
egui::ScrollArea::vertical().id_salt("export_texture_sets").max_height(list_height.max(0.0)).show(ui, |ui| {
|
||||
for (index, set) in app.session.doc.project.texture_sets.iter().enumerate() {
|
||||
let mut checked = !app.ui.export.skip.contains(&index);
|
||||
if ui.checkbox(&mut checked, &set.name).changed() {
|
||||
if checked {
|
||||
app.ui.export.skip.retain(|skipped| *skipped != index);
|
||||
} else {
|
||||
app.ui.export.skip.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
ui.vertical(|ui| match app.ui.export.tab {
|
||||
0 => export_settings_tab(app, ui),
|
||||
_ => match selected_export_plan(app) {
|
||||
Ok(plan) => {
|
||||
let files = plan.as_array().map(Vec::as_slice).unwrap_or_default();
|
||||
selected_count = Some(files.len());
|
||||
egui::ScrollArea::vertical().max_height(340.0).show(ui, |ui| {
|
||||
for file in files {
|
||||
ui.label(RichText::new(file.get("file").and_then(|value| value.as_str()).unwrap_or_default()).monospace());
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(error) => {
|
||||
selected_count = Some(0);
|
||||
ui.label(RichText::new(error.to_string()).color(tokens.danger));
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.separator();
|
||||
let selected = selected_count.unwrap_or_else(|| selected_export_plan(app).ok().and_then(|plan| plan.as_array().map(Vec::len)).unwrap_or(0));
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button(tr("Reset all")).clicked() {
|
||||
app.ui.export = crate::state::ExportUi::default();
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.add(primary_button(ui, tr("Export"))).clicked() {
|
||||
do_export = true;
|
||||
}
|
||||
|
||||
// The settings are kept with the interface, so saving them closes the window without exporting
|
||||
if ui.button(tr("Save settings")).on_hover_text(tr("Keep these settings for the next export")).clicked() {
|
||||
app.ui.windows.export = false;
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
app.ui.windows.export = false;
|
||||
}
|
||||
ui.label(trf("{n} textures selected for export", &[("n", &selected)]));
|
||||
});
|
||||
});
|
||||
});
|
||||
crate::export_templates::ask(app, ctx);
|
||||
if do_export && export_sets(app) {
|
||||
app.ui.windows.export = false;
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.export = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
@@ -944,7 +651,8 @@ mod tests {
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
// These dialog tests query English labels, independently of the system locale.
|
||||
|
||||
// Match English labels independently of the system locale
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
h.run_steps(2);
|
||||
h
|
||||
@@ -962,7 +670,7 @@ mod tests {
|
||||
harness.state_mut().ui.windows.export = true;
|
||||
harness.run_steps(5);
|
||||
let footer = harness.get_by_role_and_label(egui::Role::Button, "Reset all").rect();
|
||||
let first = harness.get_by_role_and_label(egui::Role::CheckBox, "Export set 1");
|
||||
let first = harness.get_by_label("Export set 1");
|
||||
first.hover();
|
||||
harness.run_steps(2);
|
||||
|
||||
@@ -974,11 +682,11 @@ mod tests {
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
});
|
||||
harness.run_steps(15);
|
||||
let last = harness.get_by_role_and_label(egui::Role::CheckBox, "Export set 39");
|
||||
let last = harness.get_by_label("Export set 39");
|
||||
last.click();
|
||||
harness.run_steps(4);
|
||||
|
||||
assert_eq!(harness.state().ui.export.skip, vec![last_index], "the last texture set is clickable after scrolling");
|
||||
assert_eq!(harness.state().ui.export.page, Some(last_index), "the last texture set is clickable after scrolling");
|
||||
let footer_after = harness.get_by_role_and_label(egui::Role::Button, "Reset all").rect();
|
||||
assert_eq!(footer_after, footer, "scrolling keeps the footer in place");
|
||||
assert!(footer_after.bottom() < 960.0, "the footer is inside the window");
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Export textures › file types (texturecraft #672): the reference's file type list, a bit depth
|
||||
//! list that follows the file type, dithering and "Dilation + diffusion".
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT as _, Queryable as _};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// The Export textures window open on SETTINGS
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
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);
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn combo<'a>(h: &'a Harness<'_, TextureCraftApp>, value: &str) -> egui_kittest::Node<'a> {
|
||||
h.get_all_by_role(egui::Role::ComboBox).find(|c| c.value().as_deref() == Some(value)).unwrap_or_else(|| panic!("no dropdown at {value:?}"))
|
||||
}
|
||||
|
||||
fn open_combo(h: &mut Harness<'_, TextureCraftApp>, value: &str) {
|
||||
combo(h, value).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// Pick file type `name` in the global File type list showing `from`
|
||||
fn pick_type(h: &mut Harness<'_, TextureCraftApp>, from: &str, name: &str) {
|
||||
open_combo(h, from);
|
||||
click(h, name);
|
||||
}
|
||||
|
||||
/// The entries of the open list, top to bottom
|
||||
fn entries(h: &Harness<'_, TextureCraftApp>, labels: &[&str]) -> Vec<String> {
|
||||
let mut found: Vec<(f32, String)> = labels.iter().filter_map(|l| h.query_all_by_label(l).last().map(|n| (n.rect().top(), (*l).to_string()))).collect();
|
||||
found.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
found.into_iter().map(|(_, l)| l).collect()
|
||||
}
|
||||
|
||||
const TYPES: [&str; 14] = ["bmp", "jpeg", "jng", "pgm", "png", "targa", "tiff", "hdr", "exr", "j2k", "jp2", "webp", "psd", "sbsar"];
|
||||
|
||||
#[test]
|
||||
fn the_file_type_list_is_the_reference_one_with_three_greyed() {
|
||||
let mut h = harness();
|
||||
open_combo(&mut h, "Based on output template");
|
||||
assert_eq!(entries(&h, &TYPES), TYPES.map(String::from).to_vec());
|
||||
|
||||
// Bottom up, so no tooltip covers the next entry
|
||||
for name in ["sbsar", "jp2", "j2k"] {
|
||||
assert!(h.get_all_by_label(name).last().unwrap().accesskit_node().is_disabled(), "{name} is greyed");
|
||||
h.get_all_by_label(name).last().unwrap().scroll_to_me();
|
||||
h.run_steps(6);
|
||||
let at = h.get_all_by_label(name).last().unwrap().rect().center();
|
||||
h.hover_at(at);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label("Not available yet").is_some(), "{name} at {at:?}");
|
||||
}
|
||||
assert!(!h.get_all_by_label("psd").last().unwrap().accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bit_depth_list_follows_the_file_type() {
|
||||
let mut h = harness();
|
||||
assert!(combo(&h, "").accesskit_node().is_disabled(), "empty and greyed while the template decides");
|
||||
|
||||
pick_type(&mut h, "Based on output template", "psd");
|
||||
assert_eq!((h.state().ui.export.format.as_str(), h.state().ui.export.bit_depth), ("psd", 8));
|
||||
open_combo(&mut h, "8 bits");
|
||||
assert_eq!(entries(&h, &["8 bits", "8 bits + dithering", "16 bits", "32f bits"]), ["8 bits", "8 bits + dithering", "16 bits"]);
|
||||
click(&mut h, "8 bits + dithering");
|
||||
assert!(h.state().ui.export.dithering);
|
||||
|
||||
pick_type(&mut h, "psd", "exr");
|
||||
assert_eq!((h.state().ui.export.bit_depth, h.state().ui.export.dithering), (32, false), "exr starts at 32f bits");
|
||||
open_combo(&mut h, "32f bits");
|
||||
assert_eq!(entries(&h, &["8 bits", "16f bits", "16 bits", "32f bits"]), ["16f bits", "32f bits"]);
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
|
||||
pick_type(&mut h, "exr", "tiff");
|
||||
open_combo(&mut h, "8 bits");
|
||||
assert_eq!(entries(&h, &["8 bits", "8 bits + dithering", "16 bits", "32f bits"]), ["8 bits", "8 bits + dithering", "16 bits", "32f bits"]);
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
|
||||
pick_type(&mut h, "tiff", "hdr");
|
||||
assert!(combo(&h, "32f bits").accesskit_node().is_disabled(), "hdr has only 32f bits");
|
||||
pick_type(&mut h, "hdr", "jpeg");
|
||||
open_combo(&mut h, "8 bits");
|
||||
assert_eq!(entries(&h, &["8 bits", "8 bits + dithering", "16 bits"]), ["8 bits", "8 bits + dithering"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_offers_diffusion_with_a_width() {
|
||||
let mut h = harness();
|
||||
open_combo(&mut h, "Dilation infinite");
|
||||
click(&mut h, "Dilation + diffusion");
|
||||
assert_eq!(h.state().ui.export.padding, "diffusion");
|
||||
assert!(!h.get_by_label("16").accesskit_node().is_disabled(), "diffusion has a dilation width");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_writes_the_chosen_type_and_depth() {
|
||||
let mut h = harness();
|
||||
let dir = std::env::temp_dir().join(format!("tc-export-file-types-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.dir = dir.display().to_string();
|
||||
e.format = "pgm".into();
|
||||
e.bit_depth = 16;
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Export");
|
||||
|
||||
// The export writes a texture set per frame
|
||||
for _ in 0..64 {
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
let files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).collect();
|
||||
assert!(!files.is_empty());
|
||||
for f in &files {
|
||||
assert_eq!(f.extension().unwrap(), "pgm");
|
||||
assert!(std::fs::read(f).unwrap().starts_with(b"P5\n256 256\n65535\n"), "{}", f.display());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_old_hidden_bit_depth_is_not_exported() {
|
||||
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();
|
||||
|
||||
// Saved by an older build: "From template" with 16 bits
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
(e.format, e.bit_depth) = (String::new(), 16);
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.export.bit_depth, 0, "what the window shows (no depth) is what exports");
|
||||
|
||||
// A type with a depth it does not have gets its default
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
(e.format, e.bit_depth) = ("jpeg".into(), 16);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.export.bit_depth, 8);
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! Export textures › a texture set's Output maps (texturecraft #670): a tick per map, its file
|
||||
//! name pattern, and its own file type and bit depth.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::{FileType, MapExport, SetExport};
|
||||
|
||||
/// The Export textures window open on the first texture set's page
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
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);
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
let name = h.state().session.doc.project.texture_sets[0].name.clone();
|
||||
h.get_all_by_label(&name).last().unwrap().click();
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// The number in "N textures selected for export"
|
||||
fn selected(h: &Harness<'_, TextureCraftApp>) -> usize {
|
||||
(0..500).find(|n| h.query_by_label(&format!("{n} textures selected for export")).is_some()).expect("the footer count")
|
||||
}
|
||||
|
||||
fn maps(h: &Harness<'_, TextureCraftApp>) -> std::collections::BTreeMap<usize, MapExport> {
|
||||
h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The first texture set's planned files with the window's settings
|
||||
fn plan(h: &mut Harness<'_, TextureCraftApp>) -> Vec<serde_json::Value> {
|
||||
let preset = h.state().ui.export.preset.clone();
|
||||
let v = texturecraft_engine::execute(&mut h.state_mut().session, "export.plan", &serde_json::json!({"preset": preset, "ts": 0})).unwrap();
|
||||
v.as_array().unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_rows_show_each_map_with_its_pattern_and_file_type() {
|
||||
let mut h = harness();
|
||||
let rows = plan(&mut h).len();
|
||||
assert!(h.query_by_label("Output maps").is_some());
|
||||
|
||||
// Four rows of General Export Parameters, then one per map
|
||||
assert_eq!(h.get_all_by_label("Enable override").count(), 4 + rows);
|
||||
assert!(h.query_all_by_label("png 8 bits").next().is_some());
|
||||
assert!(h.query_all_by_label("png 16 bits").next().is_some(), "height is 16-bit in the default template");
|
||||
|
||||
// A pattern longer than the column is cut at the front, the whole one is its tooltip
|
||||
let preset = texturecraft_engine::formats::builtin_preset(&h.state().ui.export.preset).unwrap();
|
||||
let long =
|
||||
plan(&mut h).iter().map(|f| preset.maps[f["map"].as_u64().unwrap() as usize].file.clone()).find(|p| p.chars().count() > 26).expect("a long pattern");
|
||||
let cut: String = format!("…{}", long.chars().skip(long.chars().count() - 25).collect::<String>());
|
||||
assert!(h.query_by_label(&long).is_none(), "{long} is cut");
|
||||
let at = h.get_all_by_label(&cut).next().unwrap().rect().center();
|
||||
h.hover_at(at);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label(&long).is_some(), "the tooltip has the whole {long}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() {
|
||||
let mut h = harness();
|
||||
let before = selected(&h);
|
||||
let rows = plan(&mut h).len();
|
||||
|
||||
// The window comes last, and its map rows last in it
|
||||
let boxes = h.get_all_by_role(egui::Role::CheckBox).count();
|
||||
h.get_all_by_role(egui::Role::CheckBox).nth(boxes - rows).unwrap().click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(selected(&h), before - 1);
|
||||
assert_eq!(maps(&h).values().filter(|m| !m.enabled).count(), 1);
|
||||
assert!(h.query_by_label("*").is_none(), "a left-out map is not an override");
|
||||
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Uncheck all");
|
||||
assert_eq!(selected(&h), before - rows);
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Invert all");
|
||||
assert_eq!(selected(&h), before);
|
||||
assert!(!h.state().ui.export.sets.contains_key(&0), "nothing left to remember");
|
||||
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Uncheck all");
|
||||
click(&mut h, "Include all");
|
||||
assert_eq!(selected(&h), before, "Include all ticks the output maps too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_override_sets_its_own_file_type_and_marks_the_set() {
|
||||
let mut h = harness();
|
||||
let rows = plan(&mut h).len();
|
||||
h.get_all_by_label("Enable override").nth(4).unwrap().click();
|
||||
h.run_steps(4);
|
||||
let m = maps(&h);
|
||||
let (_, first) = m.iter().next().unwrap();
|
||||
assert!(first.file_type.is_some(), "{m:?}");
|
||||
assert!(h.query_by_label("*").is_some(), "the set is marked");
|
||||
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Override every item");
|
||||
assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows);
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Clear all overrides");
|
||||
assert!(maps(&h).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_writes_a_map_with_its_own_file_type() {
|
||||
let mut h = harness();
|
||||
let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize;
|
||||
let dir = std::env::temp_dir().join(format!("tc-export-map-overrides-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let template = h.state().ui.export.preset.clone();
|
||||
let mut o = SetExport { maps_template: template, ..SetExport::default() };
|
||||
o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }) });
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.dir = dir.display().to_string();
|
||||
e.sets.insert(0, o);
|
||||
e.skip = (1..32).collect();
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Export");
|
||||
|
||||
// The export writes a texture set per frame
|
||||
for _ in 0..64 {
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
let names: Vec<String> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
assert_eq!(names.iter().filter(|n| n.ends_with(".tga")).count(), 1, "{names:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_the_template_no_longer_has_is_ignored() {
|
||||
let mut h = harness();
|
||||
let before = selected(&h);
|
||||
let template = h.state().ui.export.preset.clone();
|
||||
let mut o = SetExport { maps_template: template, ..SetExport::default() };
|
||||
o.maps.insert(999, MapExport { enabled: false, file_type: None });
|
||||
h.state_mut().ui.export.sets.insert(0, o);
|
||||
h.run_steps(3);
|
||||
assert_eq!(selected(&h), before, "the export still plans every file");
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
//! Export textures › a texture set's page (texturecraft #669): each set can override the output
|
||||
//! template, file type, size and padding of the global settings.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::{ConsoleLine, FileType, SetExport};
|
||||
|
||||
/// The Export textures window open on the first texture set's page
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
harness_with_session(texturecraft_engine::sample_session(256, 64).unwrap())
|
||||
}
|
||||
|
||||
fn harness_with_session(session: texturecraft_engine::Session) -> Harness<'static, TextureCraftApp> {
|
||||
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);
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
let name = h.state().session.doc.project.texture_sets[0].name.clone();
|
||||
h.get_all_by_label(&name).last().unwrap().click();
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// Open the General Export Parameters menu
|
||||
fn page_menu(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
h.get_all_by_label(egui_phosphor::regular::LIST_CHECKS).nth(1).unwrap().click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// The `row`th "Enable override" button (Output template, File type, Size, Padding)
|
||||
fn toggle(h: &mut Harness<'_, TextureCraftApp>, row: usize) {
|
||||
h.get_all_by_label("Enable override").nth(row).unwrap().click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
fn overrides(h: &Harness<'_, TextureCraftApp>) -> SetExport {
|
||||
h.state().ui.export.sets.get(&0).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A scratch folder of its own for `name`
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("tc-export-overrides-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Width of a PNG file from its header
|
||||
fn png_width(path: &std::path::Path) -> u32 {
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
u32::from_be_bytes(bytes[16..20].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_set_page_shows_what_it_inherits() {
|
||||
let h = harness();
|
||||
assert_eq!(h.state().ui.export.page, Some(0));
|
||||
assert!(h.get_all_by_label("Enable override").count() >= 4, "four rows, then the output maps");
|
||||
let own = h.state().session.doc.project.texture_sets[0].resolution;
|
||||
for text in ["Document channels + Normal + AO (No Alpha)", "Based on output template", &format!("{own}x{own} (Texture Set size)"), "Dilation infinite"] {
|
||||
assert!(h.query_by_label(text).is_some(), "{text}");
|
||||
}
|
||||
assert!(h.query_by_label("*").is_none(), "no override yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_override_turns_the_row_into_a_list_and_marks_the_set() {
|
||||
let mut h = harness();
|
||||
let own = h.state().session.doc.project.texture_sets[0].resolution;
|
||||
toggle(&mut h, 2);
|
||||
assert_eq!(overrides(&h).size, Some(own), "the override starts at the inherited size");
|
||||
let star = h.get_by_label("*").rect().center();
|
||||
h.hover_at(star);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label("Override(s) active").is_some());
|
||||
|
||||
let label = format!("{own}x{own} (Texture Set size)");
|
||||
h.get_all_by_role(egui::Role::ComboBox).find(|c| c.value().as_deref() == Some(label.as_str())).unwrap().click();
|
||||
h.run_steps(4);
|
||||
for size in ["128x128", "8192x8192"] {
|
||||
assert!(h.query_by_label(size).is_some(), "{size}");
|
||||
}
|
||||
click(&mut h, "128x128");
|
||||
assert_eq!(overrides(&h).size, Some(128));
|
||||
|
||||
toggle(&mut h, 2);
|
||||
assert!(!h.state().ui.export.sets.contains_key(&0), "switching the only override off clears the mark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_size_override_preserves_mixed_udim_tile_sizes() {
|
||||
use texturecraft_engine::{Session, execute, geom::primitives};
|
||||
|
||||
let mut session = Session::new_project("Export", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
|
||||
execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 512})).unwrap();
|
||||
let mut h = harness_with_session(session);
|
||||
let expected = execute(&mut h.state_mut().session, "export.plan", &serde_json::json!({"ts": 0})).unwrap();
|
||||
|
||||
toggle(&mut h, 2);
|
||||
let size = overrides(&h).size.unwrap();
|
||||
let actual = execute(&mut h.state_mut().session, "export.plan", &serde_json::json!({"ts": 0, "size": size})).unwrap();
|
||||
|
||||
assert_eq!(size, 512);
|
||||
assert_eq!(actual, expected);
|
||||
assert!(h.get_all_by_role(egui::Role::ComboBox).any(|node| node.value().as_deref() == Some("512x512 (Texture Set size)")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_header_menu_switches_every_override() {
|
||||
let mut h = harness();
|
||||
|
||||
// The set list has the same menu button; the page header's is the second
|
||||
page_menu(&mut h);
|
||||
click(&mut h, "Override every item");
|
||||
let o = overrides(&h);
|
||||
assert!(o.preset.is_some() && o.file_type.is_some() && o.size.is_some() && o.padding.is_some(), "{o:?}");
|
||||
|
||||
// The default template writes 8- and 16-bit files: the override keeps them until a type is picked
|
||||
assert_eq!(o.file_type.unwrap().format, "");
|
||||
page_menu(&mut h);
|
||||
click(&mut h, "Clear all overrides");
|
||||
assert!(h.state().ui.export.sets.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_set_cannot_override_to_the_templates_the_reference_leaves_out() {
|
||||
let mut h = harness();
|
||||
toggle(&mut h, 0);
|
||||
h.get_all_by_role(egui::Role::ComboBox).find(|c| c.value().as_deref() == Some("Document channels + Normal + AO (No Alpha)")).unwrap().click();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label("2D View").is_some());
|
||||
assert!(h.query_by_label("glTF PBR Metal Roughness").is_none());
|
||||
assert!(h.query_by_label("Sketchfab").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_writes_each_set_with_its_overrides_and_cancel_drops_them() {
|
||||
let mut h = harness();
|
||||
let dir = folder("size");
|
||||
h.state_mut().ui.export.dir = dir.display().to_string();
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { size: Some(128), ..SetExport::default() });
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Export");
|
||||
|
||||
// The export writes a texture set per frame
|
||||
for _ in 0..64 {
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
let finished = h.state().ui.export.console.iter().any(|l| matches!(l, ConsoleLine::Done(t) if t == "Texture export complete"));
|
||||
assert!(h.state().ui.export.job.is_none() && finished, "the export finished");
|
||||
let sets: Vec<String> = h.state().session.doc.project.texture_sets.iter().map(|t| format!("_{}_", t.name)).collect();
|
||||
let files: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e == "png")).collect();
|
||||
let of = |set: &str| files.iter().filter(|f| f.file_name().unwrap().to_string_lossy().contains(set)).collect::<Vec<_>>();
|
||||
assert!(!of(&sets[0]).is_empty());
|
||||
for f in of(&sets[0]) {
|
||||
assert_eq!(png_width(f), 128, "{}", f.display());
|
||||
}
|
||||
|
||||
// The other sets keep their own size
|
||||
for set in &sets[1..] {
|
||||
assert!(!of(set).is_empty(), "{set} was written");
|
||||
for f in of(set) {
|
||||
assert_eq!(png_width(f), 256, "{}", f.display());
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
|
||||
// The window stays open after an export; Save settings keeps the overrides
|
||||
click(&mut h, "Save settings");
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { size: Some(512), ..SetExport::default() });
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Cancel");
|
||||
assert_eq!(overrides(&h).size, Some(128), "Cancel goes back to the overrides the window opened with");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_stay_with_their_texture_set_and_their_project() {
|
||||
let mut h = harness();
|
||||
let names: Vec<String> = h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect();
|
||||
assert!(names.len() >= 2);
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.sets.insert(1, SetExport { size: Some(128), ..SetExport::default() });
|
||||
e.skip = vec![1];
|
||||
click(&mut h, "Save settings");
|
||||
|
||||
// The two texture sets trade names: the override and the tick follow the name
|
||||
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.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
assert_eq!(overrides(&h).size, Some(128), "set 0 now carries the name that had the override");
|
||||
assert_eq!(h.state().ui.export.skip, vec![0]);
|
||||
click(&mut h, "Save settings");
|
||||
|
||||
// Another project starts without them
|
||||
h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.export.sets.is_empty() && h.state().ui.export.skip.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_type_override_starts_from_the_type_of_the_template() {
|
||||
let mut h = harness();
|
||||
let library = folder("library");
|
||||
std::fs::create_dir_all(&library).unwrap();
|
||||
h.state_mut().session.load_export_presets(library.clone());
|
||||
let maps = serde_json::json!([{"file": "$textureSet_rough", "format": "Exr", "bit_depth": 32, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]);
|
||||
h.state_mut().run("export.preset.save", serde_json::json!({"preset": {"name": "One EXR", "maps": maps}})).unwrap();
|
||||
h.state_mut().ui.export.preset = "One EXR".into();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.export.format.is_empty(), "Based on output template");
|
||||
toggle(&mut h, 1);
|
||||
assert_eq!(overrides(&h).file_type, Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), "not png");
|
||||
let _ = std::fs::remove_dir_all(&library);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_keeps_each_tick_with_its_texture_set_after_they_trade_names() {
|
||||
let mut h = harness();
|
||||
let names: Vec<String> = h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect();
|
||||
h.state_mut().ui.export.skip = vec![1];
|
||||
click(&mut h, "Save settings");
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
|
||||
// While the window is open the two texture sets trade names: the tick follows the name
|
||||
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(4);
|
||||
assert_eq!(h.state().ui.export.skip, vec![0]);
|
||||
click(&mut h, "Cancel");
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.export.skip, vec![0], "Cancel and reopening keep the tick off the set named {}", names[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_all_then_cancel_restores_the_ticks_and_overrides() {
|
||||
let mut h = harness();
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.skip = vec![1];
|
||||
e.sets.insert(1, SetExport { size: Some(128), ..SetExport::default() });
|
||||
click(&mut h, "Save settings");
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
click(&mut h, "Reset all");
|
||||
assert!(h.state().ui.export.skip.is_empty() && h.state().ui.export.sets.is_empty(), "Reset all clears them");
|
||||
click(&mut h, "Cancel");
|
||||
assert_eq!(h.state().ui.export.skip, vec![1]);
|
||||
assert_eq!(h.state().ui.export.sets.get(&1).and_then(|o| o.size), Some(128), "Cancel brings the override back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ticks_saved_before_settings_named_their_project_are_kept() {
|
||||
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);
|
||||
|
||||
// Older settings: a tick off, no owner
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
(e.skip, e.owner, e.owner_id) = (vec![1], Vec::new(), None);
|
||||
e.sets.insert(1, SetExport { size: Some(128), ..SetExport::default() });
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.export.skip, vec![1]);
|
||||
assert_eq!(h.state().ui.export.sets.get(&1).and_then(|o| o.size), Some(128));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_file_type_override_keeps_the_template_types_under_a_global_one() {
|
||||
let mut h = harness();
|
||||
assert!(h.query_all_by_label("png 16 bits").next().is_some(), "the default template has a 16-bit map");
|
||||
|
||||
// The override kept the template's types (a mixed template); then a global type is chosen
|
||||
let keep = FileType { format: String::new(), bit_depth: 0, dithering: false };
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { file_type: Some(keep), ..SetExport::default() });
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
(e.format, e.bit_depth) = ("png".into(), 8);
|
||||
h.run_steps(4);
|
||||
assert!(h.query_all_by_label("png 16 bits").next().is_some(), "the set still writes the template's types");
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! Export textures › exporting (texturecraft #673): LIST OF EXPORTS as a tree, the console, the
|
||||
//! progress bar with Cancel Export, and the window staying open.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use serde_json::json;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::{ConsoleLine, ExportJob};
|
||||
|
||||
/// The Export textures window writing into a scratch folder of its own for `name`
|
||||
fn harness(name: &str) -> (Harness<'static, TextureCraftApp>, std::path::PathBuf) {
|
||||
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-progress-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
h.state_mut().ui.export.dir = dir.display().to_string();
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
(h, dir)
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click();
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn console(h: &Harness<'_, TextureCraftApp>) -> Vec<String> {
|
||||
h.state()
|
||||
.ui
|
||||
.export
|
||||
.console
|
||||
.iter()
|
||||
.map(|l| match l {
|
||||
ConsoleLine::Step(t) | ConsoleLine::Done(t) => t.clone(),
|
||||
ConsoleLine::Set(name) => format!("Texture set {name}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() {
|
||||
let (mut h, dir) = harness("run");
|
||||
let sets: Vec<String> = h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect();
|
||||
click(&mut h, "Export");
|
||||
assert_eq!(h.state().ui.export.tab, 2, "Export switches to LIST OF EXPORTS");
|
||||
h.run_steps(1);
|
||||
assert!(h.query_by_label("Cancel Export").is_some());
|
||||
assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons");
|
||||
assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export"));
|
||||
|
||||
for _ in 0..64 {
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.windows.export, "the window stays open");
|
||||
assert!(h.query_by_label("Cancel").is_some() && h.query_by_label("Cancel Export").is_none());
|
||||
let lines = console(&h);
|
||||
let set = format!("Texture set {}", sets[0]);
|
||||
let start = lines.iter().position(|l| *l == set).unwrap();
|
||||
assert_eq!(&lines[start..start + 5], [set.clone(), set.clone(), "Rendering the selected maps".into(), set.clone(), "Saving texture files".into()]);
|
||||
assert!(lines[start + 6].starts_with("Saved texture "), "{lines:?}");
|
||||
let written: Vec<String> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect();
|
||||
let finished = lines.iter().position(|l| l == "Texture export complete").unwrap();
|
||||
assert_eq!(&lines[finished - 3..finished], ["Finished writing this texture set", "All selected texture sets processed", "Collecting the exported files"]);
|
||||
assert_eq!(lines[finished + 1], "Files saved");
|
||||
assert_eq!(lines.len() - finished - 2, written.len(), "every written file is listed");
|
||||
assert!(matches!(h.state().ui.export.console.last(), Some(ConsoleLine::Done(_))), "in green");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A long export: the texture sets several times over, into `dir`
|
||||
fn long_export(h: &mut Harness<'_, TextureCraftApp>, dir: &std::path::Path) {
|
||||
let sets: Vec<usize> = (0..h.state().session.set_count()).collect();
|
||||
let params = json!({"dir": dir.display().to_string()});
|
||||
let pending: Vec<(usize, serde_json::Value)> = sets.iter().copied().cycle().take(sets.len() * 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, ..ExportJob::default() });
|
||||
}
|
||||
|
||||
/// How many texture sets the session wrote so far
|
||||
fn exports(h: &Harness<'_, TextureCraftApp>) -> usize {
|
||||
h.state().session.log.iter().filter(|l| l.starts_with("Exported ")).count()
|
||||
}
|
||||
|
||||
/// Run frames until the export ends (or a bound)
|
||||
fn finish(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
for _ in 0..64 {
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_export_stops_the_export() {
|
||||
let (mut h, dir) = harness("cancel");
|
||||
long_export(&mut h, &dir);
|
||||
h.run_steps(2);
|
||||
assert!(h.query_by_label("Cancel Export").is_some());
|
||||
assert!(h.query_all_by_label_contains("%").next().is_some(), "the bar shows the percent");
|
||||
click(&mut h, "Cancel Export");
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.export.job.is_none());
|
||||
assert!(h.state().ui.windows.export);
|
||||
let lines = console(&h);
|
||||
assert!(!lines.iter().any(|l| l == "Collecting the exported files" || l == "Texture export complete"), "the export did not finish: {lines:?}");
|
||||
assert!(h.query_by_label("Cancel").is_some(), "the buttons are back");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() {
|
||||
let (mut h, dir) = harness("tree");
|
||||
h.state_mut().ui.export.tab = 2;
|
||||
h.run_steps(4);
|
||||
let set = h.state().session.doc.project.texture_sets[0].name.clone();
|
||||
assert!(h.query_by_label(&set).is_some());
|
||||
assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some());
|
||||
assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some());
|
||||
assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none());
|
||||
assert!(h.query_by_label("CONSOLE").is_some());
|
||||
|
||||
// A row's tooltip is the full path
|
||||
let preset = h.state().ui.export.preset.clone();
|
||||
let plan = texturecraft_engine::execute(&mut h.state_mut().session, "export.plan", &serde_json::json!({"preset": preset, "ts": 0})).unwrap();
|
||||
let file = plan[0]["file"].as_str().unwrap().to_string();
|
||||
let at = h.get_by_label(&file).rect().center();
|
||||
h.hover_at(at);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label(&dir.join(&file).display().to_string()).is_some());
|
||||
|
||||
// The console's toggle hides it
|
||||
let toggle = h.get_by_label(egui_phosphor::regular::CARET_DOUBLE_RIGHT).rect().center();
|
||||
h.hover_at(toggle);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label("Hide Console").is_some());
|
||||
click(&mut h, egui_phosphor::regular::CARET_DOUBLE_RIGHT);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_output_directory_asks_the_system_to_show_the_folder() {
|
||||
let (mut h, dir) = harness("open");
|
||||
h.state_mut().ui.export.tab = 2;
|
||||
h.run_steps(4);
|
||||
h.get_by_label("Open output directory").click();
|
||||
h.run_steps(2);
|
||||
|
||||
// The test harness has no window: the folder is recorded instead of shown
|
||||
assert_eq!(h.state().file_dialogs.shown_folders(), std::slice::from_ref(&dir));
|
||||
assert!(dir.is_dir(), "a missing folder is created first");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_settings_at_export_are_kept_while_it_runs() {
|
||||
let (mut h, dir) = harness("frozen");
|
||||
let moved = dir.with_extension("moved");
|
||||
let _ = std::fs::remove_dir_all(&moved);
|
||||
click(&mut h, "Export");
|
||||
h.run_steps(1);
|
||||
assert!(h.state().ui.export.job.is_some());
|
||||
|
||||
// Another folder and size chosen while it runs reach none of the files
|
||||
h.state_mut().ui.export.dir = moved.display().to_string();
|
||||
h.state_mut().ui.export.size = 128;
|
||||
h.run_steps(1);
|
||||
|
||||
assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some());
|
||||
assert!(h.query_by_label("128x128").is_none(), "the preview shows the size taken at Export");
|
||||
|
||||
finish(&mut h);
|
||||
assert!(!moved.exists(), "nothing was written to the folder chosen later");
|
||||
let written: Vec<std::path::PathBuf> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).collect();
|
||||
let sets = h.state().session.set_count();
|
||||
assert_eq!(exports(&h), sets, "every texture set was written");
|
||||
for f in written.iter().filter(|p| p.extension().is_some_and(|e| e == "png")) {
|
||||
let width = u32::from_be_bytes(std::fs::read(f).unwrap()[16..20].try_into().unwrap());
|
||||
assert_eq!(width, 256, "{} keeps the size of the start", f.display());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_sets_writing_the_same_file_name_do_not_start_an_export() {
|
||||
let (mut h, dir) = harness("clash");
|
||||
|
||||
// A template without $textureSet gives every set the same file name (kept in a scratch library)
|
||||
let library = dir.with_extension("library");
|
||||
let _ = std::fs::remove_dir_all(&library);
|
||||
std::fs::create_dir_all(&library).unwrap();
|
||||
h.state_mut().session.load_export_presets(library.clone());
|
||||
let maps = json!([{"file": "same", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]);
|
||||
h.state_mut().run("export.preset.save", json!({"preset": {"name": "Same", "maps": maps}})).unwrap();
|
||||
h.state_mut().ui.export.preset = "Same".into();
|
||||
h.run_steps(4);
|
||||
click(&mut h, "Export");
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.export.job.is_none(), "no export runs");
|
||||
assert_eq!(exports(&h), 0);
|
||||
assert!(!dir.join("same.png").exists());
|
||||
assert!(console(&h).iter().any(|l| l.contains("both export same.png")), "{:?}", console(&h));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&library);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_another_project_stops_the_export() {
|
||||
let (mut h, dir) = harness("project");
|
||||
long_export(&mut h, &dir);
|
||||
h.run_steps(2);
|
||||
let before = exports(&h);
|
||||
assert!(before > 0 && h.state().ui.export.job.is_some());
|
||||
|
||||
h.state_mut().session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.export.job.is_none());
|
||||
assert_eq!(exports(&h), 0, "the new project exported nothing");
|
||||
assert!(console(&h).iter().any(|l| l == "Export stopped: another project was opened"), "{:?}", console(&h));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_is_disabled_without_a_ticked_texture_set() {
|
||||
let (mut h, dir) = harness("none");
|
||||
let sets = h.state().session.set_count();
|
||||
h.state_mut().ui.export.skip = (0..sets).collect();
|
||||
h.run_steps(2);
|
||||
click(&mut h, "Export");
|
||||
h.run_steps(2);
|
||||
let e = &h.state().ui.export;
|
||||
assert!(e.job.is_none() && e.console.is_empty() && e.tab == 0, "Export did nothing");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_window_writes_no_further_texture_set() {
|
||||
let (mut h, dir) = harness("close");
|
||||
long_export(&mut h, &dir);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.export.job.is_some());
|
||||
let (writes, frame) = (exports(&h), h.ctx.cumulative_frame_nr());
|
||||
|
||||
// Only the release frame closes the window and skips writing
|
||||
h.get_by_role_and_label(egui::Role::Button, "Close window").click();
|
||||
h.run_steps(1);
|
||||
assert!(!h.state().ui.windows.export && h.state().ui.export.job.is_none());
|
||||
let frames = h.ctx.cumulative_frame_nr() - frame;
|
||||
assert!(frames >= 1);
|
||||
assert_eq!((exports(&h) - writes) as u64, frames - 1, "the frame that closed the window wrote nothing");
|
||||
h.run_steps(2);
|
||||
assert_eq!((exports(&h) - writes) as u64, frames - 1);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_template_at_export_is_kept_while_it_runs() {
|
||||
let (mut h, dir) = harness("template");
|
||||
let library = dir.with_extension("library");
|
||||
let _ = std::fs::remove_dir_all(&library);
|
||||
std::fs::create_dir_all(&library).unwrap();
|
||||
h.state_mut().session.load_export_presets(library.clone());
|
||||
let map = |file: &str, channel: &str| json!({"file": file, "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": channel}}]]});
|
||||
let both = json!([map("$textureSet_rough", "Roughness"), map("$textureSet_metal", "Metallic")]);
|
||||
h.state_mut().run("export.preset.save", json!({"preset": {"name": "Two", "maps": both}})).unwrap();
|
||||
h.state_mut().ui.export.preset = "Two".into();
|
||||
h.run_steps(4);
|
||||
click(&mut h, "Export");
|
||||
h.run_steps(1);
|
||||
assert!(h.state().ui.export.job.is_some());
|
||||
|
||||
// The template loses a map while the export runs: the remaining sets still write it
|
||||
h.state_mut().run("export.preset.save", json!({"preset": {"name": "Two", "maps": [map("$textureSet_metal", "Metallic")]}})).unwrap();
|
||||
finish(&mut h);
|
||||
for set in h.state().session.doc.project.texture_sets.iter().map(|t| t.name.clone()).collect::<Vec<_>>() {
|
||||
let stem = texturecraft_engine::formats::export::sanitize_file_stem(&format!("{set}_rough"));
|
||||
assert!(dir.join(format!("{stem}.png")).exists(), "{stem}.png");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let _ = std::fs::remove_dir_all(&library);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_set_that_leaves_the_export_leaves_its_count() {
|
||||
let (mut h, dir) = harness("count");
|
||||
long_export(&mut h, &dir);
|
||||
h.run_steps(2);
|
||||
|
||||
// A rename the export cannot follow drops the set's queued writes
|
||||
texturecraft_engine::execute(&mut h.state_mut().session, "textureSet.rename", &json!({"ts": 1, "name": "renamed"})).unwrap();
|
||||
h.run_steps(1);
|
||||
let job = h.state().ui.export.job.clone().expect("the other sets are still queued");
|
||||
assert!(job.pending.iter().all(|(ts, _)| *ts != 1));
|
||||
assert_eq!(job.total - job.pending.len(), exports(&h), "the bar counts the writes done");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Export textures › SETTINGS (texturecraft #671): the reference's lists, menus and tooltips, and
|
||||
//! Cancel going back to the settings the window opened with.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// The Export textures window open on SETTINGS
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
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);
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
/// Hover the newest node labelled `label` until its tooltip shows
|
||||
fn hover(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
let center = h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center();
|
||||
h.hover_at(center);
|
||||
h.run_steps(30);
|
||||
}
|
||||
|
||||
/// Open the dropdown showing `value`
|
||||
fn open_combo(h: &mut Harness<'_, TextureCraftApp>, value: &str) {
|
||||
h.get_all_by_role(egui::Role::ComboBox).find(|c| c.value().as_deref() == Some(value)).unwrap_or_else(|| panic!("no dropdown at {value}")).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_undoes_the_changes_and_the_window_reopens_on_settings() {
|
||||
let mut h = harness();
|
||||
let before = h.state().ui.export.clone();
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.size = 512;
|
||||
e.padding = "dilation".into();
|
||||
e.skip = vec![0];
|
||||
e.tab = 2;
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Cancel");
|
||||
let app = h.state();
|
||||
assert!(!app.ui.windows.export);
|
||||
assert_eq!((app.ui.export.size, app.ui.export.padding.as_str(), app.ui.export.skip.as_slice()), (before.size, before.padding.as_str(), &[][..]));
|
||||
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.export.tab, 0, "the window reopens on SETTINGS");
|
||||
|
||||
// Save settings keeps them
|
||||
h.state_mut().ui.export.size = 1024;
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Save settings");
|
||||
assert!(!h.state().ui.windows.export);
|
||||
assert_eq!(h.state().ui.export.size, 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_the_window_is_cancel() {
|
||||
let mut h = harness();
|
||||
h.state_mut().ui.export.size = 2048;
|
||||
h.run_steps(3);
|
||||
h.get_by_role_and_label(egui::Role::Button, "Close window").click();
|
||||
h.run_steps(4);
|
||||
assert!(!h.state().ui.windows.export);
|
||||
assert_eq!(h.state().ui.export.size, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lists_hold_the_reference_entries() {
|
||||
let mut h = harness();
|
||||
open_combo(&mut h, "Based on output template");
|
||||
for item in ["bmp", "jpeg", "png", "targa", "tiff", "hdr", "exr", "webp"] {
|
||||
assert!(h.query_by_label(item).is_some(), "file type {item}");
|
||||
}
|
||||
assert!(h.query_by_label("tga").is_none());
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
|
||||
open_combo(&mut h, "Based on each Texture Set's size");
|
||||
for item in ["Maximum size for all Texture Sets", "128", "256", "8192"] {
|
||||
assert!(h.query_by_label(item).is_some(), "size {item}");
|
||||
}
|
||||
click(&mut h, "Maximum size for all Texture Sets");
|
||||
assert_eq!(h.state().ui.export.size, texturecraft_ui_egui::state::SIZE_OF_LARGEST_SET);
|
||||
|
||||
open_combo(&mut h, "Document channels + Normal + AO (No Alpha)");
|
||||
for item in ["2D View", "Document channels + Normal + AO (With Alpha)", "Sketchfab", "glTF PBR Metal Roughness", "Unreal Engine (Packed)"] {
|
||||
assert!(h.query_by_label(item).is_some(), "template {item}");
|
||||
}
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(3);
|
||||
|
||||
open_combo(&mut h, "Dilation infinite");
|
||||
let order: Vec<String> = ["No padding (passthrough)", "Dilation infinite", "Dilation + transparent", "Dilation + default background color"]
|
||||
.iter()
|
||||
.map(|l| format!("{:.0}", h.get_all_by_label(l).last().unwrap().rect().top()))
|
||||
.collect();
|
||||
let mut sorted = order.clone();
|
||||
sorted.sort_by_key(|y| y.parse::<i32>().unwrap());
|
||||
assert_eq!(order, sorted, "paddings in the reference order");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_template_has_the_reference_name_and_old_settings_follow_it() {
|
||||
let mut h = harness();
|
||||
assert_eq!(h.state().ui.export.preset, "Document channels + Normal + AO (No Alpha)");
|
||||
h.state_mut().ui.export.preset = "Document channels + Normal + AO".into();
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().ui.export.preset, "Document channels + Normal + AO (No Alpha)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_set_list_menu_checks_unchecks_and_inverts() {
|
||||
let mut h = harness();
|
||||
let sets = h.state().session.set_count();
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Uncheck all");
|
||||
assert_eq!(h.state().ui.export.skip.len(), sets);
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Invert all");
|
||||
assert!(h.state().ui.export.skip.is_empty());
|
||||
h.state_mut().ui.export.skip = vec![0];
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Check all");
|
||||
assert!(h.state().ui.export.skip.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_output_directory_resets_and_the_dilation_follows_the_padding() {
|
||||
let mut h = harness();
|
||||
let default = h.state().ui.export.dir.clone();
|
||||
h.state_mut().ui.export.dir = "/somewhere/else".into();
|
||||
h.run_steps(3);
|
||||
hover(&mut h, "R");
|
||||
assert!(h.query_by_label("Reset to default").is_some());
|
||||
click(&mut h, "R");
|
||||
assert_eq!(h.state().ui.export.dir, default);
|
||||
|
||||
hover(&mut h, "16");
|
||||
assert!(h.query_by_label("This padding mode does not use a dilation width").is_some());
|
||||
h.state_mut().ui.export.padding = "dilation".into();
|
||||
h.run_steps(3);
|
||||
hover(&mut h, "16");
|
||||
assert!(h.query_all_by_label("Dilation in pixels").next().is_some());
|
||||
click(&mut h, "16");
|
||||
assert!(h.query_by_label("Dilation (pixels)").is_some());
|
||||
|
||||
// A click on the slider sets the width and leaves the menu open
|
||||
h.get_by_role(egui::Role::Slider).click();
|
||||
h.run_steps(4);
|
||||
assert_ne!(h.state().ui.export.dilation, 16);
|
||||
assert!(h.query_by_label("Dilation (pixels)").is_some(), "the menu stays open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_actions_explain_what_they_change() {
|
||||
let mut h = harness();
|
||||
for (button, tip) in [
|
||||
("Include all", "Select every texture set, UV tile and output map"),
|
||||
("Reset all", "Restore the export defaults and select every texture"),
|
||||
("Cancel", "Restore the settings from when you opened this window"),
|
||||
("Save settings", "Keep these settings for the next export"),
|
||||
("Export", "Write the selected textures using the settings above"),
|
||||
] {
|
||||
hover(&mut h, button);
|
||||
assert!(h.query_by_label(tip).is_some(), "{button}: {tip}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_reset_puts_the_parameters_back() {
|
||||
let mut h = harness();
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.size = 4096;
|
||||
e.padding = "none".into();
|
||||
e.skip = vec![0];
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Restore the default export parameters");
|
||||
let e = &h.state().ui.export;
|
||||
assert_eq!((e.size, e.padding.as_str()), (0, "infinite"));
|
||||
assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page");
|
||||
}
|
||||
@@ -21,6 +21,11 @@ mod effect_decal;
|
||||
mod effect_rows;
|
||||
mod effect_sliders;
|
||||
mod empty_start;
|
||||
mod export_file_types;
|
||||
mod export_map_overrides;
|
||||
mod export_overrides;
|
||||
mod export_progress;
|
||||
mod export_settings;
|
||||
mod export_template_guards;
|
||||
mod file_dialogs;
|
||||
mod fill_channel_image;
|
||||
@@ -46,6 +51,7 @@ mod named_layouts;
|
||||
mod nav_buttons;
|
||||
mod new_project_baked_maps;
|
||||
mod new_project_window;
|
||||
mod output_templates;
|
||||
mod path_in_view;
|
||||
mod path_list;
|
||||
mod pen_pressure;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/// A user template library folder removed with its owner
|
||||
pub(super) struct TemplateLibrary(pub(super) std::path::PathBuf);
|
||||
|
||||
impl TemplateLibrary {
|
||||
pub(super) fn new(test: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!("texturecraft-output-templates-{test}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TemplateLibrary {
|
||||
fn drop(&mut self) {
|
||||
std::fs::remove_dir_all(&self.0).ok();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Export textures › OUTPUT TEMPLATES (texturecraft #674): the reference's layout, names and the
|
||||
//! preset list's right-click menu and F2.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::{NodeT as _, Queryable as _};
|
||||
use serde_json::json;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::{MapExport, SetExport};
|
||||
|
||||
#[path = "output_template/template_library.rs"]
|
||||
mod template_library;
|
||||
|
||||
use template_library::TemplateLibrary;
|
||||
|
||||
/// OUTPUT TEMPLATES with the user template "Mine" selected
|
||||
fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> {
|
||||
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);
|
||||
h.state_mut().session.load_export_presets(library.0.clone());
|
||||
let base = texturecraft_engine::formats::builtin_preset("Unreal Engine (Packed)").unwrap();
|
||||
let mine = texturecraft_engine::formats::ExportPreset { name: "Mine".into(), ..base };
|
||||
h.state_mut().run("export.preset.save", json!({ "preset": mine })).unwrap();
|
||||
let ui = &mut h.state_mut().ui;
|
||||
ui.windows.export = true;
|
||||
ui.export.tab = 1;
|
||||
ui.export.preset = "Mine".into();
|
||||
h.run_steps(4);
|
||||
h
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// Right-click the Presets list's `label` (listed before the selected one's name in the middle)
|
||||
fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
h.get_all_by_label(label).next().unwrap_or_else(|| panic!("no {label}")).click_secondary();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tab_shows_the_preset_tools_and_map_editor() {
|
||||
let library = TemplateLibrary::new("layout");
|
||||
let mut h = harness(&library);
|
||||
for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] {
|
||||
assert!(h.query_by_label(text).is_some(), "{text}");
|
||||
}
|
||||
assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR")));
|
||||
let maps = h.state().session.export_preset("Mine").unwrap().maps.len();
|
||||
let ts = h.state().session.ts();
|
||||
let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap();
|
||||
let exported = plan.as_array().unwrap().len();
|
||||
assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some());
|
||||
for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] {
|
||||
assert!(h.query_by_label(create).is_some(), "{create}");
|
||||
}
|
||||
click(&mut h, "R+G+B+A");
|
||||
assert_eq!(h.state().session.export_preset("Mine").unwrap().maps.len(), maps + 1, "Create adds an output map");
|
||||
|
||||
let info = h.get_by_label(egui_phosphor::regular::INFO).rect().center();
|
||||
h.hover_at(info);
|
||||
h.run_steps(30);
|
||||
assert!(h.query_by_label("Choose how the input maps are named in this editor.").is_some());
|
||||
assert!(h.query_by_label("The active texture set’s shader can affect the available map names.").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_presets_list_holds_the_sorted_templates_without_the_first_group() {
|
||||
let library = TemplateLibrary::new("list");
|
||||
let h = harness(&library);
|
||||
assert!(h.query_by_label("glTF PBR Metal Roughness").is_none());
|
||||
assert!(h.query_by_label("Document channels + Normal + AO (No Alpha)").is_none());
|
||||
let names = ["Blender (Principled BSDF)", "Mine", "Unreal Engine (Packed)"];
|
||||
let tops: Vec<f32> = names.iter().map(|n| h.get_all_by_label(n).next().unwrap().rect().top()).collect();
|
||||
assert!(tops.windows(2).all(|w| w[0] < w[1]), "sorted by name: {tops:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_and_duplicate_use_the_reference_names() {
|
||||
let library = TemplateLibrary::new("names");
|
||||
let mut h = harness(&library);
|
||||
click(&mut h, "New template");
|
||||
assert_eq!(h.state().ui.export.preset, "new_export_preset");
|
||||
right_click(&mut h, "Mine");
|
||||
click(&mut h, "Duplicate");
|
||||
assert_eq!(h.state().ui.export.preset, "Mine_copy");
|
||||
assert!(h.state().session.export_preset("Mine_copy").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_right_click_menu_renames_and_removes_user_templates_only() {
|
||||
let library = TemplateLibrary::new("menu");
|
||||
let mut h = harness(&library);
|
||||
right_click(&mut h, "Mine");
|
||||
for item in ["Rename", "Duplicate", "Remove"] {
|
||||
assert!(!h.get_by_label(item).accesskit_node().is_disabled(), "{item}");
|
||||
}
|
||||
click(&mut h, "Rename");
|
||||
assert_eq!(h.state().ui.export.renaming.as_deref(), Some("Mine"));
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
right_click(&mut h, "Mine");
|
||||
click(&mut h, "Remove");
|
||||
assert!(matches!(&h.state().ui.export.ask, Some(texturecraft_ui_egui::export_templates::Ask::Delete(n)) if n == "Mine"));
|
||||
h.state_mut().ui.export.ask = None;
|
||||
h.run_steps(2);
|
||||
|
||||
right_click(&mut h, "Unreal Engine (Packed)");
|
||||
assert!(h.get_by_label("Rename").accesskit_node().is_disabled(), "built-in templates are read-only");
|
||||
assert!(h.get_by_label("Remove").accesskit_node().is_disabled());
|
||||
assert!(!h.get_by_label("Duplicate").accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn f2_renames_the_selected_template_and_leaves_the_views_alone() {
|
||||
let library = TemplateLibrary::new("f2");
|
||||
let mut h = harness(&library);
|
||||
let layout = h.state().ui.layout;
|
||||
h.key_press(egui::Key::F2);
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.export.renaming.as_deref(), Some("Mine"));
|
||||
assert_eq!(h.state().ui.layout, layout, "F2 does not switch to the 3D view here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_preview_ignores_a_texture_sets_output_map_settings() {
|
||||
let library = TemplateLibrary::new("preview");
|
||||
let mut h = harness(&library);
|
||||
|
||||
// A two-map template on show, while the current texture set unticks map 2 of its own three-map template
|
||||
let mut two = h.state().session.export_preset("Mine").unwrap();
|
||||
two.name = "Two".into();
|
||||
two.maps.truncate(2);
|
||||
h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap();
|
||||
let own = "Unreal Engine (Packed)".to_string();
|
||||
let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() };
|
||||
o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None });
|
||||
let ts = h.state().session.ts();
|
||||
h.state_mut().ui.export.sets.insert(ts, o);
|
||||
h.state_mut().ui.export.preset = "Two".into();
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show");
|
||||
assert!(h.query_all_by_label_contains(egui_phosphor::regular::ARROW_RIGHT).count() >= 2, "both maps show their files");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() {
|
||||
let library = TemplateLibrary::new("follow");
|
||||
let mut h = harness(&library);
|
||||
let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() };
|
||||
o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None });
|
||||
|
||||
// The override is there when the window opens
|
||||
h.state_mut().ui.windows.export = false;
|
||||
h.run_steps(2);
|
||||
h.state_mut().ui.export.sets.insert(0, o);
|
||||
let ui = &mut h.state_mut().ui;
|
||||
ui.windows.export = true;
|
||||
ui.export.tab = 1;
|
||||
ui.export.preset = "Mine".into();
|
||||
h.run_steps(4);
|
||||
|
||||
// F2, a new name, Enter
|
||||
h.key_press(egui::Key::F2);
|
||||
h.run_steps(3);
|
||||
h.state_mut().ui.export.renaming = Some("Yours".into());
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().ui.export.preset, "Yours");
|
||||
let o = h.state().ui.export.sets[&0].clone();
|
||||
assert_eq!((o.preset.as_deref(), o.maps_template.as_str()), (Some("Yours"), "Yours"), "the set keeps its template and map ticks");
|
||||
assert_eq!(o.maps.len(), 1);
|
||||
|
||||
right_click(&mut h, "Yours");
|
||||
click(&mut h, "Remove");
|
||||
click(&mut h, "Delete");
|
||||
assert!(h.state().session.export_preset("Yours").is_none());
|
||||
assert!(!h.state().ui.export.sets.contains_key(&0), "the set exports with the global settings again");
|
||||
|
||||
// Cancel goes back to the settings the window opened with, minus the removed template
|
||||
click(&mut h, "Cancel");
|
||||
assert!(h.state().ui.export.sets.values().all(|o| o.preset.as_deref() != Some("Yours") && o.preset.as_deref() != Some("Mine")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_footer_counts_only_the_maps_the_texture_set_exports() {
|
||||
let library = TemplateLibrary::new("count");
|
||||
let mut h = harness(&library);
|
||||
|
||||
// Two maps; the texture set has no sheen, so only roughness is written
|
||||
let channel = |c: &str| json!([["L", {"Channel": {"channel": c}}]]);
|
||||
let maps = json!([
|
||||
{"file": "$textureSet_rough", "format": "Png", "bit_depth": 8, "channels": channel("Roughness")},
|
||||
{"file": "$textureSet_sheen", "format": "Png", "bit_depth": 8, "channels": channel("SheenWeight")},
|
||||
]);
|
||||
h.state_mut().run("export.preset.save", json!({"preset": {"name": "Mine", "maps": maps}})).unwrap();
|
||||
h.run_steps(4);
|
||||
let ts = h.state().session.ts();
|
||||
let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap();
|
||||
assert_eq!(plan.as_array().unwrap().len(), 1, "the sample set has no sheen: {plan}");
|
||||
assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen card says so");
|
||||
assert!(h.query_by_label("1 output maps will be exported.").is_some());
|
||||
assert!(h.query_by_label("2 output maps will be exported.").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_map_settings_follow_their_map_when_the_template_reorders_it() {
|
||||
let library = TemplateLibrary::new("reorder");
|
||||
let mut h = harness(&library);
|
||||
|
||||
// The first texture set leaves out the template's first map
|
||||
let off = MapExport { enabled: false, file_type: None };
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() });
|
||||
h.run_steps(2);
|
||||
let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone();
|
||||
h.get_all_by_label("Move down").next().unwrap().click();
|
||||
h.run_steps(4);
|
||||
assert_eq!(h.state().session.export_preset("Mine").unwrap().maps[1].file, first, "the map moved down");
|
||||
let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default();
|
||||
assert_eq!(maps, [(1, off)].into(), "the setting moved with its map");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() {
|
||||
let library = TemplateLibrary::new("stale");
|
||||
let mut h = harness(&library);
|
||||
let off = MapExport { enabled: false, file_type: None };
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() });
|
||||
h.run_steps(2);
|
||||
let saved = h.state().session.export_preset("Mine").unwrap();
|
||||
let last = saved.maps.len() - 1;
|
||||
|
||||
// An unfinished edit (an empty file name is not saved) moves the first map down
|
||||
h.state_mut().ui.export.draft.as_mut().unwrap().maps[last].file.clear();
|
||||
h.run_steps(2);
|
||||
h.get_all_by_label("Move down").next().unwrap().click();
|
||||
h.run_steps(4);
|
||||
|
||||
// An agent saves the template in that order meanwhile: overrides now count from it
|
||||
let mut agent = saved.clone();
|
||||
agent.maps.swap(0, 1);
|
||||
h.state_mut().run("export.preset.save", json!({ "preset": agent })).unwrap();
|
||||
h.run_steps(2);
|
||||
|
||||
// Stabilize the layout after fixing the draft so the next click hits the move button
|
||||
h.state_mut().ui.export.draft.as_mut().unwrap().maps[last].file = saved.maps[last].file.clone();
|
||||
h.run_steps(2);
|
||||
h.get_all_by_label("Move down").next().unwrap().click();
|
||||
h.run_steps(4);
|
||||
let now = h.state().session.export_preset("Mine").unwrap();
|
||||
assert_eq!(now.maps[1].file, saved.maps[1].file, "{:?}", now.maps.iter().map(|m| &m.file).collect::<Vec<_>>());
|
||||
let maps = h.state().ui.export.sets.get(&0).map(|o| o.maps.clone()).unwrap_or_default();
|
||||
assert_eq!(maps, [(1, off)].into(), "counted from the agent's order, not the edit's old base");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() {
|
||||
let library = TemplateLibrary::new("different-external-order");
|
||||
let mut harness = harness(&library);
|
||||
let saved = harness.state().session.export_preset("Mine").unwrap();
|
||||
harness.state_mut().ui.export.draft.as_mut().unwrap().maps[0].file.clear();
|
||||
|
||||
let mut external = saved.clone();
|
||||
external.maps.swap(0, 1);
|
||||
harness.state_mut().run("export.preset.save", json!({"preset": external})).unwrap();
|
||||
let disabled = MapExport { enabled: false, file_type: None };
|
||||
harness.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, disabled.clone())].into(), ..SetExport::default() });
|
||||
harness.run_steps(3);
|
||||
|
||||
// Repair the invalid first filename through the editor so the draft commits on that frame
|
||||
let first_row = harness.get_all_by_label("Move down").next().unwrap().rect().center().y;
|
||||
harness
|
||||
.get_all_by_role(egui::Role::TextInput)
|
||||
.find(|field| (field.rect().center().y - first_row).abs() < 4.0)
|
||||
.unwrap()
|
||||
.set_text_value_accesskit(&saved.maps[0].file);
|
||||
harness.run_steps(4);
|
||||
|
||||
let current = harness.state().session.export_preset("Mine").unwrap();
|
||||
assert_eq!(current, saved, "the corrected draft was saved in its own order");
|
||||
assert_eq!(harness.state().ui.export.sets[&0].maps, [(1, disabled)].into());
|
||||
}
|
||||
@@ -40,6 +40,19 @@ result is `{files}`. A layer without an enabled mask is an error. The layer menu
|
||||
file runs it; Copy mask to clipboard puts the same mask on the system clipboard as an 8-bit
|
||||
grayscale image (the whole tile atlas for a UV-tiled set).
|
||||
|
||||
`file.exportTextures`, `export.plan`, the automation `textures.export` method and the MCP
|
||||
`textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?}]`.
|
||||
Each entry overrides that map's export settings. The `map` field is its index in the selected
|
||||
template. `enabled: false` suppresses that file while reserving its name. When several texture
|
||||
sets produce the same name (ignoring case), programmatic and browser exports keep the first file
|
||||
and warn about later duplicates. The desktop export window reports the collision before writing.
|
||||
|
||||
`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
|
||||
TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and
|
||||
`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by
|
||||
`dilation` texels and fills the remaining space with a smooth blend of the island colours.
|
||||
|
||||
`effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its
|
||||
stack position, blend, opacity and visibility. Replacement filters start from defaults plus
|
||||
the supplied parameters; naming the current filter instead edits it without resetting omitted
|
||||
@@ -373,7 +386,7 @@ File access follows `--read-root` / `--write-root` as for MCP.
|
||||
| `resource.import` | `{path}` |
|
||||
| `material.save` | `{path, layer?, name?}` |
|
||||
| `material.load` | `{path}` |
|
||||
| `textures.export` | `{dir, preset?, ts?, format?, padding?, size?, bitDepth?, dilation?, normalFormat?}` |
|
||||
| `textures.export` | `{dir, preset?, ts?, format?, padding?, size?, bitDepth?, dithering?, dilation?, normalFormat?, maps?}` |
|
||||
| `render` | `{view?, width?, height?, yaw?, pitch?}` → `{width, height, png}` |
|
||||
|
||||
Brush preset operations are engine commands. Send each through `command.run` with the shown
|
||||
|
||||
+10
-4
@@ -164,13 +164,19 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
- **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map),
|
||||
Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz,
|
||||
anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in
|
||||
PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with UV padding, size
|
||||
override and OpenGL or DirectX normals.
|
||||
PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16
|
||||
bits or 32-bit float (TIFF, EXR, HDR; 16-bit half float for EXR), with UV padding (dilation,
|
||||
infinite, or dilation + diffusion), size override and OpenGL or DirectX normals.
|
||||
- **Output template editor:** build your own presets with per-channel packing, converted maps and per-channel inversion,
|
||||
and share them as JSON.
|
||||
and share them as JSON. Right-click a preset to rename, duplicate or remove it; F2 renames.
|
||||
- **Export panel** on the right bar: *Export Mesh...* asks for the mesh export options, then for
|
||||
the file; *Export Textures...* opens the Export textures window (Settings, Output templates and
|
||||
List of exports, *Include all*, *Save settings* and the number of textures the export writes).
|
||||
List of exports, *Include all*, *Save settings* and the number of textures the export writes;
|
||||
*Cancel* goes back to the settings the window opened with, *Maximum size for all Texture Sets*
|
||||
exports every set at the largest set's size; a click on a texture set overrides its template,
|
||||
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 and the written files, and can be canceled
|
||||
between texture sets).
|
||||
- **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).
|
||||
|
||||
@@ -271,3 +271,74 @@ edges in the 3D view and the UV edges, now in red, in the 2D view, and replaces
|
||||
The tile info button's icon is a grid of nine dots (the reference's has a small "i"). Not measured in the reference, so chosen here: the number box's look (a dark translucent box), the grid line strength,
|
||||
the tile shown in the hover label (only a tile the set paints; elsewhere the set name alone), the 3D wireframe's color, and
|
||||
that numbers hide once a tile is under 40 points on screen.
|
||||
|
||||
## Export textures window (batch 3, 2026-11-19)
|
||||
|
||||
**UI + tests** (`crates/ui-egui/tests/it/export_settings.rs`, `export_overrides.rs`, `export_map_overrides.rs`, `export_file_types.rs`, `export_progress.rs`, `output_templates.rs`; code in
|
||||
[`export_window.rs`](../crates/ui-egui/src/export_window.rs)).
|
||||
|
||||
- **SETTINGS** ([#671](https://github.com/storytold/texturecraft/issues/671)): the texture set
|
||||
list has the reference's menu (*Check all*, *Uncheck all*, *Invert all*); *General Export
|
||||
Parameters* has its reset button ("Restore the default export parameters"). *Output directory*
|
||||
is a button showing the path (it opens the folder picker) with an *R* button ("Reset to
|
||||
default"). The template list starts with the reference's first group (TextureCraft has
|
||||
"Document channels + Normal + AO (No Alpha)", the new name of its default template, and "glTF
|
||||
PBR Metal Roughness"; the others are greyed with "Not available yet"; one entry names another
|
||||
vendor's product and is left out), then a separator ("Some templates in this list are unavailable") and every other template sorted by name. File type lists "Based on output
|
||||
template", then the types in the reference order and names ("targa", "jpeg", "tiff"). Size
|
||||
adds "Maximum size for all Texture Sets" and 128. Padding uses the reference order; the
|
||||
dilation width is a button with a "Dilation (pixels)" slider, greyed for paddings without a
|
||||
width. Include all, Reset all, Cancel, Save settings, Export and the two greyed checkboxes carry
|
||||
tooltips explaining which settings are applied, kept or restored.
|
||||
Cancel, and closing the window, go back to the settings the window opened with; the window
|
||||
always opens on SETTINGS.
|
||||
- **Texture set pages** ([#669](https://github.com/storytold/texturecraft/issues/669)): a click
|
||||
on a texture set row shows its *General Export Parameters*: Output template, File type, Size and
|
||||
Padding with the inherited value as text (for example "1024x1024 (Texture Set size)"). The
|
||||
pencil button ("Enable override") turns a row into its list; a set with an override gets "*"
|
||||
("Override(s) active"). The header menu has *Override every item* and *Disable
|
||||
override for all items*. The template list leaves out the entries the reference leaves out
|
||||
there; sizes read "128x128" ... "8192x8192". Export, the footer count and LIST OF EXPORTS use
|
||||
each set's own settings. Ticks and overrides belong to the project and follow each texture set
|
||||
by name (another project starts without them); renaming a template on OUTPUT TEMPLATES takes
|
||||
the overrides that use it along, removing it drops them.
|
||||
- **Output maps** ([#670](https://github.com/storytold/texturecraft/issues/670)): below the
|
||||
parameters, one row per map the set exports: a tick, the file name pattern (cut at the front
|
||||
with "…" when long, the whole pattern as tooltip), its own *Enable override* and the inherited
|
||||
"png 8 bits". An override gives the map its own file type and bit depth (`maps` of
|
||||
`file.exportTextures`). The header menu has *Check all*, *Uncheck all*, *Invert all*, *Override every item* and *Clear all overrides*; *Include all* ticks every map
|
||||
again. The patterns are cut after 26 characters (the reference cuts by pixel width).
|
||||
- **File types** ([#672](https://github.com/storytold/texturecraft/issues/672)): File type
|
||||
lists bmp, jpeg, jng, pgm, png, targa, tiff, hdr, exr, j2k, jp2, webp, psd and sbsar; j2k, jp2
|
||||
and sbsar are greyed with "Not available yet" (TextureCraft has no writer for them). The bit
|
||||
depth list follows the type: "8 bits" and "8 bits + dithering" for integer formats, "16 bits" for pgm,
|
||||
png, psd and tiff, "32f bits" for tiff and hdr (hdr only that, greyed), "16f bits" and "32f
|
||||
bits" for exr; empty and greyed for "Based on output template". Padding adds "Dilation +
|
||||
diffusion" with a dilation width. PGM writes colour maps as their luminance; PSD holds the
|
||||
merged image without layers, its alpha as an extra alpha channel (readers do not show it as
|
||||
transparency).
|
||||
- **Exporting** ([#673](https://github.com/storytold/texturecraft/issues/673)): Export switches
|
||||
to LIST OF EXPORTS and writes one texture set per frame; the bottom bar becomes a progress bar
|
||||
with the percent and *Cancel Export* (it stops before the next texture set). The CONSOLE pane
|
||||
can be hidden. It logs preparation, each texture set and its saved files, and completion.
|
||||
The window stays open. LIST OF EXPORTS is a
|
||||
tree per texture set (file, size such as "1024x1024 (Texture Set size)", file type, bit depth;
|
||||
the full path as tooltip) with *Open output directory* at the top right. The files are
|
||||
written when a texture set is done, so the console lists its saved files when the set finishes. Each set's settings and the output directory are taken when Export is
|
||||
clicked. The running file list and its folder button use those settings. If the project changes
|
||||
a pending set's planned filenames or dimensions during export, the run stops before writing that set. Export
|
||||
is greyed with no texture set ticked. On desktop, if two texture sets would
|
||||
write the same filename, the export stops before writing any files. The console and an error
|
||||
message identify the clash. Closing the export window or opening another project stops a
|
||||
running desktop export. In the browser, the first file for each name is kept, later duplicates
|
||||
are skipped with a warning in the log, and the remaining files are downloaded.
|
||||
- **OUTPUT TEMPLATES** ([#674](https://github.com/storytold/texturecraft/issues/674)): the left
|
||||
list is titled *Presets* and lists the templates sorted by name, without the template list's
|
||||
first group. A right click on a preset offers *Rename*, *Duplicate* and *Remove* (Rename and
|
||||
Remove are greyed for built-in templates, which are read-only); F2 renames the selected one.
|
||||
"+" creates "new_export_preset", Duplicate "<name>_copy". *Naming pattern* (*OpenPBR*; the
|
||||
reference's second pattern names another vendor's material and is left out) with its info
|
||||
tooltip sits above the input maps. The middle reads "Current preset: <name>", *Output maps*
|
||||
with *Create:* Gray, RGB, R+G+B, RGB+A, R+G+B+A, and a footer with drag-and-drop guidance and the number of output maps. TextureCraft keeps its
|
||||
own list tools (rename, import, export) and asks before deleting; R+G+B and R+G+B+A create the
|
||||
same maps as RGB and RGB+A (each channel takes its own source in either).
|
||||
|
||||
Reference in New Issue
Block a user