From 48dc4832155fa4344f2e549ceb2f14db7e0ebcbe Mon Sep 17 00:00:00 2001 From: Rebornim <250083243+Rebornim@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:50:04 +0000 Subject: [PATCH] Export: a PSD layer is quantized to RGBA as it widens, without a floating-point RGBA copy --- crates/formats/src/export/layered_psd.rs | 63 ++++++++++-------------- crates/formats/src/export/tests.rs | 36 ++++++++++++++ 2 files changed, 62 insertions(+), 37 deletions(-) diff --git a/crates/formats/src/export/layered_psd.rs b/crates/formats/src/export/layered_psd.rs index 951a18ef..af95e664 100644 --- a/crates/formats/src/export/layered_psd.rs +++ b/crates/formats/src/export/layered_psd.rs @@ -88,9 +88,8 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 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); let encoding = Encoding { format: FileFormat::Psd, depth: bit_depth, dither: layer.dither }; - let layer_pixels = pixel_data(rgba, map.size.0, encoding)?; + let layer_pixels = rgba_pixel_data(map.data, map.component_count, &map.srgb, map.size.0, encoding)?; pixels.push((layer.name.as_str(), map.size, layer_pixels)); } if let Some(space) = embedded { @@ -107,36 +106,6 @@ pub(super) fn render_psd(renderer: &MapRenderer, planned: PlannedFile, size: (u3 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(mut data: Vec, component_count: usize, srgb: &[bool]) -> Vec { - 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) }; - - if component_count == PSD_RGBA_PLANES { - for texel in data.as_chunks_mut::().0 { - for (component, value) in texel.iter_mut().enumerate() { - *value = encode(component, *value); - } - } - - return data; - } - - 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 | 2 => { - let gray = encoded(0); - let alpha = if component_count == 2 { encoded(1) } else { 1.0 }; - [gray, gray, gray, alpha] - } - 3 => [encoded(0), encoded(1), encoded(2), 1.0], - _ => [encoded(0), encoded(1), encoded(2), encoded(3)], - } - }) - .collect() -} - /// The merged image of `layers` (bottom first, as the file stores them), one row at a time fn merged_image((width, height): (u32, u32), depth: u8, layers: &[(&str, (u32, u32), PixelData)]) -> Result { let row_len = width as usize * PSD_RGBA_PLANES; @@ -206,16 +175,36 @@ fn over(canvas: &mut [f32], canvas_width: u32, layer: &[f32], layer_width: u32) } } -/// Quantize directly into the sample type the PSD builder accepts. -fn pixel_data(samples: Vec, width: u32, encoding: Encoding) -> Result { +/// L, LA, RGB or RGBA samples quantized as the RGBA the PSD builder accepts: gray repeated, opaque without alpha, sRGB transfer applied to the components `srgb` marks, values clamped to 0-1 +fn rgba_pixel_data(mut data: Vec, component_count: usize, srgb: &[bool], width: u32, encoding: Encoding) -> Result { + let component_count = component_count.max(1); + for texel in data.chunks_exact_mut(component_count) { + for (component, value) in texel.iter_mut().enumerate() { + *value = if srgb.get(component).copied().unwrap_or(false) { linear_to_srgb(*value) } else { value.clamp(0.0, 1.0) }; + } + } + + // Widen each texel while quantizing, so no floating-point RGBA copy of the layer is made + let texel_count = data.len() / component_count; + let rgba = (0..texel_count * PSD_RGBA_PLANES).map(|index| { + let (texel, component) = (index / PSD_RGBA_PLANES, index % PSD_RGBA_PLANES); + let source = match component_count { + 1 | 2 if component < ALPHA_INDEX => Some(0), + 1 | 3 if component == ALPHA_INDEX => None, + 2 => Some(1), + _ => Some(component), + }; + source.map_or(1.0, |source| data.get(texel * component_count + source).copied().unwrap_or(0.0)) + }); + if encoding.depth == 16 { let mut pixels = Vec::new(); - pixels.try_reserve_exact(samples.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; - pixels.extend(samples.into_iter().map(quantize_u16)); + pixels.try_reserve_exact(rgba.len()).map_err(|error| FormatError::Invalid(format!("PSD sample buffer allocation failed: {error}")))?; + pixels.extend(rgba.map(quantize_u16)); return Ok(PixelData::Rgba16(pixels)); } - quantize_integer(encoding, width, PSD_RGBA_PLANES, samples.into_iter()).map(PixelData::Rgba8) + quantize_integer(encoding, width, PSD_RGBA_PLANES, rgba).map(PixelData::Rgba8) } /// An RGB PSD of `layers` (bottom first, each named by its `/`-separated group path) over the merged `composite`, uncompressed so its size is known up front diff --git a/crates/formats/src/export/tests.rs b/crates/formats/src/export/tests.rs index 0a252f7f..64fd5115 100644 --- a/crates/formats/src/export/tests.rs +++ b/crates/formats/src/export/tests.rs @@ -2153,6 +2153,42 @@ fn feedback_psd_preview_matches_layer_rgba() { } } +#[test] +fn psd_layers_hold_the_samples_of_the_same_png_at_every_layout_and_depth() { + let fx = Fx::new(&[Channel::Roughness, Channel::BaseColor]); + let base_colour = |component| SourceRef::Channel { channel: Channel::BaseColor, component }; + let mut gray_alpha = roughness(); + gray_alpha.push((Dest::A, SourceRef::Constant(0.5))); + let mut rgb = rgba_half_alpha(); + rgb.pop(); + let layouts = [roughness(), vec![(Dest::L, base_colour(0))], gray_alpha, rgb, rgba_half_alpha()]; + + for channels in layouts { + for (depth, dither) in [(8, false), (8, true), (16, false)] { + let mut png_options = one_map(FileFormat::Png, depth, channels.clone()); + png_options.dither = dither; + let mut psd_options = png_options.clone(); + psd_options.format_override = Some(FileFormat::Psd); + + let png = decode(&fx.render(&png_options)[0]); + let psd = craft_psd::PsdFile::from_bytes(&fx.render(&psd_options)[0].bytes).unwrap(); + let layer = psd.iter_layers().next().unwrap(); + + let context = format!("{channels:?} at {depth} bits, dithering {dither}"); + if depth == 16 { + // Planes of big-endian samples: red, green, blue, then transparency + let planes: Vec> = [0, 1, 2, -1].into_iter().map(|id| layer.channel_bytes(id).unwrap()).collect(); + let texel_count = planes[0].len() / 2; + let samples: Vec = + (0..texel_count).flat_map(|texel| planes.iter().map(move |plane| u16::from_be_bytes([plane[2 * texel], plane[2 * texel + 1]]))).collect(); + assert!(samples == png.to_rgba16().into_raw(), "{context}"); + } else { + assert!(layer.rgba8().unwrap().data == png.to_rgba8().into_raw(), "{context}"); + } + } + } +} + #[test] fn feedback_psd_layer_names_keep_literal_and_explicit_tile_numbers() { let mut fx = Fx::new(&default_channels());