mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 17:19:24 +01:00
Export: PSD file type writes every output map of a texture set as a layer of one file
The layers and the merged image are written with craft-psd's PsdBuilder. The USD asset and MaterialX leave the PSD out (with a warning for the USD asset).
This commit is contained in:
1 parent
7a3b95e798
commit
c561a0578f
12 files changed
+608
-287
No files matched your search
@@ -58,7 +58,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|j2k|jp2|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, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, 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|j2k|jp2|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?}] (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, JP2, TIFF and WebP, the chromaticities in EXR; TGA, BMP, HDR, J2K, 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?}",
|
||||
always,
|
||||
export_textures
|
||||
),
|
||||
@@ -76,7 +76,7 @@ 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, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name and warns about later duplicates)",
|
||||
always,
|
||||
plan
|
||||
),
|
||||
@@ -457,6 +457,7 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
"size": size,
|
||||
"sourceSize": source_size,
|
||||
"warnings": output.warnings,
|
||||
"layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::<Vec<_>>(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -763,7 +764,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}"));
|
||||
@@ -773,7 +774,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:"));
|
||||
@@ -794,6 +795,12 @@ 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));
|
||||
if kept.iter().any(|file| file.format == FileFormat::Psd) {
|
||||
let warning = format!("The USD asset doesn't read PSD files, so the material of texture set \"{}\" leaves out its PSD 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));
|
||||
}
|
||||
}
|
||||
@@ -841,7 +848,7 @@ fn reserve_export_names(
|
||||
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);
|
||||
blocked_maps.extend(plan.maps());
|
||||
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
|
||||
@@ -854,7 +861,7 @@ fn reserve_export_names(
|
||||
return true;
|
||||
}
|
||||
|
||||
blocked_maps.insert(plan.map);
|
||||
blocked_maps.extend(plan.maps());
|
||||
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",
|
||||
|
||||
@@ -197,8 +197,10 @@ 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" };
|
||||
|
||||
@@ -407,3 +407,16 @@ 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}");
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! 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_texel::linear_to_srgb;
|
||||
|
||||
use super::encoding::Encoding;
|
||||
use super::map_renderer::MapRenderer;
|
||||
use super::{ExportedFile, FileFormat, PSD_MAX_FILE_BYTES, PSD_RGBA_PLANES, PlannedFile, quantize_integer};
|
||||
use crate::{FormatError, Result};
|
||||
|
||||
/// Where alpha sits in an RGBA texel
|
||||
const ALPHA_INDEX: usize = 3;
|
||||
|
||||
/// Render the layers of `planned` one at a time and write them as one PSD
|
||||
pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile) -> Result<ExportedFile> {
|
||||
let PlannedFile { name, tile, bit_depth, mut warnings, layers, .. } = planned;
|
||||
let size = renderer.size(tile)?;
|
||||
|
||||
// Each layer as straight RGBA in 0-1, sRGB-encoded where the map's file would be, dropped once quantized
|
||||
let mut composite = vec![0.0f32; size.0 as usize * size.1 as usize * PSD_RGBA_PLANES];
|
||||
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 rgba = to_rgba(&map.data, map.component_count, &map.srgb);
|
||||
drop(map);
|
||||
over(&mut composite, &rgba);
|
||||
let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither };
|
||||
let bytes = quantize_integer(encoding, size.0, PSD_RGBA_PLANES, rgba.into_iter())?;
|
||||
pixels.push((layer.name.as_str(), pixel_data(bytes, bit_depth)));
|
||||
}
|
||||
if let Some(space) = embedded {
|
||||
warnings.push(format!("PSD export does not embed a colour space; the colours are in {}", space.name()));
|
||||
}
|
||||
|
||||
let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: false };
|
||||
let composite = pixel_data(quantize_integer(encoding, size.0, PSD_RGBA_PLANES, composite.into_iter())?, bit_depth);
|
||||
|
||||
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 })
|
||||
}
|
||||
|
||||
/// L, LA, RGB or RGBA samples as RGBA (gray repeated, opaque without alpha), sRGB transfer applied to the components `srgb` marks, values clamped to 0-1
|
||||
fn to_rgba(data: &[f32], component_count: usize, srgb: &[bool]) -> Vec<f32> {
|
||||
let encode = |component: usize, value: f32| if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(value) } else { value.clamp(0.0, 1.0) };
|
||||
data.chunks_exact(component_count.max(1))
|
||||
.flat_map(|texel| {
|
||||
let encoded = |component| encode(component, texel.get(component).copied().unwrap_or(0.0));
|
||||
match component_count {
|
||||
1 => [encoded(0), encoded(0), encoded(0), 1.0],
|
||||
2 => [encoded(0), encoded(0), encoded(0), encoded(1)],
|
||||
3 => [encoded(0), encoded(1), encoded(2), 1.0],
|
||||
_ => [encoded(0), encoded(1), encoded(2), encoded(3)],
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lay straight-alpha RGBA `layer` over `below`, in place
|
||||
fn over(below: &mut [f32], layer: &[f32]) {
|
||||
for (under, top) in below.as_chunks_mut::<PSD_RGBA_PLANES>().0.iter_mut().zip(layer.as_chunks::<PSD_RGBA_PLANES>().0) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// Native-endian quantized RGBA samples as the PSD builder takes them
|
||||
fn pixel_data(bytes: Vec<u8>, depth: u8) -> PixelData {
|
||||
if depth == 16 { PixelData::Rgba16(bytes.as_chunks::<2>().0.iter().map(|sample| u16::from_ne_bytes(*sample)).collect()) } else { PixelData::Rgba8(bytes) }
|
||||
}
|
||||
|
||||
/// 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, 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, 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, width, height, pixels));
|
||||
}
|
||||
for _ in open {
|
||||
builder.end_group()?;
|
||||
}
|
||||
|
||||
builder.composite(composite);
|
||||
builder.to_bytes()
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
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() != width as usize * height as usize {
|
||||
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 {
|
||||
set,
|
||||
comp: input.composite,
|
||||
baked: input.baked,
|
||||
coverage: input.coverage,
|
||||
res: width,
|
||||
tile_res,
|
||||
scales: set.block_scales(),
|
||||
normal_override: options.normal_format,
|
||||
project_normal: input.project.normal_format,
|
||||
};
|
||||
Ok(MapRenderer { options, set, sampler, dilation_map, grid, width, height, tile_res })
|
||||
}
|
||||
|
||||
/// The export size of a file of `tile` (None: the whole set).
|
||||
pub(super) fn size(&self, 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.size);
|
||||
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(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 matches!(options.padding, Padding::DilationDiffusion(_)) {
|
||||
let known: Vec<bool> = (y0..y0 + h)
|
||||
.flat_map(|y| (x0..x0 + w).map(move |x| (x, y)))
|
||||
.map(|(x, y)| sampler.covered(x, y) || dilation_map.is_some_and(|d| d.source(x, y).is_some()))
|
||||
.collect();
|
||||
|
||||
// Keep diffusion within each UV tile when rendering an atlas
|
||||
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, &known, 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 })
|
||||
}
|
||||
}
|
||||
+154
-216
@@ -21,15 +21,21 @@ use serde::{Deserialize, Serialize};
|
||||
use texturecraft_compose::{BakedMaps, Composite};
|
||||
use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb};
|
||||
use texturecraft_texel::{ColorSpace, linear_to_srgb};
|
||||
|
||||
use crate::{FormatError, MAX_IMAGE_SIZE, Result};
|
||||
|
||||
mod encoding;
|
||||
mod jpeg2000;
|
||||
mod layered_psd;
|
||||
mod map_override;
|
||||
mod map_renderer;
|
||||
mod planned_layer;
|
||||
mod rendered_map;
|
||||
use encoding::Encoding;
|
||||
pub use map_override::MapOverride;
|
||||
use map_renderer::MapRenderer;
|
||||
pub use planned_layer::PlannedLayer;
|
||||
|
||||
/// Height-to-normal slope: with strength 1, a height change of 1 across 1/16 of the texture
|
||||
/// width tilts the normal 45°, at any resolution.
|
||||
@@ -37,6 +43,8 @@ const HEIGHT_SPAN: f32 = 16.0;
|
||||
const JPEG_QUALITY: u8 = 95;
|
||||
const PSD_MAX_SIDE_PIXELS: u32 = 30_000;
|
||||
const PSD_MAX_FILE_BYTES: u64 = 2 * 1024 * 1024 * 1024;
|
||||
/// Planes of a PSD image or layer: red, green, blue and alpha
|
||||
const PSD_RGBA_PLANES: usize = 4;
|
||||
/// Preset limits (user presets are untrusted JSON).
|
||||
const MAX_MAPS: usize = 64;
|
||||
const MAX_TEMPLATE: usize = 256;
|
||||
@@ -92,7 +100,7 @@ pub enum FileFormat {
|
||||
Jng,
|
||||
/// Portable graymap (binary).
|
||||
Pgm,
|
||||
/// A PSD containing only its merged image.
|
||||
/// Photoshop document: every output map of a texture set in this format as a layer of one file
|
||||
Psd,
|
||||
/// JPEG 2000 codestream, lossless
|
||||
J2k,
|
||||
@@ -517,6 +525,16 @@ pub struct PlannedFile {
|
||||
/// covers every tile refers to); None when the file isn't tiled.
|
||||
pub udim_name: Option<String>,
|
||||
pub warnings: Vec<String>,
|
||||
/// A PSD's output maps, top layer first (`map` is the first); empty for a file of one map
|
||||
pub layers: Vec<PlannedLayer>,
|
||||
}
|
||||
|
||||
impl PlannedFile {
|
||||
/// The output maps the file writes
|
||||
pub fn maps(&self) -> impl Iterator<Item = usize> + '_ {
|
||||
let own = self.layers.is_empty().then_some(self.map);
|
||||
own.into_iter().chain(self.layers.iter().map(|layer| layer.map))
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -592,8 +610,7 @@ pub fn sanitize_file_path(s: &str) -> String {
|
||||
s.split('/').map(sanitize_file_stem).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
/// The files `opts` produces for texture set `ts`, without rendering (for the export dialog).
|
||||
/// Template variables: [`FILE_TOKENS`].
|
||||
/// The files `opts` produces for texture set `ts` without rendering ([`FILE_TOKENS`] are the template variables); PSD maps are layers of one file
|
||||
pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOptions) -> Result<Vec<PlannedFile>> {
|
||||
opts.preset.validate()?;
|
||||
let set = project.texture_set(ts)?;
|
||||
@@ -607,9 +624,10 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
let mut active_files = BTreeSet::new();
|
||||
let mut active_dirs = BTreeSet::new();
|
||||
let mut out = Vec::new();
|
||||
|
||||
// Maps written as PSD layers, with their tile, bit depth and warnings
|
||||
let mut psd_layers: Vec<(Option<u32>, PlannedLayer, u8, Vec<String>)> = Vec::new();
|
||||
let tiles: Vec<Option<u32>> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() };
|
||||
let grid = set.tile_grid();
|
||||
let block_resolution = set.block_resolution();
|
||||
for (i, map) in opts.preset.maps.iter().enumerate() {
|
||||
if !map.channels.iter().any(|(_, s)| source_present(set, s)) {
|
||||
continue;
|
||||
@@ -619,7 +637,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
let format = own.and_then(|o| o.format).or(opts.format_override).unwrap_or(map.format);
|
||||
let bit_depth = format.depth(own.and_then(|o| o.bit_depth).or(opts.bit_depth_override).unwrap_or(map.bit_depth));
|
||||
let enabled = own.is_none_or(|o| o.enabled);
|
||||
let psd_channels = (enabled && format == FileFormat::Psd).then(|| layout(set, map).len());
|
||||
let dither = bit_depth == 8 && !format.holds_float(bit_depth) && own.and_then(|o| o.dither).unwrap_or(opts.dither);
|
||||
let space = opts.space_for_map(map, format, bit_depth);
|
||||
let requested_space = opts.space_for_depth(format, bit_depth);
|
||||
@@ -636,25 +653,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
// Append `$udim` to names for separate UV tiles
|
||||
let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() };
|
||||
for &tile in &tiles {
|
||||
if let Some(channels) = psd_channels {
|
||||
let size = match (tile, grid) {
|
||||
(Some(tile), Some(_)) => {
|
||||
let side = tile_side(set, tile, block_resolution);
|
||||
let side = scale_export_side(side, block_resolution, opts.size);
|
||||
(side, side)
|
||||
}
|
||||
(_, Some(grid)) => {
|
||||
let side = opts.size.unwrap_or(block_resolution);
|
||||
(side.saturating_mul(grid.cols), side.saturating_mul(grid.rows))
|
||||
}
|
||||
(_, None) => {
|
||||
let side = opts.size.unwrap_or(block_resolution);
|
||||
(side, side)
|
||||
}
|
||||
};
|
||||
check_psd_size(size, channels, bit_depth)?;
|
||||
}
|
||||
|
||||
// A name of the project, mesh or texture set never adds a folder
|
||||
let no_folder = |name: &str| name.replace('/', "_");
|
||||
let stem = template
|
||||
@@ -678,7 +676,6 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
});
|
||||
let stem = sanitize_file_path(&stem);
|
||||
let ext = format.extension();
|
||||
let mut name = format!("{stem}.{ext}");
|
||||
let mut warnings = Vec::new();
|
||||
if color_map
|
||||
&& format == FileFormat::Pgm
|
||||
@@ -698,51 +695,123 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
|
||||
format.extension().to_uppercase()
|
||||
));
|
||||
}
|
||||
let packs_colour = |name: &str| {
|
||||
(color_map && requested_space != space)
|
||||
.then(|| format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name()))
|
||||
};
|
||||
|
||||
// Compare names case-insensitively for Windows and macOS
|
||||
let mut k = 2;
|
||||
while used.contains(&name.to_ascii_lowercase()) {
|
||||
name = format!("{stem}_{k}.{ext}");
|
||||
k += 1;
|
||||
// The PSD's own name holds the tile number, so its layers are named without the one appended
|
||||
if format == FileFormat::Psd {
|
||||
if enabled {
|
||||
let appended = tile.filter(|_| template != map.file).map(|number| format!(".{number}"));
|
||||
let name = appended.as_deref().and_then(|suffix| stem.strip_suffix(suffix)).unwrap_or(&stem).to_string();
|
||||
warnings.extend(packs_colour(&name));
|
||||
psd_layers.push((tile, PlannedLayer { map: i, name, dither }, bit_depth, warnings));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if k > 2 {
|
||||
warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\""));
|
||||
}
|
||||
let lower = name.to_ascii_lowercase();
|
||||
used.insert(lower.clone());
|
||||
|
||||
let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings);
|
||||
if !enabled {
|
||||
continue;
|
||||
}
|
||||
|
||||
if active_dirs.contains(&lower) {
|
||||
return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder")));
|
||||
}
|
||||
let mut prefix = lower.as_str();
|
||||
while let Some((folder, _)) = prefix.rsplit_once('/') {
|
||||
if active_files.contains(folder) {
|
||||
return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file")));
|
||||
}
|
||||
active_dirs.insert(folder.to_owned());
|
||||
prefix = folder;
|
||||
}
|
||||
active_files.insert(lower);
|
||||
|
||||
if color_map && requested_space != space {
|
||||
warnings.push(format!("\"{name}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", requested_space.name()));
|
||||
}
|
||||
claim_path(&mut active_files, &mut active_dirs, &name)?;
|
||||
warnings.extend(packs_colour(&name));
|
||||
|
||||
// Use a UDIM name only when substituting its tile recovers the output name
|
||||
// Truncation or literal placeholder text can make that substitution ambiguous
|
||||
let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| {
|
||||
let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() };
|
||||
format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "<UDIM>")
|
||||
});
|
||||
out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings });
|
||||
let udim_name = token_stem
|
||||
.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem))
|
||||
.map(|t| format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "<UDIM>"));
|
||||
out.push(PlannedFile { name, map: i, format, bit_depth, dither, tile, udim_name, warnings, layers: Vec::new() });
|
||||
}
|
||||
}
|
||||
|
||||
// Each tile's PSD maps are the layers of one file named after the texture set
|
||||
let psd_stem = sanitize_file_stem(&format!("{mesh_name}_{}", set.name));
|
||||
for &tile in &tiles {
|
||||
let in_tile: Vec<_> = psd_layers.iter().filter(|(layer_tile, ..)| *layer_tile == tile).collect();
|
||||
let Some((_, first, ..)) = in_tile.first() else { continue };
|
||||
|
||||
let bit_depth = in_tile.iter().map(|(_, _, depth, _)| *depth).max().unwrap_or(8);
|
||||
let folder_count: usize = in_tile.iter().map(|(_, layer, ..)| layer.name.matches('/').count()).sum();
|
||||
check_psd_size(psd_size(set, tile, opts.size), in_tile.len(), folder_count, bit_depth)?;
|
||||
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
for warning in in_tile.iter().flat_map(|(.., layer_warnings)| layer_warnings) {
|
||||
if !warnings.contains(warning) {
|
||||
warnings.push(warning.clone());
|
||||
}
|
||||
}
|
||||
let stem = sanitize_file_stem(&tile.map_or_else(|| psd_stem.clone(), |number| format!("{psd_stem}.{number}")));
|
||||
let ext = FileFormat::Psd.extension();
|
||||
let (name, renamed) = unique_name(&mut used, &stem, ext, &mut warnings);
|
||||
claim_path(&mut active_files, &mut active_dirs, &name)?;
|
||||
let udim_name = tile.filter(|number| stem == format!("{psd_stem}.{number}")).map(|_| format!("{psd_stem}.<UDIM>{renamed}.{ext}"));
|
||||
let layers: Vec<PlannedLayer> = in_tile.iter().map(|(_, layer, ..)| layer.clone()).collect();
|
||||
let dither = layers.iter().any(|layer| layer.dither);
|
||||
out.push(PlannedFile { name, map: first.map, format: FileFormat::Psd, bit_depth, dither, tile, udim_name, warnings, layers });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `stem.ext`, or `stem_2.ext`… when an earlier file has the name ignoring case (as Windows and macOS file systems do): the name and the suffix added
|
||||
fn unique_name(used: &mut BTreeSet<String>, stem: &str, ext: &str, warnings: &mut Vec<String>) -> (String, String) {
|
||||
let mut name = format!("{stem}.{ext}");
|
||||
let mut renamed = String::new();
|
||||
let mut k = 2;
|
||||
while used.contains(&name.to_ascii_lowercase()) {
|
||||
renamed = format!("_{k}");
|
||||
name = format!("{stem}{renamed}.{ext}");
|
||||
k += 1;
|
||||
}
|
||||
if !renamed.is_empty() {
|
||||
warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\""));
|
||||
}
|
||||
|
||||
used.insert(name.to_ascii_lowercase());
|
||||
(name, renamed)
|
||||
}
|
||||
|
||||
/// Record exported file `name` and its folders, refusing a name that is already a folder or a folder that is already a file, ignoring case
|
||||
fn claim_path(files: &mut BTreeSet<String>, dirs: &mut BTreeSet<String>, name: &str) -> Result<()> {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if dirs.contains(&lower) {
|
||||
return Err(FormatError::Invalid(format!("\"{name}\" cannot be both an exported file and a folder")));
|
||||
}
|
||||
|
||||
let mut prefix = lower.as_str();
|
||||
while let Some((folder, _)) = prefix.rsplit_once('/') {
|
||||
if files.contains(folder) {
|
||||
return Err(FormatError::Invalid(format!("\"{name}\" cannot use \"{folder}\" as a folder because another map exports that file")));
|
||||
}
|
||||
dirs.insert(folder.to_owned());
|
||||
prefix = folder;
|
||||
}
|
||||
files.insert(lower);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The size of a texture set's PSD for `tile` (None: the whole set, an atlas of a UV-tiled one)
|
||||
fn psd_size(set: &TextureSet, tile: Option<u32>, export_size: Option<u32>) -> (u32, u32) {
|
||||
let block_resolution = set.block_resolution();
|
||||
match (tile, set.tile_grid()) {
|
||||
(Some(tile), Some(_)) => {
|
||||
let side = scale_export_side(tile_side(set, tile, block_resolution), block_resolution, export_size);
|
||||
(side, side)
|
||||
}
|
||||
(_, Some(grid)) => {
|
||||
let side = export_size.unwrap_or(block_resolution);
|
||||
(side.saturating_mul(grid.cols), side.saturating_mul(grid.rows))
|
||||
}
|
||||
(_, None) => {
|
||||
let side = export_size.unwrap_or(block_resolution);
|
||||
(side, side)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Plan a selection in export order, keeping only the first case-insensitive use of a name.
|
||||
pub fn list_set_outputs(project: &Project, sets: &[usize], mesh_name: &str, opts: &ExportOptions) -> Result<Vec<(usize, PlannedFile)>> {
|
||||
let mut files = Vec::new();
|
||||
@@ -906,137 +975,23 @@ pub fn render_maps(input: &ExportInput, options: &ExportOptions) -> Result<Vec<E
|
||||
|
||||
/// Render the retained plans from `list_outputs` for this input and these options.
|
||||
pub fn render_planned_maps(input: &ExportInput, options: &ExportOptions, planned: Vec<PlannedFile>) -> Result<Vec<ExportedFile>> {
|
||||
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() != width as usize * height as usize {
|
||||
return Err(FormatError::Invalid(format!("coverage has {} texels, expected {width}×{height}", input.coverage.len())));
|
||||
}
|
||||
|
||||
if planned.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
// 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 beyond_default = matches!(options.padding, Padding::DilationDefault(_) | Padding::Infinite);
|
||||
let diffuse = matches!(options.padding, Padding::DilationDiffusion(_));
|
||||
let sampler = Sampler {
|
||||
set,
|
||||
comp: input.composite,
|
||||
baked: input.baked,
|
||||
coverage: input.coverage,
|
||||
res: width,
|
||||
tile_res,
|
||||
scales: set.block_scales(),
|
||||
normal_override: options.normal_format,
|
||||
project_normal: input.project.normal_format,
|
||||
};
|
||||
|
||||
let renderer = MapRenderer::new(input, options)?;
|
||||
planned
|
||||
.into_iter()
|
||||
.map(|planned_file| {
|
||||
let map = options.preset.maps.get(planned_file.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?;
|
||||
let channel_layout = layout(set, map);
|
||||
let component_count = channel_layout.len();
|
||||
let inverted: Vec<bool> = channel_layout.iter().map(|(d, _)| map.inverted.contains(d)).collect();
|
||||
|
||||
// The texels written: one tile, or the whole set
|
||||
let (x0, y0, w, h) = match (planned_file.tile, 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(set, t, tile_res);
|
||||
(bx * tile_res, by * tile_res, side, side)
|
||||
}
|
||||
_ => (0, 0, width, height),
|
||||
};
|
||||
|
||||
// An atlas scales by the requested size per tile
|
||||
let scale = |value| scale_export_side(value, tile_res, options.size);
|
||||
let size = (scale(w), scale(h));
|
||||
if planned_file.format == FileFormat::Psd {
|
||||
check_psd_size(size, component_count, planned_file.bit_depth)?;
|
||||
return layered_psd::render_psd(&renderer, planned_file);
|
||||
}
|
||||
|
||||
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.as_ref().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 diffuse {
|
||||
let known: Vec<bool> = (y0..y0 + h)
|
||||
.flat_map(|y| (x0..x0 + w).map(move |x| (x, y)))
|
||||
.map(|(x, y)| sampler.covered(x, y) || dilation_map.as_ref().is_some_and(|d| d.source(x, y).is_some()))
|
||||
.collect();
|
||||
|
||||
// Keep diffusion within each UV tile when rendering an atlas
|
||||
let block = if planned_file.tile.is_none() && grid.is_some() { tile_res } else { w.max(h) };
|
||||
diffuse_blocks(&mut data, (w as usize, h as usize), component_count, &known, 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, planned_file.format, planned_file.bit_depth);
|
||||
let float = planned_file.format.holds_float(planned_file.bit_depth);
|
||||
let rgb = component_count >= 3;
|
||||
let map = renderer.render(planned_file.map, planned_file.tile, planned_file.format, planned_file.bit_depth)?;
|
||||
let mut warnings = planned_file.warnings;
|
||||
let color_map = map.is_color();
|
||||
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: Vec<bool> = 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() && color_map && rgb).then_some(space);
|
||||
let bytes = encode(
|
||||
Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither },
|
||||
size,
|
||||
component_count,
|
||||
data,
|
||||
&srgb,
|
||||
embed,
|
||||
&mut warnings,
|
||||
)?;
|
||||
Ok(ExportedFile { name: planned_file.name, bytes, width: size.0, height: size.1, warnings })
|
||||
let encoding = Encoding { format: planned_file.format, depth: planned_file.bit_depth, dither: planned_file.dither };
|
||||
let bytes = encode(encoding, map.size, map.component_count, map.data, &map.srgb, map.embed, &mut warnings)?;
|
||||
Ok(ExportedFile { name: planned_file.name, bytes, width: map.size.0, height: map.size.1, warnings })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1225,7 +1180,7 @@ fn encode(
|
||||
|
||||
// Embed ICC or EXR chromaticities only where the format supports them
|
||||
if let Some(space) = embed
|
||||
&& matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::Psd | FileFormat::J2k)
|
||||
&& matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr | FileFormat::Jng | FileFormat::J2k)
|
||||
{
|
||||
warnings.push(format!("{} export does not embed a colour space; the colours are in {}", format.extension().to_ascii_uppercase(), space.name()));
|
||||
}
|
||||
@@ -1330,7 +1285,6 @@ fn encode(
|
||||
FileFormat::Bmp => CodecFormat::Bmp,
|
||||
FileFormat::Webp => CodecFormat::WebP,
|
||||
FileFormat::Pgm => CodecFormat::Pnm,
|
||||
FileFormat::Psd => return psd(bytes, size, component_count, depth).map_err(|error| encoding_error(&error)),
|
||||
FileFormat::Jng => return jng(&bytes, size, component_count).map_err(|error| encoding_error(&error)),
|
||||
FileFormat::J2k | FileFormat::Jp2 => {
|
||||
let profile = embed.and_then(crate::icc::profile);
|
||||
@@ -1338,6 +1292,7 @@ fn encode(
|
||||
return jpeg2000::write_jpeg2000(bytes, size, component_count, depth, jp2, profile.as_deref()).map_err(|error| encoding_error(&error));
|
||||
}
|
||||
FileFormat::Exr | FileFormat::Hdr => return Err(encoding_error(&"unexpected float raster format")),
|
||||
FileFormat::Psd => return Err(encoding_error(&"a PSD holds the layers of several maps (`layered_psd`)")),
|
||||
};
|
||||
let layout = match component_count {
|
||||
1 => ChannelLayout::Gray,
|
||||
@@ -1384,35 +1339,38 @@ fn quantize_integer(encoding: Encoding, width: u32, component_count: usize, samp
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn check_psd_size((width, height): (u32, u32), channels: usize, depth: u8) -> Result<()> {
|
||||
/// The PSD file of a texture set (its merged image and `layer_count` RGBA layers in `folder_count` groups) must fit PSD's side and 2 GiB limits
|
||||
fn check_psd_size((width, height): (u32, u32), layer_count: usize, folder_count: usize, depth: u8) -> Result<()> {
|
||||
// A layer record with its names, and each of a group's two records, stays below this
|
||||
const PSD_RECORD_BYTES: u64 = 2048;
|
||||
|
||||
if width == 0 || height == 0 || width > PSD_MAX_SIDE_PIXELS || height > PSD_MAX_SIDE_PIXELS {
|
||||
return Err(FormatError::Invalid(format!("PSD size {width}×{height} must be between 1 and {PSD_MAX_SIDE_PIXELS} pixels per side")));
|
||||
}
|
||||
|
||||
// Measure the flat file's overhead without allocating any pixel buffers
|
||||
let overhead = flat_psd((width, height), channels, depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?;
|
||||
let sample_bytes = u64::from(width) * u64::from(height) * channels as u64 * u64::from(depth / 8);
|
||||
if overhead + sample_bytes >= PSD_MAX_FILE_BYTES {
|
||||
return Err(FormatError::Invalid(format!("PSD size {width}×{height} would reach the 2 GiB file limit; use a smaller export size or another format")));
|
||||
// Measure the merged image's overhead without allocating any pixel buffers
|
||||
let merged = flat_psd((width, height), depth).encoded_len().map_err(|error| FormatError::Invalid(format!("PSD sizing failed: {error}")))?;
|
||||
let records = PSD_RECORD_BYTES * (layer_count as u64 + 2 * folder_count as u64);
|
||||
let planes = PSD_RGBA_PLANES as u64 * (1 + layer_count as u64);
|
||||
let sample_bytes = u64::from(width) * u64::from(height) * planes * u64::from(depth / 8);
|
||||
if merged + records + sample_bytes >= PSD_MAX_FILE_BYTES {
|
||||
return Err(FormatError::Invalid(format!(
|
||||
"a PSD of {layer_count} maps at {width}×{height} would reach the 2 GiB file limit; use a smaller export size, fewer PSD maps or another format"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_psd::PsdFile {
|
||||
use craft_psd::{ColorMode, Compression, Header, ImageData, ImageResource, PsdFile, Version};
|
||||
|
||||
const PSD_ALPHA_NAMES_RESOURCE_ID: u16 = 1006;
|
||||
let color_mode = if channels <= 2 { ColorMode::Grayscale } else { ColorMode::Rgb };
|
||||
let header = Header::new(Version::Psd, width, height, channels as u16, u16::from(depth), color_mode);
|
||||
|
||||
// A Pascal name marks the extra plane as a channel separate from merged transparency
|
||||
let resources = if matches!(channels, 2 | 4) { vec![ImageResource::new(PSD_ALPHA_NAMES_RESOURCE_ID, b"\x05Alpha".to_vec())] } else { Vec::new() };
|
||||
/// A PSD of only an RGBA merged image with no pixels yet, to measure
|
||||
fn flat_psd((width, height): (u32, u32), depth: u8) -> craft_psd::PsdFile {
|
||||
use craft_psd::{ColorMode, Compression, Header, ImageData, PsdFile, Version};
|
||||
|
||||
let header = Header::new(Version::Psd, width, height, PSD_RGBA_PLANES as u16, u16::from(depth), ColorMode::Rgb);
|
||||
PsdFile {
|
||||
header,
|
||||
color_mode_data: Vec::new(),
|
||||
resources,
|
||||
resources: Vec::new(),
|
||||
layer_info: None,
|
||||
layer_info_placement: Default::default(),
|
||||
global_layer_mask: None,
|
||||
@@ -1423,26 +1381,6 @@ fn flat_psd((width, height): (u32, u32), channels: usize, depth: u8) -> craft_ps
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a merged PSD image with raw planes, including an extra alpha plane when present.
|
||||
fn psd(bytes: Vec<u8>, size: (u32, u32), channels: usize, depth: u8) -> craft_psd::Result<Vec<u8>> {
|
||||
let mut file = flat_psd(size, channels, depth);
|
||||
let planes = &mut file.image_data.data;
|
||||
planes.try_reserve_exact(bytes.len()).map_err(|_| craft_psd::PsdError::OutOfMemory("cannot allocate PSD planes"))?;
|
||||
if depth == 16 {
|
||||
let samples = bytes.as_chunks::<2>().0;
|
||||
for channel in 0..channels {
|
||||
planes.extend(samples.iter().skip(channel).step_by(channels).flat_map(|sample| u16::from_ne_bytes(*sample).to_be_bytes()));
|
||||
}
|
||||
} else {
|
||||
for channel in 0..channels {
|
||||
planes.extend(bytes.iter().skip(channel).step_by(channels).copied());
|
||||
}
|
||||
}
|
||||
drop(bytes);
|
||||
|
||||
file.to_bytes()
|
||||
}
|
||||
|
||||
/// A JNG file: the colour as JPEG, alpha (when present) as lossless 8-bit deflate data.
|
||||
fn jng(bytes: &[u8], (w, h): (u32, u32), n: usize) -> std::result::Result<Vec<u8>, String> {
|
||||
use std::io::Write;
|
||||
|
||||
@@ -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,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>,
|
||||
}
|
||||
@@ -1122,45 +1122,89 @@ 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_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 = vec![("Mask", pixel()), ("Body/Rough", pixel()), ("Body/Color", pixel()), ("Top/Inner/Leaf", pixel())];
|
||||
|
||||
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];
|
||||
// Four tile columns: the atlas is 32768 wide, each tile's layer and merged image well under 2 GiB
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1004];
|
||||
let mut options = one_map(FileFormat::Psd, 8, roughness());
|
||||
options.size = Some(16_384);
|
||||
options.size = Some(8192);
|
||||
options.atlas = true;
|
||||
|
||||
let error = list_outputs(&fx.project, 0, "sphere", &options).unwrap_err();
|
||||
@@ -1171,7 +1215,7 @@ 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_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);
|
||||
@@ -1179,19 +1223,23 @@ 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);
|
||||
for copy in ["second", "third"] {
|
||||
assert_eq!(list_outputs(&fx.project, 0, "sphere", &options).unwrap().len(), 1);
|
||||
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), 1, 0, 16).is_err());
|
||||
assert!(check_psd_size((width, height - 1), 1, 0, 16).is_ok());
|
||||
|
||||
let mut fx = Fx::new(&default_channels());
|
||||
fx.project.texture_sets[0].uv_tiles = vec![1001, 1003, 1011];
|
||||
|
||||
@@ -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. A PSD holds several maps as layers, so it binds nothing
|
||||
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 {
|
||||
// A PSD's merged image is no one map's texture
|
||||
if file.format == FileFormat::Psd {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The first tile stands for all the tiles of a map
|
||||
if seen_maps.contains(&file.map) {
|
||||
continue;
|
||||
@@ -412,7 +417,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 +590,7 @@ mod texture_binding_tests {
|
||||
tile: None,
|
||||
udim_name: None,
|
||||
warnings: Vec::new(),
|
||||
layers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -928,10 +928,25 @@ fn preview_names(app: &mut TextureCraftApp, preset: &ExportPreset) -> Result<Vec
|
||||
}
|
||||
let plan = texturecraft_engine::execute(&mut app.session, "export.plan", &p).map_err(|e| e.to_string())?;
|
||||
let mut names = vec![None; preset.maps.len()];
|
||||
let index = |value: &Value| value.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
for f in plan.as_array().into_iter().flatten() {
|
||||
let map = f.get("map").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok());
|
||||
if let (Some(slot), Some(file)) = (map.and_then(|i| names.get_mut(i)), f.get("file").and_then(Value::as_str)) {
|
||||
*slot = Some(file.to_string());
|
||||
let Some(file) = f.get("file").and_then(Value::as_str) else { continue };
|
||||
let layers = f.get("layers").and_then(Value::as_array).filter(|layers| !layers.is_empty());
|
||||
match layers {
|
||||
// A PSD's maps each show the file and their layer
|
||||
Some(layers) => {
|
||||
for layer in layers {
|
||||
let name = layer.get("name").and_then(Value::as_str).unwrap_or_default();
|
||||
if let Some(slot) = index(layer).and_then(|i| names.get_mut(i)) {
|
||||
*slot = Some(format!("{file} › {name}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(slot) = index(f).and_then(|i| names.get_mut(i)) {
|
||||
*slot = Some(file.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
|
||||
@@ -533,28 +533,36 @@ fn file_type_text(t: &FileType) -> String {
|
||||
|
||||
/// The rows of texture set `ts`'s Output maps: the template's maps the set has sources for
|
||||
fn map_rows(app: &mut TextureCraftApp, ts: usize) -> Vec<MapRow> {
|
||||
let mut p = set_params(app, ts);
|
||||
if let Some(o) = p.as_object_mut() {
|
||||
o.remove("maps");
|
||||
let mut params = set_params(app, ts);
|
||||
if let Some(object) = params.as_object_mut() {
|
||||
object.remove("maps");
|
||||
}
|
||||
let preset = app.session.export_preset(&set_template(app, ts));
|
||||
let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", &p) else { return Vec::new() };
|
||||
let Ok(plan) = texturecraft_engine::execute(&mut app.session, "export.plan", ¶ms) else { return Vec::new() };
|
||||
let mut rows: Vec<MapRow> = Vec::new();
|
||||
for f in plan.as_array().into_iter().flatten() {
|
||||
let Some(map) = f.get("map").and_then(serde_json::Value::as_u64).map(|m| m as usize) else { continue };
|
||||
if rows.iter().any(|r| r.map == map) {
|
||||
continue;
|
||||
}
|
||||
let index = |value: &serde_json::Value| value.get("map").and_then(serde_json::Value::as_u64).map(|map| map as usize);
|
||||
for file in plan.as_array().into_iter().flatten() {
|
||||
// A PSD writes each of its layers' maps
|
||||
let layers = file.get("layers").and_then(serde_json::Value::as_array).filter(|layers| !layers.is_empty());
|
||||
let maps: Vec<usize> = match layers {
|
||||
Some(layers) => layers.iter().filter_map(index).collect(),
|
||||
None => index(file).into_iter().collect(),
|
||||
};
|
||||
for map in maps {
|
||||
if rows.iter().any(|row| row.map == map) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let format = f.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string();
|
||||
let bit_depth = f.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8;
|
||||
let dithering = f.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false);
|
||||
let pattern = preset
|
||||
.as_ref()
|
||||
.and_then(|p| p.maps.get(map))
|
||||
.map(|m| m.file.replace("$channel", texturecraft_engine::formats::export::channel_label(m)))
|
||||
.unwrap_or_default();
|
||||
rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } });
|
||||
let format = file.get("format").and_then(serde_json::Value::as_str).unwrap_or("png").to_string();
|
||||
let bit_depth = file.get("bitDepth").and_then(serde_json::Value::as_u64).unwrap_or(8) as u8;
|
||||
let dithering = file.get("dithering").and_then(serde_json::Value::as_bool).unwrap_or(false);
|
||||
let pattern = preset
|
||||
.as_ref()
|
||||
.and_then(|preset| preset.maps.get(map))
|
||||
.map(|map_spec| map_spec.file.replace("$channel", texturecraft_engine::formats::export::channel_label(map_spec)))
|
||||
.unwrap_or_default();
|
||||
rows.push(MapRow { map, pattern, inherited: FileType { format: file_type_name(&format), bit_depth, dithering } });
|
||||
}
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user