mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-28 17:19:31 +01:00
feat(fla): decode straight-edged shapes into library symbols
CPicShape records carry an i32-twips matrix translation, an inline RGBA solid fill and an edge list of i16 half-pixel deltas with a 30 marker per straight line (differentially verified against the corpus twins: the 'UFO mask' rectangle decodes byte-exactly — 218x224 px, white alpha 80/255, matrix 26.9/-1.55). Shapes with curves use markers not yet mapped; they are counted in the report rather than drawn partially. Real files decode 12 library shapes across the corpus; placements on the main timeline remain pending, so the stage stays empty for now.
This commit is contained in:
1 parent
247cd9dac4
commit
00c39aedbc
6 files changed
+260
-3
No files matched your search
Generated
+1
@@ -341,6 +341,7 @@ name = "anicraft-fla"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anicraft-doc.workspace = true
|
||||
anicraft-geom.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
[lints]
|
||||
|
||||
+150
-3
@@ -17,7 +17,8 @@
|
||||
use crate::cfb::Compound;
|
||||
use crate::records;
|
||||
use crate::report::{ImportError, Report};
|
||||
use anicraft_doc::{Document, Layer, LayerId, Scene, Stage, Timeline};
|
||||
use anicraft_doc::{Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Paint, Rgba, Scene, Shape, Stage, Symbol, SymbolKind, SymbolId, Timeline};
|
||||
use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The `Contents` stream's version byte on every corpus file of the Flash 8–CS4 era.
|
||||
@@ -81,11 +82,138 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> {
|
||||
doc.scenes.push(Arc::new(Scene { name: "Scene 1".into(), timeline, guides: Vec::new() }));
|
||||
report.skip("scenes (no readable page record)");
|
||||
}
|
||||
// The library: each item stream is a symbol whose timeline holds its decoded shapes
|
||||
// (straight-edged ones for now; curves are counted until their markers are decoded).
|
||||
let mut decoded_shapes = 0usize;
|
||||
for (stream, label) in &library {
|
||||
let Ok(bytes) = file.stream(stream) else { continue };
|
||||
let shapes = shapes(&bytes, &mut report);
|
||||
decoded_shapes += shapes.len();
|
||||
if shapes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut timeline = Timeline::default();
|
||||
let layer = Layer::new(LayerId(doc.alloc_id()), "artwork");
|
||||
let keyframe = Keyframe { elements: shapes.into_iter().map(Arc::new).collect(), ..Keyframe::new(0, 1) };
|
||||
let id = SymbolId(doc.alloc_id());
|
||||
timeline.layers.push(Arc::new(Layer { keyframes: vec![Arc::new(keyframe)], ..layer }));
|
||||
doc.library.push(Arc::new(Symbol {
|
||||
id,
|
||||
name: label.clone(),
|
||||
kind: SymbolKind::Graphic,
|
||||
linkage: None,
|
||||
scale_grid: None,
|
||||
scale_grid_kept: None,
|
||||
timeline,
|
||||
}));
|
||||
report.keep("library symbols with decoded shapes");
|
||||
}
|
||||
doc.sanitize();
|
||||
count_pending_records(&file, &mut report);
|
||||
count_pending_records(&file, decoded_shapes, &mut report);
|
||||
Ok((doc, report))
|
||||
}
|
||||
|
||||
/// Decodes a library stream's `CPicShape` records into shape elements.
|
||||
///
|
||||
/// The record layout (differentially verified; see ADR 0096 and the corpus notes): the
|
||||
/// record's name field, then a signature run — a `05` byte, a small fill-style number,
|
||||
/// `01 00`, an RGBA fill, four zero bytes — that brackets the matrix translation (i32
|
||||
/// twips, right before the `05`) and the edge list (three skipped bytes, an `01` start
|
||||
/// marker, an absolute start point, then `30`-marked deltas, all i16 half-pixels). Edge
|
||||
/// records that aren't `30`-marked are curves, whose marker vocabulary is not yet
|
||||
/// decoded: a shape with any is left out whole and counted.
|
||||
fn shapes(bytes: &[u8], report: &mut Report) -> Vec<Element> {
|
||||
let mut out = Vec::new();
|
||||
let mut from = 0usize;
|
||||
while let Some(rel) = find(&bytes[from..], b"CPicShape") {
|
||||
let at = from + rel + b"CPicShape".len();
|
||||
from = at;
|
||||
// The signature: `05`, a small style number, `01 00`, RGBA, four zeros.
|
||||
let mut sig = None;
|
||||
for i in at..(at + 160).min(bytes.len().saturating_sub(15)) {
|
||||
if bytes[i] != 0x05 {
|
||||
continue;
|
||||
}
|
||||
let Some(style) = u32_at(bytes, i + 1) else { continue };
|
||||
if !(1..=64).contains(&style) || bytes.get(i + 5) != Some(&1) || bytes.get(i + 6) != Some(&0) {
|
||||
continue;
|
||||
}
|
||||
if bytes.get(i + 11..i + 15) != Some(&[0, 0, 0, 0][..]) {
|
||||
continue;
|
||||
}
|
||||
sig = Some(i);
|
||||
break;
|
||||
}
|
||||
let Some(sig) = sig else { continue };
|
||||
let (Some(tx), Some(ty)) = (sig.checked_sub(8).and_then(|p| i32_at(bytes, p)), sig.checked_sub(4).and_then(|p| i32_at(bytes, p))) else {
|
||||
report.skip("shapes (edge header not recognised yet)");
|
||||
continue;
|
||||
};
|
||||
let (tx, ty) = (tx as f32 / 20.0, ty as f32 / 20.0);
|
||||
let Some(rgba) = bytes.get(sig + 7..sig + 11) else {
|
||||
report.skip("shapes (edge header not recognised yet)");
|
||||
continue;
|
||||
};
|
||||
let fill = Rgba::new(rgba[0] as f32 / 255.0, rgba[1] as f32 / 255.0, rgba[2] as f32 / 255.0, rgba[3] as f32 / 255.0);
|
||||
// The edges: three skipped bytes (a shape flag), then an `01` start marker.
|
||||
let edges_at = sig + 18;
|
||||
if bytes.get(edges_at) != Some(&0x01) {
|
||||
report.skip("shapes (edge header not recognised yet)");
|
||||
continue;
|
||||
}
|
||||
let read_px = |i: usize| -> Option<f32> { i16_at(bytes, i).map(|v| v as f32 / 2.0) };
|
||||
let (Some(mut x), Some(mut y)) = (read_px(edges_at + 1), read_px(edges_at + 3)) else {
|
||||
report.skip("shapes (edge header not recognised yet)");
|
||||
continue;
|
||||
};
|
||||
let mut i = edges_at + 5;
|
||||
let mut cmds = vec![PathCmd::MoveTo(Vec2::new(x, y))];
|
||||
loop {
|
||||
let (Some(dx), Some(dy)) = (read_px(i), read_px(i + 2)) else {
|
||||
report.skip("shapes with curve edges (decode pending)");
|
||||
return out;
|
||||
};
|
||||
x += dx;
|
||||
y += dy;
|
||||
cmds.push(PathCmd::LineTo(Vec2::new(x, y)));
|
||||
i += 4;
|
||||
match bytes.get(i) {
|
||||
Some(0x30) => i += 1,
|
||||
// The edge list ends when the marker stops; anything but the tail's
|
||||
// leading zeros means a curve came first — leave the shape out whole.
|
||||
Some(b) if b == &0x00 || b == &0x01 => break,
|
||||
Some(_) => {
|
||||
report.skip("shapes with curve edges (decode pending)");
|
||||
return out;
|
||||
}
|
||||
None => {
|
||||
report.skip("shapes with curve edges (decode pending)");
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
if cmds.len() < 4 {
|
||||
report.skip("shapes (too few edges to draw)");
|
||||
continue;
|
||||
}
|
||||
out.push(Element {
|
||||
id: ElementId(out.len() as u64 + 1),
|
||||
name: String::new(),
|
||||
transform: Affine::translate(tx, ty),
|
||||
color: anicraft_doc::ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape {
|
||||
path: Arc::new(Path { cmds }),
|
||||
fill: Some(Paint::Solid(fill)),
|
||||
stroke: None,
|
||||
fill_rule: FillRule::EvenOdd,
|
||||
merge: false,
|
||||
warp: None,
|
||||
}),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The document's scenes, from the `CDocumentPage` record(s): each holds the page's
|
||||
/// stream name (`P 2 1522499960`, NUL-terminated UTF-16) then the scene's label behind
|
||||
/// the `ff fe ff` marker.
|
||||
@@ -204,13 +332,17 @@ fn marked_string(data: &[u8], at: usize, third: u8) -> Option<String> {
|
||||
|
||||
/// Counts the record kinds the later decode pass will handle, so the report says what a
|
||||
/// structure-only open left out.
|
||||
fn count_pending_records(file: &Compound, report: &mut Report) {
|
||||
fn count_pending_records(file: &Compound, mut decoded_shapes: usize, report: &mut Report) {
|
||||
for entry in file.entries() {
|
||||
if entry.kind != crate::cfb::Kind::Stream || entry.path == "Contents" {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = file.stream(&entry.path) else { continue };
|
||||
for tag in records::scan_tags(&bytes) {
|
||||
if tag.name == "CPicShape" && decoded_shapes > 0 {
|
||||
decoded_shapes -= 1; // decoded into a library element above
|
||||
continue;
|
||||
}
|
||||
let what = match tag.name.as_str() {
|
||||
"CPicShape" | "CMorphSegment" => "shapes (artwork decode pending)",
|
||||
"CPicSymbol" => "symbol placements (decode pending)",
|
||||
@@ -234,3 +366,18 @@ fn find(data: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
}
|
||||
(0..=data.len() - needle.len()).find(|&i| &data[i..i + needle.len()] == needle)
|
||||
}
|
||||
|
||||
/// Bounded little-endian reads for the signature and edge scans; no panics on short data.
|
||||
fn u32_at(data: &[u8], at: usize) -> Option<u32> {
|
||||
let s = data.get(at..at.checked_add(4)?)?;
|
||||
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
|
||||
fn i32_at(data: &[u8], at: usize) -> Option<i32> {
|
||||
u32_at(data, at).map(|v| v as i32)
|
||||
}
|
||||
|
||||
fn i16_at(data: &[u8], at: usize) -> Option<i16> {
|
||||
let s = data.get(at..at.checked_add(2)?)?;
|
||||
Some(i16::from_le_bytes([s[0], s[1]]))
|
||||
}
|
||||
@@ -305,6 +305,11 @@ fn synthetic_contents() -> Vec<u8> {
|
||||
c.extend_from_slice(&utf16("P 1 1")); // the page's stream name (marker-terminated)
|
||||
c.extend_from_slice(&[0xFF, 0xFE, 0xFF, 0x07]); // the scene label: marker + length
|
||||
c.extend_from_slice(&utf16("Scene 1"));
|
||||
// A library item: the stream-name string (`01 80 17` marker) then its label.
|
||||
c.extend_from_slice(&[0x01, 0x80, 0x17, 0x08]);
|
||||
c.extend_from_slice(&utf16("Symbol 9"));
|
||||
c.extend_from_slice(&[0xFF, 0xFE, 0xFF, 0x08]);
|
||||
c.extend_from_slice(&utf16("UFO mask"));
|
||||
c.extend_from_slice(&[0u8; 8]);
|
||||
c
|
||||
}
|
||||
@@ -357,5 +362,77 @@ fn an_unsupported_version_is_refused_with_the_specific_sentence() {
|
||||
assert!(message.contains("unsupported Flash version"), "{message}");
|
||||
}
|
||||
|
||||
/// A `CPicShape` record with the decoded field layout, holding the corpus's smallest
|
||||
/// shape (Symbol 123, "UFO mask"): a 218×224 px rectangle, white fill at 31 % opacity,
|
||||
/// its matrix translated to (26.9, −1.55). The bytes are the decoded record's, written
|
||||
/// from the differential analysis (ADR 0096), not copied from any file.
|
||||
fn synthetic_shape_record() -> Vec<u8> {
|
||||
let mut d = Vec::new();
|
||||
d.extend_from_slice(&[0x09, 0x00]);
|
||||
d.extend_from_slice(b"CPicShape");
|
||||
d.extend_from_slice(&[0x04, 0x00, 0, 0, 0, 0]);
|
||||
d.extend_from_slice(&[0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x03, 0xFF, 0xFF]);
|
||||
d.extend_from_slice(&[0u8; 6]);
|
||||
d.extend_from_slice(&[0xFF, 0xFF, 0x00, 0x00]);
|
||||
d.extend_from_slice(&538i32.to_le_bytes()); // the matrix's x: 26.9 px in twips
|
||||
d.extend_from_slice(&(-31i32).to_le_bytes()); // the matrix's y: −1.55 px in twips
|
||||
d.push(0x05); // the fill signature
|
||||
d.extend_from_slice(&4u32.to_le_bytes()); // the fill style number
|
||||
d.extend_from_slice(&[0x01, 0x00]);
|
||||
d.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0x50]); // white at 80/255
|
||||
d.extend_from_slice(&[0u8; 4]);
|
||||
d.extend_from_slice(&[0xF3, 0x00, 0x00]);
|
||||
d.push(0x01); // the edge list's start marker
|
||||
d.extend_from_slice(&(-858i16).to_le_bytes()); // (−429, −81) px in half-pixels
|
||||
d.extend_from_slice(&(-162i16).to_le_bytes());
|
||||
d.extend_from_slice(&0i16.to_le_bytes()); // (0, +224) px
|
||||
d.extend_from_slice(&448i16.to_le_bytes());
|
||||
d.push(0x30); // a straight edge
|
||||
d.extend_from_slice(&(-436i16).to_le_bytes()); // (−218, 0) px
|
||||
d.extend_from_slice(&0i16.to_le_bytes());
|
||||
d.push(0x30);
|
||||
d.extend_from_slice(&0i16.to_le_bytes()); // (0, −224) px
|
||||
d.extend_from_slice(&(-448i16).to_le_bytes());
|
||||
d.push(0x30);
|
||||
d.extend_from_slice(&436i16.to_le_bytes()); // (+218, 0) px, closing the loop
|
||||
d.extend_from_slice(&0i16.to_le_bytes());
|
||||
d.extend_from_slice(&[0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x03]); // the tail
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_straight_edged_shape_decodes_with_its_geometry_and_fill() {
|
||||
use super::doc;
|
||||
let payloads = vec![
|
||||
("Contents", synthetic_contents()),
|
||||
("P 1 1", synthetic_page()),
|
||||
("Symbol 9", synthetic_shape_record()),
|
||||
];
|
||||
let bytes = write(&payloads);
|
||||
let (document, report) = doc::import(&bytes).expect("opens");
|
||||
let symbol = document.library.iter().find(|s| s.name == "UFO mask")
|
||||
.expect("a library symbol is registered");
|
||||
let layer = &symbol.timeline.layers[0];
|
||||
let elements = &layer.keyframes[0].elements;
|
||||
assert_eq!(elements.len(), 1, "the rectangle decodes as one shape");
|
||||
let shape = match &elements[0].kind {
|
||||
anicraft_doc::ElementKind::Shape(shape) => shape,
|
||||
other => panic!("expected a shape, got {other:?}"),
|
||||
};
|
||||
// The fill: white at 80/255.
|
||||
let Some(anicraft_doc::Paint::Solid(fill)) = shape.fill else { panic!("a solid fill") };
|
||||
assert!((fill.a - 80.0 / 255.0).abs() < 0.001, "fill alpha {fill:?}");
|
||||
// The matrix translation: (26.9, −1.55) px.
|
||||
assert!((elements[0].transform.m[4] - 26.9).abs() < 0.001);
|
||||
assert!((elements[0].transform.m[5] + 1.55).abs() < 0.001);
|
||||
// The path: the rectangle's four corners in half-pixel precision.
|
||||
let points: Vec<_> = shape.path.cmds.iter().map(|c| match *c {
|
||||
anicraft_geom::PathCmd::MoveTo(p) | anicraft_geom::PathCmd::LineTo(p) => (p.x, p.y),
|
||||
_ => panic!("straight edges only"),
|
||||
}).collect();
|
||||
assert_eq!(points, vec![(-429.0, -81.0), (-429.0, 143.0), (-647.0, 143.0), (-647.0, -81.0), (-429.0, -81.0)]);
|
||||
assert!(report.skipped.is_empty(), "a fully straight shape skips nothing: {:?}", report.skipped);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -102,3 +102,26 @@ fn the_corpus_opens_with_the_twins_scenes_and_layers() {
|
||||
}
|
||||
assert!(checked >= 6, "expected the corpus's 6 legacy pairs, ran {checked}");
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn the_corpus_decodes_straight_edged_library_shapes() {
|
||||
let Some(dir) = corpus() else { return };
|
||||
let mut total = 0usize;
|
||||
let mut files = 0usize;
|
||||
for entry in std::fs::read_dir(&dir).expect("corpus directory lists") {
|
||||
let path = entry.expect("entry").path();
|
||||
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue };
|
||||
if !name.ends_with("-legacy.fla") { continue; }
|
||||
let data = std::fs::read(&path).expect("file reads");
|
||||
if !anicraft_fla::is_legacy(&data) { continue; }
|
||||
let (doc, _) = anicraft_fla::import(&data).expect("import");
|
||||
let shapes: usize = doc.library.iter()
|
||||
.map(|s| s.timeline.layers.iter().map(|l| l.keyframes.iter().map(|k| k.elements.len()).sum::<usize>()).sum::<usize>())
|
||||
.sum();
|
||||
if shapes > 0 { files += 1; }
|
||||
total += shapes;
|
||||
}
|
||||
assert!(total >= 10, "expected real straight-edged shapes to decode, got {total}");
|
||||
assert!(files >= 3, "expected several files with decoded artwork, got {files}");
|
||||
}
|
||||
@@ -60,6 +60,14 @@ follow-on work tracked in `openspec/changes/add-legacy-fla-import/`.
|
||||
streams' layer records (constant `00 80 00 00 00 80 00 00 0b` anchor + `ff fe ff`-marked
|
||||
UTF-16 name, stored bottom-first). Strings are one-byte-length UTF-16 behind
|
||||
`ff fe ff` (names) or `01 80 17` (library stream names) markers.
|
||||
- **Shape records (first pass):** a `CPicShape` carries an i32-twips matrix translation, an
|
||||
inline RGBA solid fill, and an edge list whose start/deltas are i16 half-pixels with a
|
||||
`30` marker per straight line (`01 | x y | dx dy | 30 | dx dy | …`). Straight-edged
|
||||
shapes decode into library symbols' artwork (verified byte-exactly on the "UFO mask"
|
||||
rectangle fixture: 218×224 px, white α 80/255, matrix 26.9/−1.55); 12 real library
|
||||
shapes decode across the corpus. Curved shapes use additional markers still unmapped —
|
||||
they are counted, not drawn; placements on the main timeline are still pending, so the
|
||||
stage stays empty until that pass.
|
||||
- **What stays open**: frame records (durations are u16 LE near keyframes; the exact
|
||||
keyframe record layout is not yet mapped), `CPicShape` geometry, tweens, text, bitmaps
|
||||
and sounds — each counted in the report's `skipped` per kind, and a sound file's name
|
||||
|
||||
Reference in new issue
Block a user