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:
Chris Hassebrook authored and GitHub committed 2026-11-27 22:55:22 -05:00
commit d41cf01f7f
63 files changed
+5994 -1625

No files matched your search

+183 -46
View File
@@ -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(&parameters).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);
+1
View File
@@ -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;
+95 -17
View File
@@ -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() {
+93
View File
@@ -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"));
}
}