mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
The Affinity raster tests compared decoded pixels with CRCs captured from the reader's own output, so a decoding error present when the CRC was taken would pass. They now read the image's tiles straight from the archive (256-byte by 256-row planes, states 2 and 4), interleave them, scale 16-bit samples with rounding, and compare the whole buffer. The Affinity 3 signatures drop the CRC of the model's Debug output and keep the feature counts. The DXF golden test no longer rewrites its expected files when WRITE_DXF_GOLDENS is set. Each golden file is first checked against the drawing it should hold (rectangle corners, circle center, radius and bulges, ACI and true colors, lineweights), and a mismatch saves the output to the temp directory for review.
183 lines
8.4 KiB
Rust
183 lines
8.4 KiB
Rust
//! Pixel retention on current Affinity 3 documents published under MIT by Patchy.
|
||
//! Assertions use this reader's archive/stream and the original embedded image bytes;
|
||
//! no third-party Affinity parser, source code or application is used as an oracle.
|
||
|
||
use vectorcraft_affinity::{
|
||
Archive, Limits,
|
||
model::{Affine, Document, Image, Kind, Node, Pixels},
|
||
stream,
|
||
};
|
||
|
||
use crate::corpus;
|
||
|
||
fn images(nodes: &[Node], out: &mut Vec<Image>) {
|
||
for node in nodes {
|
||
if let Kind::Image(image) = &node.kind {
|
||
out.push(image.clone());
|
||
}
|
||
images(&node.children, out);
|
||
}
|
||
}
|
||
|
||
fn read_fixture(name: &str) -> Option<(Vec<u8>, Document, Vec<Image>)> {
|
||
let dir = corpus::pinned()?;
|
||
let bytes = std::fs::read(dir.join(name)).unwrap();
|
||
let doc = vectorcraft_affinity::read(&bytes, Limits::default()).unwrap();
|
||
assert!(doc.saved_by.as_deref().unwrap().starts_with("Affinity 3."));
|
||
let mut out = Vec::new();
|
||
for spread in &doc.spreads {
|
||
images(&spread.nodes, &mut out);
|
||
}
|
||
Some((bytes, doc, out))
|
||
}
|
||
|
||
fn source(bytes: &[u8]) -> Vec<u8> {
|
||
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
|
||
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
|
||
let bitmap =
|
||
doc.objects.iter().enumerate().find(|(_, o)| o.class == stream::Tag::of(b"DyBm") && o.get(stream::Tag::of(b"Bckg")).is_some()).unwrap().0;
|
||
let name = doc.entry(bitmap, b"Bckg").unwrap();
|
||
let block = stream::parse(&archive.read(name).unwrap()).unwrap();
|
||
block.bytes(block.root, b"Data").unwrap().to_vec()
|
||
}
|
||
|
||
/// The fixture's one tiled bitmap read straight from its archive entries, interleaved: RGBA8 for
|
||
/// RGBA layers (16-bit samples scaled to 8 bits with rounding) and C, M, Y, K, alpha for CMYK.
|
||
/// Each channel is a grid of 256-byte × 256-row tiles in row-major order; state 2 is a tile of
|
||
/// 0xFF, state 4 a stored tile (the next `Idx<c>` entry), and any other state a tile of zeros.
|
||
fn tiled_pixels(bytes: &[u8]) -> (u32, u32, Vec<u8>) {
|
||
const TILE: usize = 256;
|
||
let mut archive = Archive::open(bytes, Limits::default()).unwrap();
|
||
let doc = stream::parse(&archive.read("doc.dat").unwrap()).unwrap();
|
||
// The bitmap the image layer (`ImgN`) holds as `Bitm`; the document's other bitmaps are masks.
|
||
let bitmaps: Vec<usize> = (0..doc.objects.len())
|
||
.filter(|&o| doc.is(o, b"ImgN"))
|
||
.filter_map(|o| doc.obj(o, b"Bitm"))
|
||
.filter(|&b| doc.is(b, b"DyBm") && doc.field(b, b"Sta1").is_some())
|
||
.collect();
|
||
assert_eq!(bitmaps.len(), 1, "one tiled image bitmap");
|
||
let bitmap = bitmaps[0];
|
||
let width = usize::try_from(doc.int(bitmap, b"BmpW").unwrap()).unwrap();
|
||
let height = usize::try_from(doc.int(bitmap, b"BmpH").unwrap()).unwrap();
|
||
let (channels, bps) = match doc.enumeration(bitmap, b"Frmt").unwrap().0 {
|
||
0 => (4, 1),
|
||
1 => (4, 2),
|
||
4 => (5, 1),
|
||
other => panic!("format {other}"),
|
||
};
|
||
let row = width * bps;
|
||
let across = row.div_ceil(TILE);
|
||
let mut planes = Vec::new();
|
||
for c in 1..=channels {
|
||
let digit = b'0' + c as u8;
|
||
let Some(stream::Value::Array(states)) = doc.field(bitmap, &[b'S', b't', b'a', digit]) else { panic!("states of channel {c}") };
|
||
let mut stored = doc.objs(bitmap, &[b'I', b'd', b'x', digit]).into_iter();
|
||
let mut plane = vec![0u8; row * height];
|
||
for (t, state) in states.iter().enumerate().take(across * height.div_ceil(TILE)) {
|
||
let tile: Vec<u8> = match state {
|
||
stream::Value::UInt(2) => vec![0xFF; TILE * TILE],
|
||
stream::Value::UInt(4) => {
|
||
let name = doc.entry(stored.next().unwrap(), b"Data").unwrap().to_string();
|
||
let data = archive.read(&name).unwrap();
|
||
assert_eq!(data.len(), TILE * TILE, "{name}");
|
||
data
|
||
}
|
||
_ => continue,
|
||
};
|
||
let (ox, oy) = ((t % across) * TILE, (t / across) * TILE);
|
||
for y in oy..(oy + TILE).min(height) {
|
||
for x in ox..(ox + TILE).min(row) {
|
||
plane[y * row + x] = tile[(y - oy) * TILE + x - ox];
|
||
}
|
||
}
|
||
}
|
||
planes.push(plane);
|
||
}
|
||
let sample = |c: usize, i: usize| -> u8 {
|
||
if bps == 1 {
|
||
planes[c][i]
|
||
} else {
|
||
let v = u32::from(u16::from_le_bytes([planes[c][2 * i], planes[c][2 * i + 1]]));
|
||
u8::try_from((v * 255 + 32767) / 65535).unwrap()
|
||
}
|
||
};
|
||
let pixels = (0..width * height).flat_map(|i| (0..channels).map(move |c| (c, i))).map(|(c, i)| sample(c, i)).collect();
|
||
(u32::try_from(width).unwrap(), u32::try_from(height).unwrap(), pixels)
|
||
}
|
||
|
||
#[test]
|
||
fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
|
||
let Some((bytes, doc, images)) = read_fixture("patchy-embedded-jpeg.af") else { return };
|
||
assert!(doc.warnings.is_empty(), "{:?}", doc.warnings);
|
||
assert_eq!(images.len(), 1);
|
||
let image = &images[0];
|
||
assert_eq!((image.width, image.height), (400, 300));
|
||
assert_eq!(image.transform, Affine::IDENTITY);
|
||
let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") };
|
||
let expected = craft_image_codecs::decode(&source(&bytes)).unwrap().to_rgba8();
|
||
assert_eq!(pixels.as_slice(), expected.as_slice());
|
||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||
}
|
||
|
||
#[test]
|
||
fn lazy_placed_images_keep_the_original_encoded_bytes() {
|
||
let Some((bytes, doc, images)) = read_fixture("patchy-lazy-placed.af") else { return };
|
||
assert!(doc.warnings.is_empty());
|
||
assert_eq!(images.len(), 1);
|
||
assert_eq!((images[0].width, images[0].height), (400, 300));
|
||
assert_eq!(images[0].transform, Affine::IDENTITY);
|
||
assert_eq!(images[0].pixels, Pixels::Encoded(source(&bytes)));
|
||
}
|
||
|
||
#[test]
|
||
fn eight_and_sixteen_bit_channels_retain_the_same_pixel_pattern() {
|
||
let Some((bytes8, doc8, images8)) = read_fixture("patchy-rgba8.af") else { return };
|
||
let (bytes16, doc16, images16) = read_fixture("patchy-rgba16.af").unwrap();
|
||
assert!(doc8.warnings.is_empty());
|
||
assert!(doc16.warnings.is_empty());
|
||
assert_eq!(images8.len(), 1);
|
||
assert_eq!(images16, images8);
|
||
assert_eq!((images8[0].width, images8[0].height), (64, 48));
|
||
let Pixels::Rgba8(pixels) = &images8[0].pixels else { panic!() };
|
||
assert_eq!(pixels.len(), 64 * 48 * 4);
|
||
assert_eq!(&pixels[..4], &[0, 0, 0, 128]);
|
||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[3] < 255));
|
||
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
|
||
assert_eq!(tiled_pixels(&bytes8), (64, 48, pixels.clone()));
|
||
assert_eq!(tiled_pixels(&bytes16), (64, 48, pixels.clone()), "16-bit samples scaled to 8 bits");
|
||
}
|
||
|
||
#[test]
|
||
fn rotated_scaled_pixels_keep_the_full_affine_transform() {
|
||
let Some((bytes, doc, images)) = read_fixture("patchy-transform.af") else { return };
|
||
assert!(doc.warnings.is_empty());
|
||
assert_eq!(images.len(), 1);
|
||
assert_eq!((images[0].width, images[0].height), (80, 60));
|
||
let expected = [1.1742158910592235, 0.4286222593193142, -0.4286222593193142, 1.1742158910592235, 60.0, 40.0];
|
||
for (actual, expected) in images[0].transform.0.into_iter().zip(expected) {
|
||
assert!((actual - expected).abs() < 1e-12);
|
||
}
|
||
let Pixels::Rgba8(pixels) = &images[0].pixels else { panic!() };
|
||
assert_eq!(pixels.len(), 80 * 60 * 4);
|
||
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
|
||
assert_eq!(tiled_pixels(&bytes), (80, 60, pixels.clone()));
|
||
}
|
||
|
||
#[test]
|
||
fn cmyk_pixels_stay_cmyk_and_lab_losses_are_reported() {
|
||
// CMYK layers keep their inks for the importer to convert through a colour profile.
|
||
let Some((bytes, cmyk, images)) = read_fixture("patchy-cmyk.af") else { return };
|
||
assert_eq!(images.len(), 1);
|
||
assert_eq!((images[0].width, images[0].height), (64, 48));
|
||
let Pixels::Cmyka8(pixels) = &images[0].pixels else { panic!() };
|
||
assert_eq!(pixels.len(), 64 * 48 * 5);
|
||
assert_eq!(tiled_pixels(&bytes), (64, 48, pixels.clone()));
|
||
assert!(pixels.as_chunks::<5>().0.iter().any(|p| p[0] != p[3]), "inks differ between channels");
|
||
assert!(cmyk.warnings.is_empty(), "{:?}", cmyk.warnings);
|
||
assert_eq!(cmyk.cmyk_profile, None, "this file embeds no profile");
|
||
let (_, lab, images) = read_fixture("patchy-lab.af").unwrap();
|
||
assert!(images.is_empty());
|
||
assert_eq!(lab.warnings, ["pixel layers in grey, Lab or 32-bit formats"]);
|
||
}
|