mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
Merge pull request #827 from Rebornim/feat/export-pass
Export pass: layered PSD, per-map size, shader settings, Esc, hover preview, look and spec-backed templates
This commit is contained in:
63 files changed
+5994
-1625
No files matched your search
Generated
+1
-1
@@ -5982,6 +5982,7 @@ dependencies = [
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"texturecraft-engine",
|
||||
"texturecraft-formats",
|
||||
"texturecraft-render",
|
||||
@@ -6086,7 +6087,6 @@ dependencies = [
|
||||
"half",
|
||||
"image",
|
||||
"png",
|
||||
"quick-xml 0.41.0",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -55,7 +55,6 @@ rfd = "0.17"
|
||||
zip = { version = "9", default-features = false, features = ["deflate"] }
|
||||
gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] }
|
||||
flate2 = "1"
|
||||
quick-xml = "0.41"
|
||||
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
|
||||
rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
|
||||
|
||||
@@ -28,4 +28,5 @@ getrandom = { workspace = true }
|
||||
rustix = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
rmcp = { workspace = true, features = ["client"] }
|
||||
@@ -289,25 +289,50 @@ impl Headless {
|
||||
}
|
||||
|
||||
/// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…).
|
||||
pub fn export(&mut self, p: &Value) -> Result<Value, AutomationError> {
|
||||
pub fn export(&mut self, params: &Value) -> Result<Value, AutomationError> {
|
||||
use texturecraft_engine::shader_parameters::{shader_parameters_param, shader_parameters_sidecar};
|
||||
|
||||
self.require_project()?;
|
||||
let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?;
|
||||
let opts = file_cmds::export_options(&self.session, p, "textures.export")?;
|
||||
let n = self.session.set_count();
|
||||
let sets: Vec<usize> = match p.get("ts") {
|
||||
None | Some(Value::Null) => (0..n).collect(),
|
||||
Some(Value::String(a)) if a == "all" => (0..n).collect(),
|
||||
Some(v) => vec![v.as_u64().and_then(|t| usize::try_from(t).ok()).filter(|t| *t < n).ok_or_else(|| bad(format!("invalid `ts` {v}")))?],
|
||||
let dir = params.get("dir").and_then(Value::as_str).filter(|dir| !dir.is_empty()).ok_or_else(|| bad("`dir` is required"))?;
|
||||
let options = file_cmds::export_options(&self.session, params, "textures.export")?;
|
||||
let set_count = self.session.set_count();
|
||||
let sets: Vec<usize> = match params.get("ts") {
|
||||
None | Some(Value::Null) => (0..set_count).collect(),
|
||||
Some(Value::String(selection)) if selection == "all" => (0..set_count).collect(),
|
||||
Some(value) => vec![
|
||||
value
|
||||
.as_u64()
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < set_count)
|
||||
.ok_or_else(|| bad(format!("invalid `ts` {value}")))?,
|
||||
],
|
||||
};
|
||||
let files = self.session.export_files(&sets, &opts)?;
|
||||
let shader_sets = shader_parameters_param(&self.session.doc.project, params, &sets, "textures.export")?;
|
||||
|
||||
let files = self.session.export_files(&sets, &options)?;
|
||||
let sidecar = shader_sets.map(|sets| shader_parameters_sidecar(&self.session.doc.project, &sets, &files));
|
||||
self.create_dir_all(dir)?;
|
||||
let mut written = Vec::new();
|
||||
for f in &files {
|
||||
let path = join(dir, &f.name);
|
||||
self.write(&path, &f.bytes)?;
|
||||
let mut warnings = Vec::new();
|
||||
for file in files {
|
||||
let path = join(dir, &file.name);
|
||||
self.write(&path, &file.bytes)?;
|
||||
written.push(path);
|
||||
warnings.extend(file.warnings);
|
||||
}
|
||||
let warnings: Vec<&String> = files.iter().flat_map(|f| &f.warnings).collect();
|
||||
|
||||
if let Some(sidecar) = sidecar {
|
||||
let result = sidecar.and_then(|file| {
|
||||
let path = join(dir, &file.name);
|
||||
self.write(&path, &file.bytes).map_err(|error| error.to_string())?;
|
||||
Ok(path)
|
||||
});
|
||||
match result {
|
||||
Ok(path) => written.push(path),
|
||||
Err(error) => warnings.push(format!("The shader settings file was not written: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(json!({ "files": written, "warnings": warnings }))
|
||||
}
|
||||
|
||||
|
||||
@@ -177,6 +177,9 @@ pub struct ExportParams {
|
||||
/// Settings for individual maps in the selected template.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub maps: Option<Vec<ExportMapParams>>,
|
||||
/// Write shader settings for the exported sets (true) or the specified texture set indexes.
|
||||
#[serde(default, rename = "shaderParameters", skip_serializing_if = "Option::is_none")]
|
||||
pub shader_parameters: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
|
||||
|
||||
@@ -19,4 +19,7 @@ pub struct ExportMapParams {
|
||||
/// Override dithering for this map's 8-bit outputs.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub dithering: Option<bool>,
|
||||
/// Side length in pixels for this map, overriding the export size.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
@@ -88,14 +88,15 @@ async fn inspect(c: &Conn) -> Value {
|
||||
|
||||
#[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 temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
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": 0, "format": "pgm", "bitDepth": 16, "size": 256},
|
||||
{"map": 1, "enabled": false}
|
||||
]}),
|
||||
)
|
||||
@@ -104,9 +105,42 @@ async fn textures_export_accepts_per_map_settings() {
|
||||
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"));
|
||||
assert!(std::fs::read(dir.join(graymap)).unwrap().starts_with(b"P5\n256 256\n65535\n"));
|
||||
let inherited = files.iter().filter_map(Value::as_str).find(|path| path.ends_with(".png")).unwrap();
|
||||
assert_eq!(image::image_dimensions(dir.join(inherited)).unwrap(), (128, 128));
|
||||
|
||||
shutdown(client, server).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn textures_export_reports_the_shader_sidecar_and_write_failures() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let dir = temp.path();
|
||||
let (client, server) = connect(workspace(dir)).await;
|
||||
let params = json!({"dir": "textures", "shaderParameters": [0]});
|
||||
|
||||
let result = tool(&client, "textures_export", params.clone()).await;
|
||||
|
||||
let files = result["files"].as_array().unwrap();
|
||||
let sidecar = files.iter().filter_map(Value::as_str).find(|name| name.ends_with("_shaders.json")).expect("shader settings file");
|
||||
let path = dir.join(sidecar);
|
||||
let settings: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!(settings["shaders"][0]["textureSets"].as_array().unwrap().len(), 1);
|
||||
assert!(settings["shaders"][0]["model"].is_string());
|
||||
|
||||
std::fs::remove_file(&path).unwrap();
|
||||
std::fs::create_dir(&path).unwrap();
|
||||
let result = tool(&client, "textures_export", params).await;
|
||||
|
||||
assert!(result["warnings"].as_array().unwrap().iter().any(|warning| warning.as_str().is_some_and(|text| text.contains("shader settings file"))));
|
||||
assert!(result["files"].as_array().unwrap().iter().any(|file| file.as_str().is_some_and(|name| name.ends_with(".png"))));
|
||||
|
||||
let error = tool_err(&client, "textures_export", json!({"dir": "invalid", "shaderParameters": [99]})).await;
|
||||
|
||||
assert!(error.contains("shaderParameters"));
|
||||
assert!(!dir.join("invalid").exists());
|
||||
|
||||
shutdown(client, server).await;
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
fn top(s: &Value) -> &Value {
|
||||
|
||||
+183
-46
@@ -13,14 +13,17 @@ use texturecraft_core::{NormalFormat, PROJECT_EXT};
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_formats::PlannedFile;
|
||||
use texturecraft_formats::mesh_import::{MeshUvSource, import_mesh_geometry};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, Padding, ProjectFile};
|
||||
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, MapOverride, MapPreview, Padding, ProjectFile};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, primitives};
|
||||
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, normal_format_param, strp, u64p};
|
||||
use crate::session::{Document, Session};
|
||||
use crate::{EngineError, Result, cmd};
|
||||
|
||||
/// export.preview's picture width when the params name none
|
||||
const DEFAULT_PREVIEW_SIDE_PIXELS: u32 = 128;
|
||||
|
||||
type BakePaintMaps = BTreeMap<(usize, texturecraft_core::BakePaintTarget), Arc<texturecraft_bake::BakePaintMap>>;
|
||||
|
||||
fn prepare_archive<Bytes>(archive: &mut ProjectFile<Bytes, Bytes>, uv_source: Option<&Mesh>, bake_paint: &BakePaintMaps) {
|
||||
@@ -82,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export textures",
|
||||
["File"],
|
||||
None,
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?}] (per map file type and bit depth), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write <mesh>.usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
|
||||
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: bmp|jpeg|jng|pgm|png|targa|tiff|hdr|exr|webp|psd (or the extension; the maps written as psd are the layers of one <mesh>_<texture set>.psd per texture set and UV tile, which the USD asset and MaterialX don't read), bitDepth?: 8|16|32 (32 is float for tiff, hdr and exr; 16 is half float for exr), dithering?: bool (8-bit files), padding?: none|dilation|dilationDefault|diffusion|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, maps?: [{map: index into the preset's maps, enabled?: bool (false leaves the map out), format?, bitDepth?, dithering?, size?: px (wins over `size`)}] (per map file type, bit depth and size), colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, JNG, PGM and PSD exports warn about missing metadata), reservedNames?: [file names or UDIM patterns] (from earlier commands of the same export, compared ignoring case), materialX?: bool (also write an OpenPBR .mtlx per texture set, reusing compatible OpenPBR maps and writing dedicated textures for the remaining inputs), usdAsset?: true|[export params, one object per texture set (not empty)] (also write <mesh>.usd, a binary USD file, next to the textures: the whole mesh, a UsdPreviewSurface material per texture set whose inputs read the files the export wrote with its output template (base color, roughness, metallic, normal, emissive, opacity, clear coat; packed maps read their own channels); a texture set outside the export has none; true takes this command's ts, options and reservedNames, a list gives each texture set's own `ts`, options and `reservedNames`, a file the texture export skipped is not read, the export window sends it with the last command; a failure is a warning), shaderParameters?: true|[texture set indexes] (also write <project>_shaders.json: the shader's model and settings and the texture sets using it; true lists this command's ts, the export window sends every set of the export with the last command; a failure is a warning)} → {files, warnings, materialUdimPatterns?}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -100,10 +103,19 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"List export outputs",
|
||||
[],
|
||||
None,
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, format, bitDepth, dithering, size, sourceSize, warnings}] (keeps the first file per case-insensitive name and warns about later duplicates)",
|
||||
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with <UDIM> or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)",
|
||||
always,
|
||||
plan
|
||||
),
|
||||
cmd!(
|
||||
"export.preview",
|
||||
"Preview an output map",
|
||||
[],
|
||||
None,
|
||||
"{map: index into the preset's maps, side?: px (default 128, at most 512), plus the params of export.plan (the first texture set `ts` names)} → {width, height, channels: [\"R\", ...], pixels: [8-bit values as an sRGB file stores them, channels interleaved, row by row]}, or null when the texture set writes no file for the map",
|
||||
always,
|
||||
preview
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -351,51 +363,119 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Render every export file for texture sets `sets` (in memory; works on the web). A file
|
||||
/// named like one an earlier set exports is left out, with a warning (see
|
||||
/// [`texturecraft_formats::skip_repeated_names`]).
|
||||
/// named like one an earlier set exports is left out, with a warning.
|
||||
pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result<Vec<ExportedFile>> {
|
||||
let mut files = self.render_export_files(sets, opts, |_, plans| plans)?;
|
||||
texturecraft_formats::skip_repeated_names(&mut files);
|
||||
Ok(files)
|
||||
self.export_file_jobs(sets.iter().map(|&set| (set, opts)))
|
||||
}
|
||||
|
||||
/// Render one in-memory batch, using each set's own export settings when supplied.
|
||||
pub fn export_file_jobs<'a>(&mut self, jobs: impl IntoIterator<Item = (usize, &'a ExportOptions)>) -> Result<Vec<ExportedFile>> {
|
||||
self.render_export_jobs(jobs, |_, plans| plans)
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn render_export_files(
|
||||
&mut self,
|
||||
sets: &[usize],
|
||||
options: &ExportOptions,
|
||||
select: impl FnMut(usize, Vec<PlannedFile>) -> Vec<PlannedFile>,
|
||||
) -> Result<Vec<ExportedFile>> {
|
||||
self.render_export_jobs(sets.iter().map(|&set| (set, options)), select)
|
||||
}
|
||||
|
||||
fn render_export_jobs<'a>(
|
||||
&mut self,
|
||||
jobs: impl IntoIterator<Item = (usize, &'a ExportOptions)>,
|
||||
mut select: impl FnMut(usize, Vec<PlannedFile>) -> Vec<PlannedFile>,
|
||||
) -> Result<Vec<ExportedFile>> {
|
||||
let project = &self.doc.project;
|
||||
let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:"));
|
||||
let mut pending = Vec::new();
|
||||
for (set_index, options) in jobs {
|
||||
let plans = texturecraft_formats::list_outputs(project, set_index, &mesh_name, options).map_err(fe)?;
|
||||
let plans = select(set_index, plans);
|
||||
if !plans.is_empty() {
|
||||
pending.push((set_index, options, plans));
|
||||
}
|
||||
}
|
||||
|
||||
// Keep each winning plan with the options of the job that produced it
|
||||
let plans = pending.iter_mut().enumerate().flat_map(|(job, (_, _, plans))| plans.drain(..).map(move |plan| (job, plan)));
|
||||
let plans = texturecraft_formats::export::keep_first_planned_names(plans);
|
||||
if pending.len() > 1 {
|
||||
texturecraft_formats::export::validate_export_paths(plans.iter().map(|(_, plan)| plan.name.as_str())).map_err(fe)?;
|
||||
}
|
||||
|
||||
for (job, plan) in plans {
|
||||
pending[job].2.push(plan);
|
||||
}
|
||||
pending.retain(|(_, _, plans)| !plans.is_empty());
|
||||
|
||||
let mut psd_bytes = 0;
|
||||
for (set_index, options, plans) in &pending {
|
||||
let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?;
|
||||
texturecraft_formats::export::check_psd_batch(set, options, plans, &mut psd_bytes).map_err(fe)?;
|
||||
}
|
||||
|
||||
if self.solo.is_none() {
|
||||
self.update();
|
||||
}
|
||||
|
||||
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
let mut out = Vec::new();
|
||||
let empty = Default::default();
|
||||
for &set_index in sets {
|
||||
let cache = self.caches.get(set_index).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?;
|
||||
let plans = texturecraft_formats::list_outputs(&self.doc.project, set_index, &mesh_name, options).map_err(fe)?;
|
||||
let plans = select(set_index, plans);
|
||||
if plans.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let composite =
|
||||
self.document_composite(set_index, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {set_index}")))?;
|
||||
let coverage = cache.gbuf.coverage_mask();
|
||||
let input = ExportInput {
|
||||
project: &self.doc.project,
|
||||
ts: set_index,
|
||||
composite: &composite,
|
||||
baked: self.doc.baked.get(&set_index).unwrap_or(&empty),
|
||||
coverage: &coverage,
|
||||
mesh_name: &mesh_name,
|
||||
};
|
||||
out.extend(texturecraft_formats::export::render_planned_maps(&input, options, plans).map_err(fe)?);
|
||||
for (set_index, options, plans) in pending {
|
||||
let files = self.with_export_input(
|
||||
set_index,
|
||||
&mesh_name,
|
||||
|grid| Cow::Owned(grid.coverage_mask()),
|
||||
|input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe),
|
||||
)?;
|
||||
out.extend(files);
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Run `with` on texture set `set_index`'s export input: its document composite, coverage and baked maps
|
||||
fn with_export_input<T, Coverage: Clone>(
|
||||
&self,
|
||||
set_index: usize,
|
||||
mesh_name: &str,
|
||||
coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>,
|
||||
with: impl FnOnce(&ExportInput<Coverage>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let missing = || EngineError::Other(format!("no texture set {set_index}"));
|
||||
let cache = self.caches.get(set_index).ok_or_else(missing)?;
|
||||
let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?;
|
||||
let coverage = coverage(&cache.gbuf);
|
||||
let empty = Default::default();
|
||||
let input = ExportInput {
|
||||
project: &self.doc.project,
|
||||
ts: set_index,
|
||||
composite: &composite,
|
||||
baked: self.doc.baked.get(&set_index).unwrap_or(&empty),
|
||||
coverage: &coverage,
|
||||
mesh_name,
|
||||
};
|
||||
with(&input)
|
||||
}
|
||||
|
||||
/// A picture of output map `map` for the first texture set named in `params`, with each side at most `side` pixels.
|
||||
/// Returns None when the map writes no file.
|
||||
pub fn export_preview(&mut self, params: &Value, map: usize, side: u32) -> Result<Option<MapPreview>> {
|
||||
let options = export_options(self, params, "export.preview")?;
|
||||
let Some(&set_index) = sets_param(self, params, "export.preview")?.first() else { return Ok(None) };
|
||||
|
||||
if self.solo.is_none() {
|
||||
self.update();
|
||||
}
|
||||
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
|
||||
self.with_export_input(
|
||||
set_index,
|
||||
&mesh_name,
|
||||
|grid| Cow::Borrowed(&grid.tri),
|
||||
|input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> {
|
||||
@@ -457,12 +537,12 @@ pub fn export_options(session: &Session, params: &Value, cmd: &str) -> Result<Ex
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
/// `maps`: per map `{map: index into the preset's maps, enabled?, format?, bitDepth?, dithering?}`.
|
||||
/// `maps`: per map `{map: index into the preset's maps, enabled?, format?, bitDepth?, dithering?, size?}`
|
||||
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?}"))?;
|
||||
let list = list.as_array().ok_or_else(|| bad(cmd, "`maps` must be a list of {map, enabled?, format?, bitDepth?, dithering?, size?}"))?;
|
||||
for settings in list {
|
||||
let index = u64p(settings, "map").and_then(|value| usize::try_from(value).ok()).filter(|index| *index < map_count);
|
||||
let index = index.ok_or_else(|| bad(cmd, format!("`maps`: `map` must be the index of one of the preset's {map_count} maps")))?;
|
||||
@@ -481,6 +561,10 @@ fn map_overrides(params: &Value, map_count: usize, cmd: &str) -> Result<std::col
|
||||
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"))?);
|
||||
}
|
||||
if let Some(size) = settings.get("size").filter(|value| !value.is_null()) {
|
||||
let size = size.as_u64().and_then(|size| u32::try_from(size).ok()).ok_or_else(|| bad(cmd, "`maps`: `size` must be a size in texels"))?;
|
||||
options.size = Some(crate::session::check_resolution(size)?);
|
||||
}
|
||||
|
||||
overrides.insert(index, options);
|
||||
}
|
||||
@@ -510,6 +594,22 @@ fn set_index(s: &Session, v: &Value, cmd: &str) -> Result<usize> {
|
||||
v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))
|
||||
}
|
||||
|
||||
fn preview(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let map = u64p(params, "map").and_then(|map| usize::try_from(map).ok());
|
||||
let map = map.ok_or_else(|| bad("export.preview", "`map` (an output map index) is required"))?;
|
||||
let side = u64p(params, "side").map_or(DEFAULT_PREVIEW_SIDE_PIXELS, |side| side.clamp(1, u64::from(texturecraft_formats::MAX_PREVIEW_SIDE)) as u32);
|
||||
|
||||
Ok(match session.export_preview(params, map, side)? {
|
||||
Some(preview) => json!({
|
||||
"width": preview.width,
|
||||
"height": preview.height,
|
||||
"channels": preview.channels.iter().map(|dest| format!("{dest:?}")).collect::<Vec<_>>(),
|
||||
"pixels": preview.pixels,
|
||||
}),
|
||||
None => Value::Null,
|
||||
})
|
||||
}
|
||||
|
||||
fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
use texturecraft_formats::export::{list_set_outputs, scale_export_side};
|
||||
|
||||
@@ -527,18 +627,23 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let block_size = set.block_resolution();
|
||||
for (_, output) in set_outputs {
|
||||
let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile));
|
||||
let size = scale_export_side(source_size, block_size, options.size);
|
||||
|
||||
// A map's own size wins over the export's; a PSD is the size of its largest layer
|
||||
let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size);
|
||||
|
||||
files.push(json!({
|
||||
"ts": set_index,
|
||||
"map": output.map,
|
||||
"file": output.name,
|
||||
"tile": output.tile,
|
||||
"udimPattern": output.udim_name,
|
||||
"format": output.format.extension(),
|
||||
"bitDepth": output.bit_depth,
|
||||
"dithering": output.dither,
|
||||
"size": size,
|
||||
"sourceSize": source_size,
|
||||
"warnings": output.warnings,
|
||||
"layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -771,6 +876,7 @@ fn export_textures(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let reserved_patterns: Vec<_> = taken_names.keys().filter(|name| name.contains("<udim>")).cloned().collect();
|
||||
let material = params.get("materialX").and_then(Value::as_bool).unwrap_or(false);
|
||||
let usd_asset = usd_asset_param(session, params, &options, &sets)?;
|
||||
let shader_sets = crate::shader_parameters::shader_parameters_param(&session.doc.project, params, &sets, "file.exportTextures")?;
|
||||
let mut warnings = Vec::new();
|
||||
let mut udim_patterns = Vec::new();
|
||||
|
||||
@@ -830,6 +936,22 @@ fn export_textures(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if let Some(exports) = &usd_asset {
|
||||
written.extend(write_usd_asset(session, dir, exports, &mut warnings));
|
||||
}
|
||||
if let Some(shader_sets) = shader_sets {
|
||||
let name = crate::shader_parameters::shader_parameters_file(&session.doc.project.name);
|
||||
let path = dir.join(&name);
|
||||
let parameters = crate::shader_parameters::shader_parameters(&session.doc.project, &shader_sets);
|
||||
|
||||
// Check the name against this command's files and the earlier commands' `reservedNames`, as the web download and headless export do
|
||||
let roots = written.iter().filter_map(|written| written.strip_prefix(dir).ok()?.components().next()?.as_os_str().to_str());
|
||||
let checked = crate::shader_parameters::check_shader_parameters_name(&name, roots.chain(taken_names.keys().map(String::as_str)));
|
||||
|
||||
// The textures are written by now: a shaders file that fails is a warning, as a failed USD asset is
|
||||
let text = checked.and_then(|()| serde_json::to_vec_pretty(¶meters).map_err(|error| error.to_string()));
|
||||
match text.and_then(|text| texturecraft_formats::write_atomic(&path, &text).map_err(|error| error.to_string())) {
|
||||
Ok(()) => written.push(path),
|
||||
Err(error) => warnings.push(format!("The shader settings file was not written: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
session.log.info("MapExporter", format!("Exported {} textures to {}", written.len(), dir.display()));
|
||||
let mut response = json!({ "files": written.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(), "warnings": warnings });
|
||||
@@ -871,7 +993,7 @@ fn usd_asset_param(session: &Session, params: &Value, options: &ExportOptions, s
|
||||
/// warning: the textures of the command are already written.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec<String>) -> Option<std::path::PathBuf> {
|
||||
match build_usd_asset(session, dir, exports) {
|
||||
match build_usd_asset(session, dir, exports, warnings) {
|
||||
Ok(path) => Some(path),
|
||||
Err(error) => {
|
||||
warnings.push(format!("{USD_ASSET_FAILED}: {error}"));
|
||||
@@ -881,7 +1003,7 @@ fn write_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport]) -> Result<std::path::PathBuf> {
|
||||
fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAssetExport], warnings: &mut Vec<String>) -> Result<std::path::PathBuf> {
|
||||
use texturecraft_formats::{list_outputs, usd_layer_with_textures, usd_texture_bindings};
|
||||
let project = &session.doc.project;
|
||||
let mesh_name = stem_of(project.mesh.trim_start_matches("builtin:"));
|
||||
@@ -902,6 +1024,15 @@ fn build_usd_asset(session: &Session, dir: &std::path::Path, exports: &[UsdAsset
|
||||
|
||||
// A map that lost any file (a tile of a UDIM map) is not bound: its `<UDIM>` name would read a file it does not own
|
||||
kept.retain(|file| !skipped_maps.contains(&file.map));
|
||||
let mut unsupported = HashSet::new();
|
||||
for file in kept.iter().filter(|file| !file.format.usable_by_usd_asset() && unsupported.insert(file.format)) {
|
||||
let format = file.format.extension().to_ascii_uppercase();
|
||||
let warning =
|
||||
format!("The USD asset doesn't read {format} files, so the material of texture set \"{}\" leaves out those maps", texture_set.name);
|
||||
if !warnings.contains(&warning) {
|
||||
warnings.push(warning);
|
||||
}
|
||||
}
|
||||
by_set.entry(set).or_insert_with(|| usd_texture_bindings(texture_set, options, project.normal_format, &kept));
|
||||
}
|
||||
}
|
||||
@@ -948,8 +1079,20 @@ fn reserve_export_names(
|
||||
let mut blocked_maps = HashSet::new();
|
||||
plans.retain(|plan| {
|
||||
let name = plan.name.to_ascii_lowercase();
|
||||
if reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name)) {
|
||||
blocked_maps.insert(plan.map);
|
||||
let reserved = reserved_patterns.iter().any(|pattern| udim_matches(pattern, &name));
|
||||
if !reserved && let Entry::Vacant(entry) = taken_names.entry(name) {
|
||||
entry.insert(Some(set_index));
|
||||
return true;
|
||||
}
|
||||
|
||||
// A set warning outlives the file that carried it
|
||||
for warning in plan.warnings.iter().filter(|warning| texturecraft_formats::export::is_set_warning(warning)) {
|
||||
if !warnings.contains(warning) {
|
||||
warnings.push(warning.clone());
|
||||
}
|
||||
}
|
||||
blocked_maps.extend(plan.maps());
|
||||
if reserved {
|
||||
warnings.push(format!(
|
||||
"\"{}\" was not written: an earlier MaterialX document uses that UDIM pattern. Rename a texture set or change the template file names",
|
||||
plan.name
|
||||
@@ -957,12 +1100,6 @@ fn reserve_export_names(
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Entry::Vacant(entry) = taken_names.entry(name) {
|
||||
entry.insert(Some(set_index));
|
||||
return true;
|
||||
}
|
||||
|
||||
blocked_maps.insert(plan.map);
|
||||
if fallback {
|
||||
warnings.push(format!(
|
||||
"MaterialX: \"{}\" was not written: a file of the chosen template or of an earlier command of this export has the name. Rename a texture set or change the template file names",
|
||||
@@ -1039,11 +1176,11 @@ fn material_map_options(options: &ExportOptions, project_normal: NormalFormat) -
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut overrides = MapOverride::default();
|
||||
let settings = replacement.and_then(|(index, _)| options.maps.get(&index));
|
||||
let mut overrides = MapOverride { size: settings.and_then(|settings| settings.size), ..MapOverride::default() };
|
||||
let requested_format = replacement.map(|(index, _)| selected_format(index)).or(options.format_override);
|
||||
if requested_format.is_none_or(material_format) {
|
||||
overrides.format = requested_format;
|
||||
let settings = replacement.and_then(|(index, _)| options.maps.get(&index));
|
||||
overrides.bit_depth =
|
||||
settings.and_then(|settings| settings.bit_depth).or(options.bit_depth_override).or_else(|| replacement.map(|(_, selected)| selected.bit_depth));
|
||||
overrides.dither = settings.and_then(|settings| settings.dither);
|
||||
|
||||
@@ -88,6 +88,7 @@ pub mod resource_update_cmds;
|
||||
pub mod session;
|
||||
mod session_log;
|
||||
pub mod set_cmds;
|
||||
pub mod shader_parameters;
|
||||
pub mod smart_masks;
|
||||
mod solo;
|
||||
mod stylized_lighting_params;
|
||||
|
||||
@@ -2,17 +2,19 @@
|
||||
//! dialog's Output templates tab list, read, save and remove. On the desktop the user presets
|
||||
//! are mirrored as `<name>.json` files in a library folder (see [`Session::load_export_presets`]).
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_formats::export::{MAX_PRESET_NAME, sanitize_file_stem};
|
||||
use texturecraft_formats::{ExportPreset, builtin_preset, builtin_presets, preset_from_json};
|
||||
use texturecraft_formats::{ExportPreset, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, preset_from_json};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, strp};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
/// Most user presets kept (and read from the library folder).
|
||||
const MAX_USER_PRESETS: usize = 512;
|
||||
const BUILTIN_PRESET_PREFIX: &str = "builtin:";
|
||||
|
||||
/// The user's export presets.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -51,6 +53,16 @@ fn same_name(a: &str, b: &str) -> bool {
|
||||
a.trim().eq_ignore_ascii_case(b.trim())
|
||||
}
|
||||
|
||||
/// A qualified selector names a built-in independently of a saved library entry.
|
||||
pub fn unqualified_preset_name(name: &str) -> &str {
|
||||
let mut name = name.trim();
|
||||
while name.get(..BUILTIN_PRESET_PREFIX.len()).is_some_and(|prefix| prefix.eq_ignore_ascii_case(BUILTIN_PRESET_PREFIX)) {
|
||||
name = &name[BUILTIN_PRESET_PREFIX.len()..];
|
||||
}
|
||||
|
||||
name
|
||||
}
|
||||
|
||||
/// Library file stem: two names with the same stem would share a file.
|
||||
fn file_key(name: &str) -> String {
|
||||
sanitize_file_stem(name.trim()).to_ascii_lowercase()
|
||||
@@ -63,8 +75,25 @@ impl UserPresets {
|
||||
|
||||
/// `name` belongs to a built-in or to a user preset other than `skip` (or shares its file).
|
||||
fn taken(&self, name: &str, skip: Option<usize>) -> bool {
|
||||
builtin_preset(name).is_some()
|
||||
|| self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name)))
|
||||
let keeps_name = skip.and_then(|index| self.list.get(index)).is_some_and(|preset| same_name(&preset.name, name));
|
||||
(!keeps_name && builtin_preset(unqualified_preset_name(name)).is_some()) || self.user_name_taken(name, skip)
|
||||
}
|
||||
|
||||
fn user_name_taken(&self, name: &str, skip: Option<usize>) -> bool {
|
||||
let key = file_key(name);
|
||||
self.list.iter().enumerate().any(|(i, preset)| Some(i) != skip && (same_name(&preset.name, name) || file_key(&preset.name) == key))
|
||||
}
|
||||
|
||||
/// Restore a saved preset under the name existing settings use.
|
||||
pub fn restore(&mut self, preset: ExportPreset) -> std::result::Result<(), String> {
|
||||
preset.validate().map_err(|error| error.to_string())?;
|
||||
let reserved = builtin_preset(&preset.name).is_some_and(|builtin| !NEW_BUILTIN_PRESET_NAMES.contains(&builtin.name.as_str()));
|
||||
if reserved || self.user_name_taken(&preset.name, None) || self.list.len() >= MAX_USER_PRESETS {
|
||||
return Err(format!("preset \"{}\" exists already or the library is full", preset.name));
|
||||
}
|
||||
|
||||
self.list.push(preset);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The first available name, adding a numbered suffix and shortening the base to fit.
|
||||
@@ -119,7 +148,21 @@ impl UserPresets {
|
||||
impl Session {
|
||||
/// A built-in or user export preset by name (case-insensitive).
|
||||
pub fn export_preset(&self, name: &str) -> Option<ExportPreset> {
|
||||
builtin_preset(name).or_else(|| self.export_presets.find(name).and_then(|i| self.export_presets.list.get(i).cloned()))
|
||||
self.export_presets.find(name).and_then(|index| self.export_presets.list.get(index).cloned()).or_else(|| builtin_preset(unqualified_preset_name(name)))
|
||||
}
|
||||
|
||||
pub fn has_user_export_preset(&self, name: &str) -> bool {
|
||||
self.export_presets.find(name).is_some()
|
||||
}
|
||||
|
||||
/// Use the familiar built-in name unless the user's library already owns that selector.
|
||||
pub fn builtin_export_preset_id<'a>(&self, name: &'a str) -> Cow<'a, str> {
|
||||
let mut id = Cow::Borrowed(name);
|
||||
while self.has_user_export_preset(&id) {
|
||||
id = Cow::Owned(format!("{BUILTIN_PRESET_PREFIX}{id}"));
|
||||
}
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Use `dir` as the user preset library: read its `*.json` presets (replacing the list) and
|
||||
@@ -133,10 +176,8 @@ impl Session {
|
||||
files.sort();
|
||||
let mut lib = UserPresets { list: Vec::new(), dir: Some(dir) };
|
||||
for path in files.into_iter().take(MAX_USER_PRESETS) {
|
||||
match texturecraft_formats::load_preset(&path).map_err(|e| e.to_string()) {
|
||||
Ok(p) if lib.taken(&p.name, None) => warnings.push(format!("{}: preset \"{}\" exists already", path.display(), p.name)),
|
||||
Ok(p) => lib.list.push(p),
|
||||
Err(e) => warnings.push(format!("{}: {e}", path.display())),
|
||||
if let Err(error) = texturecraft_formats::load_preset(&path).map_err(|error| error.to_string()).and_then(|preset| lib.restore(preset)) {
|
||||
warnings.push(format!("{}: {error}", path.display()));
|
||||
}
|
||||
}
|
||||
self.export_presets = lib;
|
||||
@@ -144,10 +185,12 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let entry = |p: &ExportPreset, builtin: bool| json!({"name": p.name, "maps": p.maps.len(), "builtin": builtin});
|
||||
let builtins = builtin_presets();
|
||||
Ok(json!(builtins.iter().map(|p| entry(p, true)).chain(s.export_presets.list.iter().map(|p| entry(p, false))).collect::<Vec<_>>()))
|
||||
fn list(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
let entry = |name: &str, maps: usize, builtin: bool| json!({"name": name, "maps": maps, "builtin": builtin});
|
||||
let builtins = builtin_preset_catalog().iter().map(|preset| entry(&session.builtin_export_preset_id(&preset.name), preset.maps.len(), true));
|
||||
let custom = session.export_presets.list.iter().map(|preset| entry(&preset.name, preset.maps.len(), false));
|
||||
|
||||
Ok(json!(builtins.chain(custom).collect::<Vec<_>>()))
|
||||
}
|
||||
|
||||
fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
|
||||
@@ -216,11 +259,16 @@ fn save(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "export.preset.remove";
|
||||
let name = name_param(p, CMD)?;
|
||||
if builtin_preset(name).is_some() {
|
||||
return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be removed")));
|
||||
}
|
||||
let i = s.export_presets.find(name).ok_or_else(|| bad(CMD, format!("no user export preset `{name}`")))?;
|
||||
let removed = s.export_presets.list.remove(i);
|
||||
let Some(index) = s.export_presets.find(name) else {
|
||||
let message = if builtin_preset(unqualified_preset_name(name)).is_some() {
|
||||
format!("\"{name}\" is a built-in preset and can't be removed")
|
||||
} else {
|
||||
format!("no user export preset `{name}`")
|
||||
};
|
||||
return Err(bad(CMD, message));
|
||||
};
|
||||
|
||||
let removed = s.export_presets.list.remove(index);
|
||||
s.export_presets.delete(&removed.name);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
@@ -409,6 +457,36 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn feedback_existing_preset_keeps_its_name_and_export_maps() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = "Roblox SurfaceAppearance (separate maps)";
|
||||
let custom = preset(name);
|
||||
std::fs::write(dir.path().join(format!("{}.json", sanitize_file_stem(name))), custom.to_string()).unwrap();
|
||||
let mut s = session();
|
||||
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4);
|
||||
|
||||
let warnings = s.load_export_presets(dir.path().to_path_buf());
|
||||
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom);
|
||||
let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap();
|
||||
assert_eq!(plan.as_array().unwrap().len(), 1);
|
||||
assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png"));
|
||||
|
||||
let listed = run(&mut s, "export.presets", json!({})).unwrap();
|
||||
let names = listed.as_array().unwrap();
|
||||
assert!(names.iter().any(|entry| entry["name"] == name && entry["builtin"] == false));
|
||||
let builtin = format!("builtin:{name}");
|
||||
assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true));
|
||||
let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap();
|
||||
assert!(builtin_plan.as_array().unwrap().len() > 1);
|
||||
run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap();
|
||||
run(&mut s, "export.preset.remove", json!({"name": name})).unwrap();
|
||||
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_library_folder_mirrors_saves_renames_and_removals() {
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Export shader parameters: the project's shader, its settings and the texture sets using it, as JSON
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::Project;
|
||||
use texturecraft_formats::ExportedFile;
|
||||
|
||||
use crate::Result;
|
||||
use crate::commands::bad;
|
||||
|
||||
/// The project's one shader, its parameters and the names of `sets` (they all use it)
|
||||
pub fn shader_parameters(project: &Project, sets: &[usize]) -> Value {
|
||||
let display = &project.display;
|
||||
let model = if display.spec_gloss { "specularGlossiness" } else { "metallicRoughness" };
|
||||
let names: Vec<&str> = sets.iter().filter_map(|ts| project.texture_sets.get(*ts)).map(|set| set.name.as_str()).collect();
|
||||
|
||||
json!({
|
||||
"shaders": [{
|
||||
"model": model,
|
||||
"parameters": {
|
||||
"aoIntensity": display.ao_intensity,
|
||||
"ior": display.ior,
|
||||
"scatterColor": display.scatter_color,
|
||||
"scatterRadius": display.scatter_radius,
|
||||
"displacement": display.displacement,
|
||||
"parallax": display.parallax,
|
||||
},
|
||||
"textureSets": names,
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON file's name for project `name`
|
||||
pub fn shader_parameters_file(name: &str) -> String {
|
||||
format!("{}_shaders.json", texturecraft_formats::export::sanitize_file_stem(name))
|
||||
}
|
||||
|
||||
/// Refuse the file name `name` when one of the export's texture paths (`/`-separated, relative to the export folder) is that file or lies in a folder of that name, ignoring case
|
||||
pub fn check_shader_parameters_name<'a>(name: &str, texture_paths: impl IntoIterator<Item = &'a str>) -> std::result::Result<(), String> {
|
||||
if texture_paths.into_iter().any(|path| path.split('/').next().is_some_and(|root| root.eq_ignore_ascii_case(name))) {
|
||||
return Err(format!("\"{name}\" is already used by a texture file or folder"));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Build the download or headless sidecar after checking its name against every texture path.
|
||||
pub fn shader_parameters_sidecar(project: &Project, sets: &[usize], textures: &[ExportedFile]) -> std::result::Result<ExportedFile, String> {
|
||||
let name = shader_parameters_file(&project.name);
|
||||
check_shader_parameters_name(&name, textures.iter().map(|texture| texture.name.as_str()))?;
|
||||
|
||||
let bytes = serde_json::to_vec_pretty(&shader_parameters(project, sets)).map_err(|error| error.to_string())?;
|
||||
Ok(ExportedFile { name, bytes, width: 0, height: 0, warnings: Vec::new() })
|
||||
}
|
||||
|
||||
/// The texture sets `shaderParameters` asks to list: `true` takes the command's own `sets`, a list gives them all; None when it asks for no file
|
||||
pub fn shader_parameters_param(project: &Project, params: &Value, sets: &[usize], cmd: &str) -> Result<Option<Vec<usize>>> {
|
||||
match params.get("shaderParameters") {
|
||||
None | Some(Value::Null | Value::Bool(false)) => Ok(None),
|
||||
Some(Value::Bool(true)) => Ok(Some(sets.to_vec())),
|
||||
Some(Value::Array(indexes)) => indexes
|
||||
.iter()
|
||||
.map(|index| {
|
||||
index
|
||||
.as_u64()
|
||||
.and_then(|index| usize::try_from(index).ok())
|
||||
.filter(|index| *index < project.texture_sets.len())
|
||||
.ok_or_else(|| bad(cmd, "`shaderParameters` lists texture set indexes"))
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(Some),
|
||||
Some(_) => Err(bad(cmd, "`shaderParameters` must be true, false or a list of texture set indexes")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_json_names_the_shader_its_settings_and_its_texture_sets() {
|
||||
let mut session = crate::sample_session(128, 32).unwrap();
|
||||
session.doc.project.display.ior = 1.33;
|
||||
|
||||
let value = shader_parameters(&session.doc.project, &[1]);
|
||||
|
||||
let shader = &value["shaders"][0];
|
||||
|
||||
assert_eq!(shader["model"], "metallicRoughness");
|
||||
assert!((shader["parameters"]["ior"].as_f64().unwrap() - 1.33).abs() < 1e-6);
|
||||
assert_eq!(shader["textureSets"], json!([session.doc.project.texture_sets[1].name]));
|
||||
assert!(shader_parameters_file("Material Ball").ends_with("_shaders.json"));
|
||||
}
|
||||
}
|
||||
@@ -27,3 +27,161 @@ fn the_new_file_types_dithering_and_diffusion_export() {
|
||||
assert!(plan.as_array().unwrap().iter().all(|f| f["dithering"] == false), "float files are never dithered");
|
||||
assert!(execute(&mut s, "export.plan", &json!({"padding": "smudge"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_memory_psd_export_only_renders_the_first_plan_for_each_name() {
|
||||
const SMALL_SIDE: u32 = 128;
|
||||
let mesh = texturecraft_engine::geom::primitives::udim_plane();
|
||||
let mut session = texturecraft_engine::Session::new_project("test", mesh, "builtin:udim_plane", None, SMALL_SIDE).unwrap();
|
||||
let preset =
|
||||
json!({"name": "Roughness", "maps": [{"file": "rough", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}]});
|
||||
let options = |size| texturecraft_engine::file_cmds::export_options(&session, &json!({"preset": preset, "size": size, "padding": "none"}), "test").unwrap();
|
||||
let small = options(SMALL_SIDE);
|
||||
let large = options(4096);
|
||||
let first = session.export_files(&[0], &small).unwrap();
|
||||
assert!(first.len() > 1, "the mesh supplies multiple PSD tiles");
|
||||
|
||||
let jobs = std::iter::once((0, &small)).chain(std::iter::repeat_n((0, &large), 4));
|
||||
let batch = session.export_file_jobs(jobs).unwrap();
|
||||
|
||||
assert_eq!(batch.len(), first.len());
|
||||
assert!(batch.iter().zip(&first).all(|(kept, original)| kept.name == original.name && kept.bytes == original.bytes));
|
||||
assert!(batch.iter().zip(&first).all(|(kept, original)| kept.warnings.len() > original.warnings.len()));
|
||||
println!("Kept {} PSDs totaling {} encoded bytes", batch.len(), batch.iter().map(|file| file.bytes.len()).sum::<usize>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_psd_file_and_another_sets_folder_conflict_during_planning() {
|
||||
use texturecraft_engine::core::Channel;
|
||||
use texturecraft_engine::file_cmds::export_options;
|
||||
|
||||
let mut session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let sets = &mut session.doc.project.texture_sets;
|
||||
sets[0].name = "Body".into();
|
||||
sets[0].channels.retain(|(channel, _)| *channel != Channel::Metallic);
|
||||
sets[1].name = "Trim".into();
|
||||
let preset = json!({"name": "Conflicting outputs", "maps": [
|
||||
{"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]},
|
||||
{"file": "$mesh_Body.psd/detail", "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Metallic"}}]]}
|
||||
]});
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut params = json!({"preset": preset, "padding": "none", "dir": dir.path()});
|
||||
|
||||
params["ts"] = json!(0);
|
||||
let body = execute(&mut session, "export.plan", ¶ms).unwrap();
|
||||
params["ts"] = json!(1);
|
||||
let trim = execute(&mut session, "export.plan", ¶ms).unwrap();
|
||||
let file = body[0]["file"].as_str().unwrap();
|
||||
let nested_file = trim.as_array().unwrap().iter().find_map(|file| file["file"].as_str().filter(|name| name.contains('/'))).unwrap();
|
||||
assert_eq!(nested_file.split('/').next(), Some(file), "separate plans collide when combined");
|
||||
|
||||
for order in [[0, 1], [1, 0]] {
|
||||
params["ts"] = json!(order);
|
||||
let plan_error = execute(&mut session, "export.plan", ¶ms).unwrap_err();
|
||||
let options = export_options(&session, ¶ms, "export.plan").unwrap();
|
||||
let render_error = session.export_files(&order, &options).unwrap_err();
|
||||
let write_error = execute(&mut session, "file.exportTextures", ¶ms).unwrap_err();
|
||||
|
||||
for error in [plan_error, render_error, write_error] {
|
||||
assert!(error.to_string().contains("folder"), "{error}");
|
||||
}
|
||||
assert!(std::fs::read_dir(dir.path()).unwrap().next().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_size_wins_over_the_export_size_in_the_plan() {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
|
||||
let plan = execute(&mut session, "export.plan", &json!({"ts": 0, "size": 512, "maps": [{"map": 0, "size": 128}]})).unwrap();
|
||||
|
||||
let (overridden, inherited): (Vec<_>, Vec<_>) = plan.as_array().unwrap().iter().partition(|file| file["map"] == 0);
|
||||
|
||||
assert!(!overridden.is_empty() && !inherited.is_empty(), "{plan}");
|
||||
assert!(overridden.iter().all(|file| file["size"] == 128), "{plan}");
|
||||
assert!(inherited.iter().all(|file| file["size"] == 512), "{plan}");
|
||||
assert!(execute(&mut session, "export.plan", &json!({"ts": 0, "maps": [{"map": 0, "size": 100}]})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shader_parameters_write_the_shaders_json_next_to_the_textures() {
|
||||
let mut session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join(texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name));
|
||||
|
||||
let result = execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "ts": 1, "shaderParameters": [0, 1]})).unwrap();
|
||||
|
||||
assert!(result["files"].as_array().unwrap().iter().any(|f| f.as_str() == Some(file.to_str().unwrap())), "{result}");
|
||||
let written: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap();
|
||||
let names: Vec<&str> = session.doc.project.texture_sets.iter().take(2).map(|set| set.name.as_str()).collect();
|
||||
|
||||
assert_eq!(written["shaders"][0]["textureSets"], json!(names));
|
||||
assert!(execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "shaderParameters": "yes"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shaders_json_that_cannot_be_written_is_a_warning_after_the_textures() {
|
||||
let mut session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join(texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name));
|
||||
std::fs::create_dir_all(&file).unwrap();
|
||||
|
||||
let result = execute(&mut session, "file.exportTextures", &json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true})).unwrap();
|
||||
|
||||
let files = result["files"].as_array().unwrap();
|
||||
|
||||
assert!(!files.is_empty() && files.iter().all(|f| f.as_str() != Some(file.to_str().unwrap())), "{result}");
|
||||
let warnings = result["warnings"].as_array().unwrap();
|
||||
|
||||
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.starts_with("The shader settings file was not written"))), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shaders_json_named_like_an_earlier_commands_folder_is_a_warning() {
|
||||
let mut session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let name = texturecraft_engine::shader_parameters::shader_parameters_file(&session.doc.project.name);
|
||||
let reserved = format!("{}/Color.png", name.to_uppercase());
|
||||
|
||||
let result = execute(
|
||||
&mut session,
|
||||
"file.exportTextures",
|
||||
&json!({"dir": dir.path().display().to_string(), "ts": 0, "shaderParameters": true, "reservedNames": [reserved]}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert!(!dir.path().join(&name).exists(), "{result}");
|
||||
let warnings = result["warnings"].as_array().unwrap();
|
||||
|
||||
assert!(warnings.iter().any(|w| w.as_str().is_some_and(|w| w.contains("already used by a texture file or folder"))), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_psd_warning_outlives_a_reserved_file_that_carried_it() {
|
||||
let mut session = texturecraft_engine::sample_session(128, 32).unwrap();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let roughness = json!([["L", {"Channel": {"channel": "Roughness"}}]]);
|
||||
let colour = json!([["R", {"Channel": {"channel": "BaseColor"}}], ["G", {"Channel": {"channel": "BaseColor", "component": 1}}], ["B", {"Channel": {"channel": "BaseColor", "component": 2}}], ["A", {"Constant": 0.5}]]);
|
||||
let mut preset = json!({"name": "Two and a PSD", "maps": [
|
||||
{"file": "first", "format": "Png", "bit_depth": 8, "channels": roughness},
|
||||
{"file": "second", "format": "Png", "bit_depth": 8, "channels": roughness},
|
||||
]});
|
||||
|
||||
// Four 16-bit RGBA layers at 8192 pixels exceed the 2 GiB PSD limit
|
||||
for layer in 0..4 {
|
||||
preset["maps"].as_array_mut().unwrap().push(json!({"file": format!("layer{layer}"), "format": "Psd", "bit_depth": 16, "channels": colour}));
|
||||
}
|
||||
let sizes: Vec<_> = (2..6).map(|map| json!({"map": map, "size": 8192})).collect();
|
||||
let params = |reserved: Vec<String>| json!({"dir": dir.path().display().to_string(), "ts": 0, "preset": preset, "maps": sizes, "reservedNames": reserved});
|
||||
let plan = execute(&mut session, "export.plan", ¶ms(Vec::new())).unwrap();
|
||||
let first = plan[0]["file"].as_str().unwrap().to_owned();
|
||||
let second = plan[1]["file"].as_str().unwrap().to_owned();
|
||||
let psd_warning =
|
||||
|warnings: &serde_json::Value| warnings.as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains(".psd\" was not written")));
|
||||
assert!(plan.as_array().unwrap().len() == 2 && psd_warning(&plan[0]["warnings"]), "{plan}");
|
||||
|
||||
let result = execute(&mut session, "file.exportTextures", ¶ms(vec![first.clone()])).unwrap();
|
||||
|
||||
assert!(psd_warning(&result["warnings"]), "{result}");
|
||||
assert!(dir.path().join(&second).exists() && !dir.path().join(&first).exists(), "{result}");
|
||||
}
|
||||
@@ -105,3 +105,24 @@ fn a_file_name_an_earlier_texture_set_exports_is_not_overwritten() {
|
||||
}
|
||||
assert_eq!(result["files"].as_array().unwrap().len(), names.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_preview_shows_a_packed_map_small_and_nothing_for_a_left_out_one() {
|
||||
let mut s = session();
|
||||
let preset = s.export_preset("Unity HDRP (Mask Map)").unwrap();
|
||||
let mask = preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap();
|
||||
let params = json!({"preset": preset.name, "ts": 0, "map": mask, "side": 16});
|
||||
|
||||
let preview = execute(&mut s, "export.preview", ¶ms).unwrap();
|
||||
let (width, height) = (preview["width"].as_u64().unwrap(), preview["height"].as_u64().unwrap());
|
||||
|
||||
assert!(width <= 16 && height > 0, "{preview}");
|
||||
assert_eq!(preview["channels"], json!(["R", "G", "B", "A"]), "the mask map packs four channels");
|
||||
assert_eq!(preview["pixels"].as_array().unwrap().len() as u64, width * height * 4);
|
||||
|
||||
let left_out = json!({"preset": preset.name, "ts": 0, "map": mask, "maps": [{"map": mask, "enabled": false}]});
|
||||
|
||||
assert!(execute(&mut s, "export.preview", &left_out).unwrap().is_null(), "a map the export leaves out has no file to show");
|
||||
assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name})).is_err(), "the map is required");
|
||||
assert!(execute(&mut s, "export.preview", &json!({"preset": preset.name, "map": preset.maps.len()})).is_err());
|
||||
}
|
||||
@@ -197,11 +197,15 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// A PSD holds every map of the texture set as a layer
|
||||
let all = names(&result);
|
||||
assert!(all.iter().any(|f| f.ends_with(&format!("_baseColor.{ext}"))), "{format}: the template's files keep the file type: {all:?}");
|
||||
let template_file = if format == "psd" { ".psd".to_string() } else { format!("_baseColor.{ext}") };
|
||||
|
||||
assert!(all.iter().any(|f| f.ends_with(&template_file)), "{format}: the template's files keep the file type: {all:?}");
|
||||
let mtlx = files(&result).into_iter().find(|f| f.ends_with(".mtlx")).unwrap_or_else(|| panic!("{format}: no .mtlx in {all:?}"));
|
||||
let text = std::fs::read_to_string(mtlx).unwrap();
|
||||
let wanted = if format == "tiff" { "tif" } else { "png" };
|
||||
|
||||
assert!(text.contains(&format!("_base_color.{wanted}\"")), "{format}: {text}");
|
||||
for file in referenced(&text) {
|
||||
assert!(dir.join(&file).is_file(), "{format}: {file} is not in {all:?}");
|
||||
@@ -209,6 +213,27 @@ fn a_file_type_a_material_cannot_use_falls_back_to_png() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materialx_png_fallback_preserves_the_selected_maps_size() {
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
let dir = temp("map-size-fallback");
|
||||
let options = json!({
|
||||
"dir": dir.display().to_string(), "preset": OPENPBR, "ts": 0, "size": 128, "materialX": true,
|
||||
"maps": [{"map": 0, "format": "psd", "size": 256}]
|
||||
});
|
||||
|
||||
let result = execute(&mut session, "file.exportTextures", &options).unwrap();
|
||||
|
||||
let files = files(&result);
|
||||
|
||||
assert!(files.iter().any(|file| file.ends_with(".psd")), "{result}");
|
||||
let base = files.iter().find(|file| file.ends_with("_base_color.png")).unwrap();
|
||||
let roughness = files.iter().find(|file| file.ends_with("_specular_roughness.png")).unwrap();
|
||||
|
||||
assert_eq!(image::image_dimensions(base).unwrap(), (256, 256));
|
||||
assert_eq!(image::image_dimensions(roughness).unwrap(), (128, 128));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_openpbr_maps_follow_the_size_and_colour_space_of_the_export() {
|
||||
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
|
||||
|
||||
@@ -407,3 +407,17 @@ fn a_mesh_without_materials_gets_a_material_bound_to_the_default_texture_set() {
|
||||
assert!(dir.join(&read.file).is_file(), "{} was written", read.file);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_psd_of_layers_is_left_out_of_the_materials_and_said_so() {
|
||||
let mut s = ball();
|
||||
let dir = temp("psd");
|
||||
|
||||
let r = export(&mut s, &dir, json!({"ts": 0, "format": "psd", "usdAsset": true}));
|
||||
|
||||
assert!(files(&r).iter().any(|f| f.ends_with(".psd")), "{r}");
|
||||
let materials = read_back(&s, &dir);
|
||||
|
||||
assert!(materials[material_of(&s, 0)].0.is_empty(), "no input reads the PSD's merged image: {:?}", materials[material_of(&s, 0)]);
|
||||
assert!(r["warnings"].to_string().contains("doesn't read PSD files"), "{r}");
|
||||
}
|
||||
@@ -28,7 +28,6 @@ craft-image-codecs = { workspace = true }
|
||||
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
flate2 = { workspace = true }
|
||||
half = { workspace = true }
|
||||
quick-xml = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
exr = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -106,9 +106,13 @@ pub fn preset_to_json(preset: &ExportPreset) -> Result<String>;
|
||||
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), 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
|
||||
- Formats: PNG 8/16, JPEG 8 (q 95), JNG 8 (JPEG colour,
|
||||
deflate alpha), PGM 8/16 (gray; colour becomes luminance), TGA 8, TIFF 8/16/32f, BMP 8,
|
||||
WebP 8 (lossless), PSD 8/16, EXR 16f/32f (`Y`, `YA`, `RGB`, `RGBA`, ZIP), HDR 32f.
|
||||
PSD writes one file per texture set or UV tile, with each output map stored as a layer.
|
||||
For tiled sets, `ExportOptions::atlas` writes one document for the whole set. Smaller maps
|
||||
keep their sizes and align to the top left of the canvas. A `/` in a map
|
||||
name creates a layer group inside the PSD. 8-bit files can be dithered
|
||||
(`ExportOptions::dither`, an 8×8 ordered pattern). When `ExportOptions::color_space` is unset,
|
||||
color maps default to sRGB in integer files and linear Rec.709 in float files. An explicit
|
||||
override can select another supported space. PGM writes sRGB or linear Rec.709 luminance and
|
||||
@@ -137,9 +141,24 @@ Built-in presets (each one lists the public specification its packing follows in
|
||||
| OpenPBR (separate maps) | one map per OpenPBR Surface input the set has: `base_color`, `base_metalness`, `specular_roughness`, `specular_roughness_anisotropy`, `coat_weight`, `coat_roughness`, `fuzz_weight`, `fuzz_color`, `fuzz_roughness`, `transmission_weight`, `subsurface_weight`, `emission_color`, `geometry_opacity`, `geometry_normal` (OpenGL), `height` (16-bit) |
|
||||
| Unity URP Lit (Metallic Smoothness) | `BaseMap`, `MetallicMap` (R metal, A smoothness), `NormalMap` (OpenGL), `OcclusionMap`, `EmissionMap` |
|
||||
| USD Preview Surface (separate maps) | one map per UsdPreviewSurface input the set has, named like it: `diffuseColor`, `emissiveColor`, `metallic`, `roughness`, `normal` (OpenGL), `occlusion`, `opacity`, `clearcoat`, `clearcoatRoughness` |
|
||||
| Unreal Engine Subsurface Profile (Packed) | `BaseColor` (no alpha), `OcclusionRoughnessMetallic`, `Normal` (DirectX), `SubsurfaceMask` (scatter weight, for the Opacity input) |
|
||||
| glTF Specular Glossiness (archived extension) | `Diffuse` (A = opacity), `SpecularGlossiness` (RGB specular, A glossiness, from the set's own channels), `Normal` (OpenGL), `Occlusion`, `Emissive` |
|
||||
| Redshift Standard Material (separate maps) | separate maps for the listed inputs when the set supplies their sources: `BaseColor`, `Metalness`, `ReflectionRoughness`, `Normal` (OpenGL), `EmissionColor`, `Opacity`, `SubsurfaceWeight`, `CoatWeight`, `CoatRoughness`, `SheenWeight`, `SheenColor`, `SheenRoughness` |
|
||||
| Roblox SurfaceAppearance (separate maps) | `Color` (A = opacity), `Normal` (OpenGL), `Metalness`, `Roughness` |
|
||||
| Sketchfab Metalness (separate maps) | `BaseColor` (no alpha), `Metalness`, `Roughness`, `Normal` (DirectX), `AmbientOcclusion`, `Emission` |
|
||||
| Separate maps | one file per channel, gray where scalar, height 16-bit |
|
||||
| Mesh maps | every baked map (`$channel` = map id), 16-bit |
|
||||
|
||||
The preset column gives the stable automation and saved-setting names. When a user preset shares
|
||||
a table name, that name selects the user preset so saved settings keep working. To select the
|
||||
built-in through automation, pass the exact `name` from its `builtin: true` entry in
|
||||
`export.presets`.
|
||||
|
||||
The export window describes four templates by their output. **Packed maps with a scattering mask**
|
||||
targets Unreal Engine's subsurface input. **Separate coat, sheen and scattering maps** targets Redshift.
|
||||
**Four maps with opacity in color** targets Roblox, and **Six maps with a negative-Y normal**
|
||||
targets Sketchfab.
|
||||
|
||||
### Project file (`project_file`)
|
||||
|
||||
```rust
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! A texture set's PSD: each output map a layer, a `/` in its name a layer group
|
||||
|
||||
use craft_psd::{Compression, GroupSpec, LayerSpec, PixelData, PsdBuilder};
|
||||
use texturecraft_core::TextureSet;
|
||||
use texturecraft_texel::linear_to_srgb;
|
||||
|
||||
use super::encoding::Encoding;
|
||||
use super::map_renderer::MapRenderer;
|
||||
use super::{
|
||||
ExportOptions, ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, Padding, PlannedFile, PlannedLayer, check_psd_size, psd_size,
|
||||
quantize_integer, quantize_u8, quantize_u16,
|
||||
};
|
||||
use crate::{FormatError, Result};
|
||||
|
||||
/// Where alpha sits in an RGBA texel
|
||||
const ALPHA_INDEX: usize = 3;
|
||||
|
||||
/// Check the file limits and the working memory against `working_limit` (None: unlimited), returning the canvas size and estimated encoded bytes
|
||||
pub(super) fn preflight<'a>(
|
||||
set: &TextureSet,
|
||||
options: &ExportOptions,
|
||||
tile: Option<u32>,
|
||||
depth: u8,
|
||||
layers: impl Iterator<Item = &'a PlannedLayer> + Clone,
|
||||
working_limit: Option<u64>,
|
||||
) -> Result<((u32, u32), u64)> {
|
||||
let (canvas, file_bytes, working_bytes) = working_set(set, options, tile, depth, layers)?;
|
||||
if working_limit.is_some_and(|limit| working_bytes >= limit) {
|
||||
let (width, height) = canvas;
|
||||
return Err(FormatError::Invalid(format!(
|
||||
"a PSD at {width}×{height} would exceed the working memory budget; use a smaller export size, fewer PSD maps or another format"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok((canvas, file_bytes))
|
||||
}
|
||||
|
||||
/// The canvas size, estimated encoded bytes and peak working bytes of one PSD, after checking the file limits
|
||||
fn working_set<'a>(
|
||||
set: &TextureSet,
|
||||
options: &ExportOptions,
|
||||
tile: Option<u32>,
|
||||
depth: u8,
|
||||
layers: impl Iterator<Item = &'a PlannedLayer> + Clone,
|
||||
) -> Result<((u32, u32), u64, u64)> {
|
||||
let texels = |(width, height)| u64::from(width) * u64::from(height);
|
||||
let folder_count = layers.clone().map(|layer| layer.name.matches('/').count()).sum();
|
||||
let sizes = layers.map(|layer| psd_size(set, tile, options.map_size(layer.map)));
|
||||
let (canvas, file_bytes) = check_psd_size(sizes.clone(), folder_count, depth)?;
|
||||
let float_bytes_per_texel = (PSD_RGBA_PLANES * size_of::<f32>()) as u64;
|
||||
let source_bytes = texels(psd_size(set, tile, None)).saturating_mul(float_bytes_per_texel);
|
||||
let largest_layer_bytes = sizes.map(texels).max().unwrap_or(0) * float_bytes_per_texel;
|
||||
|
||||
// The merged image is built a row at a time: a canvas row and a layer row in floating point
|
||||
let merge_bytes = 2 * u64::from(canvas.0) * float_bytes_per_texel;
|
||||
|
||||
// Resizing overlaps source and destination, and RGBA conversion can overlap two output buffers
|
||||
let mut scratch_bytes = source_bytes.saturating_add(largest_layer_bytes).max(2 * largest_layer_bytes);
|
||||
if matches!(options.padding, Padding::DilationDiffusion(_)) {
|
||||
// A copied block, its weights, and the smaller pyramid levels fit within this source allowance
|
||||
scratch_bytes = scratch_bytes.max(source_bytes.saturating_mul(3));
|
||||
}
|
||||
|
||||
let mut padding_bytes = 0;
|
||||
let mut padding_peak = 0;
|
||||
if options.padding != Padding::None {
|
||||
let atlas_texels = texels(set.size());
|
||||
padding_bytes = atlas_texels.saturating_mul(size_of::<u32>() as u64);
|
||||
|
||||
// The atlas keeps its dilation indices after the frontiers are freed
|
||||
padding_peak = padding_bytes.saturating_add(atlas_texels.saturating_mul((4 * size_of::<usize>()) as u64));
|
||||
}
|
||||
|
||||
// The quantized layers kept so far and the merged image are part of the file; the encoder can hold staged pixels, planes and the output at once
|
||||
let rendering = scratch_bytes.max(merge_bytes).saturating_add(file_bytes);
|
||||
let encoding = 3 * file_bytes;
|
||||
let working_bytes = padding_bytes.saturating_add(rendering.max(encoding)).max(padding_peak);
|
||||
Ok((canvas, file_bytes, working_bytes))
|
||||
}
|
||||
|
||||
/// Render each layer at its requested size, aligned to the upper-left corner of the PSD canvas.
|
||||
pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u32, u32)) -> Result<ExportedFile> {
|
||||
let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned;
|
||||
|
||||
// Only the current layer is in floating point; the others are kept as the file stores them
|
||||
let mut pixels = Vec::with_capacity(layers.len());
|
||||
let mut embedded = None;
|
||||
for layer in layers.iter().rev() {
|
||||
let map = renderer.render(layer.map, tile, FileFormat::Psd, bit_depth)?;
|
||||
embedded = map.embed.or(embedded);
|
||||
let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither };
|
||||
let layer_pixels = rgba_pixel_data(map.data, map.component_count, &map.srgb, map.size.0, encoding)?;
|
||||
pixels.push((layer.name.as_str(), map.size, layer_pixels));
|
||||
}
|
||||
if let Some(space) = embedded {
|
||||
warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name()));
|
||||
}
|
||||
|
||||
let composite = merged_image(size, bit_depth, &pixels)?;
|
||||
|
||||
let bytes = write_layers(size, bit_depth, pixels, composite).map_err(|error| FormatError::Invalid(format!("psd encoding failed: {error}")))?;
|
||||
if bytes.len() as u64 >= PSD_MAX_FILE_BYTES {
|
||||
return Err(FormatError::Invalid(format!("\"{name}\" would reach the 2 GiB PSD file limit; use a smaller export size or fewer PSD maps")));
|
||||
}
|
||||
|
||||
Ok(ExportedFile { name, bytes, width: size.0, height: size.1, warnings })
|
||||
}
|
||||
|
||||
/// The merged image of `layers` (bottom first, as the file stores them), one row at a time
|
||||
fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u32), PixelData)]) -> Result<PixelData> {
|
||||
let row_len = width as usize * PSD_RGBA_PLANES;
|
||||
let sample_count = row_len * height as usize;
|
||||
let mut merged_row = vec![0.0f32; row_len];
|
||||
let mut layer_row = Vec::with_capacity(row_len);
|
||||
let reserve_error = |error| FormatError::Invalid(format!("PSD merged image allocation failed: {error}"));
|
||||
if depth == 16 {
|
||||
let mut merged = Vec::new();
|
||||
merged.try_reserve_exact(sample_count).map_err(reserve_error)?;
|
||||
for y in 0..height as usize {
|
||||
merge_row(y, width, layers, &mut merged_row, &mut layer_row);
|
||||
merged.extend(merged_row.iter().map(|&value| quantize_u16(value)));
|
||||
}
|
||||
return Ok(PixelData::Rgba16(merged));
|
||||
}
|
||||
|
||||
let mut merged = Vec::new();
|
||||
merged.try_reserve_exact(sample_count).map_err(reserve_error)?;
|
||||
for y in 0..height as usize {
|
||||
merge_row(y, width, layers, &mut merged_row, &mut layer_row);
|
||||
merged.extend(merged_row.iter().copied().map(quantize_u8));
|
||||
}
|
||||
|
||||
Ok(PixelData::Rgba8(merged))
|
||||
}
|
||||
|
||||
/// Row `y` of the merged image into `merged_row`, each layer's row decoded into `layer_row` in turn
|
||||
fn merge_row(y: usize, width: u32, layers: &[(&str, (u32, u32), PixelData)], merged_row: &mut [f32], layer_row: &mut Vec<f32>) {
|
||||
merged_row.fill(0.0);
|
||||
for (_, (layer_width, layer_height), samples) in layers {
|
||||
if y >= *layer_height as usize {
|
||||
continue;
|
||||
}
|
||||
|
||||
let span = *layer_width as usize * PSD_RGBA_PLANES;
|
||||
let range = y * span..(y + 1) * span;
|
||||
layer_row.clear();
|
||||
match samples {
|
||||
PixelData::Rgba8(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u8::MAX))),
|
||||
PixelData::Rgba16(samples) => layer_row.extend(samples.get(range).unwrap_or_default().iter().map(|&v| f32::from(v) / f32::from(u16::MAX))),
|
||||
_ => continue,
|
||||
}
|
||||
over(merged_row, width, layer_row, *layer_width);
|
||||
}
|
||||
}
|
||||
|
||||
/// Composite a straight-alpha RGBA layer at the top left of the canvas.
|
||||
fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) {
|
||||
let canvas_rows = canvas.chunks_exact_mut(canvas_width as usize * PSD_RGBA_PLANES);
|
||||
let layer_rows = layer.chunks_exact(layer_width as usize * PSD_RGBA_PLANES);
|
||||
for (canvas_row, layer_row) in canvas_rows.zip(layer_rows) {
|
||||
let canvas_texels = canvas_row.as_chunks_mut::<PSD_RGBA_PLANES>().0;
|
||||
let layer_texels = layer_row.as_chunks::<PSD_RGBA_PLANES>().0;
|
||||
for (under, top) in canvas_texels.iter_mut().zip(layer_texels) {
|
||||
let (top_alpha, under_alpha) = (top[ALPHA_INDEX], under[ALPHA_INDEX]);
|
||||
let alpha = top_alpha + under_alpha * (1.0 - top_alpha);
|
||||
if alpha <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (value, top_value) in under.iter_mut().zip(top).take(ALPHA_INDEX) {
|
||||
*value = (top_value * top_alpha + *value * under_alpha * (1.0 - top_alpha)) / alpha;
|
||||
}
|
||||
under[ALPHA_INDEX] = alpha;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// L, LA, RGB or RGBA samples quantized as the RGBA the PSD builder accepts: gray repeated, opaque without alpha, sRGB transfer applied to the components `srgb` marks, values clamped to 0-1
|
||||
fn rgba_pixel_data(mut data: Vec<f32>, component_count: usize, srgb: &[bool], width: u32, encoding: Encoding) -> Result<PixelData> {
|
||||
let component_count = component_count.max(1);
|
||||
for texel in data.chunks_exact_mut(component_count) {
|
||||
for (component, value) in texel.iter_mut().enumerate() {
|
||||
*value = if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) };
|
||||
}
|
||||
}
|
||||
|
||||
// Widen each texel while quantizing, so no floating-point RGBA copy of the layer is made
|
||||
let texel_count = data.len() / component_count;
|
||||
let rgba = (0..texel_count * PSD_RGBA_PLANES).map(|index| {
|
||||
let (texel, component) = (index / PSD_RGBA_PLANES, index % PSD_RGBA_PLANES);
|
||||
let source = match component_count {
|
||||
1 | 2 if component < ALPHA_INDEX => Some(0),
|
||||
1 | 3 if component == ALPHA_INDEX => None,
|
||||
2 => Some(1),
|
||||
_ => Some(component),
|
||||
};
|
||||
source.map_or(1.0, |source| data.get(texel * component_count + source).copied().unwrap_or(0.0))
|
||||
});
|
||||
|
||||
if encoding.depth == 16 {
|
||||
let mut pixels = Vec::new();
|
||||
pixels.try_reserve_exact(rgba.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?;
|
||||
pixels.extend(rgba.map(quantize_u16));
|
||||
return Ok(PixelData::Rgba16(pixels));
|
||||
}
|
||||
|
||||
quantize_integer(encoding, width, PSD_RGBA_PLANES, rgba).map(PixelData::Rgba8)
|
||||
}
|
||||
|
||||
/// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front
|
||||
pub(super) fn write_layers(
|
||||
(width, height): (u32, u32),
|
||||
depth: u8,
|
||||
layers: Vec<(&str, (u32, u32), PixelData)>,
|
||||
composite: PixelData,
|
||||
) -> craft_psd::Result<Vec<u8>> {
|
||||
let mut builder = PsdBuilder::new(width, height).depth(u16::from(depth)).compression(Compression::Raw);
|
||||
|
||||
// The builder stacks bottom up, so the groups open and close in that order too
|
||||
let mut open: Vec<&str> = Vec::new();
|
||||
for (path, (layer_width, layer_height), pixels) in layers {
|
||||
let mut parts: Vec<&str> = path.split('/').collect();
|
||||
let name = parts.pop().unwrap_or_default();
|
||||
let shared = open.iter().zip(&parts).take_while(|(open, part)| open == part).count();
|
||||
for _ in shared..open.len() {
|
||||
builder.end_group()?;
|
||||
}
|
||||
open.truncate(shared);
|
||||
for group in parts.iter().skip(shared) {
|
||||
builder.begin_group(GroupSpec::new(*group));
|
||||
open.push(group);
|
||||
}
|
||||
|
||||
builder.push_layer(LayerSpec::new(name, 0, 0, layer_width, layer_height, pixels));
|
||||
}
|
||||
for _ in open {
|
||||
builder.end_group()?;
|
||||
}
|
||||
|
||||
builder.composite(composite);
|
||||
builder.to_bytes()
|
||||
}
|
||||
@@ -14,10 +14,13 @@ pub struct MapOverride {
|
||||
/// Instead of the export's dithering of 8-bit files.
|
||||
#[serde(default)]
|
||||
pub dither: Option<bool>,
|
||||
/// Output size (power of two) instead of the export's
|
||||
#[serde(default)]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
|
||||
impl Default for MapOverride {
|
||||
fn default() -> Self {
|
||||
MapOverride { enabled: true, format: None, bit_depth: None, dither: None }
|
||||
MapOverride { enabled: true, format: None, bit_depth: None, dither: None, size: None }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
//! A small picture of one output map, sampled from the texture set as the export samples it
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_texel::linear_to_srgb;
|
||||
|
||||
use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Sampler, SourceRef, layout, list_outputs, rec709_luminance};
|
||||
use crate::{FormatError, Result};
|
||||
|
||||
/// The largest preview side: a preview is a glance, never a second export
|
||||
pub const MAX_PREVIEW_SIDE: u32 = 512;
|
||||
|
||||
/// One output map, small: its channels in file order and the 8-bit values an sRGB file of it stores (colour channels sRGB-encoded, data as is)
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct MapPreview {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub channels: Vec<Dest>,
|
||||
/// `channels.len()` values per pixel, row by row
|
||||
pub pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
impl MapPreview {
|
||||
/// Output map `map` of `options`' template for `input`'s set, with each side at most `side` pixels.
|
||||
/// Returns None when the map writes no file. Texels off the UV islands show the default.
|
||||
pub fn sample(input: &ExportInput, options: &ExportOptions, map: usize, side: u32) -> Result<Option<MapPreview>> {
|
||||
Self::sample_coverage(input, options, map, side, false)
|
||||
}
|
||||
|
||||
/// Sample the engine's triangle indices directly, using the UV rasterizer's uncovered sentinel.
|
||||
pub fn sample_triangles(input: &ExportInput<u32>, options: &ExportOptions, map: usize, side: u32) -> Result<Option<MapPreview>> {
|
||||
Self::sample_coverage(input, options, map, side, texturecraft_geom::NO_TRI)
|
||||
}
|
||||
|
||||
fn sample_coverage<Coverage: PartialEq + Sync>(
|
||||
input: &ExportInput<Coverage>,
|
||||
options: &ExportOptions,
|
||||
map: usize,
|
||||
side: u32,
|
||||
uncovered: Coverage,
|
||||
) -> Result<Option<MapPreview>> {
|
||||
let set = input.project.texture_set(input.ts)?;
|
||||
let spec = options.preset.maps.get(map).ok_or_else(|| FormatError::Invalid(format!("the template has no output map {map}")))?;
|
||||
let planned = list_outputs(input.project, input.ts, input.mesh_name, options)?;
|
||||
let Some(file) = planned.iter().find(|file| file.maps().any(|written| written == map)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let (composite_width, height) = (input.composite.resolution, input.composite.height);
|
||||
if composite_width == 0 || height == 0 || input.coverage.len() as u64 != u64::from(composite_width) * u64::from(height) {
|
||||
return Err(FormatError::Invalid(format!("composite size {composite_width}×{height} does not match its coverage")));
|
||||
}
|
||||
|
||||
// The file's longer side bounds the preview: the map's own size, else the export size, else the set's
|
||||
let tile_res = (composite_width / set.tile_grid().map_or(1, |grid| grid.cols.max(1))).max(1);
|
||||
let file_side = |source| super::scale_export_side(source, tile_res, options.map_size(map));
|
||||
let source_side = composite_width.max(height);
|
||||
let preview_side = side.clamp(1, MAX_PREVIEW_SIDE).min(file_side(composite_width).max(file_side(height))).min(source_side);
|
||||
let width = super::scale_export_side(composite_width, source_side, Some(preview_side));
|
||||
let rows = super::scale_export_side(height, source_side, Some(preview_side));
|
||||
let sampler = Sampler::new(input, options, set, tile_res, uncovered);
|
||||
let mut channel_layout = layout(set, spec);
|
||||
let grayscale = file.format == FileFormat::Pgm;
|
||||
if grayscale || matches!(file.format, FileFormat::Jpeg | FileFormat::Hdr) {
|
||||
channel_layout.retain(|(dest, _)| *dest != Dest::A);
|
||||
}
|
||||
|
||||
let gray_source = channel_layout.first().filter(|(dest, _)| *dest == Dest::L);
|
||||
let psd = file.format == FileFormat::Psd;
|
||||
let rgb_from_gray = gray_source.filter(|_| {
|
||||
matches!(file.format, FileFormat::Psd | FileFormat::Hdr | FileFormat::Webp)
|
||||
|| (file.format == FileFormat::Tiff && (file.bit_depth == 32 || channel_layout.len() == 2))
|
||||
});
|
||||
let channels = if grayscale {
|
||||
vec![Dest::L]
|
||||
} else if psd {
|
||||
vec![Dest::R, Dest::G, Dest::B, Dest::A]
|
||||
} else if rgb_from_gray.is_some() {
|
||||
[Dest::R, Dest::G, Dest::B].into_iter().chain(channel_layout.iter().skip(1).map(|(dest, _)| *dest)).collect()
|
||||
} else {
|
||||
channel_layout.iter().map(|(dest, _)| *dest).collect()
|
||||
};
|
||||
|
||||
let component_count = channels.len();
|
||||
let color = spec.is_color();
|
||||
let max_sample = f32::from(u8::MAX);
|
||||
let preview_sample = |value: f32, dest| {
|
||||
let stored = if color && dest != Dest::A { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) };
|
||||
(stored * max_sample + 0.5) as u8
|
||||
};
|
||||
|
||||
// Sample at the centre of each preview pixel
|
||||
let source_texel = |pixel: u32, preview_side: u32, source_side: u32| {
|
||||
((u64::from(pixel) * 2 + 1) * u64::from(source_side) / (2 * u64::from(preview_side))).min(u64::from(source_side) - 1) as u32
|
||||
};
|
||||
|
||||
let mut pixels = vec![0u8; width as usize * rows as usize * component_count];
|
||||
pixels.par_chunks_mut(width as usize * component_count).enumerate().for_each(|(row, values)| {
|
||||
let y = source_texel(row as u32, rows, height);
|
||||
for (column, pixel) in values.chunks_exact_mut(component_count).enumerate() {
|
||||
let x = source_texel(column as u32, width, composite_width);
|
||||
let at = if sampler.covered(x, y) { At::Texel(x, y) } else { At::Default };
|
||||
let mut cache = None;
|
||||
let mut sample = |&(dest, source): &(Dest, &SourceRef)| {
|
||||
let sample = sampler.sample(source, at, &mut cache);
|
||||
if spec.inverted.contains(&dest) { 1.0 - sample } else { sample }
|
||||
};
|
||||
|
||||
if grayscale && let [luminance] = pixel {
|
||||
let value = match channel_layout.as_slice() {
|
||||
[red, green, blue] => rec709_luminance(sample(red), sample(green), sample(blue)),
|
||||
[gray] => sample(gray),
|
||||
_ => 0.0,
|
||||
};
|
||||
*luminance = preview_sample(value, Dest::L);
|
||||
} else if let (Some(gray), [red, green, blue, alpha @ ..]) = (rgb_from_gray, &mut *pixel) {
|
||||
let value = preview_sample(sample(gray), Dest::L);
|
||||
(*red, *green, *blue) = (value, value, value);
|
||||
if let [alpha] = alpha {
|
||||
*alpha = channel_layout.get(1).map_or(u8::MAX, |source| preview_sample(sample(source), Dest::A));
|
||||
}
|
||||
} else {
|
||||
for (output, channel) in pixel.iter_mut().zip(&channel_layout) {
|
||||
*output = preview_sample(sample(channel), channel.0);
|
||||
}
|
||||
if psd && channel_layout.len() < component_count {
|
||||
pixel[component_count - 1] = u8::MAX;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(Some(MapPreview { width, height: rows, channels, pixels }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{TextureSet, TileGrid};
|
||||
use texturecraft_texel::{ColorSpace, DilationMap};
|
||||
|
||||
use super::rendered_map::RenderedMap;
|
||||
use super::{At, Dest, ExportInput, ExportOptions, FileFormat, Padding, Sampler, diffuse_blocks, layout, resize, scale_export_side, tile_side};
|
||||
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
|
||||
|
||||
/// Renders the output maps of one texture set's export: the padding and sampling every map shares
|
||||
pub(super) struct MapRenderer<'a> {
|
||||
options: &'a ExportOptions,
|
||||
set: &'a TextureSet,
|
||||
sampler: Sampler<'a>,
|
||||
dilation_map: Option<DilationMap>,
|
||||
grid: Option<TileGrid>,
|
||||
/// The composite's size
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Texels per atlas block (the width for a set without UV tiles)
|
||||
tile_res: u32,
|
||||
}
|
||||
|
||||
impl<'a> MapRenderer<'a> {
|
||||
pub(super) fn new(input: &ExportInput<'a>, options: &'a ExportOptions) -> Result<MapRenderer<'a>> {
|
||||
let set = input.project.texture_set(input.ts)?;
|
||||
let (width, height) = (input.composite.resolution, input.composite.height);
|
||||
let grid = set.tile_grid();
|
||||
let tile_res = width / grid.map_or(1, |g| g.cols.max(1));
|
||||
if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) {
|
||||
return Err(FormatError::Invalid(format!("composite size {width}×{height} does not fit texture set \"{}\"", set.name)));
|
||||
}
|
||||
|
||||
if input.coverage.len() as u64 != u64::from(width) * u64::from(height) {
|
||||
return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len())));
|
||||
}
|
||||
|
||||
// Padding stays inside each UV tile
|
||||
let dilation_map = match options.padding {
|
||||
Padding::None => None,
|
||||
Padding::Dilation(d) | Padding::DilationDefault(d) | Padding::DilationDiffusion(d) => {
|
||||
Some(DilationMap::in_blocks(input.coverage, width, height, Some(d), tile_res))
|
||||
}
|
||||
Padding::Infinite => Some(DilationMap::in_blocks(input.coverage, width, height, None, tile_res)),
|
||||
};
|
||||
let sampler = Sampler::new(input, options, set, tile_res, false);
|
||||
Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res })
|
||||
}
|
||||
|
||||
/// The export size of map `map_index`'s file of `tile` (None: the whole set)
|
||||
pub(super) fn size(&self, map_index: usize, tile: Option<u32>) -> Result<(u32, u32)> {
|
||||
let (_, _, w, h) = self.region(tile)?;
|
||||
|
||||
// An atlas scales by the requested size per tile
|
||||
let scale = |value| scale_export_side(value, self.tile_res, self.options.map_size(map_index));
|
||||
Ok((scale(w), scale(h)))
|
||||
}
|
||||
|
||||
/// The composite texels a file of `tile` covers: one tile, or the whole set
|
||||
fn region(&self, tile: Option<u32>) -> Result<(u32, u32, u32, u32)> {
|
||||
match (tile, self.grid) {
|
||||
(Some(t), Some(g)) => {
|
||||
let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?;
|
||||
|
||||
// A tile smaller than its block fills the block's top-left corner
|
||||
let side = tile_side(self.set, t, self.tile_res);
|
||||
Ok((bx * self.tile_res, by * self.tile_res, side, side))
|
||||
}
|
||||
_ => Ok((0, 0, self.width, self.height)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Map `map_index` of the preset for `tile`, as `format` at `bit_depth` holds it
|
||||
pub(super) fn render(&self, map_index: usize, tile: Option<u32>, format: FileFormat, bit_depth: u8) -> Result<RenderedMap> {
|
||||
let options = self.options;
|
||||
let map = options.preset.maps.get(map_index).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?;
|
||||
let channel_layout = layout(self.set, map);
|
||||
let component_count = channel_layout.len();
|
||||
let inverted: Vec<bool> = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect();
|
||||
let (x0, y0, w, h) = self.region(tile)?;
|
||||
let size = self.size(map_index, tile)?;
|
||||
let sampler = &self.sampler;
|
||||
let dilation_map = self.dilation_map.as_ref();
|
||||
let beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite);
|
||||
|
||||
let mut data = vec![0.0f32; w as usize * h as usize * component_count];
|
||||
data.par_chunks_mut(w as usize * component_count).enumerate().for_each(|(row_y, row)| {
|
||||
let y = y0 + row_y as u32;
|
||||
for (column, x) in (x0..x0 + w).enumerate() {
|
||||
let at = if sampler.covered(x, y) {
|
||||
Some(At::Texel(x, y))
|
||||
} else {
|
||||
match dilation_map.and_then(|d| d.source(x, y)) {
|
||||
Some((sx, sy)) => Some(At::Texel(sx, sy)),
|
||||
None => beyond_default.then_some(At::Default),
|
||||
}
|
||||
};
|
||||
let Some(at) = at else { continue };
|
||||
let mut cache = None;
|
||||
for (component, (_, source)) in channel_layout.iter().enumerate() {
|
||||
if let Some(value) = row.get_mut(column * component_count + component) {
|
||||
let sample = sampler.sample(source, at, &mut cache);
|
||||
*value = if inverted.get(component).copied().unwrap_or(false) { 1.0 - sample } else { sample };
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Diffuse into the texels the dilation did not reach
|
||||
if let (Padding::DilationDiffusion(_), Some(dilation)) = (options.padding, dilation_map) {
|
||||
let block = if tile.is_none() && self.grid.is_some() { self.tile_res } else { w.max(h) };
|
||||
diffuse_blocks(&mut data, (w as usize, h as usize), component_count, dilation, (x0 as usize, y0 as usize), block as usize);
|
||||
}
|
||||
|
||||
let mut data = resize(data, (w, h), component_count, size);
|
||||
|
||||
// Integer sRGB converts in `encode`; other color spaces convert here
|
||||
let space = options.space_for_map(map, format, bit_depth);
|
||||
let float = format.holds_float(bit_depth);
|
||||
let convert = (space != ColorSpace::Srgb || float) && space != ColorSpace::LinearRec709;
|
||||
if convert {
|
||||
data.par_chunks_mut(component_count).for_each(|px| {
|
||||
if let [r, g, b, ..] = px {
|
||||
[*r, *g, *b] = space.from_linear_rec709([*r, *g, *b]);
|
||||
}
|
||||
});
|
||||
}
|
||||
let srgb = channel_layout.iter().map(|(d, _)| *d != Dest::A && !float && space == ColorSpace::Srgb).collect();
|
||||
|
||||
// A colour space the user chose is written into the colour maps (data maps have none)
|
||||
let embed = (options.color_space.is_some() && map.is_color() && component_count >= 3).then_some(space);
|
||||
Ok(RenderedMap { data, size, component_count, srgb, embed })
|
||||
}
|
||||
}
|
||||
+557
-307
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
/// An output map written as a layer of a texture set's PSD (see [`super::list_outputs`])
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PlannedLayer {
|
||||
/// Index into the preset's maps
|
||||
pub map: usize,
|
||||
/// The map's file name, a `/` separating the groups the layer sits in
|
||||
pub name: String,
|
||||
/// 8-bit samples written with dithering
|
||||
pub dither: bool,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/// The memory limits PSD planning holds an export to: a browser tab's address space needs them, a native export renders one layer at a time without them
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct PsdBudget {
|
||||
/// Pixel buffers of one document, including the renderer's padding and encoder
|
||||
pub(super) working_bytes: Option<u64>,
|
||||
/// Encoded documents one batch holds in memory, with headroom for a document's working buffers and ZIP packaging
|
||||
pub(super) batch_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
impl PsdBudget {
|
||||
/// A browser tab's: the export and the app share its 4 GiB address space
|
||||
pub(super) const WEB: Self = Self { working_bytes: Some(2 * 1024 * 1024 * 1024), batch_bytes: Some(1024 * 1024 * 1024) };
|
||||
/// A desktop export's: the machine bounds it, as it does every other file type
|
||||
pub(super) const NATIVE: Self = Self { working_bytes: None, batch_bytes: None };
|
||||
/// The budget of the platform this build runs on
|
||||
pub(super) const TARGET: Self = if cfg!(target_arch = "wasm32") { Self::WEB } else { Self::NATIVE };
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use texturecraft_texel::ColorSpace;
|
||||
|
||||
/// One output map's linear samples at its export size, ready to encode
|
||||
pub(super) struct RenderedMap {
|
||||
/// Interleaved L, LA, RGB or RGBA samples
|
||||
pub data: Vec<f32>,
|
||||
pub size: (u32, u32),
|
||||
pub component_count: usize,
|
||||
/// Per component: whether encoding applies the sRGB transfer
|
||||
pub srgb: Vec<bool>,
|
||||
/// The colour space recorded in the file, when the user chose one for a colour map
|
||||
pub embed: Option<ColorSpace>,
|
||||
}
|
||||
@@ -373,6 +373,7 @@ fn every_format_encodes_and_decodes() {
|
||||
opts.format_override = Some(format);
|
||||
opts.bit_depth_override = Some(depth);
|
||||
let files = fx.render(&opts);
|
||||
|
||||
assert_eq!(files.len(), 4, "{format:?}");
|
||||
for f in &files {
|
||||
assert!(f.name.ends_with(format.extension()));
|
||||
@@ -385,6 +386,7 @@ fn every_format_encodes_and_decodes() {
|
||||
|
||||
// Roughness 0.25 everywhere survives every format (JPEG within its loss)
|
||||
let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1];
|
||||
|
||||
assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}");
|
||||
let base = find(&files, "_BaseColor.");
|
||||
match format {
|
||||
@@ -555,6 +557,34 @@ fn gray_map(file: &str, src: SourceRef) -> MapSpec {
|
||||
MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_output_with_its_own_size_keeps_it() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let preset = ExportPreset {
|
||||
name: "sizes".into(),
|
||||
maps: vec![
|
||||
gray_map("small", SourceRef::Channel { channel: Channel::Roughness, component: 0 }),
|
||||
gray_map("set_size", SourceRef::Channel { channel: Channel::Metallic, component: 0 }),
|
||||
],
|
||||
};
|
||||
let mut options = ExportOptions::new(preset);
|
||||
options.maps.insert(0, MapOverride { size: Some(32), ..MapOverride::default() });
|
||||
|
||||
for (export_size, other) in [(None, RES), (Some(128), 128)] {
|
||||
let files = fx.render(&ExportOptions { size: export_size, ..options.clone() });
|
||||
|
||||
assert_eq!(find(&files, "small.png").width, 32, "its own size wins over {export_size:?}");
|
||||
assert_eq!(find(&files, "set_size.png").width, other);
|
||||
}
|
||||
|
||||
// A PSD is as large as its largest layer
|
||||
options.format_override = Some(FileFormat::Psd);
|
||||
assert_eq!(fx.render(&options)[0].width, RES);
|
||||
|
||||
options.maps.insert(0, MapOverride { size: Some(100), ..MapOverride::default() });
|
||||
assert!(list_outputs(&fx.project, 0, "sphere", &options).is_err(), "a size that isn't a power of two is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_rejects_bad_presets() {
|
||||
let ok = ExportPreset { name: "Mine".into(), maps: vec![gray_map("$mesh_$textureSet_$channel ($colorSpace) $project", SourceRef::Constant(1.0))] };
|
||||
@@ -729,6 +759,9 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() {
|
||||
|
||||
// A folder stays in the placeholder name
|
||||
assert_eq!(udim_names("Base/$textureSet_$udim".into()), [Some("Base/Body_<UDIM>.png".to_string()), Some("Base/Body_<UDIM>.png".to_string())]);
|
||||
|
||||
// A name without the token gets the tile as a suffix, and so does its placeholder
|
||||
assert_eq!(udim_names("$textureSet".into()), [Some("Body.<UDIM>.png".to_string()), Some("Body.<UDIM>.png".to_string())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1121,45 +1154,121 @@ fn pgm_is_a_binary_graymap() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_holds_the_merged_image_planar() {
|
||||
fn psd_holds_every_map_as_a_layer_over_their_merged_image() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let f = &fx.render(&one_map(FileFormat::Psd, 8, rgba_half_alpha()))[0];
|
||||
let b = &f.bytes;
|
||||
assert_eq!(&b[0..4], b"8BPS");
|
||||
assert_eq!(u16::from_be_bytes([b[12], b[13]]), 4, "channels");
|
||||
assert_eq!((u32::from_be_bytes(b[14..18].try_into().unwrap()), u32::from_be_bytes(b[18..22].try_into().unwrap())), (64, 64));
|
||||
assert_eq!((u16::from_be_bytes([b[22], b[23]]), u16::from_be_bytes([b[24], b[25]])), (8, 3), "8-bit RGB");
|
||||
let parsed = craft_psd::PsdFile::from_bytes(b).unwrap();
|
||||
assert!(!parsed.merged_has_alpha());
|
||||
assert_eq!(parsed.alpha_channel_names(), ["Alpha"]);
|
||||
let samples = parsed.decode_merged().unwrap();
|
||||
assert_eq!(samples.len(), 4 * 64 * 64);
|
||||
let plane = |c: usize| &samples[c * 64 * 64..(c + 1) * 64 * 64];
|
||||
assert!(plane(3).iter().all(|a| *a == 128), "alpha plane");
|
||||
let png = decode(&fx.render(&one_map(FileFormat::Png, 8, rgba_half_alpha()))[0]).to_rgba8();
|
||||
assert_eq!(plane(0)[64 * 10 + 40], png.get_pixel(40, 10)[0], "the red plane holds the same values as a PNG");
|
||||
let mut png_options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap());
|
||||
png_options.bit_depth_override = Some(8);
|
||||
let pngs = fx.render(&png_options);
|
||||
let mut options = png_options.clone();
|
||||
options.format_override = Some(FileFormat::Psd);
|
||||
|
||||
let f16 = &fx.render(&one_map(FileFormat::Psd, 16, roughness()))[0];
|
||||
assert_eq!((u16::from_be_bytes([f16.bytes[12], f16.bytes[13]]), u16::from_be_bytes([f16.bytes[22], f16.bytes[23]])), (1, 16));
|
||||
assert_eq!(f16.bytes.len(), 26 + 12 + 2 + 2 * 64 * 64);
|
||||
let planned = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
let files = fx.render(&options);
|
||||
|
||||
let mut gray_alpha = roughness();
|
||||
gray_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
let f16 = &fx.render(&one_map(FileFormat::Psd, 16, gray_alpha))[0];
|
||||
let parsed = craft_psd::PsdFile::from_bytes(&f16.bytes).unwrap();
|
||||
assert!(!parsed.merged_has_alpha());
|
||||
assert_eq!(parsed.alpha_channel_names(), ["Alpha"]);
|
||||
let samples = parsed.decode_merged().unwrap();
|
||||
assert_eq!(samples.len(), 2 * 2 * 64 * 64);
|
||||
assert!(samples[2 * 64 * 64..].as_chunks::<2>().0.iter().all(|sample| *sample == [128, 0]));
|
||||
assert_eq!(planned.len(), 1, "one PSD for the texture set: {planned:?}");
|
||||
assert_eq!(planned[0].layers.len(), pngs.len());
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].name, "sphere_Body_Set.psd");
|
||||
let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap();
|
||||
let layers: Vec<_> = parsed.iter_layers().collect();
|
||||
|
||||
assert_eq!(layers.len(), pngs.len());
|
||||
|
||||
// The file stacks bottom up, so the first map is the top layer
|
||||
for (layer, png) in layers.iter().rev().zip(&pngs) {
|
||||
assert_eq!(format!("{}.png", layer.name()), png.name);
|
||||
assert_eq!(layer.rgba8().unwrap().data, decode(png).to_rgba8().into_raw(), "{}: the layer holds the map's texels", png.name);
|
||||
}
|
||||
let top = layers.last().unwrap().rgba8().unwrap().data;
|
||||
|
||||
assert!(top.as_chunks::<4>().0.iter().all(|texel| texel[3] == u8::MAX), "the base colour is opaque");
|
||||
assert_eq!(parsed.composite_rgba8().unwrap().data, top, "the merged image shows the opaque top layer");
|
||||
|
||||
options.bit_depth_override = Some(16);
|
||||
let deep = &fx.render(&options)[0];
|
||||
|
||||
assert_eq!(craft_psd::PsdFile::from_bytes(&deep.bytes).unwrap().header.depth, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_keeps_small_layers_at_the_requested_size() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap());
|
||||
options.format_override = Some(FileFormat::Psd);
|
||||
options.bit_depth_override = Some(8);
|
||||
options.maps.insert(0, MapOverride { size: Some(RES / 2), ..Default::default() });
|
||||
options.maps.insert(1, MapOverride { size: Some(RES / 4), ..Default::default() });
|
||||
|
||||
let files = fx.render(&options);
|
||||
let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap();
|
||||
let layers: Vec<_> = psd.iter_layers().map(|layer| layer.rgba8().unwrap()).collect();
|
||||
let merged = psd.composite_rgba8().unwrap();
|
||||
|
||||
assert_eq!((merged.width, merged.height), (RES, RES));
|
||||
assert_eq!(layers.iter().map(|layer| (layer.width, layer.height)).collect::<Vec<_>>(), [(RES, RES), (RES / 4, RES / 4), (RES / 2, RES / 2)]);
|
||||
let pixel = |x: u32, y: u32| ((y * RES + x) * 4) as usize;
|
||||
|
||||
assert_eq!(&merged.data[..4], &layers[2].data[..4]);
|
||||
let outside_top_layers = pixel(RES - 1, 0);
|
||||
|
||||
assert_eq!(&merged.data[outside_top_layers..outside_top_layers + 4], &layers[0].data[outside_top_layers..outside_top_layers + 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_folder_templates_become_layer_groups_of_one_file_not_folders() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let rough = |file: &str| gray_map(file, SourceRef::Channel { channel: Channel::Roughness, component: 0 });
|
||||
let preset = ExportPreset { name: "t".into(), maps: vec![rough("Body/$textureSet_Rough"), rough("Top/Inner/Leaf"), rough("Mask")] };
|
||||
let mut options = ExportOptions::new(preset);
|
||||
options.format_override = Some(FileFormat::Psd);
|
||||
|
||||
let files = fx.render(&options);
|
||||
|
||||
assert_eq!(files.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(), ["sphere_Body_Set.psd"], "no folder for a PSD's layers");
|
||||
let parsed = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap();
|
||||
let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name();
|
||||
let tree = parsed.layer_tree();
|
||||
|
||||
// The tree lists bottom up and the first map is the top layer
|
||||
let groups: Vec<_> = tree.iter().rev().filter(|node| node.is_group()).map(name).collect();
|
||||
|
||||
assert_eq!(groups, ["Body", "Top"]);
|
||||
let body = tree.iter().find(|node| node.is_group() && name(node) == "Body").unwrap();
|
||||
|
||||
assert_eq!(body.children().iter().map(name).collect::<Vec<_>>(), ["Body_Set_Rough"], "$textureSet is filled in inside a layer name");
|
||||
assert!(tree.iter().any(|node| !node.is_group() && name(node) == "Mask"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_layer_groups_follow_the_slashes_of_their_names() {
|
||||
let pixel = || craft_psd::PixelData::Rgba8(vec![10, 20, 30, 255]);
|
||||
let layers = ["Mask", "Body/Rough", "Body/Color", "Top/Inner/Leaf"].into_iter().map(|name| (name, (1, 1), pixel())).collect();
|
||||
|
||||
let bytes = layered_psd::write_layers((1, 1), 8, layers, pixel()).unwrap();
|
||||
|
||||
let parsed = craft_psd::PsdFile::from_bytes(&bytes).unwrap();
|
||||
let name = |node: &craft_psd::tree::LayerNode| parsed.layer(node.index()).unwrap().name();
|
||||
let tree = parsed.layer_tree();
|
||||
|
||||
assert_eq!(
|
||||
tree.iter().map(|node| (name(node), node.is_group())).collect::<Vec<_>>(),
|
||||
[("Mask".to_string(), false), ("Body".to_string(), true), ("Top".to_string(), true)]
|
||||
);
|
||||
assert_eq!(tree[1].children().iter().map(name).collect::<Vec<_>>(), ["Rough", "Color"]);
|
||||
let inner = &tree[2].children()[0];
|
||||
|
||||
assert!(inner.is_group() && name(inner) == "Inner");
|
||||
assert_eq!(inner.children().iter().map(name).collect::<Vec<_>>(), ["Leaf"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1002];
|
||||
|
||||
// Eight tile columns make a 32768-wide atlas while the individual PSDs stay within budget
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1008];
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
options.size = Some(16_384);
|
||||
options.size = Some(4096);
|
||||
options.atlas = true;
|
||||
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
@@ -1170,7 +1279,123 @@ fn psd_plan_rejects_a_version_one_atlas_over_its_dimension_limit() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() {
|
||||
fn psd_plan_preserves_each_udim_suffix_after_truncating_the_stem() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1002];
|
||||
let options = one_map(FileFormat::Psd, 8, roughness());
|
||||
let mesh_name = "a".repeat(MAX_STEM);
|
||||
|
||||
let plan = list_outputs(&fx.project, 0, &mesh_name, &options).unwrap();
|
||||
|
||||
assert_eq!(plan.len(), 2);
|
||||
for (file, tile) in plan.iter().zip([1001, 1002]) {
|
||||
assert!(file.name.ends_with(&format!(".{tile}.psd")), "{}", file.name);
|
||||
assert_eq!(file.udim_name.as_ref().unwrap().replace("<UDIM>", &tile.to_string()), file.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_long_mesh_names_keep_distinct_texture_sets_and_tiles() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1002];
|
||||
let mut trim = fx.project.texture_sets[0].clone();
|
||||
trim.name = "Trim".into();
|
||||
fx.project.texture_sets.push(trim);
|
||||
let options = one_map(FileFormat::Psd, 8, roughness());
|
||||
|
||||
let plan = list_set_outputs(&fx.project, &[0, 1], &"m".repeat(MAX_STEM), &options).unwrap();
|
||||
|
||||
assert_eq!(plan.len(), 4, "both tiles of both sets must survive deduplication");
|
||||
for (set, file) in plan {
|
||||
let tile = file.tile.unwrap();
|
||||
let set_name = sanitize_file_stem(&fx.project.texture_sets[set].name);
|
||||
assert!(file.name.contains(&set_name), "{}", file.name);
|
||||
assert!(file.name.ends_with(&format!(".{tile}.psd")), "{}", file.name);
|
||||
assert_eq!(file.udim_name.unwrap().replace("<UDIM>", &tile.to_string()), file.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_reserved_export_stem_remains_bounded_and_idempotent() {
|
||||
let raw = format!("CON.{}", "x".repeat(MAX_STEM));
|
||||
|
||||
let sanitized = sanitize_file_stem(&raw);
|
||||
|
||||
assert!(sanitized.starts_with("_CON."));
|
||||
assert!(sanitized.len() <= MAX_STEM, "{} bytes", sanitized.len());
|
||||
assert_eq!(sanitize_file_stem(&sanitized), sanitized);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_dithering_tracks_the_document_depth() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
options.dither = true;
|
||||
let mut second = options.preset.maps[0].clone();
|
||||
second.file = "second".into();
|
||||
options.preset.maps.push(second);
|
||||
options.maps.insert(1, MapOverride { dither: Some(false), ..MapOverride::default() });
|
||||
|
||||
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
assert!(plan[0].dither && plan[0].layers[0].dither && !plan[0].layers[1].dither);
|
||||
|
||||
options.preset.maps[1].bit_depth = 16;
|
||||
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
|
||||
assert_eq!(plan[0].bit_depth, 16);
|
||||
assert!(!plan[0].dither && plan[0].layers.iter().all(|layer| !layer.dither));
|
||||
assert!(plan[0].warnings.iter().any(|warning| warning.contains("dithering") && warning.contains("16-bit")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_rejects_large_working_set_during_planning() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Psd, 8, rgba_half_alpha());
|
||||
options.size = Some(8192);
|
||||
|
||||
let error = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("working memory"), "{error}");
|
||||
options.size = Some(4096);
|
||||
assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_native_export_plans_psds_a_browser_tab_cannot_hold() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
let mut one = one_map(FileFormat::Psd, 8, rgba_half_alpha());
|
||||
one.size = Some(MAX_IMAGE_SIZE / 2);
|
||||
let mut separate = ExportOptions::new(builtin_preset("Separate maps").unwrap());
|
||||
separate.format_override = Some(FileFormat::Psd);
|
||||
separate.size = Some(4096);
|
||||
fx.project.texture_sets[0].uv_tiles = (1001..1005).collect();
|
||||
|
||||
let plans = [list_outputs(&fx.project, 0, "sphere", &one), list_outputs(&fx.project, 0, "sphere", &separate)];
|
||||
|
||||
for plan in plans {
|
||||
let plan = plan.unwrap();
|
||||
assert!(!plan.is_empty() && plan.iter().all(|file| file.format == FileFormat::Psd), "{plan:?}");
|
||||
}
|
||||
assert!(list_set_outputs(&fx.project, &[0], "sphere", &separate).is_ok(), "a desktop batch holds every tile's PSD");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_psd_that_cannot_be_planned_leaves_the_sets_other_maps() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Png, 8, roughness());
|
||||
let mut psd = options.preset.maps[0].clone();
|
||||
(psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 16, rgba_half_alpha());
|
||||
options.preset.maps.push(psd);
|
||||
options.size = Some(MAX_IMAGE_SIZE);
|
||||
|
||||
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
|
||||
assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}");
|
||||
assert!(plan[0].warnings.iter().any(|warning| warning.contains(".psd") && warning.contains("2 GiB")), "{:?}", plan[0].warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_plan_counts_every_layer_against_the_version_one_byte_limit() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Psd, 16, rgba_half_alpha());
|
||||
options.size = Some(16_384);
|
||||
@@ -1178,19 +1403,26 @@ fn psd_plan_rejects_a_file_over_the_version_one_byte_limit() {
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("PSD") && error.to_string().contains("2 GiB"), "{error}");
|
||||
options.bit_depth_override = Some(8);
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1);
|
||||
options.bit_depth_override = None;
|
||||
options.preset.maps[0].channels.pop();
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1);
|
||||
options.size = Some(8192);
|
||||
let layer_size = (8192, 8192);
|
||||
for copy in ["second", "third"] {
|
||||
assert!(check_psd_size(std::iter::repeat_n(layer_size, options.preset.maps.len()), 0, 16).is_ok());
|
||||
let mut map = options.preset.maps[0].clone();
|
||||
map.file = copy.into();
|
||||
options.preset.maps.push(map);
|
||||
}
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("3 maps") && error.to_string().contains("2 GiB"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() {
|
||||
// These RGBA16 planes are 32 bytes below 2 GiB before headers and the alpha name
|
||||
let (width, height) = (10_924, 24_573);
|
||||
assert!(check_psd_size((width, height), 4, 16).is_err());
|
||||
assert!(check_psd_size((width, height - 1), 4, 16).is_ok());
|
||||
fn psd_byte_limit_includes_the_merged_image_and_keeps_separate_tiles_valid() {
|
||||
// One RGBA16 layer and the merged image: 87360 bytes over 2 GiB, a row less 87424 bytes below
|
||||
let (width, height) = (10_924, 12_287);
|
||||
|
||||
assert!(check_psd_size([(width, height)], 0, 16).is_err());
|
||||
assert!(check_psd_size([(width, height - 1)], 0, 16).is_ok());
|
||||
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011];
|
||||
@@ -1201,10 +1433,25 @@ fn psd_byte_limit_includes_resources_and_keeps_separate_tiles_valid() {
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("2 GiB"), "{error}");
|
||||
options.size = Some(4096);
|
||||
assert!(plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap_err().to_string().contains("working memory"));
|
||||
options.atlas = false;
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_rejects_a_composite_with_a_different_size_from_the_plan() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
let source_size = RES * 2;
|
||||
fx.comp = Composite::new(&default_channels(), source_size);
|
||||
fx.coverage.resize((source_size * source_size) as usize, true);
|
||||
let options = one_map(FileFormat::Psd, 8, roughness());
|
||||
|
||||
let error = render_maps(&fx.input(), &options).unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("does not match the planned texture set size"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jng_has_jpeg_colour_and_lossless_alpha() {
|
||||
use std::io::Read;
|
||||
@@ -1576,6 +1823,527 @@ fn write_files_accepts_a_long_nested_folder_and_stem() {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_preview_bounds_the_longer_side_of_a_tall_atlas() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1031];
|
||||
fx.comp = Composite::with_size(&default_channels(), RES, RES * 4);
|
||||
fx.coverage.resize((RES * RES * 4) as usize, true);
|
||||
let options = one_map(FileFormat::Png, 8, roughness());
|
||||
let max_side = 32;
|
||||
|
||||
let preview = MapPreview::sample(&fx.input(), &options, 0, max_side).unwrap().unwrap();
|
||||
|
||||
assert_eq!(preview.height, max_side);
|
||||
assert_eq!(preview.width * 4, preview.height);
|
||||
assert_eq!(preview.pixels.len(), (preview.width * preview.height) as usize);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_preview_is_no_larger_than_the_maps_own_size() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Png, 8, roughness());
|
||||
let own = RES / 4;
|
||||
options.maps.insert(0, MapOverride { size: Some(own), ..MapOverride::default() });
|
||||
let file = decode(&fx.render(&options)[0]);
|
||||
|
||||
let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap();
|
||||
|
||||
assert_eq!((preview.width, preview.height), file.dimensions(), "the preview shows the file at its own size");
|
||||
options.size = Some(RES / 2);
|
||||
options.maps.clear();
|
||||
let export_sized = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap();
|
||||
|
||||
assert!(export_sized.width > preview.width && export_sized.width < RES, "the export size bounds a map without its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_preview_holds_the_values_its_file_stores() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.set_all(Channel::Metallic, |x, _| [x as f32 / 63.0; 3]);
|
||||
fx.set_all(Channel::Roughness, |_, y| [y as f32 / 63.0; 3]);
|
||||
let mut options = ExportOptions::new(builtin_preset("Unity HDRP (Mask Map)").unwrap());
|
||||
let mask = options.preset.maps.iter().position(|map| map.file.contains("MaskMap")).unwrap();
|
||||
let base = options.preset.maps.iter().position(|map| map.file.contains("BaseMap")).unwrap();
|
||||
options.preset.maps[mask].inverted.push(Dest::R);
|
||||
let files = fx.render(&options);
|
||||
|
||||
// The packed data map, one channel inverted, and the sRGB colour map
|
||||
for (index, suffix) in [(mask, "MaskMap"), (base, "BaseMap")] {
|
||||
let file = decode(find(&files, suffix));
|
||||
let preview = MapPreview::sample(&fx.input(), &options, index, RES).unwrap().unwrap();
|
||||
|
||||
assert_eq!((preview.width, preview.height), file.dimensions());
|
||||
assert_eq!(preview.channels.len(), usize::from(file.color().channel_count()), "{suffix}");
|
||||
assert!(preview.pixels == file.into_bytes(), "{suffix}: the preview shows what the file stores");
|
||||
}
|
||||
|
||||
let small = MapPreview::sample(&fx.input(), &options, mask, 8).unwrap().unwrap();
|
||||
|
||||
assert!(small.width < RES && small.pixels.len() == (small.width * small.height) as usize * 4, "a smaller preview samples the same map");
|
||||
assert!(MapPreview::sample(&fx.input(), &options, options.preset.maps.len(), 8).is_err(), "a map the template doesn't have is an error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_jpeg_previews_omit_the_alpha_channel() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut la = roughness();
|
||||
la.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
for (channels, expected) in [(la, vec![Dest::L]), (rgba_half_alpha(), vec![Dest::R, Dest::G, Dest::B])] {
|
||||
let mut options = one_map(FileFormat::Png, 8, channels);
|
||||
let png_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap();
|
||||
options.maps.insert(0, MapOverride { format: Some(FileFormat::Jpeg), ..MapOverride::default() });
|
||||
|
||||
let jpeg_preview = MapPreview::sample(&fx.input(), &options, 0, 16).unwrap().unwrap();
|
||||
let jpeg = decode(&fx.render(&options)[0]);
|
||||
|
||||
assert_eq!(jpeg_preview.channels, expected);
|
||||
assert_eq!(jpeg_preview.channels.len(), usize::from(jpeg.color().channel_count()));
|
||||
let colors: Vec<_> = png_preview.pixels.chunks_exact(png_preview.channels.len()).flat_map(|pixel| pixel[..expected.len()].iter().copied()).collect();
|
||||
assert_eq!(jpeg_preview.pixels, colors);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_preview_matches_the_exported_channels_and_samples() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut gray_alpha = roughness();
|
||||
gray_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
let mut rgb = rgba_half_alpha();
|
||||
rgb.retain(|(dest, _)| *dest != Dest::A);
|
||||
|
||||
for (layout, expected) in
|
||||
[(roughness(), &[Dest::R, Dest::G, Dest::B][..]), (gray_alpha, &[Dest::R, Dest::G, Dest::B, Dest::A][..]), (rgb, &[Dest::R, Dest::G, Dest::B][..])]
|
||||
{
|
||||
let options = one_map(FileFormat::Webp, 8, layout);
|
||||
|
||||
let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap();
|
||||
let image = decode(&fx.render(&options)[0]);
|
||||
|
||||
assert_eq!(preview.channels, expected);
|
||||
assert_eq!(preview.channels.len(), usize::from(image.color().channel_count()));
|
||||
assert_eq!(preview.pixels, image.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pgm_preview_shows_exported_luminance_without_alpha() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut gray_with_alpha = roughness();
|
||||
gray_with_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
|
||||
for channels in [gray_with_alpha, rgba_half_alpha()] {
|
||||
let mut options = one_map(FileFormat::Png, 8, channels);
|
||||
options.maps.insert(0, MapOverride { format: Some(FileFormat::Pgm), ..MapOverride::default() });
|
||||
|
||||
let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap();
|
||||
let files = fx.render(&options);
|
||||
let pgm_samples = files[0].bytes.strip_prefix(b"P5\n64 64\n255\n").unwrap();
|
||||
|
||||
assert_eq!(preview.channels, [Dest::L]);
|
||||
assert_eq!(preview.pixels, pgm_samples);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdr_and_tiff_previews_show_channels_written_by_the_encoder() {
|
||||
let fx = Fx::new(&default_channels());
|
||||
let mut gray_with_alpha = roughness();
|
||||
gray_with_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
let rgb = [Dest::R, Dest::G, Dest::B];
|
||||
let rgba = [Dest::R, Dest::G, Dest::B, Dest::A];
|
||||
|
||||
for (format, depth, layout, expected) in [
|
||||
(FileFormat::Hdr, 32, &gray_with_alpha, rgb.as_slice()),
|
||||
(FileFormat::Hdr, 32, &rgba_half_alpha(), rgb.as_slice()),
|
||||
(FileFormat::Tiff, 8, &gray_with_alpha, rgba.as_slice()),
|
||||
(FileFormat::Tiff, 32, &gray_with_alpha, rgba.as_slice()),
|
||||
(FileFormat::Tiff, 32, &roughness(), rgb.as_slice()),
|
||||
] {
|
||||
let mut options = one_map(format, depth, layout.clone());
|
||||
if layout[0].0 == Dest::L {
|
||||
options.preset.maps[0].inverted.push(Dest::L);
|
||||
}
|
||||
|
||||
let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap();
|
||||
let file = decode(&fx.render(&options)[0]);
|
||||
let components = usize::from(file.color().channel_count());
|
||||
|
||||
assert_eq!(preview.channels, expected, "{format:?} at {depth} bits");
|
||||
assert_eq!(preview.channels.len(), components);
|
||||
assert_eq!(preview.pixels.len(), (file.width() * file.height()) as usize * components);
|
||||
let decoded_pixels = file.to_rgba32f();
|
||||
for (preview_pixel, decoded) in preview.pixels.chunks_exact(components).zip(decoded_pixels.pixels()) {
|
||||
for (actual, sample) in preview_pixel.iter().zip(decoded.0) {
|
||||
let value = if options.preset.maps[0].is_color() && format == FileFormat::Hdr { linear_to_srgb(sample) } else { sample };
|
||||
assert!((i32::from(*actual) - byte(value)).abs() <= 2, "{format:?} at {depth} bits: {actual} vs {value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangle_coverage_preserves_uncovered_texels_and_height_normal_neighbours_in_previews() {
|
||||
let mut fixture = Fx::new(&default_channels());
|
||||
fixture.set_all(Channel::Height, |x, y| [(x + y) as f32 / RES as f32; 3]);
|
||||
for (index, covered) in fixture.coverage.iter_mut().enumerate() {
|
||||
*covered = index % 3 != 0;
|
||||
}
|
||||
let triangles: Vec<_> = fixture.coverage.iter().map(|covered| if *covered { 0 } else { texturecraft_geom::NO_TRI }).collect();
|
||||
let input = fixture.input();
|
||||
let triangle_input =
|
||||
ExportInput { project: input.project, ts: input.ts, composite: input.composite, baked: input.baked, coverage: &triangles, mesh_name: input.mesh_name };
|
||||
let options = ExportOptions::new(builtin_preset("glTF PBR Metal Roughness").unwrap());
|
||||
|
||||
for map in 0..3 {
|
||||
let expected = MapPreview::sample(&input, &options, map, RES).unwrap().unwrap();
|
||||
let actual = MapPreview::sample_triangles(&triangle_input, &options, map, RES).unwrap().unwrap();
|
||||
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tilts every normal of `fx` and returns the green byte an OpenGL normal map stores for it
|
||||
fn tilt_normals(fx: &mut Fx) -> i32 {
|
||||
let tilt = Vec3::new(0.3, 0.4, 0.0);
|
||||
let tilt = Vec3::new(tilt.x, tilt.y, (1.0 - tilt.length_squared()).sqrt());
|
||||
fx.set_all(Channel::Normal, |_, _| (tilt * 0.5 + Vec3::splat(0.5)).to_array());
|
||||
byte(tilt.y * 0.5 + 0.5)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unreal_subsurface_template_writes_the_scatter_mask_beside_the_packed_maps() {
|
||||
let mut channels = default_channels();
|
||||
channels.extend([Channel::AmbientOcclusion, Channel::Opacity, Channel::ScatterWeight]);
|
||||
let mut fx = Fx::new(&channels);
|
||||
fx.set_all(Channel::AmbientOcclusion, |_, _| [0.6; 3]);
|
||||
fx.set_all(Channel::Roughness, |_, _| [0.4; 3]);
|
||||
fx.set_all(Channel::Metallic, |_, _| [0.8; 3]);
|
||||
fx.set_all(Channel::Opacity, |_, _| [0.9; 3]);
|
||||
fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]);
|
||||
let open_gl_green = tilt_normals(&mut fx);
|
||||
|
||||
let files = fx.render_preset("Unreal Engine Subsurface Profile (Packed)");
|
||||
|
||||
let mask = find(&files, "_SubsurfaceMask.png");
|
||||
|
||||
assert_eq!(decode(mask).color(), image::ColorType::L8, "the mask is one 8-bit channel");
|
||||
assert_close(pixel(mask), [byte(0.7), byte(0.7), byte(0.7), 255], "scatter weight in the mask");
|
||||
let [r, g, b, _] = pixel(find(&files, "_OcclusionRoughnessMetallic.png"));
|
||||
assert_close([r, g, b, 0], [byte(0.6), byte(0.4), byte(0.8), 0], "R occlusion, G roughness, B metallic");
|
||||
assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "opacity feeds the mask, not the base color's alpha");
|
||||
let green = pixel(find(&files, "_Normal.png"))[1];
|
||||
|
||||
assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gltf_specular_glossiness_template_packs_a_specular_glossiness_sets_own_channels() {
|
||||
let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::Normal, Channel::Height, Channel::Opacity]);
|
||||
let specular = [0.2, 0.5, 0.8];
|
||||
fx.set_all(Channel::Specular, |_, _| specular);
|
||||
fx.set_all(Channel::Glossiness, |_, _| [0.3; 3]);
|
||||
fx.set_all(Channel::Opacity, |_, _| [0.9; 3]);
|
||||
let open_gl_green = tilt_normals(&mut fx);
|
||||
|
||||
let files = fx.render_preset("glTF Specular Glossiness (archived extension)");
|
||||
|
||||
let specular_glossiness = find(&files, "_SpecularGlossiness.png");
|
||||
|
||||
assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8);
|
||||
let srgb = specular.map(|v| byte(linear_to_srgb(v)));
|
||||
assert_close(pixel(specular_glossiness), [srgb[0], srgb[1], srgb[2], byte(0.3)], "sRGB specular, linear glossiness in alpha");
|
||||
let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v)));
|
||||
assert_close(pixel(find(&files, "_Diffuse.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB diffuse, opacity in alpha");
|
||||
let green = pixel(find(&files, "_Normal.png"))[1];
|
||||
|
||||
assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_gltf_specular_glossiness_file_is_rgba_and_fully_glossy_without_a_glossiness_channel() {
|
||||
let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Normal]);
|
||||
fx.set_all(Channel::Specular, |_, _| [0.2, 0.5, 0.8]);
|
||||
|
||||
let files = fx.render_preset("glTF Specular Glossiness (archived extension)");
|
||||
|
||||
let specular_glossiness = find(&files, "_SpecularGlossiness.png");
|
||||
assert_eq!(decode(specular_glossiness).color(), image::ColorType::Rgba8, "the extension reads glossiness from alpha");
|
||||
assert_eq!(pixel(specular_glossiness)[3], 255, "glossinessFactor defaults to 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_redshift_template_writes_one_map_per_input_the_set_has() {
|
||||
let mut channels = default_channels();
|
||||
channels.extend([Channel::ScatterWeight, Channel::CoatWeight]);
|
||||
let mut fx = Fx::new(&channels);
|
||||
fx.set_all(Channel::Roughness, |_, _| [0.4; 3]);
|
||||
fx.set_all(Channel::Metallic, |_, _| [0.8; 3]);
|
||||
fx.set_all(Channel::ScatterWeight, |_, _| [0.7; 3]);
|
||||
fx.set_all(Channel::CoatWeight, |_, _| [0.2; 3]);
|
||||
let open_gl_green = tilt_normals(&mut fx);
|
||||
|
||||
let files = fx.render_preset("Redshift Standard Material (separate maps)");
|
||||
|
||||
let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
|
||||
for (input, expected) in [("Metalness", 0.8), ("ReflectionRoughness", 0.4), ("SubsurfaceWeight", 0.7), ("CoatWeight", 0.2)] {
|
||||
let file = find(&files, &format!("_{input}.png"));
|
||||
|
||||
assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is one 8-bit channel: {names:?}");
|
||||
assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input);
|
||||
}
|
||||
let green = pixel(find(&files, "_Normal.png"))[1];
|
||||
|
||||
assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}");
|
||||
assert!(!names.iter().any(|name| name.contains("Sheen") || name.contains("CoatRoughness")), "inputs the set lacks write no maps: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_roblox_template_writes_opacity_in_the_colour_alpha_and_opengl_normals() {
|
||||
let mut fx = packing_fixture();
|
||||
let open_gl_green = tilt_normals(&mut fx);
|
||||
|
||||
let files = fx.render_preset("Roblox SurfaceAppearance (separate maps)");
|
||||
|
||||
let base = fx.comp.value(Channel::BaseColor, 3, 3).map(|v| byte(linear_to_srgb(v)));
|
||||
assert_close(pixel(find(&files, "_Color.png")), [base[0], base[1], base[2], byte(0.9)], "sRGB colour, opacity in alpha");
|
||||
for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4)] {
|
||||
let file = find(&files, &format!("_{input}.png"));
|
||||
|
||||
assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is grayscale");
|
||||
assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input);
|
||||
}
|
||||
let green = pixel(find(&files, "_Normal.png"))[1];
|
||||
|
||||
assert!((green - open_gl_green).abs() <= 1, "OpenGL normal: green {green}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sketchfab_template_writes_directx_normals_and_one_map_per_channel() {
|
||||
let mut fx = packing_fixture();
|
||||
let open_gl_green = tilt_normals(&mut fx);
|
||||
|
||||
let files = fx.render_preset("Sketchfab Metalness (separate maps)");
|
||||
|
||||
assert_eq!(decode(find(&files, "_BaseColor.png")).color(), image::ColorType::Rgb8, "no alpha on the base color");
|
||||
for (input, expected) in [("Metalness", 0.8), ("Roughness", 0.4), ("AmbientOcclusion", 0.6)] {
|
||||
let file = find(&files, &format!("_{input}.png"));
|
||||
|
||||
assert_eq!(decode(file).color(), image::ColorType::L8, "{input} is linear grayscale");
|
||||
assert_close(pixel(file), [byte(expected), byte(expected), byte(expected), 255], input);
|
||||
}
|
||||
let green = pixel(find(&files, "_Normal.png"))[1];
|
||||
|
||||
assert!((green - (255 - open_gl_green)).abs() <= 1, "DirectX normal: green {green}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_preview_matches_layer_rgba() {
|
||||
let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]);
|
||||
let mut gray_alpha = roughness();
|
||||
gray_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
|
||||
for channels in [roughness(), gray_alpha, rgba_half_alpha()] {
|
||||
let options = one_map(FileFormat::Psd, 8, channels);
|
||||
|
||||
let preview = MapPreview::sample(&fx.input(), &options, 0, RES).unwrap().unwrap();
|
||||
let files = fx.render(&options);
|
||||
let psd = craft_psd::PsdFile::from_bytes(&files[0].bytes).unwrap();
|
||||
let layer = psd.iter_layers().next().unwrap().rgba8().unwrap();
|
||||
|
||||
assert_eq!(preview.channels, [Dest::R, Dest::G, Dest::B, Dest::A]);
|
||||
assert!(preview.pixels == layer.data, "the preview shows the layer's stored channels");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_layers_hold_the_samples_of_the_same_png_at_every_layout_and_depth() {
|
||||
let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]);
|
||||
let base_colour = |component| SourceRef::Channel { channel: Channel::BaseColor, component };
|
||||
let mut gray_alpha = roughness();
|
||||
gray_alpha.push((Dest::A, SourceRef::Constant(0.5)));
|
||||
let mut rgb = rgba_half_alpha();
|
||||
rgb.pop();
|
||||
let layouts = [roughness(), vec![(Dest::L, base_colour(0))], gray_alpha, rgb, rgba_half_alpha()];
|
||||
|
||||
for channels in layouts {
|
||||
for (depth, dither) in [(8, false), (8, true), (16, false)] {
|
||||
let mut png_options = one_map(FileFormat::Png, depth, channels.clone());
|
||||
png_options.dither = dither;
|
||||
let mut psd_options = png_options.clone();
|
||||
psd_options.format_override = Some(FileFormat::Psd);
|
||||
|
||||
let png = decode(&fx.render(&png_options)[0]);
|
||||
let psd = craft_psd::PsdFile::from_bytes(&fx.render(&psd_options)[0].bytes).unwrap();
|
||||
let layer = psd.iter_layers().next().unwrap();
|
||||
|
||||
let context = format!("{channels:?} at {depth} bits, dithering {dither}");
|
||||
if depth == 16 {
|
||||
// Planes of big-endian samples: red, green, blue, then transparency
|
||||
let planes: Vec<Vec<u8>> = [0, 1, 2, -1].into_iter().map(|id| layer.channel_bytes(id).unwrap()).collect();
|
||||
let texel_count = planes[0].len() / 2;
|
||||
let samples: Vec<u16> =
|
||||
(0..texel_count).flat_map(|texel| planes.iter().map(move |plane| u16::from_be_bytes([plane[2 * texel], plane[2 * texel + 1]]))).collect();
|
||||
assert!(samples == png.to_rgba16().into_raw(), "{context}");
|
||||
} else {
|
||||
assert!(layer.rgba8().unwrap().data == png.to_rgba8().into_raw(), "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001];
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
let literal = format!("{}.1001", "a".repeat(MAX_STEM - ".1001".len()));
|
||||
options.preset.maps[0].file = literal.clone();
|
||||
|
||||
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
|
||||
assert_eq!(plan[0].layers[0].name, literal);
|
||||
|
||||
options.preset.maps[0].file = "Group/Map.$udim".into();
|
||||
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
assert_eq!(plan[0].layers[0].name, "Group/Map.1001");
|
||||
|
||||
options.preset.maps[0].file = "Map".into();
|
||||
options.format_override = Some(FileFormat::Png);
|
||||
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
|
||||
assert_eq!(plan[0].name, "Map.1001.png");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_tiled_and_untiled_sets_keep_both_documents() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].name = "Body".into();
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1002];
|
||||
for name in ["body.1001", "Body.1001_1", "Trim"] {
|
||||
let mut untiled = fx.project.texture_sets[0].clone();
|
||||
untiled.name = name.into();
|
||||
untiled.uv_tiles.clear();
|
||||
fx.project.texture_sets.push(untiled);
|
||||
}
|
||||
let options = one_map(FileFormat::Psd, 8, roughness());
|
||||
|
||||
let plans = list_set_outputs(&fx.project, &[1, 0, 2, 3], "sphere", &options).unwrap();
|
||||
|
||||
assert_eq!(plans.len(), 5);
|
||||
assert_eq!(plans[1].1.name, "sphere_Body.1001.psd");
|
||||
assert_eq!(plans[2].1.name, "sphere_Body.1002.psd");
|
||||
assert_eq!(plans[3].1.name, "sphere_Body.1001_1.psd");
|
||||
assert_eq!(plans[4].1.name, "sphere_Trim.psd");
|
||||
let separate = list_outputs(&fx.project, 1, "sphere", &options).unwrap();
|
||||
assert_eq!(plans[0].1.name, separate[0].name, "individual desktop jobs agree with selection planning");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_document_names_survive_sanitization_and_case_collisions() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].name = "Body Coat".into();
|
||||
for (name, tiles) in [
|
||||
("body_coat", vec![]),
|
||||
("Body_Coat_0", vec![]),
|
||||
("Body Coat", vec![1001, 1002]),
|
||||
("BODY_COAT", vec![1001]),
|
||||
("Trim", vec![]),
|
||||
("body_coat", vec![1011]),
|
||||
] {
|
||||
let mut set = fx.project.texture_sets[0].clone();
|
||||
set.name = name.into();
|
||||
set.uv_tiles = tiles;
|
||||
fx.project.texture_sets.push(set);
|
||||
}
|
||||
let options = one_map(FileFormat::Psd, 8, roughness());
|
||||
let indices = [6, 5, 4, 3, 2, 1, 0];
|
||||
|
||||
let batch = list_set_outputs(&fx.project, &indices, "sphere", &options).unwrap();
|
||||
let separate: Vec<_> = indices
|
||||
.into_iter()
|
||||
.flat_map(|index| list_outputs(&fx.project, index, "sphere", &options).unwrap().into_iter().map(move |file| (index, file.name)))
|
||||
.collect();
|
||||
|
||||
assert_eq!(batch.into_iter().map(|(index, file)| (index, file.name)).collect::<Vec<_>>(), separate);
|
||||
for (index, unchanged) in [(2, "sphere_Body_Coat_0.psd"), (5, "sphere_Trim.psd"), (6, "sphere_body_coat.1011.psd")] {
|
||||
assert!(separate.iter().any(|(set, name)| *set == index && name == unchanged));
|
||||
}
|
||||
let tiled = list_outputs(&fx.project, 3, "sphere", &options).unwrap();
|
||||
assert!(tiled[0].udim_name.is_some());
|
||||
assert_eq!(tiled[0].udim_name, tiled[1].udim_name, "tiles of one set keep the same pattern");
|
||||
|
||||
let atlas_options = ExportOptions { atlas: true, ..options };
|
||||
let atlas = list_set_outputs(&fx.project, &indices, "sphere", &atlas_options).unwrap();
|
||||
assert_eq!(atlas.len(), indices.len(), "atlas documents also need distinct names");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn psd_batch_budget_counts_only_retained_documents() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
options.size = Some(4096);
|
||||
fx.project.texture_sets[0].uv_tiles = (1001..1006).collect();
|
||||
let mut other = fx.project.texture_sets[0].clone();
|
||||
other.name = "Other".into();
|
||||
fx.project.texture_sets.push(other);
|
||||
|
||||
let once = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap();
|
||||
let repeated = plan_set_outputs(&fx.project, &[0, 0], "sphere", &options, PsdBudget::WEB).unwrap();
|
||||
let distinct = plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB);
|
||||
let (_, bytes_per_tile) = check_psd_size([(4096, 4096)], 0, 8).unwrap();
|
||||
|
||||
assert_eq!(once.len(), repeated.len());
|
||||
assert!(once.iter().zip(&repeated).all(|((_, first), (_, kept))| first.name == kept.name && kept.warnings.len() > first.warnings.len()));
|
||||
assert!(matches!(distinct, Err(FormatError::TooLarge(message)) if message.contains("total PSD")));
|
||||
println!(
|
||||
"PSD preflight: {bytes_per_tile} estimated bytes per tile, {} retained bytes, {} bytes if counted twice, limit {:?}",
|
||||
bytes_per_tile * once.len() as u64,
|
||||
bytes_per_tile * (once.len() + repeated.len()) as u64,
|
||||
PsdBudget::WEB.batch_bytes
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_batch_rejects_large_retained_output_before_rendering() {
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
options.padding = Padding::None;
|
||||
options.size = Some(4096);
|
||||
fx.project.texture_sets[0].uv_tiles = (1001..1008).collect();
|
||||
|
||||
let smaller = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).unwrap();
|
||||
assert_eq!(smaller.len(), 7, "seven 128 MiB payloads fit with record overhead");
|
||||
fx.project.texture_sets[0].uv_tiles.extend(1008..1034);
|
||||
|
||||
let oversized = plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB);
|
||||
assert!(matches!(&oversized, Err(error) if error.to_string().contains("total PSD")), "the 33 individually valid tiles must be rejected as a batch");
|
||||
|
||||
let set = &fx.project.texture_sets[0];
|
||||
let (width, height) = set.size();
|
||||
fx.comp = Composite::with_size(&default_channels(), width, height);
|
||||
fx.coverage.resize((width * height) as usize, true);
|
||||
let planned = plan_outputs(&fx.project, 0, "sphere", &options, PsdBudget::WEB).unwrap();
|
||||
let error = render_planned_maps_within(&fx.input(), &options, planned, PsdBudget::WEB).unwrap_err();
|
||||
assert!(error.to_string().contains("total PSD"), "{error}");
|
||||
|
||||
let (_, estimated_bytes) = check_psd_size([(4096, 4096)], 0, 8).unwrap();
|
||||
println!(
|
||||
"PSD preflight: {estimated_bytes} estimated bytes per tile; {} across 33 tiles; batch limit {:?}",
|
||||
estimated_bytes * 33,
|
||||
PsdBudget::WEB.batch_bytes
|
||||
);
|
||||
|
||||
let mut small = fx.project.texture_sets[0].clone();
|
||||
small.uv_tiles = (1001..1006).collect();
|
||||
fx.project.texture_sets[0] = small.clone();
|
||||
small.name = "Other".into();
|
||||
fx.project.texture_sets.push(small);
|
||||
assert!(plan_set_outputs(&fx.project, &[0], "sphere", &options, PsdBudget::WEB).is_ok());
|
||||
assert!(plan_set_outputs(&fx.project, &[1], "sphere", &options, PsdBudget::WEB).is_ok());
|
||||
assert!(plan_set_outputs(&fx.project, &[0, 1], "sphere", &options, PsdBudget::WEB).is_err(), "the budget includes all selected sets");
|
||||
assert!(list_set_outputs(&fx.project, &[0, 1], "sphere", &options).is_ok(), "a desktop batch has no such budget");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specular_glossiness_exports_ignore_the_ior_specular_setting() {
|
||||
let mut fx = Fx::new(&[Channel::BaseColor, Channel::Specular, Channel::Glossiness, Channel::SpecularLevel]);
|
||||
|
||||
@@ -42,8 +42,8 @@ pub mod project_file;
|
||||
pub mod zip_read;
|
||||
|
||||
pub use export::{
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MapOverride, MapSpec, Padding, PlannedFile, SourceRef, VirtualMap, list_outputs,
|
||||
render_maps, skip_repeated_names,
|
||||
Dest, ExportInput, ExportOptions, ExportPreset, ExportedFile, FileFormat, MAX_PREVIEW_SIDE, MapOverride, MapPreview, MapSpec, Padding, PlannedFile,
|
||||
SourceRef, VirtualMap, list_outputs, render_maps, skip_repeated_names,
|
||||
};
|
||||
pub use image_res::{DecodedImage, coverage_png, decode_cooked_image, decode_image, decode_image_within, gray16_png, gray16_resource};
|
||||
pub use mesh_export::{
|
||||
@@ -53,7 +53,7 @@ pub use mesh_export::{
|
||||
pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_high_poly_bytes, import_mesh_bytes, mesh_report, self_contained_mesh};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use presets::load_preset;
|
||||
pub use presets::{DEFAULT_PRESET, builtin_preset, builtin_presets, preset_from_json, preset_to_json};
|
||||
pub use presets::{DEFAULT_PRESET, NEW_BUILTIN_PRESET_NAMES, builtin_preset, builtin_preset_catalog, builtin_presets, preset_from_json, preset_to_json};
|
||||
pub use project_file::{
|
||||
BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, MAX_RESOURCE_NAME_LEN, ProjectFile, RamReservation, load_project_bytes, project_open_limit_gib,
|
||||
sanitize_resource_name, save_project_bytes, set_project_open_limit_gib,
|
||||
|
||||
@@ -386,11 +386,16 @@ fn output_for_slot<'m>(slot: usize, map: &'m MapSpec, set: &TextureSet, format:
|
||||
/// opacity, clear coat and clear coat roughness. Maps with none of them (ambient occlusion,
|
||||
/// height, specular/glossiness, baked maps...) bind nothing, and neither do channels the set has
|
||||
/// no data for. `project_normal` is the project's normal convention, used by normal maps that
|
||||
/// follow it.
|
||||
/// follow it. Layered PSD files are omitted.
|
||||
pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_normal: NormalFormat, files: &[PlannedFile]) -> Vec<UsdTextureBinding> {
|
||||
let mut out: Vec<UsdTextureBinding> = Vec::new();
|
||||
let mut seen_maps = Vec::new();
|
||||
for file in files {
|
||||
// PSD stores several maps in one file
|
||||
if !file.format.usable_by_usd_asset() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The first tile stands for all the tiles of a map
|
||||
if seen_maps.contains(&file.map) {
|
||||
continue;
|
||||
@@ -405,6 +410,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm
|
||||
(None, None) => file.name.clone(),
|
||||
(None, Some(_)) => continue,
|
||||
};
|
||||
|
||||
let srgb = opts.space_for_map(map, file.format, file.bit_depth) == ColorSpace::Srgb;
|
||||
for slot in 0..SLOTS.len() {
|
||||
if out.iter().any(|binding| binding.slot == slot) {
|
||||
@@ -412,7 +418,7 @@ pub fn usd_texture_bindings(set: &TextureSet, opts: &ExportOptions, project_norm
|
||||
}
|
||||
|
||||
let Some((output, source)) = output_for_slot(slot, map, set, file.format) else { continue };
|
||||
let normal = (slot == 3).then(|| {
|
||||
let normal = (SLOTS[slot].0 == "Normal").then(|| {
|
||||
opts.normal_format.unwrap_or(match source {
|
||||
SourceRef::Virtual { map: VirtualMap::NormalOpenGl, .. } => NormalFormat::OpenGl,
|
||||
SourceRef::Virtual { map: VirtualMap::NormalDirectX, .. } => NormalFormat::DirectX,
|
||||
@@ -585,6 +591,7 @@ mod texture_binding_tests {
|
||||
tile: None,
|
||||
udim_name: None,
|
||||
warnings: Vec::new(),
|
||||
layers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,8 +94,8 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
}),
|
||||
// Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material
|
||||
preset("glTF PBR Metal Roughness", gltf_pbr_maps(|s| format!("$mesh_$textureSet_{s}"))),
|
||||
// Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material (R occlusion, G roughness, B metallic) and the base color, roughness, metallic and normal inputs of
|
||||
// https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine
|
||||
// Spec: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#metallic-roughness-material
|
||||
// Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/physically-based-materials-in-unreal-engine
|
||||
preset(
|
||||
"Unreal Engine (Packed)",
|
||||
vec![map("BaseColor", 8, base_with_alpha()), map("OcclusionRoughnessMetallic", 8, orm()), map("Normal", 8, normal(VirtualMap::NormalDirectX))],
|
||||
@@ -219,6 +219,77 @@ pub fn builtin_presets() -> Vec<ExportPreset> {
|
||||
map("clearcoatRoughness", 8, gray(ch(Channel::CoatRoughness, 0))),
|
||||
],
|
||||
),
|
||||
// Spec: https://dev.epicgames.com/documentation/en-us/unreal-engine/subsurface-profile-shading-model-in-unreal-engine (the Opacity input masks the scattering, so the base color has no alpha)
|
||||
preset(
|
||||
"Unreal Engine Subsurface Profile (Packed)",
|
||||
vec![
|
||||
map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))),
|
||||
map("OcclusionRoughnessMetallic", 8, orm()),
|
||||
map("Normal", 8, normal(VirtualMap::NormalDirectX)),
|
||||
map("SubsurfaceMask", 8, gray(ch(Channel::ScatterWeight, 0))),
|
||||
],
|
||||
),
|
||||
// Spec: https://github.com/KhronosGroup/glTF/blob/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness/README.md (diffuse with alpha, specular RGB with glossiness in A)
|
||||
preset(
|
||||
"glTF Specular Glossiness (archived extension)",
|
||||
vec![
|
||||
map("Diffuse", 8, base_with_alpha()),
|
||||
map("SpecularGlossiness", 8, {
|
||||
let mut specular_glossiness = rgb(|k| ch(Channel::Specular, k));
|
||||
specular_glossiness.push((Dest::A, ch(Channel::Glossiness, 0)));
|
||||
specular_glossiness
|
||||
}),
|
||||
map("Normal", 8, normal(VirtualMap::NormalOpenGl)),
|
||||
map("Occlusion", 8, gray(virt(VirtualMap::AoMixed, 0))),
|
||||
map("Emissive", 8, rgb(|k| ch(Channel::Emissive, k))),
|
||||
],
|
||||
),
|
||||
// Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Standard_Material.html (the Standard Material inputs)
|
||||
// Spec: https://help.maxon.net/r3d/maya/en-us/Content/html/Bump+Map.html (normal maps in OpenGL format)
|
||||
preset("Redshift Standard Material (separate maps)", {
|
||||
let gray8 = |name: &str, c: Channel| map(name, 8, gray(ch(c, 0)));
|
||||
let rgb8 = |name: &str, c: Channel| map(name, 8, rgb(|k| ch(c, k)));
|
||||
vec![
|
||||
rgb8("BaseColor", Channel::BaseColor),
|
||||
gray8("Metalness", Channel::Metallic),
|
||||
gray8("ReflectionRoughness", Channel::Roughness),
|
||||
map("Normal", 8, normal(VirtualMap::NormalOpenGl)),
|
||||
rgb8("EmissionColor", Channel::Emissive),
|
||||
gray8("Opacity", Channel::Opacity),
|
||||
gray8("SubsurfaceWeight", Channel::ScatterWeight),
|
||||
gray8("CoatWeight", Channel::CoatWeight),
|
||||
gray8("CoatRoughness", Channel::CoatRoughness),
|
||||
gray8("SheenWeight", Channel::SheenWeight),
|
||||
rgb8("SheenColor", Channel::SheenColor),
|
||||
gray8("SheenRoughness", Channel::SheenRoughness),
|
||||
]
|
||||
}),
|
||||
// Spec: https://create.roblox.com/docs/art/modeling/surface-appearance (ColorMap alpha is opacity)
|
||||
// Spec: https://create.roblox.com/docs/art/modeling/texture-specifications (OpenGL normals only; grayscale metalness and roughness)
|
||||
// Spec: https://create.roblox.com/docs/art/modeling/reimport (the file name suffix it assigns to each map)
|
||||
preset(
|
||||
"Roblox SurfaceAppearance (separate maps)",
|
||||
vec![
|
||||
map("Color", 8, base_with_alpha()),
|
||||
map("Normal", 8, normal(VirtualMap::NormalOpenGl)),
|
||||
map("Metalness", 8, gray(ch(Channel::Metallic, 0))),
|
||||
map("Roughness", 8, gray(ch(Channel::Roughness, 0))),
|
||||
],
|
||||
),
|
||||
// Spec: https://help.sketchfab.com/en/articles/16152630-pbr-maps (sRGB base color, linear grayscale metalness; no alpha, the docs don't say opacity reads it)
|
||||
// Spec: https://help.sketchfab.com/en/articles/16152634-materials-pbr (roughness, AO and emission channels)
|
||||
// Spec: https://help.sketchfab.com/en/articles/16152621-normal-map-bump-map (DirectX normals by default)
|
||||
preset(
|
||||
"Sketchfab Metalness (separate maps)",
|
||||
vec![
|
||||
map("BaseColor", 8, rgb(|k| ch(Channel::BaseColor, k))),
|
||||
map("Metalness", 8, gray(ch(Channel::Metallic, 0))),
|
||||
map("Roughness", 8, gray(ch(Channel::Roughness, 0))),
|
||||
map("Normal", 8, normal(VirtualMap::NormalDirectX)),
|
||||
map("AmbientOcclusion", 8, gray(virt(VirtualMap::AoMixed, 0))),
|
||||
map("Emission", 8, rgb(|k| ch(Channel::Emissive, k))),
|
||||
],
|
||||
),
|
||||
preset("Separate maps", Channel::ALL.into_iter().map(channel_map).collect()),
|
||||
preset(
|
||||
"Mesh maps",
|
||||
@@ -240,11 +311,27 @@ pub const DEFAULT_PRESET: &str = "Document channels + Normal + AO (No Alpha)";
|
||||
/// scripts still use it).
|
||||
const OLD_DEFAULT_PRESET: &str = "Document channels + Normal + AO";
|
||||
|
||||
/// Names introduced with the export update, which could previously belong to saved user presets.
|
||||
pub const NEW_BUILTIN_PRESET_NAMES: [&str; 5] = [
|
||||
"Unreal Engine Subsurface Profile (Packed)",
|
||||
"glTF Specular Glossiness (archived extension)",
|
||||
"Redshift Standard Material (separate maps)",
|
||||
"Roblox SurfaceAppearance (separate maps)",
|
||||
"Sketchfab Metalness (separate maps)",
|
||||
];
|
||||
|
||||
/// The immutable built-in templates shared by menu and command lookups.
|
||||
pub fn builtin_preset_catalog() -> &'static [ExportPreset] {
|
||||
static CATALOG: std::sync::LazyLock<Vec<ExportPreset>> = std::sync::LazyLock::new(builtin_presets);
|
||||
&CATALOG
|
||||
}
|
||||
|
||||
/// A built-in preset by name (case-insensitive).
|
||||
pub fn builtin_preset(name: &str) -> Option<ExportPreset> {
|
||||
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))
|
||||
|
||||
builtin_preset_catalog().iter().find(|preset| preset.name.eq_ignore_ascii_case(name)).cloned()
|
||||
}
|
||||
|
||||
/// Parse and validate a user preset.
|
||||
|
||||
@@ -1386,7 +1386,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con
|
||||
let layer_id = layer.id.0;
|
||||
let keymap = app.ui.keymap.clone();
|
||||
|
||||
// The row menu can act on several selected layers. A thumbnail identifies one layer.
|
||||
// A thumbnail menu always acts on its own layer
|
||||
let several = if content_thumbnail { None } else { selection_with(app, layer.id) };
|
||||
let run = |app: &mut TextureCraftApp, ui: &mut Ui, label: &str, id: &str, params: Value, enabled: bool| {
|
||||
let mut button = egui::Button::new(label);
|
||||
@@ -1479,7 +1479,7 @@ fn layer_context_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, con
|
||||
|
||||
/// Mask management is available from the row and directly from the mask thumbnail.
|
||||
fn mask_management_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, mask_thumbnail: bool) {
|
||||
// An instance inherits its source mask until it has its own.
|
||||
// An instance inherits its source mask until it has its own
|
||||
let project = &app.session.doc.project;
|
||||
let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|owner| owner.mask.as_ref());
|
||||
let (has_mask, mask_on) = (mask.is_some(), mask.is_some_and(|mask| mask.enabled));
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,84 @@
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::util::id_type_map::RawKey;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::map_preview_pictures::MapPreviewPictures;
|
||||
use super::{PlannedOutput, planned_outputs};
|
||||
use crate::TextureCraftApp;
|
||||
|
||||
/// Pixels across an output map's hover preview: enough to read the packing, cheap to sample
|
||||
const PREVIEW_SIDE_PIXELS: u32 = 150;
|
||||
|
||||
/// The current template plan and its hover pictures, invalidated together on edits.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct MapPreviewCache {
|
||||
key: u64,
|
||||
plan: Result<Arc<[Option<PlannedOutput>]>, String>,
|
||||
pictures: HashMap<usize, Option<Arc<MapPreviewPictures>>>,
|
||||
}
|
||||
|
||||
impl MapPreviewCache {
|
||||
fn id() -> egui::Id {
|
||||
egui::Id::unique("export_map_preview_cache")
|
||||
}
|
||||
|
||||
fn key(app: &TextureCraftApp, params: &Value) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
params.hash(&mut hasher);
|
||||
(app.session.project_id, app.session.revision).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// Output map `index`'s pictures once made; None until then
|
||||
pub(super) fn get(ctx: &egui::Context, index: usize) -> Option<Option<Arc<MapPreviewPictures>>> {
|
||||
ctx.data(|data| {
|
||||
let cache = data.get_temp_raw(RawKey::new::<Self>(Self::id()))?.downcast_ref::<Self>()?;
|
||||
cache.pictures.get(&index).cloned()
|
||||
})
|
||||
}
|
||||
|
||||
/// Release the plan and its pictures when their tab is dismissed.
|
||||
pub(super) fn clear(ctx: &egui::Context) {
|
||||
ctx.data_mut(|data| data.remove::<Self>(Self::id()));
|
||||
}
|
||||
|
||||
/// Keep one descriptor per map until the settings or document change.
|
||||
pub(super) fn plan(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value) -> Result<Arc<[Option<PlannedOutput>]>, String> {
|
||||
let key = Self::key(app, params);
|
||||
let cached = ctx.data_mut(|data| {
|
||||
let cache = data.get_temp_raw(RawKey::new::<Self>(Self::id()))?.downcast_ref::<Self>()?;
|
||||
if cache.key == key {
|
||||
return Some(cache.plan.clone());
|
||||
}
|
||||
|
||||
data.remove::<Self>(Self::id());
|
||||
None
|
||||
});
|
||||
if let Some(plan) = cached {
|
||||
return plan;
|
||||
}
|
||||
|
||||
let plan = planned_outputs(app, params).map(Arc::from);
|
||||
ctx.data_mut(|data| data.insert_temp(Self::id(), Self { key, plan: plan.clone(), pictures: HashMap::new() }));
|
||||
plan
|
||||
}
|
||||
|
||||
/// Make output map `index`'s pictures for `params` unless they are made, and draw again to show them
|
||||
pub(super) fn fill(app: &mut TextureCraftApp, ctx: &egui::Context, params: &Value, index: usize) {
|
||||
if Self::get(ctx, index).is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let preview = app.session.export_preview(params, index, PREVIEW_SIDE_PIXELS).ok().flatten();
|
||||
let pictures = preview.map(|preview| Arc::new(MapPreviewPictures::new(ctx, &preview, index)));
|
||||
ctx.data_mut(|data| {
|
||||
if let Some(cache) = data.get_temp_raw_mut(RawKey::new::<Self>(Self::id())).and_then(|entry| entry.downcast_mut::<Self>()) {
|
||||
cache.pictures.insert(index, pictures);
|
||||
}
|
||||
});
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use egui::{Color32, ColorImage, TextureHandle, TextureOptions};
|
||||
use texturecraft_engine::formats::{Dest, MapPreview};
|
||||
|
||||
/// An output map's file, small, then each of its channels in grey, as textures to draw
|
||||
pub(super) struct MapPreviewPictures {
|
||||
pub(super) file: TextureHandle,
|
||||
/// Empty for a one-channel file, whose picture is its channel
|
||||
pub(super) channels: Vec<(Dest, TextureHandle)>,
|
||||
/// Height over width
|
||||
pub(super) aspect: f32,
|
||||
}
|
||||
|
||||
impl MapPreviewPictures {
|
||||
/// The pictures of `preview`, the preview of output map `index`
|
||||
pub(super) fn new(ctx: &egui::Context, preview: &MapPreview, index: usize) -> MapPreviewPictures {
|
||||
let size = [preview.width as usize, preview.height as usize];
|
||||
let pixel_count = size[0] * size[1];
|
||||
let count = preview.channels.len().max(1);
|
||||
let value = |pixel: usize, channel: usize| preview.pixels.get(pixel * count + channel).copied().unwrap_or(0);
|
||||
let load = |name: String, image: ColorImage| ctx.load_texture(name, image, TextureOptions::LINEAR);
|
||||
|
||||
// Keep alpha separate so the file preview shows the stored colour
|
||||
let color = preview.channels.starts_with(&[Dest::R, Dest::G, Dest::B]);
|
||||
let pixels: Vec<_> = (0..pixel_count)
|
||||
.map(|pixel| if color { Color32::from_rgb(value(pixel, 0), value(pixel, 1), value(pixel, 2)) } else { Color32::from_gray(value(pixel, 0)) })
|
||||
.collect();
|
||||
let grayscale = !color || pixels.iter().all(|pixel| pixel.r() == pixel.g() && pixel.g() == pixel.b());
|
||||
let file = load(format!("export_map_preview_{index}"), ColorImage::new(size, pixels));
|
||||
|
||||
// A gray file texture can also draw each of its colour channels
|
||||
let channels = if preview.channels.len() > 1 {
|
||||
let channel = |(channel_index, dest): (usize, &Dest)| {
|
||||
if grayscale && *dest != Dest::A {
|
||||
return (*dest, file.clone());
|
||||
}
|
||||
|
||||
let image = ColorImage::from_gray_iter(size, (0..pixel_count).map(|pixel| value(pixel, channel_index)));
|
||||
(*dest, load(format!("export_map_preview_{index}_{channel_index}"), image))
|
||||
};
|
||||
preview.channels.iter().enumerate().map(channel).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
MapPreviewPictures { file, channels, aspect: preview.height as f32 / preview.width.max(1) as f32 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/// An output map card's index, the card count (for the grip's moves) and the width its lists' values line up on
|
||||
pub(super) struct OutputCard {
|
||||
pub(super) index: usize,
|
||||
pub(super) count: usize,
|
||||
pub(super) value_width: f32,
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
use texturecraft_engine::formats::FileFormat;
|
||||
|
||||
/// A file an output map writes for the current texture set, as `export.plan` lists it
|
||||
#[derive(Clone)]
|
||||
pub(super) struct PlannedOutput {
|
||||
pub(super) file: String,
|
||||
/// The picture shows the full atlas while export writes individual tiles
|
||||
pub(super) tiled: bool,
|
||||
/// Pixels per side (export.plan never plans an atlas, so every file is square)
|
||||
pub(super) size: u64,
|
||||
pub(super) format: Option<FileFormat>,
|
||||
pub(super) bit_depth: u8,
|
||||
pub(super) dithering: bool,
|
||||
}
|
||||
@@ -6,4 +6,6 @@ pub(super) struct RowEdit {
|
||||
pub(super) action: Option<MapAction>,
|
||||
/// A map dropped on a channel swatch, to ask which of its channels to use.
|
||||
pub(super) pending: Option<PendingDrop>,
|
||||
/// The output map whose channel swatch the pointer is on, for its file preview
|
||||
pub(super) hovered_output: Option<usize>,
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use egui::Color32;
|
||||
pub(super) struct SwatchLook {
|
||||
/// The source map's colour (None: empty or a constant).
|
||||
pub(super) fill: Option<Color32>,
|
||||
/// One bar per channel of the source the swatch reads.
|
||||
pub(super) bars: Vec<Color32>,
|
||||
/// The underline in the colour of the channel the swatch's letters name (None: a constant)
|
||||
pub(super) bar: Option<Color32>,
|
||||
pub(super) inverted: bool,
|
||||
}
|
||||
+1015
-680
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,334 @@
|
||||
//! The Export textures window's own controls, drawn at the places its layout gives them: tabs,
|
||||
//! checks, dropdowns, buttons and icon buttons in the window's colours ([`ExportLook`])
|
||||
|
||||
use egui::{Align2, Color32, CornerRadius, FontId, Id, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
|
||||
use super::export_look::{CONTROL_HEIGHT, CONTROL_RADIUS, ExportLook, TEXT_SIZE};
|
||||
use crate::theme::semibold;
|
||||
|
||||
/// Side and corner radius of a check box
|
||||
const CHECK_SIZE: f32 = 13.0;
|
||||
const CHECK_RADIUS: u8 = 2;
|
||||
|
||||
/// The tick inside a check box: its three points from the box's left edge and centre, and its width
|
||||
const TICK_POINTS: [(f32, f32); 3] = [(3.2, 0.2), (5.6, 2.6), (9.8, -2.6)];
|
||||
const TICK_WIDTH: f32 = 1.7;
|
||||
|
||||
/// Air between a check box and its label
|
||||
pub(crate) const CHECK_LABEL_GAP: f32 = 5.0;
|
||||
|
||||
/// From a dropdown's left edge to its value, and from its right edge to its chevron's centre
|
||||
pub(crate) const VALUE_INSET: f32 = 7.0;
|
||||
pub(crate) const CHEVRON_INSET: f32 = 11.0;
|
||||
|
||||
/// Size of a chevron and of the window's icons
|
||||
pub(crate) const CHEVRON_SIZE: f32 = 12.0;
|
||||
|
||||
/// The air on either side of a tab's name
|
||||
const TAB_PADDING: f32 = 14.0;
|
||||
/// A tab's corner radius
|
||||
const TAB_RADIUS: u8 = 4;
|
||||
/// Gap between tabs
|
||||
const TAB_GAP: f32 = 3.0;
|
||||
/// How far a tab reaches under the divider, where the body's colour covers its lower corners
|
||||
const TAB_OVERLAP: f32 = 4.0;
|
||||
|
||||
/// A quiet dropdown's hover face: its padding round the value and chevron, and half its height
|
||||
const TEXT_DROPDOWN_PADDING: f32 = 3.0;
|
||||
const TEXT_DROPDOWN_HALF_HEIGHT: f32 = 9.0;
|
||||
|
||||
/// Hit area of an icon button around its glyph
|
||||
const ICON_HIT_SIZE: f32 = 20.0;
|
||||
|
||||
/// Width of the keyboard focus outline on the window's drawn controls
|
||||
const FOCUS_OUTLINE_WIDTH: f32 = 2.0;
|
||||
|
||||
/// Whether a control that cannot be used looks greyed; a built-in template's cards keep their look
|
||||
pub(crate) fn looks_disabled(ui: &Ui, enabled: bool) -> bool {
|
||||
!enabled && ui.visuals().disabled_alpha() < 1.0
|
||||
}
|
||||
|
||||
/// The window's regular and semibold text
|
||||
pub(crate) fn font(bold: bool) -> FontId {
|
||||
if bold { semibold(TEXT_SIZE) } else { FontId::proportional(TEXT_SIZE) }
|
||||
}
|
||||
|
||||
/// Width of `text` in the window's font
|
||||
pub(crate) fn text_width(ui: &Ui, text: &str, bold: bool) -> f32 {
|
||||
ui.painter().layout_no_wrap(text.to_owned(), font(bold), Color32::WHITE).size().x
|
||||
}
|
||||
|
||||
/// `text` with its left edge at `left` and its middle at `y`
|
||||
pub(crate) fn text_at(ui: &Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Rect {
|
||||
ui.painter().text(pos2(left, y), Align2::LEFT_CENTER, text, font(bold), color)
|
||||
}
|
||||
|
||||
/// `text` cut with "…" at its end (or its start, for file names) to fit `room`
|
||||
pub(crate) fn fitted(ui: &Ui, text: &str, room: f32, from_start: bool, bold: bool) -> String {
|
||||
if text_width(ui, text, bold) <= room {
|
||||
return text.to_owned();
|
||||
}
|
||||
|
||||
let mut cuts: Vec<_> = text.char_indices().skip(1).map(|(offset, _)| offset).collect();
|
||||
if !from_start {
|
||||
cuts.reverse();
|
||||
}
|
||||
|
||||
let truncate = |cut| if from_start { format!("…{}", &text[cut..]) } else { format!("{}…", &text[..cut]) };
|
||||
let first_fit = cuts.partition_point(|&cut| text_width(ui, &truncate(cut), bold) > room);
|
||||
cuts.get(first_fit).map_or_else(|| "…".to_owned(), |&cut| truncate(cut))
|
||||
}
|
||||
|
||||
/// A glyph centred on `centre`
|
||||
pub(crate) fn glyph(ui: &Ui, centre: Pos2, glyph: &str, size: f32, color: Color32) {
|
||||
ui.painter().text(centre, Align2::CENTER_CENTER, glyph, FontId::proportional(size), color);
|
||||
}
|
||||
|
||||
/// The keyboard focus outline of a drawn control, in the text colour
|
||||
pub(crate) fn paint_focus(ui: &Ui, response: &Response) {
|
||||
if response.has_focus() {
|
||||
let stroke = Stroke::new(FOCUS_OUTLINE_WIDTH, ExportLook::get(ui.ctx()).text);
|
||||
ui.painter().rect_stroke(response.rect, CONTROL_RADIUS, stroke, StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
|
||||
/// A horizontal or vertical divider line, one point thick
|
||||
pub(crate) fn divider(ui: &Ui, rect: Rect) {
|
||||
ui.painter().rect_filled(rect, 0.0, ExportLook::get(ui.ctx()).divider);
|
||||
}
|
||||
|
||||
/// Sentence-case rounded tabs along `strip`'s bottom from `left`, the open one joined to the body; returns the clicked one
|
||||
pub(crate) fn tabs(ui: &mut Ui, strip: Rect, left: f32, labels: &[&str], open: usize) -> Option<usize> {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let bottom = strip.bottom();
|
||||
divider(ui, Rect::from_min_max(pos2(strip.left(), bottom - 1.0), pos2(strip.right(), bottom)));
|
||||
let mut clicked = None;
|
||||
let mut x = left;
|
||||
for (index, label) in labels.iter().enumerate() {
|
||||
let selected = index == open;
|
||||
let width = text_width(ui, label, selected) + 2.0 * TAB_PADDING;
|
||||
let rect = Rect::from_min_max(pos2(x, strip.top()), pos2(x + width, bottom));
|
||||
let response = ui.interact(rect, ui.scope_id().with(("export_tab", index)), Sense::click());
|
||||
response.widget_info(|| WidgetInfo::selected(Role::Tab, true, selected, *label));
|
||||
|
||||
// The tab's lower corners reach under the divider and are covered by the body's colour
|
||||
let painter = ui.painter();
|
||||
let face = Rect::from_min_max(rect.min, pos2(rect.right(), bottom + TAB_OVERLAP));
|
||||
let below = Rect::from_min_max(pos2(rect.left(), bottom - 1.0), pos2(rect.right(), bottom + TAB_OVERLAP + 1.0));
|
||||
if selected {
|
||||
painter.rect(face, TAB_RADIUS, look.window, Stroke::new(1.0, look.control_border), StrokeKind::Inside);
|
||||
painter.rect_filled(below.shrink2(vec2(1.0, 0.0)), 0.0, look.window);
|
||||
} else {
|
||||
let fill = if response.hovered() { look.raised } else { look.chrome };
|
||||
painter.rect_filled(face.with_min_y(face.top() + 1.0), TAB_RADIUS, fill);
|
||||
painter.rect_filled(below, 0.0, look.window);
|
||||
painter.rect_filled(below.with_max_y(bottom), 0.0, look.divider);
|
||||
}
|
||||
let color = if selected || response.hovered() { look.text } else { look.text_dim };
|
||||
painter.text(rect.center() + vec2(0.0, 1.0), Align2::CENTER_CENTER, *label, font(selected), color);
|
||||
paint_focus(ui, &response);
|
||||
if response.clicked() {
|
||||
clicked = Some(index);
|
||||
}
|
||||
x += width + TAB_GAP;
|
||||
}
|
||||
clicked
|
||||
}
|
||||
|
||||
/// A check box from `left` with its middle at `y`: dim and ticked when on, dark with a light edge when off
|
||||
pub(crate) fn paint_check(ui: &Ui, left: f32, y: f32, on: bool) {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let rect = Rect::from_min_size(pos2(left, y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE));
|
||||
let painter = ui.painter();
|
||||
if on {
|
||||
painter.rect_filled(rect, CHECK_RADIUS, look.text_dim);
|
||||
let points = TICK_POINTS.iter().map(|(dx, dy)| pos2(left + dx, y + dy)).collect();
|
||||
painter.add(egui::Shape::line(points, Stroke::new(TICK_WIDTH, look.window)));
|
||||
} else {
|
||||
painter.rect(rect, CHECK_RADIUS, look.control, Stroke::new(1.0, look.control_border), StrokeKind::Inside);
|
||||
}
|
||||
}
|
||||
|
||||
/// A check box at `at` (its left edge's middle) with `label` after it, toggled by a click in `hit`
|
||||
pub(crate) fn check(ui: &mut Ui, id: Id, hit: Rect, at: Pos2, on: &mut bool, label: Option<&str>, name: &str) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let mut response = ui.interact(hit, id, Sense::click());
|
||||
if response.clicked() {
|
||||
*on = !*on;
|
||||
response.mark_changed();
|
||||
}
|
||||
let checked = *on;
|
||||
response.widget_info(|| WidgetInfo::selected(Role::CheckBox, true, checked, name));
|
||||
paint_check(ui, at.x, at.y, checked);
|
||||
if let Some(label) = label {
|
||||
text_at(ui, at.x + CHECK_SIZE + CHECK_LABEL_GAP, at.y, label, look.text, false);
|
||||
}
|
||||
paint_focus(ui, &response);
|
||||
response
|
||||
}
|
||||
|
||||
/// The rect of a control `left`..`right` with its middle at `y`
|
||||
pub(crate) fn control_rect(left: f32, right: f32, y: f32) -> Rect {
|
||||
Rect::from_min_max(pos2(left, y - CONTROL_HEIGHT / 2.0), pos2(right, y + CONTROL_HEIGHT / 2.0))
|
||||
}
|
||||
|
||||
/// A dropdown's chevron, pointing up while its list is open, drawn just inside the right edge of the button `rect`
|
||||
pub(crate) fn chevron_icon(ui: &Ui, rect: Rect, visuals: &egui::style::WidgetVisuals, open: bool) {
|
||||
let centre = pos2(rect.right() + VALUE_INSET - CHEVRON_INSET, rect.center().y);
|
||||
glyph(ui, centre, if open { ic::CARET_UP } else { ic::CARET_DOWN }, CHEVRON_SIZE, visuals.fg_stroke.color);
|
||||
}
|
||||
|
||||
/// A dropdown filling `rect`, showing `shown`, its list as wide as it and flush under it
|
||||
pub(crate) fn combo<R>(
|
||||
ui: &mut Ui,
|
||||
rect: Rect,
|
||||
id: impl std::hash::Hash + std::fmt::Debug,
|
||||
shown: impl Into<String>,
|
||||
list: impl FnOnce(&mut Ui) -> R,
|
||||
) -> egui::InnerResponse<Option<R>> {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let shown: String = shown.into();
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
egui::ComboBox::from_id_salt(id)
|
||||
.width(rect.width())
|
||||
.height(f32::INFINITY)
|
||||
.selected_text(shown)
|
||||
.wrap_mode(egui::TextWrapMode::Truncate)
|
||||
.icon(chevron_icon)
|
||||
.popup_style(look.list_style())
|
||||
.show_ui(ui, list)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
/// A button drawn as a dropdown showing `shown`, for a menu that is no option list; lighter when it cannot be used
|
||||
pub(crate) fn combo_button(ui: &mut Ui, rect: Rect, id: Id, shown: &str, enabled: bool) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let sense = if enabled { Sense::click() } else { Sense::hover() };
|
||||
let response = ui.interact(rect, id, sense);
|
||||
response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, shown));
|
||||
let (fill, color) = match (enabled, response.hovered()) {
|
||||
(false, _) => (look.raised, look.text_dim),
|
||||
(true, true) => (look.raised, look.text),
|
||||
(true, false) => (look.control, look.text),
|
||||
};
|
||||
let painter = ui.painter();
|
||||
painter.rect(rect, CONTROL_RADIUS, fill, Stroke::new(1.0, look.control_border), StrokeKind::Inside);
|
||||
painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), color);
|
||||
glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, color);
|
||||
paint_focus(ui, &response);
|
||||
response
|
||||
}
|
||||
|
||||
/// A field showing `text` cut with "…" at its end that acts as a button, as the output directory does
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn field_button(ui: &mut Ui, rect: Rect, id: Id, text: &str) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let response = ui.interact(rect, id, Sense::click());
|
||||
response.widget_info(|| WidgetInfo::labeled(Role::Button, true, text));
|
||||
let border = if response.hovered() { look.outline } else { look.control_border };
|
||||
ui.painter().rect(rect, CONTROL_RADIUS, look.control, Stroke::new(1.0, border), StrokeKind::Inside);
|
||||
let shown = fitted(ui, text, rect.width() - 2.0 * VALUE_INSET, false, false);
|
||||
text_at(ui, rect.left() + VALUE_INSET, rect.center().y, &shown, look.text, false);
|
||||
paint_focus(ui, &response);
|
||||
response
|
||||
}
|
||||
|
||||
/// A dropdown that cannot be used: a step lighter than the others, its value and chevron dim; `id` tells it from the rows' other ones
|
||||
pub(crate) fn disabled_combo(ui: &mut Ui, rect: Rect, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, name: &str) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let response = ui.interact(rect, ui.scope_id().with(("export_disabled_combo", id)), Sense::hover());
|
||||
response.widget_info(|| {
|
||||
let mut info = WidgetInfo::labeled(Role::ComboBox, false, name);
|
||||
info.current_text_value = Some(shown.to_owned());
|
||||
info
|
||||
});
|
||||
let painter = ui.painter();
|
||||
painter.rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside);
|
||||
painter.text(rect.left_center() + vec2(VALUE_INSET, 0.0), Align2::LEFT_CENTER, shown, font(false), look.text_dim);
|
||||
glyph(ui, rect.right_center() - vec2(CHEVRON_INSET, 0.0), ic::CARET_DOWN, CHEVRON_SIZE, look.text_dim);
|
||||
response
|
||||
}
|
||||
|
||||
/// Text that reads as a label to assistive technology and tests: `text` from `left`, its middle at `y`; its response takes a tooltip
|
||||
pub(crate) fn label_at(ui: &mut Ui, left: f32, y: f32, text: &str, color: Color32, bold: bool) -> Response {
|
||||
let rect = text_at(ui, left, y, text, color, bold);
|
||||
let response = ui.interact(rect, ui.scope_id().with(("export_label", text, left.to_bits(), y.to_bits())), Sense::hover());
|
||||
response.widget_info(|| WidgetInfo::labeled(Role::Label, true, text));
|
||||
response
|
||||
}
|
||||
|
||||
/// A button filling `rect`: a step darker than the window with a light edge, or the accent for the one primary action
|
||||
pub(crate) fn button(ui: &mut Ui, rect: Rect, label: &str, primary: bool, enabled: bool) -> Response {
|
||||
let id = ui.scope_id().with(("export_button", label));
|
||||
button_with_id(ui, id, rect, label, label, primary, enabled)
|
||||
}
|
||||
|
||||
/// [`button`] for one of several buttons with the same label (each output map card's "$")
|
||||
pub(crate) fn button_with_id(ui: &mut Ui, id: Id, rect: Rect, label: &str, name: &str, primary: bool, enabled: bool) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let sense = if enabled { Sense::click() } else { Sense::hover() };
|
||||
let response = ui.interact(rect, id, sense);
|
||||
response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, name));
|
||||
let (fill, border) = match (primary, enabled && response.hovered()) {
|
||||
(true, _) => (look.accent, look.accent),
|
||||
(false, true) => (look.raised, look.outline),
|
||||
(false, false) => (look.control, look.control_border),
|
||||
};
|
||||
let painter = ui.painter();
|
||||
let fade = if enabled { 1.0 } else { ui.visuals().disabled_alpha() };
|
||||
painter.rect(rect, CONTROL_RADIUS, fill.gamma_multiply(fade), Stroke::new(1.0, border.gamma_multiply(fade)), StrokeKind::Inside);
|
||||
let color = if looks_disabled(ui, enabled) {
|
||||
look.text_dim
|
||||
} else if primary {
|
||||
look.lettering_on(fill)
|
||||
} else {
|
||||
look.text
|
||||
};
|
||||
painter.text(rect.center(), Align2::CENTER_CENTER, label, font(primary), color);
|
||||
paint_focus(ui, &response);
|
||||
response
|
||||
}
|
||||
|
||||
/// A glyph that acts as a button, centred on `centre`; `lit` frames it as switched on
|
||||
pub(crate) fn icon_button(ui: &mut Ui, centre: Pos2, icon: &str, size: f32, name: &str, enabled: bool, lit: bool) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let rect = Rect::from_center_size(centre, vec2(ICON_HIT_SIZE, ICON_HIT_SIZE));
|
||||
let sense = if enabled { Sense::click() } else { Sense::hover() };
|
||||
let response = ui.interact(rect, ui.scope_id().with(("export_icon", name)), sense);
|
||||
response.widget_info(|| WidgetInfo::selected(Role::Button, enabled, lit, name));
|
||||
if lit {
|
||||
ui.painter().rect(rect, CONTROL_RADIUS, look.raised, Stroke::new(1.0, look.control_border), StrokeKind::Inside);
|
||||
}
|
||||
let color = match (enabled, lit || response.hovered()) {
|
||||
(false, _) if looks_disabled(ui, enabled) => look.control_border,
|
||||
(false, _) => look.text_dim,
|
||||
(true, true) => look.text,
|
||||
(true, false) => look.text_dim,
|
||||
};
|
||||
glyph(ui, centre, icon, size, color);
|
||||
paint_focus(ui, &response);
|
||||
response
|
||||
}
|
||||
|
||||
/// A card's quiet dropdown: its value from `value_left` and a chevron at `chevron_x`, no box
|
||||
pub(crate) fn text_dropdown(ui: &mut Ui, id: Id, value_left: f32, chevron_x: f32, y: f32, value: &str) -> Response {
|
||||
let look = ExportLook::get(ui.ctx());
|
||||
let enabled = ui.is_enabled();
|
||||
let rect = Rect::from_min_max(
|
||||
pos2(value_left - TEXT_DROPDOWN_PADDING, y - TEXT_DROPDOWN_HALF_HEIGHT),
|
||||
pos2(chevron_x + CHEVRON_SIZE / 2.0 + TEXT_DROPDOWN_PADDING, y + TEXT_DROPDOWN_HALF_HEIGHT),
|
||||
);
|
||||
let response = ui.interact(rect, id, if enabled { Sense::click() } else { Sense::hover() });
|
||||
let name = format!("{value} {}", ic::CARET_DOWN);
|
||||
response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &name));
|
||||
if response.hovered() && enabled {
|
||||
ui.painter().rect_filled(rect, CornerRadius::same(CONTROL_RADIUS), look.raised);
|
||||
}
|
||||
let color = if looks_disabled(ui, enabled) { look.text_dim } else { look.text };
|
||||
text_at(ui, value_left, y, value, color, false);
|
||||
glyph(ui, pos2(chevron_x, y), ic::CARET_DOWN, CHEVRON_SIZE, color);
|
||||
paint_focus(ui, &response);
|
||||
response
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
use egui::{Color32, CornerRadius, Stroke, Style, TextStyle, style::StyleModifier};
|
||||
|
||||
use crate::theme::{Tokens, contrast_ratio, lerp_color};
|
||||
|
||||
/// Text size of the whole window, labels and values alike
|
||||
pub(crate) const TEXT_SIZE: f32 = 12.0;
|
||||
|
||||
/// Height and corner radius of the window's controls: dropdowns, fields and buttons
|
||||
pub(crate) const CONTROL_HEIGHT: f32 = 25.0;
|
||||
pub(crate) const CONTROL_RADIUS: u8 = 3;
|
||||
|
||||
/// Height of an option in an open list
|
||||
const OPTION_HEIGHT: f32 = 22.0;
|
||||
/// An open list's margin round its options
|
||||
const LIST_MARGIN: i8 = 3;
|
||||
/// An option's text inset, lining up with the dropdown's value above it
|
||||
const OPTION_INSET: f32 = 3.0;
|
||||
|
||||
/// A scroll bar's strip beside its list: the bar and the air on either side of it
|
||||
const SCROLL_BAR_WIDTH: f32 = 4.0;
|
||||
const SCROLL_BAR_MARGIN: f32 = 4.0;
|
||||
|
||||
/// How far the dividers sit below the frame colour, so they read on it
|
||||
const DIVIDER_DARKENING: f32 = 0.26;
|
||||
|
||||
/// Split the difference between the field outline and text so control edges read against the panel
|
||||
const BORDER_TEXT_MIX: f32 = 0.5;
|
||||
|
||||
/// How far the Presets list's names sit from the text colour towards the dim one
|
||||
const LIST_TEXT_DIMMING: f32 = 0.37;
|
||||
|
||||
/// The Export textures window's colours from the theme: controls a step darker than the window, raised faces a step lighter
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ExportLook {
|
||||
pub(crate) window: Color32,
|
||||
pub(crate) control: Color32,
|
||||
pub(crate) control_border: Color32,
|
||||
/// A step lighter than controls: hover, lit and unusable faces
|
||||
pub(crate) raised: Color32,
|
||||
pub(crate) chrome: Color32,
|
||||
pub(crate) divider: Color32,
|
||||
pub(crate) outline: Color32,
|
||||
pub(crate) text: Color32,
|
||||
pub(crate) text_dim: Color32,
|
||||
pub(crate) list_text: Color32,
|
||||
pub(crate) accent: Color32,
|
||||
}
|
||||
|
||||
impl ExportLook {
|
||||
pub(crate) fn get(ctx: &egui::Context) -> Self {
|
||||
let tokens = Tokens::get(ctx);
|
||||
Self {
|
||||
window: tokens.panel,
|
||||
control: tokens.row,
|
||||
control_border: lerp_color(tokens.field_border, tokens.text, BORDER_TEXT_MIX),
|
||||
raised: tokens.separator,
|
||||
chrome: tokens.chrome,
|
||||
divider: lerp_color(tokens.chrome, Color32::BLACK, DIVIDER_DARKENING),
|
||||
outline: lerp_color(tokens.button_border, tokens.text, BORDER_TEXT_MIX),
|
||||
text: tokens.text,
|
||||
text_dim: tokens.text_dim,
|
||||
list_text: lerp_color(tokens.text, tokens.text_dim, LIST_TEXT_DIMMING),
|
||||
accent: tokens.accent,
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefer the theme lettering when it meets the normal-text contrast threshold.
|
||||
pub(crate) fn lettering_on(&self, fill: Color32) -> Color32 {
|
||||
const MIN_TEXT_CONTRAST: f32 = 4.5;
|
||||
if contrast_ratio(self.text, fill) >= MIN_TEXT_CONTRAST {
|
||||
return self.text;
|
||||
}
|
||||
|
||||
if contrast_ratio(Color32::WHITE, fill) >= MIN_TEXT_CONTRAST { Color32::WHITE } else { Color32::BLACK }
|
||||
}
|
||||
|
||||
/// 12 point text, the window's control colours, scroll bars in their own strip beside the list
|
||||
pub(crate) fn apply(&self, style: &mut Style) {
|
||||
for text_style in [TextStyle::Body, TextStyle::Button] {
|
||||
if let Some(font) = style.text_styles.get_mut(&text_style) {
|
||||
font.size = TEXT_SIZE;
|
||||
}
|
||||
}
|
||||
style.spacing.interact_size.y = CONTROL_HEIGHT;
|
||||
style.spacing.button_padding.x = super::drawn::VALUE_INSET;
|
||||
style.spacing.scroll = egui::style::ScrollStyle {
|
||||
bar_width: SCROLL_BAR_WIDTH,
|
||||
bar_inner_margin: SCROLL_BAR_MARGIN,
|
||||
bar_outer_margin: SCROLL_BAR_MARGIN,
|
||||
..egui::style::ScrollStyle::solid()
|
||||
};
|
||||
|
||||
// The scroll strip shows no track, only the bar
|
||||
style.visuals.extreme_bg_color = Color32::TRANSPARENT;
|
||||
let widgets = &mut style.visuals.widgets;
|
||||
for (state, fill, border) in [
|
||||
(&mut widgets.inactive, self.control, self.control_border),
|
||||
(&mut widgets.hovered, self.raised, self.outline),
|
||||
(&mut widgets.active, self.raised, self.outline),
|
||||
(&mut widgets.open, self.control, self.control_border),
|
||||
] {
|
||||
state.weak_bg_fill = fill;
|
||||
state.bg_stroke = Stroke::new(1.0, border);
|
||||
state.corner_radius = CornerRadius::same(CONTROL_RADIUS);
|
||||
state.expansion = 0.0;
|
||||
}
|
||||
|
||||
// Scroll bars and checks use the strong fill: the raised grey
|
||||
widgets.inactive.bg_fill = self.raised;
|
||||
widgets.hovered.bg_fill = self.outline;
|
||||
widgets.active.bg_fill = self.outline;
|
||||
widgets.inactive.fg_stroke.color = self.text;
|
||||
widgets.open.fg_stroke.color = self.text;
|
||||
style.visuals.selection.bg_fill = self.chrome;
|
||||
style.visuals.selection.stroke = Stroke::new(1.0, self.text);
|
||||
}
|
||||
|
||||
/// An open list: flush under its button, one light edge, the chosen option in the frame colour
|
||||
pub(crate) fn list_style(&self) -> StyleModifier {
|
||||
let look = *self;
|
||||
StyleModifier::new(move |style: &mut Style| {
|
||||
look.apply(style);
|
||||
style.spacing.interact_size.y = OPTION_HEIGHT;
|
||||
style.spacing.menu_margin = egui::Margin::same(LIST_MARGIN);
|
||||
style.spacing.button_padding.x = OPTION_INSET;
|
||||
style.spacing.item_spacing.y = 0.0;
|
||||
style.visuals.window_fill = look.control;
|
||||
style.visuals.window_stroke = Stroke::new(1.0, look.control_border);
|
||||
style.visuals.menu_corner_radius = CornerRadius::same(CONTROL_RADIUS);
|
||||
style.visuals.widgets.hovered.weak_bg_fill = look.raised;
|
||||
style.visuals.widgets.hovered.bg_stroke = Stroke::NONE;
|
||||
style.visuals.widgets.inactive.bg_stroke = Stroke::NONE;
|
||||
style.visuals.widgets.active.bg_stroke = Stroke::NONE;
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::theme::{Accent, Brightness, apply};
|
||||
|
||||
#[test]
|
||||
fn export_button_and_empty_swatch_text_and_control_edges_read_in_each_theme() {
|
||||
let context = egui::Context::default();
|
||||
for brightness in Brightness::ALL {
|
||||
for accent in Accent::ALL {
|
||||
apply(&context, brightness, accent);
|
||||
let look = ExportLook::get(&context);
|
||||
|
||||
for fill in [look.accent, look.raised] {
|
||||
assert!(contrast_ratio(look.lettering_on(fill), fill) >= 4.5, "{brightness:?} {accent:?}");
|
||||
}
|
||||
for background in [look.window, look.control] {
|
||||
assert!(contrast_ratio(look.control_border, background) >= 3.0, "{brightness:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
use egui::{Pos2, pos2};
|
||||
|
||||
/// Where a Settings page lays out from: the window's left edge, the tab row's top and the page's right edge
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct PagePlace {
|
||||
pub(super) left: f32,
|
||||
pub(super) top: f32,
|
||||
pub(super) right: f32,
|
||||
}
|
||||
|
||||
impl PagePlace {
|
||||
/// `x` from the window's left edge
|
||||
pub(super) fn x(&self, x: f32) -> f32 {
|
||||
self.left + x
|
||||
}
|
||||
|
||||
/// `y` from the top of the tab row
|
||||
pub(super) fn y(&self, y: f32) -> f32 {
|
||||
self.top + y
|
||||
}
|
||||
|
||||
/// A point `from_right` in from the page's right edge, at `y` from the tab row's top
|
||||
pub(super) fn right_inset(&self, from_right: f32, y: f32) -> Pos2 {
|
||||
pos2(self.right - from_right, self.top + y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/// A file row of LIST OF EXPORTS: the texts of its columns and its whole path
|
||||
pub(super) struct TreeFile {
|
||||
pub(super) name: String,
|
||||
pub(super) size: String,
|
||||
pub(super) format: String,
|
||||
pub(super) bits: String,
|
||||
pub(super) path: String,
|
||||
}
|
||||
+19
-10
@@ -483,7 +483,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
// The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V
|
||||
// Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V
|
||||
// Unbound Shift+Delete and Shift+Insert use the standard cut and paste shortcuts
|
||||
ctx.input_mut(|input| {
|
||||
let held = input.modifiers;
|
||||
let aliases: Vec<_> = input
|
||||
@@ -537,11 +537,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
|
||||
}
|
||||
|
||||
// The open list or the picker window closes on this Escape itself
|
||||
let export = &app.ui.export;
|
||||
let escape_is_free = !popup_open && !picker_open;
|
||||
|
||||
// Local export inputs handle Escape during drawing
|
||||
let export_input_active = app.ui.windows.export && (export.field_had_keyboard || export.pending_drop.is_some() || export.renaming.is_some());
|
||||
if confirming_reset {
|
||||
// Its keys were handled before the shortcuts ran
|
||||
} else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if escape_is_free && export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
// The Output templates question: Escape answers it with the safe choice
|
||||
app.ui.export.ask = None;
|
||||
} else if app.ui.windows.project_config.is_some() {
|
||||
@@ -551,19 +554,25 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
} else if app.ui.windows.import_resources.is_some() {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
crate::import_resources::keys_in(app, input, nothing_focused, popup_open);
|
||||
} else if !popup_open && app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if popup_open || export_input_active {
|
||||
// The open list or export input handles the key
|
||||
} else if app.picking_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.picking_color = None;
|
||||
} else if !popup_open && point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if point_pick_armed && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
cancel_point_pick = true;
|
||||
} else if escape_is_free && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if !escape_is_free {
|
||||
// The picker window handles the key
|
||||
} else if app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.properties_popup = None;
|
||||
} else if escape_is_free && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.ui.rail_panel = None;
|
||||
} else if escape_is_free && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
crate::id_color_pick::IdColorPick::end(app);
|
||||
} else if escape_is_free && app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.picking_symmetry_plane = false;
|
||||
} else if escape_is_free && app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if app.ui.windows.export {
|
||||
crate::export_window::keys_in(app, input);
|
||||
} else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.session.cancel_stroke();
|
||||
app.session.cancel_path();
|
||||
}
|
||||
|
||||
@@ -404,6 +404,9 @@ pub struct ExportUi {
|
||||
/// `file.exportTextures`).
|
||||
#[serde(default)]
|
||||
pub materialx: bool,
|
||||
/// Also write `<project>_shaders.json`: the shader's settings and the texture sets using it (`shaderParameters` of `file.exportTextures`)
|
||||
#[serde(default)]
|
||||
pub shader_parameters: bool,
|
||||
/// Texture sets excluded from export.
|
||||
pub skip: Vec<usize>,
|
||||
/// Per texture set (by index) overrides of the settings above.
|
||||
@@ -447,6 +450,9 @@ pub struct ExportUi {
|
||||
/// Output templates tab: F2 asked to rename the selected preset.
|
||||
#[serde(skip)]
|
||||
pub rename_key: bool,
|
||||
/// A text field of the window had the keyboard when the last frame ended
|
||||
#[serde(skip)]
|
||||
pub field_had_keyboard: bool,
|
||||
/// Output templates tab: the question waiting for an answer (delete, or drop an unsaved edit).
|
||||
#[serde(skip)]
|
||||
pub ask: Option<crate::export_templates::Ask>,
|
||||
@@ -478,6 +484,7 @@ impl Default for ExportUi {
|
||||
color_space: String::new(),
|
||||
usd_asset: false,
|
||||
materialx: false,
|
||||
shader_parameters: false,
|
||||
skip: Vec::new(),
|
||||
sets: Default::default(),
|
||||
owner: Vec::new(),
|
||||
@@ -492,6 +499,7 @@ impl Default for ExportUi {
|
||||
pending_drop: None,
|
||||
renaming: None,
|
||||
rename_key: false,
|
||||
field_had_keyboard: false,
|
||||
ask: None,
|
||||
opened_with: None,
|
||||
job: None,
|
||||
@@ -503,7 +511,7 @@ impl Default for ExportUi {
|
||||
|
||||
/// The LIST OF EXPORTS console's width when the window opens, as in the reference
|
||||
fn default_console_width() -> f32 {
|
||||
300.0
|
||||
crate::export_window::CONSOLE_WIDTH
|
||||
}
|
||||
|
||||
fn default_export_dir() -> String {
|
||||
|
||||
@@ -20,6 +20,8 @@ pub struct ExportJob {
|
||||
/// Also write the mesh and materials as a USD asset with the last texture set, as ticked when
|
||||
/// Export was clicked.
|
||||
pub usd_asset: bool,
|
||||
/// Also write the shader parameters with the last texture set, listing every texture set of the export, as ticked when Export was clicked
|
||||
pub shader_parameters: bool,
|
||||
/// The params of the texture sets written so far, for the USD asset.
|
||||
pub sent: Vec<serde_json::Value>,
|
||||
/// Warning messages already shown in this export.
|
||||
|
||||
@@ -10,6 +10,9 @@ pub struct MapExport {
|
||||
pub enabled: bool,
|
||||
#[serde(default)]
|
||||
pub file_type: Option<FileType>,
|
||||
/// The map's own size in texels per side, which wins over the export size
|
||||
#[serde(default)]
|
||||
pub size: Option<u32>,
|
||||
}
|
||||
|
||||
fn enabled_by_default() -> bool {
|
||||
@@ -18,6 +21,6 @@ fn enabled_by_default() -> bool {
|
||||
|
||||
impl Default for MapExport {
|
||||
fn default() -> Self {
|
||||
MapExport { enabled: true, file_type: None }
|
||||
MapExport { enabled: true, file_type: None, size: None }
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,11 @@ pub struct SetExport {
|
||||
impl SetExport {
|
||||
/// Whether anything is overridden (the set is marked "*").
|
||||
pub fn any(&self) -> bool {
|
||||
self.preset.is_some() || self.file_type.is_some() || self.size.is_some() || self.padding.is_some() || self.maps.values().any(|m| m.file_type.is_some())
|
||||
self.preset.is_some()
|
||||
|| self.file_type.is_some()
|
||||
|| self.size.is_some()
|
||||
|| self.padding.is_some()
|
||||
|| self.maps.values().any(|m| m.file_type.is_some() || m.size.is_some())
|
||||
}
|
||||
|
||||
/// Whether the set exports as the global settings say (no override, every map ticked).
|
||||
|
||||
@@ -449,7 +449,7 @@ pub fn legible_tint(tint: Color32, background: Color32, text: Color32) -> Color3
|
||||
const WCAG_FLARE: f32 = 0.05;
|
||||
|
||||
/// The WCAG contrast ratio of two opaque colors (1..21)
|
||||
fn contrast_ratio(a: Color32, b: Color32) -> f32 {
|
||||
pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f32 {
|
||||
let luminance = |color: Color32| {
|
||||
let linear = egui::Rgba::from(color);
|
||||
|
||||
|
||||
@@ -234,12 +234,15 @@ pub fn project_file_name(app: &TextureCraftApp) -> String {
|
||||
fn zip_files(files: Vec<ExportedFile>) -> Result<Vec<u8>, String> {
|
||||
let mut zip = craft_zip::Writer::new();
|
||||
for f in files {
|
||||
// add_with reserves ZIP64 headers up front, even for small entries.
|
||||
// Reserve ZIP64 headers up front, even for small entries
|
||||
zip.add_with(&f.name, craft_zip::Compression::Deflated, |out| out.write_all(&f.bytes)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
zip.finish().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
use texturecraft_engine::shader_parameters::shader_parameters_sidecar;
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub use web::{
|
||||
download, export_mesh, export_textures, import_bake_mesh, import_environment, import_images, import_material, import_preset, open, open_sample_project,
|
||||
@@ -357,14 +360,24 @@ mod web {
|
||||
}
|
||||
|
||||
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())?);
|
||||
}
|
||||
let options = jobs
|
||||
.iter()
|
||||
.map(|(_, params)| texturecraft_engine::file_cmds::export_options(&app.session, params, "file.exportTextures"))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|error| error.to_string())?;
|
||||
let jobs_with_options = jobs.iter().zip(&options).map(|((set_index, _), options)| (*set_index, options));
|
||||
let mut files = app.session.export_file_jobs(jobs_with_options).map_err(|error| error.to_string())?;
|
||||
|
||||
// Keep one file for each case-insensitive name in the download
|
||||
texturecraft_engine::formats::skip_repeated_names(&mut files);
|
||||
if app.ui.export.shader_parameters {
|
||||
let sets: Vec<usize> = jobs.iter().map(|(set_index, _)| *set_index).collect();
|
||||
match shader_parameters_sidecar(&app.session.doc.project, &sets, &files) {
|
||||
Ok(sidecar) => files.push(sidecar),
|
||||
Err(error) => {
|
||||
app.session.log.warnings("MapExporter", [format!("The shader settings file was not written: {error}")]);
|
||||
app.toast(trf("The shader settings file was not written: {error}", &[("error", &error)]), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
app.session.log.warnings("MapExporter", files.iter().flat_map(|file| file.warnings.iter().cloned()));
|
||||
let file_count = files.len();
|
||||
|
||||
@@ -530,6 +543,28 @@ mod tests {
|
||||
assert!(harness.state().session.doc.bake_meshes.cage.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shader_sidecar_does_not_take_a_texture_folder_name() {
|
||||
let project = texturecraft_engine::core::Project::new("Chair", "builtin:sphere");
|
||||
let name = "chair_SHADERS.json/Color.png";
|
||||
let mut files = vec![ExportedFile { name: name.into(), bytes: vec![1, 2, 3], width: 1, height: 1, warnings: Vec::new() }];
|
||||
|
||||
let error = shader_parameters_sidecar(&project, &[], &files).unwrap_err();
|
||||
|
||||
assert!(error.contains("Chair_shaders.json"));
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].name, name);
|
||||
|
||||
files[0].name = "Chair_shaders.json_backup/Color.png".into();
|
||||
files.push(shader_parameters_sidecar(&project, &[], &files).unwrap());
|
||||
let bytes = zip_files(files).unwrap();
|
||||
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
|
||||
assert_eq!(archive.len(), 2);
|
||||
assert!(archive.by_name("Chair_shaders.json_backup/Color.png").is_ok());
|
||||
assert!(archive.by_name("Chair_shaders.json").is_ok());
|
||||
}
|
||||
|
||||
#[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() };
|
||||
|
||||
@@ -2,15 +2,21 @@
|
||||
//! name pattern, and its own file type and bit depth.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use egui_kittest::kittest::{NodeT as _, Queryable as _};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::state::{FileType, MapExport, SetExport};
|
||||
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
/// The Export textures window open on the first texture set's page
|
||||
fn harness() -> Harness<'static, TextureCraftApp> {
|
||||
harness_at(egui::vec2(1600.0, 960.0))
|
||||
}
|
||||
|
||||
fn harness_at(size: egui::Vec2) -> 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))
|
||||
.with_size(size)
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
@@ -48,25 +54,57 @@ fn plan(h: &mut Harness<'_, TextureCraftApp>) -> Vec<serde_json::Value> {
|
||||
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_eq!(h.get_all_by_label_contains("Enable override for ").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
|
||||
// A pattern longer than the column (the packed template's) is cut at the front, the whole one is its tooltip
|
||||
h.state_mut().ui.export.preset = "Unreal Engine (Packed)".into();
|
||||
h.run_steps(4);
|
||||
let preset = texturecraft_engine::formats::builtin_preset(&h.state().ui.export.preset).unwrap();
|
||||
let long =
|
||||
plan(&mut h).iter().map(|f| preset.maps[f["map"].as_u64().unwrap() as usize].file.clone()).find(|p| p.chars().count() > 26).expect("a long pattern");
|
||||
let cut: String = format!("…{}", long.chars().skip(long.chars().count() - 25).collect::<String>());
|
||||
let long = preset.maps.iter().map(|map| map.file.clone()).max_by_key(|file| file.chars().count()).unwrap();
|
||||
let cut = h
|
||||
.query_all_by_label_contains("…")
|
||||
.find_map(|node| node.accesskit_node().value().filter(|text| long.ends_with(text.trim_start_matches('…'))))
|
||||
.expect("the pattern's end, cut at the front");
|
||||
assert!(h.query_by_label(&long).is_none(), "{long} is cut");
|
||||
let at = h.get_all_by_label(&cut).next().unwrap().rect().center();
|
||||
let at = h.get_all_by_role_and_label(egui::Role::Label, &cut).next().unwrap().rect().center();
|
||||
h.hover_at(at);
|
||||
h.run_steps(30);
|
||||
|
||||
assert!(h.query_by_label(&long).is_some(), "the tooltip has the whole {long}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_psd_preflight_keeps_map_controls_available() {
|
||||
let mut h = harness();
|
||||
let available = plan(&mut h).len();
|
||||
assert!(available >= 3);
|
||||
let preset = h.state().ui.export.preset.clone();
|
||||
let settings = &mut h.state_mut().ui.export;
|
||||
settings.format = "psd".into();
|
||||
settings.bit_depth = 16;
|
||||
settings.size = 8192;
|
||||
let params = serde_json::json!({"ts": 0, "preset": preset, "format": "psd", "bitDepth": 16, "size": 8192});
|
||||
|
||||
let error = texturecraft_engine::execute(&mut h.state_mut().session, "export.plan", ¶ms).unwrap_err();
|
||||
assert!(error.to_string().contains("2 GiB"), "{error}");
|
||||
h.run_steps(4);
|
||||
|
||||
assert_eq!(h.get_all_by_label_contains("Enable override for map ").count(), available);
|
||||
let size = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list");
|
||||
size.click();
|
||||
h.run_steps(4);
|
||||
click(&mut h, "128x128");
|
||||
|
||||
assert!(maps(&h).values().any(|map| map.size == Some(128)));
|
||||
assert_eq!(h.state().ui.export.size, 8192);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() {
|
||||
let mut h = harness();
|
||||
@@ -77,21 +115,25 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() {
|
||||
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, "Output maps menu");
|
||||
click(&mut h, "Uncheck all");
|
||||
|
||||
assert_eq!(selected(&h), before - rows);
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Output maps menu");
|
||||
click(&mut h, "Invert all");
|
||||
|
||||
assert_eq!(selected(&h), before);
|
||||
assert!(!h.state().ui.export.sets.contains_key(&0), "nothing left to remember");
|
||||
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Output maps menu");
|
||||
click(&mut h, "Uncheck all");
|
||||
click(&mut h, "Include all");
|
||||
|
||||
assert_eq!(selected(&h), before, "Include all ticks the output maps too");
|
||||
}
|
||||
|
||||
@@ -99,18 +141,21 @@ fn unticking_a_map_leaves_it_out_and_the_menu_ticks_all() {
|
||||
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.get_all_by_label_contains("Enable override for ").nth(4).unwrap().click();
|
||||
h.run_steps(4);
|
||||
let m = maps(&h);
|
||||
let (_, first) = m.iter().next().unwrap();
|
||||
|
||||
assert!(first.file_type.is_some(), "{m:?}");
|
||||
assert!(h.query_by_label("*").is_some(), "the set is marked");
|
||||
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Output maps menu");
|
||||
click(&mut h, "Override every item");
|
||||
|
||||
assert_eq!(maps(&h).values().filter(|m| m.file_type.is_some()).count(), rows);
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Output maps menu");
|
||||
click(&mut h, "Clear all overrides");
|
||||
|
||||
assert!(maps(&h).is_empty());
|
||||
}
|
||||
|
||||
@@ -118,11 +163,10 @@ fn a_map_override_sets_its_own_file_type_and_marks_the_set() {
|
||||
fn export_writes_a_map_with_its_own_file_type() {
|
||||
let mut h = harness();
|
||||
let first = plan(&mut h)[0]["map"].as_u64().unwrap() as usize;
|
||||
let dir = std::env::temp_dir().join(format!("tc-export-map-overrides-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let dir = TempDir::new("export-map-overrides");
|
||||
let template = h.state().ui.export.preset.clone();
|
||||
let mut o = SetExport { maps_template: template, ..SetExport::default() };
|
||||
o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }) });
|
||||
o.maps.insert(first, MapExport { enabled: true, file_type: Some(FileType { format: "targa".into(), bit_depth: 8, dithering: false }), size: None });
|
||||
let e = &mut h.state_mut().ui.export;
|
||||
e.dir = dir.display().to_string();
|
||||
e.sets.insert(0, o);
|
||||
@@ -139,9 +183,9 @@ fn export_writes_a_map_with_its_own_file_type() {
|
||||
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();
|
||||
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]
|
||||
@@ -150,9 +194,10 @@ fn a_map_the_template_no_longer_has_is_ignored() {
|
||||
let before = selected(&h);
|
||||
let template = h.state().ui.export.preset.clone();
|
||||
let mut o = SetExport { maps_template: template, ..SetExport::default() };
|
||||
o.maps.insert(999, MapExport { enabled: false, file_type: None });
|
||||
o.maps.insert(999, MapExport { enabled: false, file_type: None, size: None });
|
||||
h.state_mut().ui.export.sets.insert(0, o);
|
||||
h.run_steps(3);
|
||||
|
||||
assert_eq!(selected(&h), before, "the export still plans every file");
|
||||
}
|
||||
|
||||
@@ -166,3 +211,91 @@ fn each_row_names_its_own_map() {
|
||||
assert!(h.query_all_by_label_contains(&format!("_{id}")).next().is_some(), "a row for {id}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texture_set_map_sizes_are_reachable_on_a_narrow_screen() {
|
||||
let mut h = harness_at(egui::vec2(800.0, 480.0));
|
||||
let header = h.get_by_label("General Export Parameters").rect().center();
|
||||
let size_rect = |h: &Harness<'_, TextureCraftApp>| {
|
||||
h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map size list").rect()
|
||||
};
|
||||
let before = size_rect(&h);
|
||||
|
||||
h.hover_at(header);
|
||||
h.event(egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: egui::vec2(-500.0, -200.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
});
|
||||
h.run_steps(12);
|
||||
|
||||
let after = size_rect(&h);
|
||||
|
||||
assert!(after.left() < before.left(), "{before:?} → {after:?}");
|
||||
assert!(h.ctx.content_rect().contains_rect(after), "{after:?}");
|
||||
h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).unwrap().click();
|
||||
h.run_steps(4);
|
||||
click(&mut h, "128x128");
|
||||
|
||||
assert!(maps(&h).values().any(|map| map.size == Some(128)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_map_picks_its_own_size_and_the_export_writes_it_at_that_size() {
|
||||
let mut h = harness();
|
||||
let expected = plan(&mut h);
|
||||
let first = expected[0]["map"].as_u64().unwrap() as usize;
|
||||
let combo = h.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Export size")).expect("a map's size list");
|
||||
combo.click();
|
||||
h.run_steps(4);
|
||||
click(&mut h, "128x128");
|
||||
|
||||
assert_eq!(maps(&h).get(&first).and_then(|map| map.size), Some(128), "{:?}", maps(&h));
|
||||
assert!(h.query_by_label("*").is_some(), "the set is marked");
|
||||
|
||||
let dir = TempDir::new("export-map-sizes");
|
||||
let set_count = h.state().session.set_count();
|
||||
let export = &mut h.state_mut().ui.export;
|
||||
export.dir = dir.display().to_string();
|
||||
export.skip = (1..set_count).collect();
|
||||
h.run_steps(3);
|
||||
click(&mut h, "Export");
|
||||
for _ in 0..64 {
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.run_steps(2);
|
||||
|
||||
assert_eq!(std::fs::read_dir(&*dir).unwrap().count(), expected.len());
|
||||
for file in expected {
|
||||
let path = dir.join(file["file"].as_str().unwrap());
|
||||
let side = if file["map"].as_u64().unwrap() as usize == first { 128 } else { 256 };
|
||||
|
||||
assert_eq!(image::image_dimensions(&path).unwrap(), (side, side), "{}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_with_a_one_depth_file_type_each_have_their_own_bit_depth_list() {
|
||||
let mut h = harness();
|
||||
let rows: Vec<usize> = plan(&mut h).iter().take(2).map(|file| file["map"].as_u64().unwrap() as usize).collect();
|
||||
let template = h.state().ui.export.preset.clone();
|
||||
let mut o = SetExport { maps_template: template, ..SetExport::default() };
|
||||
for map in &rows {
|
||||
o.maps.insert(*map, MapExport { enabled: true, file_type: Some(FileType { format: "hdr".into(), bit_depth: 32, dithering: false }), size: None });
|
||||
}
|
||||
h.state_mut().ui.export.sets.insert(0, o);
|
||||
h.run_steps(4);
|
||||
|
||||
let greyed: Vec<_> =
|
||||
h.get_all_by_role(egui::Role::ComboBox).filter(|node| node.value().as_deref() == Some("32f bits")).map(|node| node.accesskit_node().id()).collect();
|
||||
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert_eq!(greyed.len(), 2, "each row's greyed bit depth list is its own node");
|
||||
assert_ne!(greyed[0], greyed[1]);
|
||||
}
|
||||
@@ -33,13 +33,13 @@ fn click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
|
||||
/// Open the General Export Parameters menu
|
||||
fn page_menu(h: &mut Harness<'_, TextureCraftApp>) {
|
||||
h.get_all_by_label(egui_phosphor::regular::LIST_CHECKS).nth(1).unwrap().click();
|
||||
h.get_by_label("General Export Parameters menu").click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// 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.get_all_by_label_contains("Enable override for ").nth(row).unwrap().click();
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
@@ -63,8 +63,9 @@ fn png_width(path: &std::path::Path) -> u32 {
|
||||
#[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");
|
||||
assert!(h.get_all_by_label_contains("Enable override for ").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}");
|
||||
@@ -302,3 +303,19 @@ fn an_empty_file_type_override_keeps_the_template_types_under_a_global_one() {
|
||||
h.run_steps(4);
|
||||
assert!(h.query_all_by_label("png 16 bits").next().is_some(), "the set still writes the template's types");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_size_override_changes_only_the_size_row() {
|
||||
let mut harness = harness();
|
||||
let size = harness.state().session.doc.project.texture_sets[0].block_resolution();
|
||||
|
||||
harness.get_by_role_and_label(egui::Role::Button, "Enable override for Size").focus();
|
||||
harness.run_steps(2);
|
||||
harness.key_press(egui::Key::Space);
|
||||
harness.run_steps(4);
|
||||
|
||||
let settings = overrides(&harness);
|
||||
|
||||
assert_eq!(settings.size, Some(size));
|
||||
assert!(settings.preset.is_none() && settings.file_type.is_none() && settings.padding.is_none() && settings.maps.is_empty());
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! progress bar with Cancel Export, and the window staying open.
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::NodeT;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use serde_json::json;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
@@ -50,6 +51,7 @@ fn export_shows_progress_logs_the_steps_and_keeps_the_window_open() {
|
||||
assert_eq!(h.state().ui.export.tab, 2, "Export switches to LIST OF EXPORTS");
|
||||
h.run_steps(1);
|
||||
assert!(h.query_by_label("Cancel Export").is_some());
|
||||
assert_eq!(h.get_by_role(egui::Role::ProgressIndicator).accesskit_node().live(), egui::accesskit::Live::Polite);
|
||||
assert!(h.query_by_label("Cancel").is_none(), "the progress bar replaces the buttons");
|
||||
assert_eq!(console(&h).first().map(String::as_str), Some("Preparing texture export"));
|
||||
|
||||
@@ -134,7 +136,7 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() {
|
||||
assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some());
|
||||
assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some());
|
||||
assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none());
|
||||
assert!(h.query_by_label("CONSOLE").is_some());
|
||||
assert!(h.query_by_label("Console").is_some());
|
||||
|
||||
// A row's tooltip is the full path
|
||||
let preset = h.state().ui.export.preset.clone();
|
||||
@@ -143,17 +145,50 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() {
|
||||
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 strip at the console's edge hides it, then shows it again
|
||||
h.get_by_role_and_label(egui::Role::Button, "Hide Console").click();
|
||||
h.run_steps(4);
|
||||
assert!(h.state().ui.export.console_hidden && h.query_by_label("CONSOLE").is_none());
|
||||
|
||||
assert!(h.state().ui.export.console_hidden && h.query_by_label("Console").is_none());
|
||||
h.get_by_role_and_label(egui::Role::Button, "Show Console").click();
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(!h.state().ui.export.console_hidden);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_filenames_leave_the_export_details_reachable_by_scrolling() {
|
||||
let (mut h, _) = harness("wide-tree");
|
||||
let name = "Wide".repeat(44);
|
||||
h.state_mut().session.doc.project.texture_sets[0].name.clone_from(&name);
|
||||
h.state_mut().ui.export.tab = 2;
|
||||
h.run_steps(4);
|
||||
let bits_label = "16 bits";
|
||||
let bits_fit = |h: &Harness<'_, TextureCraftApp>| {
|
||||
h.output().shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == bits_label => clipped.clip_rect.contains_rect(text.visual_bounding_rect()),
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
assert!(!bits_fit(&h), "the bit-depth column starts beyond the viewport");
|
||||
h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).focus();
|
||||
h.run_steps(3);
|
||||
assert!(h.get_by_role_and_label(egui::Role::DisclosureTriangle, &name).is_focused());
|
||||
|
||||
for _ in 0..12 {
|
||||
h.key_press(egui::Key::ArrowRight);
|
||||
h.run_steps(2);
|
||||
}
|
||||
h.run_steps(10);
|
||||
|
||||
assert!(bits_fit(&h), "horizontal keyboard scrolling brings bit depth into the viewport");
|
||||
assert!(h.query_all_by_label(bits_label).next().is_some(), "bit depth has an accessibility label");
|
||||
assert!(h.query_by_label("Console").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_output_directory_asks_the_system_to_show_the_folder() {
|
||||
let (mut h, dir) = harness("open");
|
||||
@@ -220,6 +255,40 @@ fn texture_sets_writing_the_same_file_name_do_not_start_an_export() {
|
||||
let _ = std::fs::remove_dir_all(&library);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_texture_set_cannot_export_into_another_sets_psd_file() {
|
||||
use texturecraft_ui_egui::state::SetExport;
|
||||
|
||||
let (mut h, _) = harness("psd-folder-clash");
|
||||
let scratch = tempfile::tempdir().unwrap();
|
||||
let dir = scratch.path().join("textures");
|
||||
let library = tempfile::tempdir().unwrap();
|
||||
let app = h.state_mut();
|
||||
app.ui.export.dir = dir.display().to_string();
|
||||
app.session.load_export_presets(library.path().to_path_buf());
|
||||
let psd = json!({"name": "Layered", "maps": [
|
||||
{"file": "roughness", "format": "Psd", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}
|
||||
]});
|
||||
app.run("export.preset.save", json!({"preset": psd})).unwrap();
|
||||
let plan = app.run("export.plan", json!({"preset": "Layered", "ts": 0})).unwrap();
|
||||
let file_name = plan[0]["file"].as_str().unwrap();
|
||||
let nested = json!({"name": "Nested", "maps": [
|
||||
{"file": format!("{file_name}/detail"), "format": "Png", "bit_depth": 8, "channels": [["L", {"Channel": {"channel": "Roughness"}}]]}
|
||||
]});
|
||||
app.run("export.preset.save", json!({"preset": nested})).unwrap();
|
||||
app.ui.export.preset = "Layered".into();
|
||||
app.ui.export.sets.insert(1, SetExport { preset: Some("Nested".into()), ..Default::default() });
|
||||
h.run_steps(4);
|
||||
|
||||
click(&mut h, "Export");
|
||||
finish(&mut h);
|
||||
|
||||
assert!(h.state().ui.export.job.is_none());
|
||||
assert_eq!(exports(&h), 0, "the full selection must be checked before starting");
|
||||
assert!(!dir.exists());
|
||||
assert!(console(&h).iter().any(|line| line.contains("folder")), "{:?}", console(&h));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_another_project_stops_the_export() {
|
||||
let (mut h, dir) = harness("project");
|
||||
|
||||
@@ -52,7 +52,7 @@ fn the_window_has_the_reference_size() {
|
||||
let h = harness(egui::vec2(1600.0, 960.0));
|
||||
let reset = window_button_rect(&h, "Reset all", 1600.0);
|
||||
let export = window_button_rect(&h, "Export", 1600.0);
|
||||
let tabs = h.get_by_label("SETTINGS").rect();
|
||||
let tabs = h.get_by_role_and_label(egui::Role::Tab, "Settings").rect();
|
||||
|
||||
let width = export.max.x - reset.min.x;
|
||||
let height = export.max.y - tabs.min.y;
|
||||
|
||||
@@ -75,6 +75,47 @@ fn closing_the_window_is_cancel() {
|
||||
assert_eq!(h.state().ui.export.size, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_is_cancel() {
|
||||
let mut h = harness();
|
||||
h.state_mut().ui.export.size = 2048;
|
||||
h.run_steps(3);
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(!h.state().ui.windows.export);
|
||||
assert_eq!(h.state().ui.export.size, 0, "the opening settings are back");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_cancels_when_a_button_has_keyboard_focus() {
|
||||
let mut h = harness();
|
||||
h.get_by_role_and_label(egui::Role::Button, "Save settings").focus();
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.get_by_role_and_label(egui::Role::Button, "Save settings").is_focused());
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(!h.state().ui.windows.export);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_in_an_open_dropdown_closes_only_the_dropdown() {
|
||||
let mut h = harness();
|
||||
open_combo(&mut h, "Based on output template");
|
||||
|
||||
assert!(h.query_by_label("png").is_some());
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.query_by_label("png").is_none(), "the dropdown closed");
|
||||
assert!(h.state().ui.windows.export, "the window stays open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lists_hold_the_reference_entries() {
|
||||
let mut h = harness();
|
||||
@@ -122,15 +163,18 @@ fn a_saved_legacy_preset_name_resolves_to_its_current_name() {
|
||||
fn the_set_list_menu_checks_unchecks_and_inverts() {
|
||||
let mut h = harness();
|
||||
let sets = h.state().session.set_count();
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Texture set list menu");
|
||||
click(&mut h, "Uncheck all");
|
||||
|
||||
assert_eq!(h.state().ui.export.skip.len(), sets);
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Texture set list menu");
|
||||
click(&mut h, "Invert all");
|
||||
|
||||
assert!(h.state().ui.export.skip.is_empty());
|
||||
h.state_mut().ui.export.skip = vec![0];
|
||||
click(&mut h, egui_phosphor::regular::LIST_CHECKS);
|
||||
click(&mut h, "Texture set list menu");
|
||||
click(&mut h, "Check all");
|
||||
|
||||
assert!(h.state().ui.export.skip.is_empty());
|
||||
}
|
||||
|
||||
@@ -140,9 +184,8 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() {
|
||||
let default = h.state().ui.export.dir.clone();
|
||||
h.state_mut().ui.export.dir = "/somewhere/else".into();
|
||||
h.run_steps(3);
|
||||
hover(&mut h, "R");
|
||||
assert!(h.query_by_label("Reset to default").is_some());
|
||||
click(&mut h, "R");
|
||||
click(&mut h, "Reset to default");
|
||||
|
||||
assert_eq!(h.state().ui.export.dir, default);
|
||||
|
||||
hover(&mut h, "16");
|
||||
@@ -152,11 +195,13 @@ fn the_output_directory_resets_and_the_dilation_follows_the_padding() {
|
||||
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");
|
||||
}
|
||||
@@ -174,3 +219,24 @@ fn the_page_reset_puts_the_parameters_back() {
|
||||
assert_eq!((e.size, e.padding.as_str()), (0, "infinite"));
|
||||
assert_eq!(e.skip, vec![0], "the texture set ticks are not parameters of the page");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_escape_clears_a_pick_before_cancelling_export() {
|
||||
let mut h = harness();
|
||||
let pick = egui::Id::unique("export_escape_screen_color_pick");
|
||||
h.state_mut().picking_color = Some(pick);
|
||||
h.state_mut().ui.export.size = 512;
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.state().picking_color.is_none(), "the armed pick receives Escape first");
|
||||
assert!(h.query_by_role_and_label(egui::Role::Button, "Save settings").is_some());
|
||||
assert_eq!(h.state().ui.export.size, 512);
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(!h.state().ui.windows.export);
|
||||
assert_eq!(h.state().ui.export.size, 0);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Export textures › SETTINGS: Export shader settings writes `<project>_shaders.json`, the
|
||||
//! shader's settings and every texture set of the export, with the export's last texture set
|
||||
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable as _;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
use super::temp_dir::TempDir;
|
||||
|
||||
#[test]
|
||||
fn ticking_export_shader_settings_writes_the_json_listing_every_exported_set() {
|
||||
let session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let mut h = Harness::builder()
|
||||
.with_size(egui::vec2(1600.0, 960.0))
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
h.run_steps(4);
|
||||
let dir = TempDir::new("export-shader-parameters");
|
||||
h.state_mut().ui.export.dir = dir.display().to_string();
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
|
||||
h.get_by_role_and_label(egui::Role::CheckBox, "Export shader settings").click();
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.state().ui.export.shader_parameters);
|
||||
h.get_all_by_label("Export").last().unwrap().click();
|
||||
for _ in 0..64 {
|
||||
h.run_steps(1);
|
||||
if h.state().ui.export.job.is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
h.run_steps(2);
|
||||
|
||||
let project = &h.state().session.doc.project;
|
||||
let file = dir.join(texturecraft_engine::shader_parameters::shader_parameters_file(&project.name));
|
||||
let json: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap_or_else(|_| panic!("{} was written", file.display()))).unwrap();
|
||||
let names: Vec<&str> = project.texture_sets.iter().map(|set| set.name.as_str()).collect();
|
||||
|
||||
assert_eq!(json["shaders"][0]["textureSets"], serde_json::json!(names), "every texture set of the export, written once: {json}");
|
||||
assert!(json["shaders"][0]["parameters"]["ior"].is_number());
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use egui::Key;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
use serde_json::json;
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
@@ -169,3 +169,20 @@ fn the_settings_dropdown_asks_about_an_unfinished_edit_too() {
|
||||
texturecraft_ui_egui::export_templates::select(h.state_mut(), "Beta tpl".into());
|
||||
assert_eq!(selected(&h), "Beta tpl", "a valid edit switches at once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_templates_keeps_export_and_save_until_an_edit_does_not_validate() {
|
||||
let library = Library::new("footer-on-templates");
|
||||
let mut h = harness(&library);
|
||||
|
||||
// The window's footer is drawn after the app's own menus, which have an Export too
|
||||
let disabled = |h: &Harness<'_, TextureCraftApp>, label: &str| h.get_all_by_label(label).last().unwrap().accesskit_node().is_disabled();
|
||||
|
||||
assert!(!disabled(&h, "Export"), "Export works from the templates tab");
|
||||
assert!(!disabled(&h, "Save settings"), "Save settings works from the templates tab");
|
||||
|
||||
break_draft(&mut h);
|
||||
|
||||
assert!(disabled(&h, "Export"), "an invalid edit holds Export");
|
||||
assert!(disabled(&h, "Save settings"), "an invalid edit holds Save settings");
|
||||
}
|
||||
@@ -447,6 +447,7 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() {
|
||||
layer
|
||||
};
|
||||
h.run_steps(3);
|
||||
|
||||
assert_eq!(h.state().session.selected_layer(), Some(selected));
|
||||
|
||||
let at = thumb(&h, "Masked fill", true);
|
||||
@@ -455,19 +456,22 @@ fn thumbnail_menus_apply_actions_to_the_clicked_layer_and_stack() {
|
||||
h.get_by_label("Toggle mask").click();
|
||||
h.run_steps(3);
|
||||
let project = &h.state().session.doc.project;
|
||||
|
||||
assert!(!project.layers[&clicked].mask.as_ref().unwrap().enabled);
|
||||
assert!(project.layers[&selected].mask.as_ref().unwrap().enabled);
|
||||
assert_eq!(h.state().session.target, StackTarget::Mask);
|
||||
|
||||
// The same layer's mask is still selected when its material menu opens.
|
||||
// Opening the material menu must preserve the selected mask
|
||||
let at = thumb(&h, "Masked fill", false);
|
||||
right_click(&mut h, at);
|
||||
assert!(h.query_by_label("Toggle mask").is_none());
|
||||
|
||||
// The same items as the toolbar's Add effect on the content: a generator can't go there, so it is greyed
|
||||
assert!(h.get_by_label_contains("Add generator").accesskit_node().is_disabled());
|
||||
h.get_by_label_contains("Add levels").click();
|
||||
h.run_steps(3);
|
||||
let layer = &h.state().session.doc.project.layers[&clicked];
|
||||
|
||||
assert_eq!(layer.content_effects.len(), 2);
|
||||
assert_eq!(layer.mask.as_ref().unwrap().effects.len(), 1);
|
||||
}
|
||||
|
||||
@@ -34,6 +34,7 @@ mod export_overrides;
|
||||
mod export_progress;
|
||||
mod export_reference_texts;
|
||||
mod export_settings;
|
||||
mod export_shader_parameters;
|
||||
mod export_template_guards;
|
||||
mod export_usd_asset;
|
||||
mod file_dialogs;
|
||||
|
||||
@@ -18,9 +18,13 @@ use template_library::TemplateLibrary;
|
||||
|
||||
/// OUTPUT TEMPLATES with the user template "Mine" selected
|
||||
fn harness(library: &TemplateLibrary) -> Harness<'static, TextureCraftApp> {
|
||||
harness_at(library, egui::vec2(1600.0, 960.0))
|
||||
}
|
||||
|
||||
fn harness_at(library: &TemplateLibrary, size: egui::Vec2) -> 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))
|
||||
.with_size(size)
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
h.state_mut().ui.prefs.language = "en".into();
|
||||
@@ -98,24 +102,38 @@ fn right_click(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
|
||||
fn the_tab_shows_the_preset_tools_and_map_editor() {
|
||||
let library = TemplateLibrary::new("layout");
|
||||
let mut h = harness(&library);
|
||||
for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:", "Drop an input map onto a channel to assign it to that output."] {
|
||||
for text in ["Presets", "Naming pattern", "Current preset:", "Output maps", "Create:"] {
|
||||
assert!(h.query_by_label(text).is_some(), "{text}");
|
||||
}
|
||||
let hint = "Drop an input map onto a channel to assign it to that output.";
|
||||
|
||||
assert!(h.query_by_label(hint).is_none(), "the drag hint is no line under the cards");
|
||||
let metallic = h.get_by_role_and_label(egui::Role::ListItem, "Metallic").rect().center();
|
||||
h.hover_at(metallic);
|
||||
h.run_steps(30);
|
||||
|
||||
assert!(h.query_by_label(hint).is_some(), "a map entry's tooltip says how to use it");
|
||||
h.hover_at(egui::pos2(1.0, 1.0));
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.get_all_by_role(egui::Role::ComboBox).any(|c| c.value().as_deref() == Some("OpenPBR")));
|
||||
let maps = h.state().session.export_preset("Mine").unwrap().maps.len();
|
||||
let ts = h.state().session.ts();
|
||||
let plan = h.state_mut().run("export.plan", json!({"preset": "Mine", "ts": ts})).unwrap();
|
||||
let exported = plan.as_array().unwrap().len();
|
||||
assert!(h.query_by_label(&format!("{exported} output maps will be exported.")).is_some());
|
||||
|
||||
assert!(h.query_by_label(&format!("{exported} output maps will be exported")).is_some());
|
||||
for create in ["Gray", "RGB", "R+G+B", "RGB+A", "R+G+B+A"] {
|
||||
assert!(h.query_by_label(create).is_some(), "{create}");
|
||||
}
|
||||
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());
|
||||
}
|
||||
@@ -152,12 +170,17 @@ fn the_right_click_menu_renames_and_removes_user_templates_only() {
|
||||
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);
|
||||
|
||||
assert!(h.state().ui.export.renaming.is_none(), "Escape ends the rename");
|
||||
assert!(h.state().ui.windows.export, "and leaves the window open");
|
||||
|
||||
right_click(&mut h, "Mine");
|
||||
click(&mut h, "Remove");
|
||||
|
||||
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);
|
||||
@@ -191,17 +214,19 @@ fn the_preview_ignores_a_texture_sets_output_map_settings() {
|
||||
h.state_mut().run("export.preset.save", json!({ "preset": two })).unwrap();
|
||||
let own = "Unreal Engine (Packed)".to_string();
|
||||
let mut o = texturecraft_ui_egui::state::SetExport { preset: Some(own.clone()), maps_template: own, ..Default::default() };
|
||||
o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None });
|
||||
o.maps.insert(2, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None });
|
||||
let ts = h.state().session.ts();
|
||||
h.state_mut().ui.export.sets.insert(ts, o);
|
||||
h.state_mut().ui.export.preset = "Two".into();
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.query_by_label_contains("Not saved").is_none(), "the preview plans the template on show");
|
||||
let plan = h.state_mut().run("export.plan", json!({"preset": "Two", "ts": ts})).unwrap();
|
||||
for index in 0..2 {
|
||||
let file = plan.as_array().unwrap().iter().find(|f| f["map"] == index).unwrap()["file"].as_str().unwrap().to_string();
|
||||
hover_name_field(&mut h, index);
|
||||
let planned = format!("{} {file}", egui_phosphor::regular::ARROW_RIGHT);
|
||||
|
||||
assert!(h.query_all_by_label(&planned).next().is_some(), "map {index} shows its own file {file}");
|
||||
}
|
||||
}
|
||||
@@ -211,7 +236,7 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() {
|
||||
let library = TemplateLibrary::new("follow");
|
||||
let mut h = harness(&library);
|
||||
let mut o = texturecraft_ui_egui::state::SetExport { preset: Some("Mine".into()), maps_template: "Mine".into(), ..Default::default() };
|
||||
o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None });
|
||||
o.maps.insert(1, texturecraft_ui_egui::state::MapExport { enabled: false, file_type: None, size: None });
|
||||
|
||||
// The override is there when the window opens
|
||||
h.state_mut().ui.windows.export = false;
|
||||
@@ -229,19 +254,23 @@ fn texture_set_overrides_follow_a_renamed_template_and_drop_a_removed_one() {
|
||||
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")));
|
||||
}
|
||||
|
||||
@@ -260,11 +289,12 @@ fn the_footer_counts_only_the_maps_the_texture_set_exports() {
|
||||
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}");
|
||||
hover_name_field(&mut h, 1);
|
||||
assert!(h.query_all_by_label_contains("Not exported").next().is_some(), "the sheen row says so");
|
||||
assert!(h.query_by_label("1 output maps will be exported.").is_some());
|
||||
assert!(h.query_by_label("2 output maps will be exported.").is_none());
|
||||
assert!(h.query_by_label("1 output maps will be exported").is_some());
|
||||
assert!(h.query_by_label("2 output maps will be exported").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -273,13 +303,14 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() {
|
||||
let mut h = harness(&library);
|
||||
|
||||
// The first texture set leaves out the template's first map
|
||||
let off = MapExport { enabled: false, file_type: None };
|
||||
let off = MapExport { enabled: false, file_type: None, size: None };
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() });
|
||||
h.run_steps(2);
|
||||
let first = h.state().session.export_preset("Mine").unwrap().maps[0].file.clone();
|
||||
move_map(&mut h, 0, "Move down");
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -287,7 +318,7 @@ fn per_map_settings_follow_their_map_when_the_template_reorders_it() {
|
||||
fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() {
|
||||
let library = TemplateLibrary::new("stale");
|
||||
let mut h = harness(&library);
|
||||
let off = MapExport { enabled: false, file_type: None };
|
||||
let off = MapExport { enabled: false, file_type: None, size: None };
|
||||
h.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, off.clone())].into(), ..SetExport::default() });
|
||||
h.run_steps(2);
|
||||
let saved = h.state().session.export_preset("Mine").unwrap();
|
||||
@@ -309,8 +340,10 @@ fn a_draft_in_the_same_order_as_the_external_save_remaps_from_that_order() {
|
||||
h.run_steps(2);
|
||||
move_map(&mut h, 0, "Move down");
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -324,7 +357,7 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() {
|
||||
let mut external = saved.clone();
|
||||
external.maps.swap(0, 1);
|
||||
harness.state_mut().run("export.preset.save", json!({"preset": external})).unwrap();
|
||||
let disabled = MapExport { enabled: false, file_type: None };
|
||||
let disabled = MapExport { enabled: false, file_type: None, size: None };
|
||||
harness.state_mut().ui.export.sets.insert(0, SetExport { maps_template: "Mine".into(), maps: [(0, disabled.clone())].into(), ..SetExport::default() });
|
||||
harness.run_steps(3);
|
||||
|
||||
@@ -334,17 +367,18 @@ fn a_retained_draft_keeps_overrides_with_maps_after_an_external_reorder() {
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() {
|
||||
fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_has_no_count_or_reset() {
|
||||
let library = TemplateLibrary::new("bottom-bar");
|
||||
let h = harness(&library);
|
||||
|
||||
let naming = h.get_by_label("Naming pattern").rect();
|
||||
let tabs = h.get_by_label("OUTPUT TEMPLATES").rect();
|
||||
let tabs = h.get_by_role_and_label(egui::Role::Tab, "Output templates").rect();
|
||||
let presets = h.get_by_label("Presets").rect();
|
||||
|
||||
assert!(naming.center().y < presets.top() && (naming.center().y - tabs.center().y).abs() < tabs.height(), "on the tab row: {naming:?}");
|
||||
@@ -353,13 +387,13 @@ fn the_tab_row_holds_the_naming_pattern_and_the_bottom_bar_only_cancels() {
|
||||
assert!(h.query_by_label(absent).is_none(), "{absent}");
|
||||
}
|
||||
assert!(h.query_by_label_contains("textures selected for export").is_none());
|
||||
for greyed in ["Save settings", "Export"] {
|
||||
for active in ["Save settings", "Export", "Cancel"] {
|
||||
// The rail at the right edge has an Export button of its own
|
||||
let button =
|
||||
h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(greyed)).unwrap();
|
||||
assert!(button.accesskit_node().is_disabled(), "{greyed}");
|
||||
h.get_all_by_role(egui::Role::Button).rfind(|b| b.rect().max.x < RAIL_LEFT_EDGE && b.accesskit_node().label().as_deref() == Some(active)).unwrap();
|
||||
|
||||
assert!(!button.accesskit_node().is_disabled(), "{active}");
|
||||
}
|
||||
assert!(!h.get_all_by_label("Cancel").last().unwrap().accesskit_node().is_disabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -494,6 +528,31 @@ fn a_color_map_dropped_on_the_rgb_swatch_offers_rgb_channels() {
|
||||
assert!(h.query_all_by_label("RGB: Base color, RGB").next().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_in_a_file_name_field_leaves_the_field_and_keeps_the_window() {
|
||||
let library = TemplateLibrary::new("escape-in-a-field");
|
||||
let mut h = harness(&library);
|
||||
let field = name_field(&h, 0).center();
|
||||
h.hover_at(field);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos: field, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.step();
|
||||
}
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.ctx.egui_wants_keyboard_input(), "the field has the keyboard");
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.state().ui.windows.export, "the window stays open");
|
||||
assert!(!h.ctx.egui_wants_keyboard_input(), "the field let go of the keyboard");
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(!h.state().ui.windows.export, "a second Escape is Cancel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_closes_the_from_popup_without_assigning() {
|
||||
let library = TemplateLibrary::new("drop-escape");
|
||||
@@ -513,6 +572,7 @@ fn escape_closes_the_from_popup_without_assigning() {
|
||||
|
||||
assert!(h.query_by_label("Which part of Metallic?").is_none(), "Escape closes the popup");
|
||||
assert!(h.state().ui.export.pending_drop.is_none());
|
||||
assert!(h.state().ui.windows.export, "the window stays open");
|
||||
assert_eq!(h.state().session.export_preset("Mine").unwrap(), before, "nothing was assigned");
|
||||
}
|
||||
|
||||
@@ -592,7 +652,7 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() {
|
||||
click(&mut h, "R+G+B+A");
|
||||
|
||||
let input_maps = h.get_by_label("Input maps").rect();
|
||||
let removes: Vec<egui::Rect> = h.get_all_by_label("Remove this output").map(|node| node.rect()).collect();
|
||||
let removes: Vec<egui::Rect> = h.get_all_by_label_contains("Remove output ").map(|node| node.rect()).collect();
|
||||
let alpha = last_window_button(&h, "A: Empty (writes white)").rect();
|
||||
|
||||
assert!(!removes.is_empty());
|
||||
@@ -610,12 +670,121 @@ fn on_a_small_screen_an_rgba_row_keeps_its_controls_in_the_window() {
|
||||
// The row's file format list starts right of its last swatch instead of covering it
|
||||
let format =
|
||||
h.get_all_by_role(egui::Role::Button).rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png"))).unwrap().rect();
|
||||
|
||||
assert!(alpha.right() <= format.left(), "the swatches and the lists do not overlap: {alpha:?} {format:?}");
|
||||
|
||||
// The panes stay inside the window: the side pane ends where the bottom bar's buttons end
|
||||
let cancel = h.get_all_by_label("Cancel").last().unwrap().rect();
|
||||
let export = last_window_button(&h, "Export").rect();
|
||||
let converted = h.get_by_label("Converted maps").rect();
|
||||
|
||||
assert!(cancel.max.x <= 1000.0 && cancel.max.y <= 700.0, "{cancel:?}");
|
||||
assert!(converted.left() < export.right() && converted.right() <= export.right() + 1.0, "{converted:?} {export:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_narrow_template_editor_keeps_the_alpha_swatch_clear_of_the_file_type_menu() {
|
||||
let library = TemplateLibrary::new("narrow-template-editor");
|
||||
let mut harness = harness_at(&library, egui::vec2(800.0, 480.0));
|
||||
let create = harness.get_by_role_and_label(egui::Role::Button, "R+G+B+A");
|
||||
create.scroll_to_me();
|
||||
harness.run_steps(4);
|
||||
|
||||
click(&mut harness, "R+G+B+A");
|
||||
let alpha = last_window_button(&harness, "A: Empty (writes white)").rect();
|
||||
let format = harness
|
||||
.get_all_by_role(egui::Role::Button)
|
||||
.rfind(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with("png")))
|
||||
.unwrap()
|
||||
.rect();
|
||||
|
||||
assert!(alpha.right() <= format.left(), "alpha {alpha:?} overlaps format {format:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hovering_a_channel_swatch_shows_the_file_its_output_writes() {
|
||||
let library = TemplateLibrary::new("map-preview");
|
||||
let mut h = harness(&library);
|
||||
let swatch =
|
||||
h.get_all_by_role(egui::Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with("B: Metallic"))).unwrap().rect().center();
|
||||
let pictures = h.query_all_by_role(egui::Role::Image).count();
|
||||
let roughness_lines = h.query_all_by_label("Roughness, gray value").count();
|
||||
let file_names = h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count();
|
||||
|
||||
assert!(h.query_by_label_contains(" · png").is_none(), "nothing shows before the hover");
|
||||
|
||||
h.hover_at(swatch);
|
||||
h.run_steps(30);
|
||||
|
||||
assert!(h.query_all_by_label_contains("OcclusionRoughnessMetallic.png").count() > file_names, "the file's name");
|
||||
assert!(h.query_by_label_contains(" · png").is_some(), "the file's size and type");
|
||||
assert!(h.query_all_by_role(egui::Role::Image).count() > pictures, "the file and its channels, small");
|
||||
assert!(h.query_all_by_label("Roughness, gray value").count() > roughness_lines, "another channel's source is named");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaving_output_templates_releases_pictures_from_each_hovered_map() {
|
||||
let library = TemplateLibrary::new("preview-lifetime");
|
||||
let mut h = harness(&library);
|
||||
let previews = |h: &Harness<'_, TextureCraftApp>| {
|
||||
h.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("export_map_preview_")).count()
|
||||
};
|
||||
let hover_map = |h: &mut Harness<'_, TextureCraftApp>, name: &str| {
|
||||
let swatch = h
|
||||
.get_all_by_role(egui::Role::Button)
|
||||
.find(|button| button.accesskit_node().label().is_some_and(|label| label.starts_with(name)))
|
||||
.unwrap_or_else(|| panic!("no swatch for {name}"))
|
||||
.rect();
|
||||
h.hover_at(swatch.center());
|
||||
h.run_steps(30);
|
||||
};
|
||||
|
||||
hover_map(&mut h, "B: Metallic");
|
||||
let first = previews(&h);
|
||||
|
||||
assert!(first > 0);
|
||||
hover_map(&mut h, "RGB: Base color");
|
||||
assert!(previews(&h) > first);
|
||||
|
||||
click(&mut h, "Settings");
|
||||
|
||||
assert_eq!(previews(&h), 0);
|
||||
|
||||
click(&mut h, "Output templates");
|
||||
hover_map(&mut h, "B: Metallic");
|
||||
assert_eq!(previews(&h), first);
|
||||
click(&mut h, "Cancel");
|
||||
|
||||
assert_eq!(previews(&h), 0);
|
||||
|
||||
h.state_mut().ui.windows.export = true;
|
||||
h.run_steps(4);
|
||||
click(&mut h, "Output templates");
|
||||
hover_map(&mut h, "B: Metallic");
|
||||
assert_eq!(previews(&h), first);
|
||||
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(!h.state().ui.windows.export);
|
||||
assert_eq!(previews(&h), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_template_preview_counts_overrides_only_for_its_own_maps() {
|
||||
let library = TemplateLibrary::new("preview-map-overrides");
|
||||
let mut h = harness(&library);
|
||||
let ts = h.state().session.ts();
|
||||
let plan = h.state_mut().run("export.plan", json!({"ts": ts, "preset": "Mine"})).unwrap();
|
||||
let initial = plan.as_array().unwrap().len();
|
||||
assert!(initial > 0);
|
||||
let disabled = MapExport { enabled: false, ..MapExport::default() };
|
||||
h.state_mut().ui.export.sets.insert(ts, SetExport { maps_template: "Mine".into(), maps: [(0, disabled)].into(), ..SetExport::default() });
|
||||
|
||||
h.run_steps(4);
|
||||
|
||||
assert!(h.query_by_label(&format!("{} output maps will be exported", initial - 1)).is_some());
|
||||
h.state_mut().ui.export.sets.get_mut(&ts).unwrap().preset = Some("Separate maps".into());
|
||||
h.run_steps(4);
|
||||
assert!(h.query_by_label(&format!("{initial} output maps will be exported")).is_some());
|
||||
}
|
||||
@@ -115,22 +115,26 @@ fn the_export_panel_leads_to_export_textures_and_the_mesh_options() {
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(harness.state().ui.windows.export, "Export Textures... opens the Export textures window");
|
||||
for label in
|
||||
["SETTINGS", "OUTPUT TEMPLATES", "LIST OF EXPORTS", "Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"]
|
||||
{
|
||||
for tab in ["Settings", "Output templates", "List of exports"] {
|
||||
assert!(harness.query_by_role_and_label(egui::Role::Tab, tab).is_some(), "{tab}");
|
||||
}
|
||||
for label in ["Include all", "Global settings", "General Export Parameters", "Reset all", "Save settings"] {
|
||||
assert!(harness.query_by_label(label).is_some(), "{label}");
|
||||
}
|
||||
assert!(harness.query_by_label_contains("textures selected for export").is_some());
|
||||
assert!(!says_not_available(&mut harness, "Export USD asset"));
|
||||
assert!(says_not_available(&mut harness, "Export shader settings"));
|
||||
for label in ["Export USD asset", "Export shader settings"] {
|
||||
assert!(!says_not_available(&mut harness, label), "{label}");
|
||||
}
|
||||
|
||||
harness.get_by_label("Save settings").click();
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(!harness.state().ui.windows.export, "Save settings closes the window");
|
||||
|
||||
click_rail(&mut harness, "Export");
|
||||
button_left_of_rail(&harness, "Export Mesh...").click();
|
||||
harness.run_steps(SETTLE_FRAMES);
|
||||
|
||||
assert!(harness.query_by_label("Mesh Export Options").is_some(), "Export Mesh... asks for the options first");
|
||||
}
|
||||
|
||||
|
||||
@@ -3445,3 +3445,93 @@ fn sheet_scroll_end_snapshots() {
|
||||
harness.run_steps(30);
|
||||
save(&mut harness, &output_dir, "sheet-end-scrolled-medium");
|
||||
}
|
||||
|
||||
/// The Export textures window on each tab at its mocks' size; TC_SNAPSHOT_THEME=medium (default), dark or light
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn export_window_snapshots() {
|
||||
use texturecraft_ui_egui::state::{FileType, MapExport, SetExport};
|
||||
|
||||
// Below General Export Parameters, where the 1112x662 window draws nothing
|
||||
const EMPTY_SPOT: egui::Pos2 = egui::pos2(736.0, 530.0);
|
||||
|
||||
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return };
|
||||
std::fs::create_dir_all(&output_dir).unwrap();
|
||||
let (brightness, theme) = match std::env::var("TC_SNAPSHOT_THEME").as_deref() {
|
||||
Ok("dark") => (Brightness::Dark, "dark"),
|
||||
Ok("light") => (Brightness::Light, "light"),
|
||||
_ => (Brightness::MediumDark, "medium"),
|
||||
};
|
||||
|
||||
// Ball and Base, then enough texture sets that the set list scrolls
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let template = session.doc.project.texture_sets[0].clone();
|
||||
while session.doc.project.texture_sets.len() < 60 {
|
||||
let mut set = template.clone();
|
||||
set.name = format!("Set {}", session.doc.project.texture_sets.len() + 1);
|
||||
session.doc.project.texture_sets.push(set);
|
||||
}
|
||||
let mut harness = Harness::builder()
|
||||
.with_size(egui::vec2(1112.0, 662.0))
|
||||
.with_pixels_per_point(2.0)
|
||||
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
|
||||
.wgpu()
|
||||
.build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
harness.state_mut().ui.prefs.language = "en".into();
|
||||
harness.state_mut().ui.prefs.brightness = brightness;
|
||||
harness.set_render_cursor(false);
|
||||
{
|
||||
let e = &mut harness.state_mut().ui.export;
|
||||
e.dir = "/home/user/Documents/TextureCraft/export".into();
|
||||
e.preset = "Document channels + Normal + AO (No Alpha)".into();
|
||||
e.padding = "infinite".into();
|
||||
e.skip = vec![4];
|
||||
}
|
||||
harness.state_mut().ui.windows.export = true;
|
||||
harness.run_steps(4);
|
||||
let color_space = harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Default")).unwrap().rect();
|
||||
harness.hover_at(color_space.center());
|
||||
harness.run_steps(30);
|
||||
save(&mut harness, &output_dir, &format!("ep-settings-global-{theme}"));
|
||||
harness.hover_at(egui::pos2(1.0, 1.0));
|
||||
|
||||
harness.get_all_by_role(egui::Role::ComboBox).find(|combo| combo.value().as_deref() == Some("Based on output template")).unwrap().click();
|
||||
harness.run_steps(3);
|
||||
save(&mut harness, &output_dir, &format!("ep-settings-file-type-open-{theme}"));
|
||||
harness.key_press(egui::Key::Escape);
|
||||
harness.run_steps(3);
|
||||
|
||||
// The closed list keeps the keyboard focus (and its ring) until a click lands on the page's empty column
|
||||
harness.hover_at(EMPTY_SPOT);
|
||||
for pressed in [true, false] {
|
||||
harness.event(egui::Event::PointerButton { pos: EMPTY_SPOT, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
|
||||
harness.step();
|
||||
}
|
||||
harness.hover_at(egui::pos2(1.0, 1.0));
|
||||
harness.run_steps(3);
|
||||
|
||||
// Base with its own size and its height map as 32-bit exr
|
||||
{
|
||||
let e = &mut harness.state_mut().ui.export;
|
||||
e.page = Some(1);
|
||||
let mut set = SetExport { size: Some(1024), ..SetExport::default() };
|
||||
set.maps_template = e.preset.clone();
|
||||
let template = texturecraft_engine::formats::builtin_preset(&e.preset).unwrap();
|
||||
let height = template.maps.iter().position(|map| texturecraft_engine::formats::export::channel_label(map) == "height").unwrap();
|
||||
set.maps.insert(height, MapExport { file_type: Some(FileType { format: "exr".into(), bit_depth: 32, dithering: false }), ..MapExport::default() });
|
||||
set.maps.insert(2, MapExport { enabled: false, ..MapExport::default() });
|
||||
e.sets.insert(1, set);
|
||||
}
|
||||
save(&mut harness, &output_dir, &format!("ep-settings-set-{theme}"));
|
||||
|
||||
harness.state_mut().ui.export.page = None;
|
||||
harness.state_mut().ui.export.tab = 1;
|
||||
harness.state_mut().ui.export.preset = "Unreal Engine (Packed)".into();
|
||||
harness.run_steps(3);
|
||||
harness.get_by_role_and_label(egui::Role::Button, "Unreal Engine (Packed)").scroll_to_me();
|
||||
save(&mut harness, &output_dir, &format!("ep-templates-unreal-{theme}"));
|
||||
|
||||
harness.state_mut().ui.export.preset = "Document channels + Normal + AO (No Alpha)".into();
|
||||
harness.state_mut().ui.export.tab = 2;
|
||||
save(&mut harness, &output_dir, &format!("ep-list-{theme}"));
|
||||
}
|
||||
@@ -42,11 +42,19 @@ file runs it; Copy mask to clipboard puts the same mask on the system clipboard
|
||||
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?}]`.
|
||||
`textures_export` tool accept `maps: [{map, enabled?, format?, bitDepth?, dithering?, size?}]`.
|
||||
Each entry overrides that map's export settings. The `map` field is its index in the selected
|
||||
template. `enabled: false` suppresses that file while reserving its name. When several texture
|
||||
sets produce the same name (ignoring case), programmatic and browser exports keep the first file
|
||||
and warn about later duplicates. The desktop export window reports the collision before writing.
|
||||
template. A map's `size` in pixels overrides the export size. `enabled: false` leaves out a PSD layer
|
||||
or suppresses a raster file while reserving its name. When several texture sets produce the same
|
||||
name (ignoring case), programmatic and browser exports keep the first file and warn about later
|
||||
duplicates. The desktop export window reports the collision before writing. Texture planning
|
||||
rejects a selection that uses the same path as both a file and a folder before rendering.
|
||||
|
||||
`shaderParameters: true` writes `<project>_shaders.json` beside the textures with the shader
|
||||
model, its settings and the names of the exported texture sets. An array of texture set
|
||||
indexes selects which sets to list. The desktop command, headless `textures.export` and MCP
|
||||
`textures_export` include a written sidecar in `files` and report a sidecar write failure in
|
||||
`warnings` after writing the textures.
|
||||
|
||||
`file.exportTextures` with `usdAsset` also writes `<mesh>.usd` (binary USD, Crate) next to the textures: the whole mesh
|
||||
(every texture set, whatever `ts` selects) with one UsdPreviewSurface material per texture set. A
|
||||
@@ -77,9 +85,31 @@ shared by different sets.
|
||||
`format` accepts the export window's names (`bmp`, `jpeg`, `jng`, `pgm`, `png`, `targa`, `tiff`,
|
||||
`hdr`, `exr`, `webp`, `psd`) and their extensions. `bitDepth: 32` selects floating point for
|
||||
TIFF, EXR and HDR. `dithering: true` dithers 8-bit integer output with an ordered pattern, and
|
||||
`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels). `padding: "diffusion"` dilates by
|
||||
`export.plan` reports the effective setting and per-file dimensions (`size` and `sourceSize`, both in pixels).
|
||||
Tiled files include their UV tile number in `tile` and, when available, their filename template
|
||||
with a `<UDIM>` placeholder in `udimPattern`. These fields are null when they do not apply.
|
||||
`export.preview` takes the same parameters plus `map` (an index into the template's maps) and
|
||||
`side` (the maximum width or height, in pixels, capped at 512). It returns
|
||||
`{width, height, channels, pixels}` for the first texture set named by `ts`, or null when the
|
||||
set writes no file for that map. For a UV-tiled set the picture shows the atlas. HDR previews
|
||||
list RGB without alpha. TIFF and WebP previews list RGB or RGBA when the encoder stores
|
||||
luminance in three channels. PSD previews show the output layer's RGBA channels. The preview uses 8-bit values,
|
||||
with sRGB colour channels and linear data channels. Texels outside the UV islands use the
|
||||
channel defaults.
|
||||
`padding: "diffusion"` dilates by
|
||||
`dilation` texels and fills the remaining space with a smooth blend of the island colours.
|
||||
|
||||
Layered PSD: the maps written as `psd` are the layers of one `<mesh>_<texture set>.psd` per
|
||||
texture set and UV tile (`<mesh>_<texture set>.<UDIM>.psd` for a tiled set), so the template's file
|
||||
names don't name the file: they become the layer names, a `/` in one making layer groups. The
|
||||
document name is sanitized like other file names and can be shortened or disambiguated (a
|
||||
texture-set index suffix when two sets' names give the same stem, as "A B" and "A_B" do), so read
|
||||
the actual names from `export.plan`. A PSD that would pass 30000 pixels a side or 2 GiB is left
|
||||
out with a warning on the set's first other file (an error when it is the set's only file). In the
|
||||
browser, estimates of a PSD's working buffers and of a batch's encoded PSD output are also bounded;
|
||||
they don't bound the tab's total memory, as raster outputs and ZIP packaging use memory outside
|
||||
them. MaterialX uses compatible companion maps for this format. USD omits their texture bindings and returns a warning.
|
||||
|
||||
`effect.set {effect, filter: "blur", radius: 5}` replaces a filter in place, preserving its
|
||||
stack position, blend, opacity and visibility. Replacement filters start from defaults plus
|
||||
the supplied parameters; naming the current filter instead edits it without resetting omitted
|
||||
|
||||
+1
-1
@@ -186,7 +186,7 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
|
||||
stroke turns it on for the Normal map if the set has no Auto-rebake map.
|
||||
- **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map),
|
||||
Unity Standard, Unity URP Lit, USD Preview Surface, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz,
|
||||
anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in
|
||||
anisotropy, transmission and subsurface maps), Unreal Engine (subsurface profile), glTF specular/glossiness (archived extension), Redshift Standard Material, Roblox SurfaceAppearance, Sketchfab (metalness), separate maps, mesh maps and document channels, in
|
||||
PNG, JPEG, JNG, PGM, TGA, TIFF, BMP, WEBP, PSD, EXR or HDR at 8 bits (optionally dithered), 16
|
||||
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.
|
||||
|
||||
Reference in new issue
Block a user