mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-29 01:24:08 +01:00
feat(fla): legacy timelines, keyframes and symbol placements on the stage
Item streams are an MFC CArchive object graph (class declarations, 0x8000|n class references, back references, 00 00 for none). A bounded reader (archive.rs) walks it: pages, layers (type, colour, folders, parents), keyframes with their raw artwork, duration, tween type and flags, ease, labels and six custom ease curves, and symbol instances (matrix, transformation point, first frame, loop mode, colour effect, blend, library item id from Contents). Library symbols get their full timelines; Contents also yields each item's type and the stage size. Undecoded objects (texts, bitmaps, filters, button settings) are skipped to where their parent continues and counted; a stream that does not decode falls back to the structure-only reading. Verified differentially against the Animate twins on every corpus pair: 337/337 timelines, 1628/1628 layers, 6993/6993 keyframes and 4457/4457 instances match (matrix within 0.01 / 0.05 px); rendered movietemplate frames 1, 70, 120 and 184 are byte-identical to the twin's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8d2c3008c2
commit
4ea949dc42
8 files changed
+2117
-137
No files matched your search
Generated
+1
@@ -343,6 +343,7 @@ dependencies = [
|
||||
"anicraft-doc",
|
||||
"anicraft-geom",
|
||||
"craft-xfl",
|
||||
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b67b9f90c50091a3090f93fa054c34e409edba11)",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
|
||||
@@ -15,6 +15,8 @@ thiserror.workspace = true
|
||||
[dev-dependencies]
|
||||
# The env-gated corpus tests read the Animate twins (zip packages, XFL edge strings).
|
||||
craft-xfl.workspace = true
|
||||
# The twins' XML trees, for the timeline differential (keyframes, instances).
|
||||
craft-xml.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,825 @@
|
||||
//! The object graph of a legacy item stream: a page's or a symbol's timeline as Flash 8–CS4
|
||||
//! serialized it (ADR 0096).
|
||||
//!
|
||||
//! Learned differentially from the corpus's legacy files and their Animate twins; no Flash or
|
||||
//! Animate code involved. An item stream (`P <n> <stamp>`, `S <n> <stamp>`, `Symbol <n>`) is one
|
||||
//! byte (`01`), then an object graph written the way MFC's `CArchive` writes objects (its
|
||||
//! documented behaviour): every object starts with a tag — `FF FF`, a u16 schema, a u16 length
|
||||
//! and the class name for a class not seen yet; `0x8000 | n` for an object of class number `n`;
|
||||
//! a bare `n` for an object written before (a back-reference); `00 00` for none; `7F FF` and a
|
||||
//! u32 for numbers past 0x7FFE. Classes and objects share one numbering, from 1, in the order
|
||||
//! they first appear.
|
||||
//!
|
||||
//! Every `CPic*` object begins alike — `04`, a flag byte, its child objects up to a `00 00`,
|
||||
//! two i32 (a point in twips, or `0x80000000` for none), a u16 and a kind byte (page 07, layer
|
||||
//! 0B, frame and shape 03, symbol instance 13, text 0D, bitmap 02) — and then its own fields:
|
||||
//!
|
||||
//! ```text
|
||||
//! page children: layers, bottom first · u16 u16 u32 · u32 n · n × 8 (ruler guides)
|
||||
//! layer children: keyframes · name · current, hidden, locked u8 · i32 · RGBA colour ·
|
||||
//! u32 outline · u32 · u8 type (0 normal, 1 guide, 3 folder, 4 mask) ·
|
||||
//! parent layer (an object: the folder, mask or guide it sits under) · u8 u8
|
||||
//! frame children: the keyframe's objects · its raw artwork (a shape body, see
|
||||
//! [`crate::shape`]) · u32 n · n × 32 (cubic drawing hints) · 18 · u16 duration ·
|
||||
//! u8 tween (0 none, 1 classic, 2 shape) · u8 tween flags · i16 ease ·
|
||||
//! u16 sound · u16 n · n × 8 (envelope) · u16 loops · u8 sync · u32 in · u32 out ·
|
||||
//! u16 zoom · label · frame actions (16 bytes, the script) · 8 bytes · u32 label kind (1 comment) ·
|
||||
//! shape-tween cache (an object) · 4 bytes · shape hints (an object) · string ·
|
||||
//! 5 × u32, the last 1 when custom eases follow: 6 curves (position, rotation, scale,
|
||||
//! colour, filters, all), each u32 n and n anchors of 3 points (in handle, anchor,
|
||||
//! out handle) as f64 x, y
|
||||
//! shape children: a group's members · a shape body · cubic hints; the base u16 is 1 for a
|
||||
//! drawing object; without members, flag bit 0 marks a loose (raw) shape and no
|
||||
//! bit a group of one
|
||||
//! instance a, b, c, d (16.16), tx, ty (twips) · u16 first frame · u16 loop (0 loop,
|
||||
//! 1 play once, 2 single frame) · u8 · 4 × (i16 multiplier in 1/256, i16 offset)
|
||||
//! for A, R, G, B · u8 colour style (0 none, 1 brightness, 2 tint, 3 advanced,
|
||||
//! 4 alpha) · u8 · i16 percent · RGBA tint · instance name · u16 library item id ·
|
||||
//! 3 bytes · persistent data (u8 flag; u32 1, u32 n, n × (u8 5, name, value)) · u8 ·
|
||||
//! u8 filter count · u8 blend (SWF numbering) · u16; movie clips (`CPicSprite`) and
|
||||
//! buttons (`CPicButton`) carry more after it
|
||||
//! ```
|
||||
//!
|
||||
//! The instance's two base i32 are its transformation point already placed on the stage
|
||||
//! (`M · p`). Strings are UTF-16 behind `FF FE FF` and a u8 length (`FF`, then a u16, past 254).
|
||||
//!
|
||||
//! What isn't decoded — texts, bitmaps, a movie clip's or button's extra settings — is skipped
|
||||
//! by finding where the parent continues: its own end (`00 00`, then its base with its kind
|
||||
//! byte) or the next sibling object, checked by parsing that sibling. Nothing here panics or
|
||||
//! reads past the end; a stream that doesn't make sense is refused as a whole.
|
||||
|
||||
use crate::shape::{self, ShapeRecord};
|
||||
use anicraft_geom::Affine;
|
||||
|
||||
/// Most objects one stream may hold.
|
||||
pub const MAX_OBJECTS: usize = 1 << 20;
|
||||
/// Deepest nesting of objects (groups in groups, a layer written inside another's record).
|
||||
const MAX_DEPTH: usize = 64;
|
||||
/// Longest string read, in UTF-16 units.
|
||||
const MAX_STRING: usize = 1 << 20;
|
||||
/// Bytes scanned while skipping undecoded objects, per stream.
|
||||
const SCAN_BUDGET: usize = 256 << 20;
|
||||
/// Trial parses while skipping, per stream.
|
||||
const MAX_TRIALS: usize = 1 << 16;
|
||||
/// Most envelope points, persistent-data entries, guides or ease anchors in one list.
|
||||
const MAX_LIST: usize = 1 << 16;
|
||||
/// The base point of a page, layer or frame: none.
|
||||
const NO_POINT: [u8; 8] = [0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80];
|
||||
|
||||
pub const KIND_PAGE: u8 = 0x07;
|
||||
pub const KIND_LAYER: u8 = 0x0B;
|
||||
pub const KIND_SHAPE: u8 = 0x03;
|
||||
pub const KIND_INSTANCE: u8 = 0x13;
|
||||
|
||||
/// The stream doesn't follow the grammar here.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Bad;
|
||||
|
||||
type R<T> = Result<T, Bad>;
|
||||
|
||||
/// A layer record.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LayerRec {
|
||||
pub name: String,
|
||||
pub current: bool,
|
||||
pub hidden: bool,
|
||||
pub locked: bool,
|
||||
pub outline: bool,
|
||||
pub color: [u8; 4],
|
||||
/// 0 normal, 1 guide, 3 folder, 4 mask.
|
||||
pub kind: u8,
|
||||
/// The layer it sits under (a folder, a mask or a guide), as a node.
|
||||
pub parent: Option<usize>,
|
||||
/// Its keyframes in order, as nodes.
|
||||
pub frames: Vec<usize>,
|
||||
}
|
||||
|
||||
/// A keyframe record.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct FrameRec {
|
||||
pub duration: u16,
|
||||
/// 0 none, 1 classic (motion), 2 shape.
|
||||
pub tween: u8,
|
||||
pub tween_flags: u8,
|
||||
/// The classic ease, −100..=100.
|
||||
pub ease: i16,
|
||||
/// The sound's library item id (0: none).
|
||||
pub sound: u16,
|
||||
pub label: String,
|
||||
/// 1: the label is a comment.
|
||||
pub label_kind: u32,
|
||||
/// Custom ease curves by group (position, rotation, scale, colour, filters, all): each a
|
||||
/// list of anchors (in handle x, y, anchor x, y, out handle x, y). Empty: no custom ease.
|
||||
pub eases: Vec<Vec<[f64; 6]>>,
|
||||
/// The keyframe's raw artwork (`None` when it didn't decode).
|
||||
pub raw: Option<ShapeRecord>,
|
||||
/// Why the raw artwork didn't decode, when it didn't.
|
||||
pub raw_error: Option<shape::ShapeError>,
|
||||
pub hints: bool,
|
||||
/// The keyframe has a frame script (kept for a later pass).
|
||||
pub script: bool,
|
||||
/// The keyframe's objects, bottom first, as nodes.
|
||||
pub elements: Vec<usize>,
|
||||
}
|
||||
|
||||
/// A symbol instance's colour effect as stored.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub struct ColorRec {
|
||||
/// Multipliers in 1/256 and offsets, alpha, red, green, blue.
|
||||
pub mul: [i16; 4],
|
||||
pub add: [i16; 4],
|
||||
/// 0 none, 1 brightness, 2 tint, 3 advanced, 4 alpha.
|
||||
pub style: u8,
|
||||
pub percent: i16,
|
||||
pub tint: [u8; 4],
|
||||
}
|
||||
|
||||
/// Which class an instance was.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum InstanceClass {
|
||||
#[default]
|
||||
Graphic,
|
||||
MovieClip,
|
||||
Button,
|
||||
}
|
||||
|
||||
/// A symbol instance record.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InstanceRec {
|
||||
pub class: InstanceClass,
|
||||
pub locked: bool,
|
||||
pub matrix: Affine,
|
||||
/// The transformation point placed on the stage (`M · p`), in twips.
|
||||
pub point: (i32, i32),
|
||||
pub first_frame: u16,
|
||||
pub loop_mode: u16,
|
||||
pub color: ColorRec,
|
||||
pub name: String,
|
||||
/// The library item id (`Contents`).
|
||||
pub item: u16,
|
||||
pub blend: u8,
|
||||
pub filters: u8,
|
||||
/// The record's tail (a movie clip's or button's settings, filters) was skipped.
|
||||
pub extras_skipped: bool,
|
||||
}
|
||||
|
||||
/// A shape object: a drawing object, a loose shape, or a group.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ShapeObj {
|
||||
pub flag: u8,
|
||||
pub drawing_object: bool,
|
||||
pub record: Option<ShapeRecord>,
|
||||
pub members: Vec<usize>,
|
||||
}
|
||||
|
||||
/// One decoded object.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Node {
|
||||
/// Being read (or a class number's placeholder).
|
||||
Pending,
|
||||
Page { layers: Vec<usize> },
|
||||
Layer(LayerRec),
|
||||
Frame(Box<FrameRec>),
|
||||
Shape(ShapeObj),
|
||||
Instance(Box<InstanceRec>),
|
||||
/// A shape tween's cache, or its hints: rebuilt by AniCraft.
|
||||
Morph,
|
||||
Hints,
|
||||
/// An object not decoded, by class name.
|
||||
Skipped(String),
|
||||
}
|
||||
|
||||
/// A stream's objects.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Graph {
|
||||
pub nodes: Vec<Node>,
|
||||
/// The page.
|
||||
pub root: usize,
|
||||
/// Undecoded stretches skipped.
|
||||
pub resyncs: usize,
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
pub fn node(&self, i: usize) -> Option<&Node> {
|
||||
self.nodes.get(i)
|
||||
}
|
||||
/// The layers, bottom first, each once.
|
||||
pub fn layers(&self) -> Vec<usize> {
|
||||
let Some(Node::Page { layers }) = self.nodes.get(self.root) else { return Vec::new() };
|
||||
let mut out: Vec<usize> = Vec::with_capacity(layers.len());
|
||||
for &l in layers {
|
||||
if matches!(self.nodes.get(l), Some(Node::Layer(_))) && !out.contains(&l) {
|
||||
out.push(l);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Entry {
|
||||
Null,
|
||||
Class(usize),
|
||||
Object(usize),
|
||||
}
|
||||
|
||||
enum Tag {
|
||||
Null,
|
||||
Ref(usize),
|
||||
New(usize),
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
d: &'a [u8],
|
||||
at: usize,
|
||||
map: Vec<Entry>,
|
||||
classes: Vec<String>,
|
||||
nodes: Vec<Node>,
|
||||
depth: usize,
|
||||
budget: usize,
|
||||
trials: usize,
|
||||
resyncs: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Snap {
|
||||
at: usize,
|
||||
map: usize,
|
||||
classes: usize,
|
||||
nodes: usize,
|
||||
}
|
||||
|
||||
struct Base {
|
||||
flag: u8,
|
||||
children: Vec<usize>,
|
||||
x: i32,
|
||||
y: i32,
|
||||
word: u16,
|
||||
}
|
||||
|
||||
/// Decodes an item stream's object graph (its first byte, then the page object).
|
||||
pub fn parse(data: &[u8]) -> Result<Graph, Bad> {
|
||||
if data.first() != Some(&0x01) {
|
||||
return Err(Bad);
|
||||
}
|
||||
let mut p = Parser { d: data, at: 1, map: vec![Entry::Null], classes: Vec::new(), nodes: Vec::new(), depth: 0, budget: SCAN_BUDGET, trials: 0, resyncs: 0 };
|
||||
let root = p.obj(None)?.ok_or(Bad)?;
|
||||
if !matches!(p.nodes.get(root), Some(Node::Page { .. })) {
|
||||
return Err(Bad);
|
||||
}
|
||||
Ok(Graph { nodes: p.nodes, root, resyncs: p.resyncs })
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
fn take(&mut self, n: usize) -> R<&'a [u8]> {
|
||||
let end = self.at.checked_add(n).ok_or(Bad)?;
|
||||
let s = self.d.get(self.at..end).ok_or(Bad)?;
|
||||
self.at = end;
|
||||
Ok(s)
|
||||
}
|
||||
fn arr<const N: usize>(&mut self) -> R<[u8; N]> {
|
||||
<[u8; N]>::try_from(self.take(N)?).map_err(|_| Bad)
|
||||
}
|
||||
fn u8(&mut self) -> R<u8> {
|
||||
Ok(self.arr::<1>()?[0])
|
||||
}
|
||||
fn u16(&mut self) -> R<u16> {
|
||||
Ok(u16::from_le_bytes(self.arr()?))
|
||||
}
|
||||
fn i16(&mut self) -> R<i16> {
|
||||
Ok(i16::from_le_bytes(self.arr()?))
|
||||
}
|
||||
fn u32(&mut self) -> R<u32> {
|
||||
Ok(u32::from_le_bytes(self.arr()?))
|
||||
}
|
||||
fn i32(&mut self) -> R<i32> {
|
||||
Ok(i32::from_le_bytes(self.arr()?))
|
||||
}
|
||||
fn f64(&mut self) -> R<f64> {
|
||||
Ok(f64::from_le_bytes(self.arr()?))
|
||||
}
|
||||
fn skip(&mut self, n: usize) -> R<()> {
|
||||
self.take(n).map(|_| ())
|
||||
}
|
||||
/// A length-bounded list count.
|
||||
fn count(&mut self, n: u32) -> R<usize> {
|
||||
let n = n as usize;
|
||||
if n > MAX_LIST { Err(Bad) } else { Ok(n) }
|
||||
}
|
||||
/// `FF FE FF`, a u8 length (`FF`: a u16 follows; `FFFF`: a u32), UTF-16 units.
|
||||
fn string(&mut self) -> R<String> {
|
||||
if self.take(3)? != [0xFF, 0xFE, 0xFF] {
|
||||
return Err(Bad);
|
||||
}
|
||||
let mut n = self.u8()? as usize;
|
||||
if n == 0xFF {
|
||||
n = self.u16()? as usize;
|
||||
if n == 0xFFFF {
|
||||
n = self.u32()? as usize;
|
||||
}
|
||||
}
|
||||
if n > MAX_STRING {
|
||||
return Err(Bad);
|
||||
}
|
||||
let bytes = self.take(n.checked_mul(2).ok_or(Bad)?)?;
|
||||
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect();
|
||||
Ok(String::from_utf16_lossy(&units))
|
||||
}
|
||||
fn matrix(&mut self) -> R<Affine> {
|
||||
let mut m = [0f32; 6];
|
||||
for (i, v) in m.iter_mut().enumerate() {
|
||||
let raw = self.i32()? as f32;
|
||||
*v = if i < 4 { raw / 65536.0 } else { raw / 20.0 };
|
||||
}
|
||||
Ok(Affine { m })
|
||||
}
|
||||
|
||||
fn snap(&self) -> Snap {
|
||||
Snap { at: self.at, map: self.map.len(), classes: self.classes.len(), nodes: self.nodes.len() }
|
||||
}
|
||||
fn restore(&mut self, s: Snap) {
|
||||
self.at = s.at;
|
||||
self.map.truncate(s.map);
|
||||
self.classes.truncate(s.classes);
|
||||
self.nodes.truncate(s.nodes);
|
||||
}
|
||||
|
||||
fn class_of(&self, index: usize) -> R<usize> {
|
||||
match self.map.get(index) {
|
||||
Some(Entry::Class(c)) => Ok(*c),
|
||||
_ => Err(Bad),
|
||||
}
|
||||
}
|
||||
|
||||
fn declare(&mut self, name: String) -> usize {
|
||||
let c = self.classes.len();
|
||||
self.classes.push(name);
|
||||
self.map.push(Entry::Class(c));
|
||||
c
|
||||
}
|
||||
|
||||
fn tag(&mut self) -> R<Tag> {
|
||||
let t = self.u16()?;
|
||||
Ok(match t {
|
||||
0 => Tag::Null,
|
||||
0xFFFF => {
|
||||
let _schema = self.u16()?;
|
||||
let n = self.u16()? as usize;
|
||||
if !(1..=64).contains(&n) {
|
||||
return Err(Bad);
|
||||
}
|
||||
let name = self.take(n)?;
|
||||
if !name.iter().all(|b| b.is_ascii_graphic()) {
|
||||
return Err(Bad);
|
||||
}
|
||||
let name = String::from_utf8_lossy(name).into_owned();
|
||||
Tag::New(self.declare(name))
|
||||
}
|
||||
0x7FFF => {
|
||||
let big = self.u32()?;
|
||||
if big & 0x8000_0000 != 0 {
|
||||
Tag::New(self.class_of((big & 0x7FFF_FFFF) as usize)?)
|
||||
} else {
|
||||
Tag::Ref(big as usize)
|
||||
}
|
||||
}
|
||||
t if t & 0x8000 != 0 => Tag::New(self.class_of((t & 0x7FFF) as usize)?),
|
||||
t => Tag::Ref(t as usize),
|
||||
})
|
||||
}
|
||||
|
||||
/// One object (`None` for the null tag). `parent` is the kind byte of the object it is a
|
||||
/// child of, when it is one: where an undecoded tail ends.
|
||||
fn obj(&mut self, parent: Option<u8>) -> R<Option<usize>> {
|
||||
match self.tag()? {
|
||||
Tag::Null => Ok(None),
|
||||
Tag::Ref(i) => match self.map.get(i) {
|
||||
Some(Entry::Object(n)) => Ok(Some(*n)),
|
||||
_ => Err(Bad),
|
||||
},
|
||||
Tag::New(class) => {
|
||||
if self.map.len() >= MAX_OBJECTS || self.depth >= MAX_DEPTH {
|
||||
return Err(Bad);
|
||||
}
|
||||
let n = self.nodes.len();
|
||||
self.nodes.push(Node::Pending);
|
||||
self.map.push(Entry::Object(n));
|
||||
self.depth += 1;
|
||||
let node = self.body(class, parent);
|
||||
self.depth -= 1;
|
||||
let node = node?;
|
||||
if let Some(slot) = self.nodes.get_mut(n) {
|
||||
*slot = node;
|
||||
}
|
||||
Ok(Some(n))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn body(&mut self, class: usize, parent: Option<u8>) -> R<Node> {
|
||||
let name = self.classes.get(class).cloned().unwrap_or_default();
|
||||
match name.as_str() {
|
||||
"CPicPage" => {
|
||||
let base = self.base(KIND_PAGE)?;
|
||||
self.skip(8)?;
|
||||
let n = self.u32()?;
|
||||
let n = self.count(n)?;
|
||||
self.skip(n.checked_mul(8).ok_or(Bad)?)?;
|
||||
Ok(Node::Page { layers: base.children })
|
||||
}
|
||||
"CPicLayer" => self.layer(),
|
||||
"CPicFrame" => self.frame(),
|
||||
"CPicShape" => {
|
||||
let base = self.base(KIND_SHAPE)?;
|
||||
let record = self.shape_body()?;
|
||||
Ok(Node::Shape(ShapeObj { flag: base.flag, drawing_object: base.word == 1, record: Some(record), members: base.children }))
|
||||
}
|
||||
"CPicSymbol" => self.instance(InstanceClass::Graphic, parent),
|
||||
"CPicSprite" => self.instance(InstanceClass::MovieClip, parent),
|
||||
"CPicButton" => self.instance(InstanceClass::Button, parent),
|
||||
"CPicMorphShape" => self.morph(),
|
||||
"CMorphSegment" => {
|
||||
self.skip(32)?;
|
||||
let n = self.u16()?;
|
||||
for _ in 0..n {
|
||||
self.obj(None)?;
|
||||
}
|
||||
Ok(Node::Morph)
|
||||
}
|
||||
"CMorphCurve" => {
|
||||
self.skip(36)?;
|
||||
Ok(Node::Morph)
|
||||
}
|
||||
"CObList" => {
|
||||
let n = self.u16()?;
|
||||
for _ in 0..n {
|
||||
self.obj(None)?;
|
||||
}
|
||||
Ok(Node::Hints)
|
||||
}
|
||||
"CMorphHintItem" => {
|
||||
self.skip(20)?;
|
||||
Ok(Node::Hints)
|
||||
}
|
||||
// Texts, bitmaps and anything newer: skipped to where their parent continues.
|
||||
_ => {
|
||||
self.resync(parent)?;
|
||||
Ok(Node::Skipped(name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The common head of a `CPic*` object; `kind` is the kind byte it must end with.
|
||||
fn base(&mut self, kind: u8) -> R<Base> {
|
||||
if self.u8()? != 0x04 {
|
||||
return Err(Bad);
|
||||
}
|
||||
let flag = self.u8()?;
|
||||
let mut children = Vec::new();
|
||||
loop {
|
||||
let snap = self.snap();
|
||||
match self.obj(Some(kind)) {
|
||||
Ok(None) => break,
|
||||
Ok(Some(n)) => children.push(n),
|
||||
Err(Bad) => {
|
||||
self.restore(snap);
|
||||
children.push(self.skip_child(kind)?);
|
||||
}
|
||||
}
|
||||
if children.len() > MAX_OBJECTS {
|
||||
return Err(Bad);
|
||||
}
|
||||
}
|
||||
let x = self.i32()?;
|
||||
let y = self.i32()?;
|
||||
let word = self.u16()?;
|
||||
if self.u8()? != kind {
|
||||
return Err(Bad);
|
||||
}
|
||||
Ok(Base { flag, children, x, y, word })
|
||||
}
|
||||
|
||||
/// Skips the child object starting here (one that didn't decode): its tag, then up to
|
||||
/// where its parent (of kind `parent`) continues. Returns its placeholder node.
|
||||
fn skip_child(&mut self, parent: u8) -> R<usize> {
|
||||
let class = match self.tag()? {
|
||||
Tag::New(c) => c,
|
||||
_ => return Err(Bad),
|
||||
};
|
||||
if self.map.len() >= MAX_OBJECTS {
|
||||
return Err(Bad);
|
||||
}
|
||||
let n = self.nodes.len();
|
||||
self.nodes.push(Node::Skipped(self.classes.get(class).cloned().unwrap_or_default()));
|
||||
self.map.push(Entry::Object(n));
|
||||
self.resync(Some(parent))?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Moves past bytes not decoded to where the parent continues: its end (when its kind is
|
||||
/// known) or the next sibling, which must parse.
|
||||
fn resync(&mut self, parent: Option<u8>) -> R<()> {
|
||||
let from = self.at;
|
||||
for i in from..self.d.len() {
|
||||
self.budget = self.budget.checked_sub(1).ok_or(Bad)?;
|
||||
if parent.is_some_and(|k| self.parent_end_at(i, k)) {
|
||||
self.count_declarations(from, i);
|
||||
self.at = i;
|
||||
self.resyncs += 1;
|
||||
return Ok(());
|
||||
}
|
||||
if self.sibling_head_at(i) && self.trials < MAX_TRIALS && self.depth < MAX_DEPTH {
|
||||
self.trials += 1;
|
||||
let before = self.snap();
|
||||
self.count_declarations(from, i);
|
||||
let after = Snap { at: i, ..self.snap() };
|
||||
self.at = i;
|
||||
let ok = matches!(self.obj(parent), Ok(Some(_)));
|
||||
// What a trial reads counts against the budget too (a hostile stream can't
|
||||
// make the skipping quadratic).
|
||||
self.budget = self.budget.saturating_sub(self.at.saturating_sub(i));
|
||||
if ok {
|
||||
self.restore(after);
|
||||
self.resyncs += 1;
|
||||
return Ok(());
|
||||
}
|
||||
self.restore(before);
|
||||
}
|
||||
}
|
||||
Err(Bad)
|
||||
}
|
||||
|
||||
/// Whether the parent's children end at `i`: `00 00`, then a base with no point and the
|
||||
/// parent's kind, then the start of what that kind holds next.
|
||||
fn parent_end_at(&self, i: usize, kind: u8) -> bool {
|
||||
let d = self.d;
|
||||
let at = |o: usize| i.checked_add(o).and_then(|j| d.get(j)).copied();
|
||||
if at(0) != Some(0) || at(1) != Some(0) || at(12) != Some(kind) {
|
||||
return false;
|
||||
}
|
||||
let point = i.checked_add(2).and_then(|s| d.get(s..s.checked_add(8)?));
|
||||
if point != Some(&NO_POINT[..]) || at(10).is_none_or(|w| w > 1) || at(11) != Some(0) {
|
||||
return false;
|
||||
}
|
||||
match kind {
|
||||
KIND_SHAPE => at(13 + 24) == Some(0x05),
|
||||
KIND_LAYER => at(13) == Some(0xFF) && at(14) == Some(0xFE) && at(15) == Some(0xFF),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an object of a known class (or a new class's declaration) starts at `i`.
|
||||
fn sibling_head_at(&self, i: usize) -> bool {
|
||||
let d = self.d;
|
||||
let byte = |o: usize| i.checked_add(o).and_then(|j| d.get(j)).copied();
|
||||
let (Some(lo), Some(hi)) = (byte(0), byte(1)) else { return false };
|
||||
let t = u16::from_le_bytes([lo, hi]);
|
||||
let body = if t == 0xFFFF {
|
||||
let len = match (byte(4), byte(5)) {
|
||||
(Some(a), Some(b)) => u16::from_le_bytes([a, b]) as usize,
|
||||
_ => return false,
|
||||
};
|
||||
if byte(6) != Some(b'C') || !(4..=40).contains(&len) {
|
||||
return false;
|
||||
}
|
||||
6 + len
|
||||
} else if t & 0x8000 != 0 && t != 0x7FFF {
|
||||
if !matches!(self.map.get((t & 0x7FFF) as usize), Some(Entry::Class(_))) {
|
||||
return false;
|
||||
}
|
||||
2
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
byte(body) == Some(0x04) && byte(body + 1).is_some_and(|f| f < 0x10)
|
||||
}
|
||||
|
||||
/// Class declarations inside skipped bytes, so later class numbers stay right (each
|
||||
/// declares a class and, right after, an object of it).
|
||||
fn count_declarations(&mut self, from: usize, to: usize) {
|
||||
let Some(span) = self.d.get(from..to) else { return };
|
||||
let mut i = 0usize;
|
||||
while i + 6 < span.len() {
|
||||
let len = span.get(i + 4..i + 6).map_or(0, |b| u16::from_le_bytes([b.first().copied().unwrap_or(0), b.get(1).copied().unwrap_or(0)]) as usize);
|
||||
let name = span.get(i + 6..i + 6 + len);
|
||||
if span.get(i..i + 2) == Some(&[0xFF, 0xFF][..])
|
||||
&& (4..=40).contains(&len)
|
||||
&& let Some(name) = name
|
||||
&& name.first() == Some(&b'C')
|
||||
&& name.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'_')
|
||||
&& self.map.len() + 2 < MAX_OBJECTS
|
||||
{
|
||||
let name = String::from_utf8_lossy(name).into_owned();
|
||||
self.declare(name.clone());
|
||||
let n = self.nodes.len();
|
||||
self.nodes.push(Node::Skipped(name));
|
||||
self.map.push(Entry::Object(n));
|
||||
i += 6 + len;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape body here: matrix, `05`, the shape grammar, then the cubic hints.
|
||||
fn shape_body(&mut self) -> R<ShapeRecord> {
|
||||
self.shape_body_or_why().map_err(|_| Bad)
|
||||
}
|
||||
|
||||
/// A shape body, or why it didn't decode.
|
||||
fn shape_body_or_why(&mut self) -> Result<ShapeRecord, shape::ShapeError> {
|
||||
let at05 = self.at.checked_add(24).ok_or(shape::ShapeError::Truncated)?;
|
||||
let record = shape::decode(self.d, at05)?;
|
||||
self.at = record.end;
|
||||
let n = self.u32().map_err(|_| shape::ShapeError::Truncated)? as usize;
|
||||
if n > shape::MAX_EDGES {
|
||||
return Err(shape::ShapeError::TooLarge);
|
||||
}
|
||||
self.skip(n.saturating_mul(32)).map_err(|_| shape::ShapeError::Truncated)?;
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
fn layer(&mut self) -> R<Node> {
|
||||
let base = self.base(KIND_LAYER)?;
|
||||
let name = self.string()?;
|
||||
let [current, hidden, locked] = self.arr::<3>()?;
|
||||
self.skip(4)?;
|
||||
let color = self.arr::<4>()?;
|
||||
let outline = self.u32()? != 0;
|
||||
self.skip(4)?;
|
||||
let kind = self.u8()?;
|
||||
let parent = self.obj(None)?;
|
||||
self.skip(2)?;
|
||||
Ok(Node::Layer(LayerRec { name, current: current != 0, hidden: hidden != 0, locked: locked != 0, outline, color, kind, parent, frames: base.children }))
|
||||
}
|
||||
|
||||
fn frame(&mut self) -> R<Node> {
|
||||
let base = self.base(KIND_SHAPE)?;
|
||||
let start = self.at;
|
||||
let (raw, raw_error) = match self.shape_body_or_why() {
|
||||
Ok(r) => (Some(r), None),
|
||||
Err(why) => {
|
||||
// Artwork in a layout not decoded: find the frame's own fields.
|
||||
self.at = start;
|
||||
self.find_frame_tail()?;
|
||||
(None, Some(why))
|
||||
}
|
||||
};
|
||||
let mut f = self.frame_tail()?;
|
||||
f.raw = raw;
|
||||
f.raw_error = raw_error;
|
||||
f.elements = base.children;
|
||||
Ok(Node::Frame(Box::new(f)))
|
||||
}
|
||||
|
||||
/// Moves to the frame fields after raw artwork that didn't decode: the first `18` from
|
||||
/// which the fields parse and the next object (or the layer's end) follows.
|
||||
fn find_frame_tail(&mut self) -> R<()> {
|
||||
let from = self.at;
|
||||
for i in from..self.d.len() {
|
||||
self.budget = self.budget.checked_sub(1).ok_or(Bad)?;
|
||||
if self.d.get(i) != Some(&0x18) || self.trials >= MAX_TRIALS {
|
||||
continue;
|
||||
}
|
||||
self.trials += 1;
|
||||
let snap = self.snap();
|
||||
self.at = i;
|
||||
let ok = self.frame_tail().is_ok() && (self.parent_end_at(self.at, KIND_LAYER) || self.sibling_head_at(self.at));
|
||||
self.budget = self.budget.saturating_sub(self.at.saturating_sub(i));
|
||||
self.restore(snap);
|
||||
if ok {
|
||||
self.at = i;
|
||||
self.resyncs += 1;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(Bad)
|
||||
}
|
||||
|
||||
fn frame_tail(&mut self) -> R<FrameRec> {
|
||||
if self.u8()? != 0x18 {
|
||||
return Err(Bad);
|
||||
}
|
||||
let duration = self.u16()?;
|
||||
let tween = self.u8()?;
|
||||
let tween_flags = self.u8()?;
|
||||
let ease = self.i16()?;
|
||||
let sound = self.u16()?;
|
||||
let n = self.u16()?;
|
||||
let n = self.count(n as u32)?;
|
||||
self.skip(n.checked_mul(8).ok_or(Bad)?)?;
|
||||
self.skip(2 + 1 + 4 + 4 + 2)?; // loops, sync, in, out, zoom
|
||||
let label = self.string()?;
|
||||
self.skip(16)?; // the frame actions' header
|
||||
let script = !self.string()?.trim().is_empty();
|
||||
self.skip(8)?;
|
||||
let label_kind = self.u32()?;
|
||||
self.obj(None)?; // the shape tween's cache
|
||||
self.skip(4)?;
|
||||
let hints = self.obj(None)?.is_some();
|
||||
self.string()?;
|
||||
let mut flags = [0u32; 5];
|
||||
for v in flags.iter_mut() {
|
||||
*v = self.u32()?;
|
||||
}
|
||||
let mut eases = Vec::new();
|
||||
if flags[4] != 0 {
|
||||
for _ in 0..6 {
|
||||
let n = self.u32()?;
|
||||
let n = self.count(n)?;
|
||||
let mut curve = Vec::with_capacity(n.min(64));
|
||||
for _ in 0..n {
|
||||
let mut a = [0f64; 6];
|
||||
for v in a.iter_mut() {
|
||||
*v = self.f64()?;
|
||||
}
|
||||
curve.push(a);
|
||||
}
|
||||
eases.push(curve);
|
||||
}
|
||||
}
|
||||
Ok(FrameRec { duration, tween, tween_flags, ease, sound, label, label_kind, eases, raw: None, raw_error: None, hints, script, elements: Vec::new() })
|
||||
}
|
||||
|
||||
fn instance(&mut self, class: InstanceClass, parent: Option<u8>) -> R<Node> {
|
||||
let base = self.base(KIND_INSTANCE)?;
|
||||
let matrix = self.matrix()?;
|
||||
let first_frame = self.u16()?;
|
||||
let loop_mode = self.u16()?;
|
||||
self.skip(1)?;
|
||||
let mut color = ColorRec::default();
|
||||
for i in 0..4 {
|
||||
let (m, a) = (self.i16()?, self.i16()?);
|
||||
if let (Some(mm), Some(aa)) = (color.mul.get_mut(i), color.add.get_mut(i)) {
|
||||
*mm = m;
|
||||
*aa = a;
|
||||
}
|
||||
}
|
||||
color.style = self.u8()?;
|
||||
self.skip(1)?;
|
||||
color.percent = self.i16()?;
|
||||
color.tint = self.arr()?;
|
||||
let name = self.string()?;
|
||||
let item = self.u16()?;
|
||||
self.skip(3)?;
|
||||
if self.u8()? != 0 {
|
||||
if self.u32()? != 1 {
|
||||
return Err(Bad);
|
||||
}
|
||||
let n = self.u32()?;
|
||||
for _ in 0..self.count(n)? {
|
||||
if self.u8()? != 0x05 {
|
||||
return Err(Bad);
|
||||
}
|
||||
self.string()?;
|
||||
self.string()?;
|
||||
}
|
||||
}
|
||||
self.skip(1)?;
|
||||
let filters = self.u8()?;
|
||||
let mut rec = InstanceRec { class, locked: base.flag & 0x04 != 0, matrix, point: (base.x, base.y), first_frame, loop_mode, color, name, item, blend: 1, filters, extras_skipped: false };
|
||||
if filters == 0 {
|
||||
rec.blend = self.u8()?;
|
||||
self.skip(2)?;
|
||||
}
|
||||
if filters != 0 || class != InstanceClass::Graphic {
|
||||
// Filters (layout not decoded) and a movie clip's or button's settings.
|
||||
self.resync(parent)?;
|
||||
rec.extras_skipped = true;
|
||||
}
|
||||
Ok(Node::Instance(Box::new(rec)))
|
||||
}
|
||||
|
||||
/// A shape tween's cache: version 2, two matrices, 8 bytes, its segments (objects), then
|
||||
/// its fill styles (RGBA, kind, a byte; a gradient adds a matrix, a count and 5-byte
|
||||
/// stops) and strokes (10 bytes each).
|
||||
fn morph(&mut self) -> R<Node> {
|
||||
if self.u8()? != 0x02 {
|
||||
return Err(Bad);
|
||||
}
|
||||
self.skip(48 + 8)?;
|
||||
let n = self.u16()?;
|
||||
for _ in 0..n {
|
||||
self.obj(None)?;
|
||||
}
|
||||
self.skip(2)?;
|
||||
let fills = self.u16()?;
|
||||
for _ in 0..fills {
|
||||
self.skip(4)?;
|
||||
let kind = self.u8()?;
|
||||
self.skip(1)?;
|
||||
match kind {
|
||||
0x00 => {}
|
||||
0x10 | 0x12 => {
|
||||
self.skip(24)?;
|
||||
let stops = self.u8()? as usize;
|
||||
self.skip(stops * 5)?;
|
||||
}
|
||||
_ => return Err(Bad),
|
||||
}
|
||||
}
|
||||
let strokes = self.u16()? as usize;
|
||||
self.skip(strokes * 10)?;
|
||||
Ok(Node::Morph)
|
||||
}
|
||||
}
|
||||
+466
-98
@@ -1,24 +1,31 @@
|
||||
//! Structural decode of a legacy document: scenes, layers and library names into the
|
||||
//! AniCraft document model.
|
||||
//! A legacy document into the AniCraft model: scenes, layers, keyframes and their artwork,
|
||||
//! symbol instances, tweens and the library (ADR 0096).
|
||||
//!
|
||||
//! Observed format (Flash 8–CS4 era; see ADR 0096 and the corpus notes): every stream
|
||||
//! starts with a 5-byte prologue, and its records are fields of `ff fe ff`- or
|
||||
//! `01 80 17`-prefixed strings (UTF-16, a one-byte length) and raw numerics. The
|
||||
//! `Contents` stream lists the document: library items (stream name + label pairs) and
|
||||
//! one `CDocumentPage` record per scene (page stream name + scene label). A page stream
|
||||
//! (`P <n> <stamp>`) holds its scene's timeline: one record per layer, whose name trails
|
||||
//! the layer's data behind a constant `00 80 00 00 00 80 00 00 0b` anchor — layers are
|
||||
//! stored bottom-first, so the decode reverses them for AniCraft's top-first timelines.
|
||||
//! Observed format (Flash 8–CS4 era; see ADR 0096 and the corpus notes): the `Contents`
|
||||
//! stream lists the document — library items (stream name, label, item id, symbol type), the
|
||||
//! stage, and one `CDocumentPage` record per scene (page stream name + scene label). Every page
|
||||
//! stream (`P <n> <stamp>`) and library stream (`S <n> <stamp>`, `Symbol <n>`) holds one
|
||||
//! timeline as an object graph ([`crate::archive`]): layers (stored bottom-first), their
|
||||
//! keyframes, each keyframe's raw artwork and objects (symbol instances, drawing objects,
|
||||
//! groups). The mapping mirrors the XFL importer's, so a legacy file and its Animate twin open
|
||||
//! with the same structure: folder layers hold no frames, raw shapes merge (ADR 0042), comments
|
||||
//! are reported, classic and shape tweens with their eases.
|
||||
//!
|
||||
//! This pass decodes the *structure* only. Frame records, artwork, tweens, text, bitmaps
|
||||
//! and sounds stay for the record-level decode pass and are counted in the report, so a
|
||||
//! file opens with its scenes, layers and library rather than failing outright.
|
||||
//! What isn't decoded yet — texts, bitmaps, sounds, a movie clip's or button's extra settings
|
||||
//! — is left out and counted in the report; a timeline that doesn't decode at all falls back
|
||||
//! to the structure-only reading (layer names, a symbol's first shape).
|
||||
|
||||
use crate::archive::{self, Graph, InstanceClass, Node};
|
||||
use crate::cfb::Compound;
|
||||
use crate::records;
|
||||
use crate::shape;
|
||||
use crate::report::{ImportError, Report};
|
||||
use anicraft_doc::{Document, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, Scene, Stage, Symbol, SymbolKind, SymbolId, Timeline};
|
||||
use anicraft_doc::ColorTransform;
|
||||
use anicraft_doc::{
|
||||
BlendMode, ColorEffect, CustomEase, Document, EaseGroup, Easing, Element, ElementId, ElementKind, Keyframe, Layer, LayerId, LayerKind, LoopMode, Rgba, Scene, Stage, Symbol,
|
||||
SymbolId, SymbolKind, Timeline, Tween, TweenKind,
|
||||
};
|
||||
use anicraft_geom::Vec2;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The `Contents` stream's version byte on every corpus file of the Flash 8–CS4 era.
|
||||
@@ -32,6 +39,10 @@ const STRING_MARKER: [u8; 3] = [0xFF, 0xFE, 0xFF];
|
||||
const LAYER_ANCHOR: [u8; 9] = [0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x0B];
|
||||
/// Longest name read (layer, scene and library labels).
|
||||
const MAX_NAME: usize = 64;
|
||||
/// Latest frame kept (as the XFL importer).
|
||||
const MAX_FRAME: u32 = 100_000;
|
||||
/// Deepest group nesting kept.
|
||||
const MAX_GROUP_DEPTH: usize = 32;
|
||||
|
||||
/// A scene as the document lists it: its page stream's name and the scene's label.
|
||||
struct Page {
|
||||
@@ -39,7 +50,27 @@ struct Page {
|
||||
label: String,
|
||||
}
|
||||
|
||||
/// Imports a legacy `.fla`'s structure into the AniCraft model.
|
||||
/// A library item as `Contents` lists it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LibraryItem {
|
||||
/// Its stream (`S 54 1522499933`, `Symbol 125`).
|
||||
pub stream: String,
|
||||
pub label: String,
|
||||
/// The id placements refer to it by.
|
||||
pub id: u32,
|
||||
/// 0 graphic, 1 button, 2 movie clip.
|
||||
pub kind: u8,
|
||||
}
|
||||
|
||||
/// What the mapping needs while it builds timelines.
|
||||
struct Ctx<'a> {
|
||||
doc: &'a mut Document,
|
||||
report: &'a mut Report,
|
||||
/// Library item id → symbol.
|
||||
symbols: &'a HashMap<u32, SymbolId>,
|
||||
}
|
||||
|
||||
/// Imports a legacy `.fla` into the AniCraft model.
|
||||
pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> {
|
||||
let file = Compound::new(data)?;
|
||||
let contents = file.stream("Contents")?;
|
||||
@@ -48,32 +79,59 @@ pub fn import(data: &[u8]) -> Result<(Document, Report), ImportError> {
|
||||
}
|
||||
let mut report = Report::default();
|
||||
let pages = pages(&contents)?;
|
||||
let library = library(&contents, &mut report);
|
||||
if !library.is_empty() {
|
||||
let items = library_items(&contents);
|
||||
if !items.is_empty() {
|
||||
report.keep("library names");
|
||||
}
|
||||
|
||||
let mut doc = Document::default();
|
||||
doc.scenes.clear();
|
||||
doc.stage = Stage::default();
|
||||
// v1: frame records, artwork, tweens, text and media stay for the decode pass; the
|
||||
// document opens with its scenes, layers and library names.
|
||||
report.notes.push("the era's frame records, artwork, tweens, text and media are decoded in a later pass; the document opens with its scenes, layers and library".into());
|
||||
doc.library.clear();
|
||||
doc.stage = stage(&contents).unwrap_or_default();
|
||||
// Symbols first, so instances can refer to any of them.
|
||||
let mut symbols: HashMap<u32, SymbolId> = HashMap::new();
|
||||
let mut ids = Vec::with_capacity(items.len());
|
||||
for item in &items {
|
||||
let id = SymbolId(doc.alloc_id());
|
||||
symbols.insert(item.id, id);
|
||||
ids.push(id);
|
||||
}
|
||||
for (item, &id) in items.iter().zip(&ids) {
|
||||
let timeline = match file.stream(&item.stream) {
|
||||
Ok(bytes) => library_timeline(&bytes, &item.label, &mut doc, &mut report, &symbols),
|
||||
Err(_) => {
|
||||
report.skip_named("library symbols whose stream is missing", item.label.clone());
|
||||
Timeline { layers: vec![Arc::new(Layer::new(LayerId(doc.alloc_id()), "Layer 1"))] }
|
||||
}
|
||||
};
|
||||
let kind = match item.kind {
|
||||
0 => SymbolKind::Graphic,
|
||||
1 => SymbolKind::Button,
|
||||
_ => SymbolKind::MovieClip,
|
||||
};
|
||||
doc.library.push(Arc::new(Symbol { id, name: item.label.clone(), kind, linkage: None, scale_grid: None, scale_grid_kept: None, timeline }));
|
||||
report.keep("library symbols");
|
||||
}
|
||||
for page in &pages {
|
||||
let mut timeline = Timeline::default();
|
||||
if let Ok(bytes) = file.stream(&page.stream) {
|
||||
// Layer records are stored bottom-first; AniCraft's timelines are top-first.
|
||||
for name in layer_names(&bytes).into_iter().rev() {
|
||||
let id = LayerId(doc.alloc_id());
|
||||
timeline.layers.push(Arc::new(Layer::new(id, name)));
|
||||
report.keep("layers");
|
||||
}
|
||||
} else {
|
||||
report.skip_named("scenes whose page stream is missing", page.label.clone());
|
||||
match file.stream(&page.stream) {
|
||||
Ok(bytes) => match archive::parse(&bytes) {
|
||||
Ok(graph) => {
|
||||
let mut ctx = Ctx { doc: &mut doc, report: &mut report, symbols: &symbols };
|
||||
timeline = build_timeline(&graph, &mut ctx);
|
||||
}
|
||||
Err(_) => {
|
||||
// The structure-only reading: the layer names.
|
||||
report.skip_named("scenes whose timeline didn't decode (layer names only)", page.label.clone());
|
||||
for name in layer_names(&bytes).into_iter().rev() {
|
||||
timeline.layers.push(Arc::new(Layer::new(LayerId(doc.alloc_id()), name)));
|
||||
}
|
||||
}
|
||||
},
|
||||
Err(_) => report.skip_named("scenes whose page stream is missing", page.label.clone()),
|
||||
}
|
||||
let id = LayerId(doc.alloc_id());
|
||||
if timeline.layers.is_empty() {
|
||||
timeline.layers.push(Arc::new(Layer::new(id, "Layer 1")));
|
||||
timeline.layers.push(Arc::new(Layer::new(LayerId(doc.alloc_id()), "Layer 1")));
|
||||
}
|
||||
doc.scenes.push(Arc::new(Scene { name: page.label.clone(), timeline, guides: Vec::new() }));
|
||||
}
|
||||
@@ -82,42 +140,363 @@ 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 first shape
|
||||
// record's artwork (the frame-level decode will place the rest).
|
||||
let mut decoded_shapes = 0usize;
|
||||
for (stream, label) in &library {
|
||||
let Ok(bytes) = file.stream(stream) else { continue };
|
||||
let shapes = shapes(&bytes, &mut report);
|
||||
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,
|
||||
}));
|
||||
decoded_shapes += 1;
|
||||
report.keep("library symbols with decoded shapes");
|
||||
}
|
||||
doc.sanitize();
|
||||
count_pending_records(&file, decoded_shapes, &mut report);
|
||||
Ok((doc, report))
|
||||
}
|
||||
|
||||
/// Decodes a library stream's first `CPicShape` record (the object that names the class)
|
||||
/// into shape elements: one per fill style, then one per stroke style, carried by the
|
||||
/// record's matrix. The record grammar — straight and quadratic edges, styles, gradients —
|
||||
/// is in [`crate::shape`]. A record that doesn't decode is left out whole and counted; the
|
||||
/// stream's other shape records wait for the frame-level decode that places them.
|
||||
/// A library item's timeline: its stream's object graph, or (when that doesn't decode) its
|
||||
/// first shape record on one keyframe.
|
||||
fn library_timeline(bytes: &[u8], label: &str, doc: &mut Document, report: &mut Report, symbols: &HashMap<u32, SymbolId>) -> Timeline {
|
||||
if let Ok(graph) = archive::parse(bytes) {
|
||||
let mut ctx = Ctx { doc, report, symbols };
|
||||
let tl = build_timeline(&graph, &mut ctx);
|
||||
if !tl.layers.is_empty() {
|
||||
return tl;
|
||||
}
|
||||
}
|
||||
let shapes = shapes(bytes, report);
|
||||
let layer = Layer::new(LayerId(doc.alloc_id()), "artwork");
|
||||
if shapes.is_empty() {
|
||||
report.skip_named("library symbols whose timeline didn't decode", label.to_string());
|
||||
return Timeline { layers: vec![Arc::new(layer)] };
|
||||
}
|
||||
report.skip_named("library symbols whose timeline didn't decode (first drawing shown)", label.to_string());
|
||||
let elements = shapes.into_iter().map(|mut e| {
|
||||
e.id = ElementId(doc.alloc_id());
|
||||
Arc::new(e)
|
||||
}).collect();
|
||||
let keyframe = Keyframe { elements, ..Keyframe::new(0, 1) };
|
||||
Timeline { layers: vec![Arc::new(Layer { keyframes: vec![Arc::new(keyframe)], ..layer })] }
|
||||
}
|
||||
|
||||
/// A timeline from a decoded graph: layers top-first, keyframes with their artwork and tweens.
|
||||
fn build_timeline(graph: &Graph, ctx: &mut Ctx) -> Timeline {
|
||||
let order = graph.layers();
|
||||
let mut ids: HashMap<usize, LayerId> = HashMap::new();
|
||||
for &n in &order {
|
||||
ids.insert(n, LayerId(ctx.doc.alloc_id()));
|
||||
}
|
||||
let mut layers = Vec::with_capacity(order.len());
|
||||
for &n in order.iter().rev() {
|
||||
let (Some(Node::Layer(rec)), Some(&id)) = (graph.node(n), ids.get(&n)) else { continue };
|
||||
let mut layer = Layer::new(id, rec.name.chars().take(256).collect::<String>());
|
||||
layer.kind = match rec.kind {
|
||||
1 => LayerKind::Guide,
|
||||
3 => LayerKind::Folder,
|
||||
4 => LayerKind::Mask,
|
||||
_ => LayerKind::Normal,
|
||||
};
|
||||
layer.parent = rec.parent.and_then(|p| ids.get(&p).copied()).filter(|p| *p != id);
|
||||
layer.visible = !rec.hidden;
|
||||
layer.locked = rec.locked;
|
||||
layer.outline = rec.outline;
|
||||
let [r, g, b, a] = rec.color;
|
||||
layer.color = Rgba::new(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a as f32 / 255.0);
|
||||
ctx.report.keep("layers");
|
||||
if layer.kind == LayerKind::Folder {
|
||||
// A folder holds layers, never frames.
|
||||
layer.keyframes.clear();
|
||||
layers.push(Arc::new(layer));
|
||||
continue;
|
||||
}
|
||||
let mut keys = Vec::new();
|
||||
let mut start = 0u32;
|
||||
for &f in &rec.frames {
|
||||
let Some(Node::Frame(frame)) = graph.node(f) else {
|
||||
ctx.report.skip("keyframes that didn't decode");
|
||||
continue;
|
||||
};
|
||||
let duration = u32::from(frame.duration);
|
||||
let at = start.min(MAX_FRAME);
|
||||
start = start.saturating_add(duration);
|
||||
// A zero-length frame record holds nothing that shows (Animate drops it too).
|
||||
if duration == 0 {
|
||||
continue;
|
||||
}
|
||||
keys.push(Arc::new(keyframe(graph, frame, at, duration.clamp(1, MAX_FRAME), ctx)));
|
||||
ctx.report.keep("keyframes");
|
||||
}
|
||||
if !keys.is_empty() {
|
||||
layer.keyframes = keys;
|
||||
}
|
||||
layer.normalize();
|
||||
layers.push(Arc::new(layer));
|
||||
}
|
||||
let mut tl = Timeline { layers };
|
||||
tl.repair_masks();
|
||||
tl
|
||||
}
|
||||
|
||||
fn keyframe(graph: &Graph, frame: &archive::FrameRec, start: u32, duration: u32, ctx: &mut Ctx) -> Keyframe {
|
||||
let mut k = Keyframe::new(start, duration);
|
||||
if !frame.label.is_empty() {
|
||||
if frame.label_kind == 1 {
|
||||
// A note to the animator that nothing can go to: no place for it yet.
|
||||
ctx.report.skip("frame comments");
|
||||
} else {
|
||||
k.label = frame.label.chars().take(256).collect();
|
||||
}
|
||||
}
|
||||
match frame.tween {
|
||||
1 | 2 => {
|
||||
let kind = if frame.tween == 2 { TweenKind::Shape } else { TweenKind::Classic };
|
||||
let (easing, groups) = easing(frame, ctx.report);
|
||||
let mut t = Tween { easing, kind, ..Tween::default() };
|
||||
for (g, e) in groups {
|
||||
t.set_ease(g, Some(e));
|
||||
}
|
||||
k.tween = Some(t);
|
||||
if frame.hints {
|
||||
ctx.report.skip("shape hints (left out)");
|
||||
}
|
||||
}
|
||||
0 => {}
|
||||
_ => ctx.report.skip("tweens of an unknown kind (kept as keyframes)"),
|
||||
}
|
||||
if frame.script {
|
||||
ctx.report.skip("frame scripts (decode pending)");
|
||||
}
|
||||
if frame.sound != 0 {
|
||||
ctx.report.skip("frame sounds (decode pending)");
|
||||
}
|
||||
let mut elements = Vec::new();
|
||||
// The keyframe's raw artwork sits below its objects, its shapes merging (ADR 0042).
|
||||
match &frame.raw {
|
||||
Some(record) => push_shapes(record, true, ctx, &mut elements),
|
||||
None => {
|
||||
if let Some(why) = frame.raw_error {
|
||||
ctx.report.skip(shape_skip(why));
|
||||
}
|
||||
}
|
||||
}
|
||||
for &e in &frame.elements {
|
||||
element(graph, e, ctx, &mut elements, 0);
|
||||
}
|
||||
k.elements = elements;
|
||||
k
|
||||
}
|
||||
|
||||
/// A tween's ease (as the XFL importer reads it): the classic slider, or the custom curves —
|
||||
/// one for everything, or one per property group.
|
||||
fn easing(frame: &archive::FrameRec, report: &mut Report) -> (Easing, Vec<(EaseGroup, Easing)>) {
|
||||
let acc = (frame.ease as f32).clamp(-100.0, 100.0);
|
||||
let classic = if acc == 0.0 { Easing::Linear } else { Easing::Classic(acc) };
|
||||
if frame.eases.iter().all(Vec::is_empty) {
|
||||
return (classic, Vec::new());
|
||||
}
|
||||
const GROUPS: [EaseGroup; 5] = [EaseGroup::Position, EaseGroup::Rotation, EaseGroup::Scale, EaseGroup::Color, EaseGroup::Filters];
|
||||
if let Some(all) = frame.eases.get(5).filter(|c| !c.is_empty()) {
|
||||
return (curve(all, report).unwrap_or(classic), Vec::new());
|
||||
}
|
||||
let groups = GROUPS.iter().zip(&frame.eases).filter(|(_, c)| !c.is_empty()).filter_map(|(g, c)| curve(c, report).map(|e| (*g, e))).collect();
|
||||
(classic, groups)
|
||||
}
|
||||
|
||||
/// One custom ease curve from its anchors (in handle, anchor, out handle), as the XFL
|
||||
/// importer makes them: one segment is a cubic Bézier, more a custom ease.
|
||||
fn curve(anchors: &[[f64; 6]], report: &mut Report) -> Option<Easing> {
|
||||
let mut pts: Vec<Vec2> = Vec::with_capacity(anchors.len() * 3);
|
||||
for (i, a) in anchors.iter().enumerate() {
|
||||
let p = |x: f64, y: f64| Vec2::new(x as f32, y as f32);
|
||||
if i > 0 {
|
||||
pts.push(p(a[0], a[1]));
|
||||
}
|
||||
pts.push(p(a[2], a[3]));
|
||||
if i + 1 < anchors.len() {
|
||||
pts.push(p(a[4], a[5]));
|
||||
}
|
||||
}
|
||||
if pts.iter().any(|p| !p.is_finite()) || pts.len() / 3 + 1 > anicraft_doc::MAX_EASE_POINTS {
|
||||
report.skip("custom ease curves with a broken point list (drawn with the simple ease)");
|
||||
return None;
|
||||
}
|
||||
let Some(c) = CustomEase::from_flat(&pts) else {
|
||||
report.skip("custom ease curves with a broken point list (drawn with the simple ease)");
|
||||
return None;
|
||||
};
|
||||
Some(match c.points() {
|
||||
[a, b] => Easing::CubicBezier(a.out.x, a.out.y, b.at.x + b.h_in.x, b.at.y + b.h_in.y),
|
||||
_ => Easing::Custom(Arc::new(c)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The AniCraft elements for one decoded object, pushed bottom-first.
|
||||
fn element(graph: &Graph, n: usize, ctx: &mut Ctx, out: &mut Vec<Arc<Element>>, depth: usize) {
|
||||
match graph.node(n) {
|
||||
Some(Node::Instance(inst)) => {
|
||||
if let Some(e) = instance(inst, ctx) {
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
}
|
||||
Some(Node::Shape(s)) => {
|
||||
let group = !s.drawing_object && (!s.members.is_empty() || s.flag & 1 == 0);
|
||||
if !group {
|
||||
if let Some(record) = &s.record {
|
||||
push_shapes(record, !s.drawing_object, ctx, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if depth >= MAX_GROUP_DEPTH {
|
||||
ctx.report.skip("groups nested more than 32 deep");
|
||||
return;
|
||||
}
|
||||
// A group (ADR 0073): its own body, then its members; their shapes merge only with
|
||||
// each other.
|
||||
let mut members = Vec::new();
|
||||
if let Some(record) = &s.record {
|
||||
push_shapes(record, true, ctx, &mut members);
|
||||
}
|
||||
for &m in &s.members {
|
||||
element(graph, m, ctx, &mut members, depth + 1);
|
||||
}
|
||||
if !members.is_empty() {
|
||||
let layer = LayerId(ctx.doc.alloc_id());
|
||||
let id = ElementId(ctx.doc.alloc_id());
|
||||
out.push(Arc::new(Element { id, name: String::new(), transform: anicraft_geom::Affine::IDENTITY, color: ColorEffect::default(), kind: ElementKind::group(layer, members) }));
|
||||
}
|
||||
}
|
||||
Some(Node::Skipped(class)) => {
|
||||
let what = match class.as_str() {
|
||||
"CPicShape" => "shapes whose edge records didn't decode",
|
||||
"CPicText" => "texts (decode pending)",
|
||||
"CPicBitmap" => "bitmaps (decode pending)",
|
||||
"CPicVideo" => "videos (decode pending)",
|
||||
_ => "objects of a kind not decoded (left out)",
|
||||
};
|
||||
ctx.report.skip(what);
|
||||
}
|
||||
Some(Node::Morph | Node::Hints | Node::Pending) | None => {}
|
||||
Some(_) => ctx.report.skip("objects of a kind not decoded (left out)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The report kind for a shape that didn't decode.
|
||||
fn shape_skip(why: shape::ShapeError) -> &'static str {
|
||||
match why {
|
||||
shape::ShapeError::FillKind(0x40..=0x43) => "shapes with bitmap fills (decode pending)",
|
||||
shape::ShapeError::FillKind(_) => "shapes with fills of an unknown kind",
|
||||
_ => "shapes whose edge records didn't decode",
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape record's AniCraft shapes (one per fill, then per stroke), carried by its matrix.
|
||||
fn push_shapes(record: &shape::ShapeRecord, merge: bool, ctx: &mut Ctx, out: &mut Vec<Arc<Element>>) {
|
||||
for what in &record.approximations {
|
||||
ctx.report.skip(what);
|
||||
}
|
||||
for mut s in record.shapes() {
|
||||
s.merge = merge;
|
||||
let id = ElementId(ctx.doc.alloc_id());
|
||||
out.push(Arc::new(Element { id, name: String::new(), transform: record.matrix, color: ColorEffect::default(), kind: ElementKind::Shape(s) }));
|
||||
}
|
||||
}
|
||||
|
||||
/// A symbol instance (as the XFL importer builds `DOMSymbolInstance`).
|
||||
fn instance(inst: &archive::InstanceRec, ctx: &mut Ctx) -> Option<Element> {
|
||||
let Some(&symbol) = ctx.symbols.get(&u32::from(inst.item)) else {
|
||||
ctx.report.skip("instances of missing symbols");
|
||||
return None;
|
||||
};
|
||||
// Graphics pick their frame by loop mode; movie clips and buttons play their own timeline.
|
||||
let loop_mode = match (inst.class, inst.loop_mode) {
|
||||
(InstanceClass::Graphic, 1) => LoopMode::PlayOnce,
|
||||
(InstanceClass::Graphic, 2) => LoopMode::SingleFrame,
|
||||
_ => LoopMode::Loop,
|
||||
};
|
||||
let blend = match inst.blend {
|
||||
2 => BlendMode::Layer,
|
||||
3 => BlendMode::Multiply,
|
||||
4 => BlendMode::Screen,
|
||||
5 => BlendMode::Lighten,
|
||||
6 => BlendMode::Darken,
|
||||
7 => BlendMode::Difference,
|
||||
8 => BlendMode::Add,
|
||||
9 => BlendMode::Subtract,
|
||||
10 => BlendMode::Invert,
|
||||
11 => BlendMode::Alpha,
|
||||
12 => BlendMode::Erase,
|
||||
13 => BlendMode::Overlay,
|
||||
14 => BlendMode::HardLight,
|
||||
_ => BlendMode::Normal,
|
||||
};
|
||||
if inst.filters != 0 {
|
||||
ctx.report.skip("filters and blend modes on filtered instances (left out)");
|
||||
} else if inst.extras_skipped {
|
||||
ctx.report.skip("movie clip and button settings (scripts, component data; left out)");
|
||||
}
|
||||
let m = inst.matrix;
|
||||
// The stored point is the transformation point placed by the matrix: back into the
|
||||
// instance's own space. Kept only when the artist moved it off the registration point.
|
||||
let placed = Vec2::new(inst.point.0 as f32 / 20.0, inst.point.1 as f32 / 20.0);
|
||||
let pivot = m.inverse().map(|inv| inv.apply(placed)).filter(|p| p.is_finite() && (p.x.abs() > 0.025 || p.y.abs() > 0.025));
|
||||
let mut e = Element {
|
||||
id: ElementId(ctx.doc.alloc_id()),
|
||||
name: String::new(),
|
||||
transform: m,
|
||||
color: color_effect(&inst.color),
|
||||
kind: ElementKind::Symbol { symbol, loop_mode, first_frame: u32::from(inst.first_frame).min(MAX_FRAME), blend, filters: Vec::new(), events: Vec::new(), pivot },
|
||||
};
|
||||
let name = inst.name.trim();
|
||||
if !name.is_empty() {
|
||||
if anicraft_doc::actions::valid_instance_name(name) {
|
||||
e.name = name.to_string();
|
||||
} else {
|
||||
ctx.report.skip("instance names actions can't use (left out)");
|
||||
}
|
||||
}
|
||||
ctx.report.keep("symbol instances");
|
||||
Some(e)
|
||||
}
|
||||
|
||||
/// An instance's colour effect by its style, as the XFL importer reads Animate's.
|
||||
fn color_effect(c: &archive::ColorRec) -> ColorEffect {
|
||||
let mul = |i: usize| c.mul.get(i).map_or(1.0, |v| *v as f32 / 256.0);
|
||||
let add = |i: usize| c.add.get(i).map_or(0.0, |v| *v as f32 / 255.0);
|
||||
let alpha = mul(0);
|
||||
let pct = (c.percent as f32 / 100.0).clamp(-1.0, 1.0);
|
||||
let with_alpha = |fx: ColorEffect| if alpha != 1.0 { fx.with_alpha(alpha) } else { fx };
|
||||
let fx = match c.style {
|
||||
1 if pct != 0.0 => with_alpha(ColorEffect::Brightness(pct)),
|
||||
2 => {
|
||||
let [r, g, b, _] = c.tint;
|
||||
with_alpha(ColorEffect::Tint { color: Rgba::new(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0), amount: pct })
|
||||
}
|
||||
3 => {
|
||||
let t = ColorTransform { mul: [mul(1), mul(2), mul(3), mul(0)], add: [add(1), add(2), add(3), add(0)] };
|
||||
if t.is_identity() { ColorEffect::None } else { ColorEffect::Advanced(t) }
|
||||
}
|
||||
4 if alpha != 1.0 => ColorEffect::Alpha(alpha),
|
||||
_ => ColorEffect::None,
|
||||
};
|
||||
fx.sanitized()
|
||||
}
|
||||
|
||||
/// The stage: its size, frame rate and colour, in the document properties `Contents` lists
|
||||
/// before the `legacyLineSpacing` property: the stage rectangle (i32 left, right, top, bottom
|
||||
/// in twips) 74 bytes before that property's name, the background (RGBA) 21 bytes before it
|
||||
/// and the frame rate (16.16) 13 bytes before it. `None` when they don't make a stage.
|
||||
pub fn stage(contents: &[u8]) -> Option<Stage> {
|
||||
let name: Vec<u8> = "legacyLineSpacing".encode_utf16().flat_map(u16::to_le_bytes).collect();
|
||||
let mut needle = vec![0xFF, 0xFE, 0xFF, 17];
|
||||
needle.extend_from_slice(&name);
|
||||
let at = find(contents, &needle)?;
|
||||
let i32_at = |o: usize| -> Option<i32> { let s = at.checked_sub(o)?; contents.get(s..s + 4).and_then(|b| b.try_into().ok()).map(i32::from_le_bytes) };
|
||||
let (left, right, top, bottom) = (i32_at(74)?, i32_at(70)?, i32_at(66)?, i32_at(62)?);
|
||||
let fps = i32_at(13)? as f32 / 65536.0;
|
||||
let bg = contents.get(at.checked_sub(21)?..at.checked_sub(17)?)?;
|
||||
let (w, h) = ((right - left) / 20, (bottom - top) / 20);
|
||||
let edge = 1..=anicraft_doc::MAX_STAGE_EDGE as i32;
|
||||
if !edge.contains(&w) || !edge.contains(&h) || !(1.0..=120.0).contains(&fps) {
|
||||
return None;
|
||||
}
|
||||
let c = |i: usize| bg.get(i).map_or(1.0, |v| *v as f32 / 255.0);
|
||||
Some(Stage { width: w as u32, height: h as u32, fps, background: Rgba::new(c(0), c(1), c(2), 1.0) })
|
||||
}
|
||||
|
||||
/// The fallback for a library stream whose timeline doesn't decode: its first `CPicShape`
|
||||
/// record (the object that names the class) as shape elements, one per fill style, then one
|
||||
/// per stroke style, carried by the record's matrix. A record that doesn't decode is left
|
||||
/// out whole and counted.
|
||||
fn shapes(bytes: &[u8], report: &mut Report) -> Vec<Element> {
|
||||
let Some(name) = find(bytes, b"CPicShape") else { return Vec::new() };
|
||||
let after = name + b"CPicShape".len();
|
||||
@@ -213,19 +592,37 @@ fn pages(contents: &[u8]) -> Result<Vec<Page>, ImportError> {
|
||||
/// The library: stream-name strings (`01 80 17` prefix) each followed by a label string
|
||||
/// (`ff fe ff`), e.g. `Symbol 125` → `UFO rays`, as (stream, label) pairs.
|
||||
pub fn library(contents: &[u8], report: &mut Report) -> Vec<(String, String)> {
|
||||
let items = library_items(contents);
|
||||
if !items.is_empty() {
|
||||
report.keep("library names");
|
||||
}
|
||||
items.into_iter().map(|i| (i.stream, i.label)).collect()
|
||||
}
|
||||
|
||||
/// The library's symbols: each a stream-name string (`01 80 17` prefix), its label (`ff fe ff`),
|
||||
/// then a u32 item id (what placements refer to; not always the stream's number) and a symbol
|
||||
/// type byte (0 graphic, 1 button, 2 movie clip).
|
||||
pub fn library_items(contents: &[u8]) -> Vec<LibraryItem> {
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while i + STREAM_NAME_PREFIX.len() + 2 <= contents.len() {
|
||||
if contents[i] == STREAM_NAME_PREFIX[0] && contents[i + 1] == STREAM_NAME_PREFIX[1] && contents[i + 2] == 0x17
|
||||
if contents.get(i..i + 2) == Some(&STREAM_NAME_PREFIX[..]) && contents.get(i + 2) == Some(&0x17)
|
||||
&& let Some(name) = marked_string(contents, i + 2, 0x17) {
|
||||
// The label follows within the same record: take the first string ahead.
|
||||
let from = i + 4 + 2 * name.len();
|
||||
let to = (from + 256).min(contents.len());
|
||||
for j in from..to {
|
||||
if let Some(label) = after_marker(contents, j) {
|
||||
report.keep("library names");
|
||||
i = j + 4 + 2 * label.len();
|
||||
out.push((name, label));
|
||||
// `j` is the marker's last byte; the length, then the UTF-16 units.
|
||||
let end = j + 2 + 2 * label.encode_utf16().count();
|
||||
let id = contents.get(end..end + 4).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes);
|
||||
let kind = contents.get(end + 4).copied();
|
||||
i = end;
|
||||
if let (Some(id), Some(kind)) = (id, kind)
|
||||
&& (name.starts_with("S ") || name.starts_with("Symbol "))
|
||||
{
|
||||
out.push(LibraryItem { stream: name, label, id, kind });
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -278,35 +675,6 @@ fn marked_string(data: &[u8], at: usize, third: u8) -> Option<String> {
|
||||
(text.chars().all(|c| !c.is_control())).then_some(text)
|
||||
}
|
||||
|
||||
/// 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, 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 symbol above
|
||||
continue;
|
||||
}
|
||||
let what = match tag.name.as_str() {
|
||||
"CPicShape" | "CMorphSegment" => "shapes (artwork decode pending)",
|
||||
"CPicSymbol" => "symbol placements (decode pending)",
|
||||
"CPicText" => "texts (decode pending)",
|
||||
"CPicButton" => "buttons (decode pending)",
|
||||
"CPicMorphShape" => "shape tweens (decode pending)",
|
||||
"CMediaBits" | "CPicBitmap" => "bitmaps (decode pending)",
|
||||
"CMediaSound" => "sounds (decode pending)",
|
||||
"CPicScript" => "frame scripts (decode pending)",
|
||||
_ => continue,
|
||||
};
|
||||
report.skip(what);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds `needle` in `data` (small, bounded scans; the streams are capped by the reader).
|
||||
fn find(data: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
if needle.is_empty() || data.len() < needle.len() {
|
||||
|
||||
@@ -12,11 +12,13 @@
|
||||
//! Container hardening follows ADR 0054's zip profile: the file is capped at 1 GiB and every
|
||||
//! stream at 256 MiB, chains (FAT, mini-FAT, DIFAT, directory tree) are cycle-guarded, nothing
|
||||
//! is written to disk, and hostile or damaged input is refused with a one-sentence error —
|
||||
//! never a panic. [`doc`] decodes the document's structure, and [`shape`] the `CPicShape`
|
||||
//! records' styles and straight and curved edges (ADR 0096).
|
||||
//! never a panic. [`archive`] reads an item stream's object graph (layers, keyframes, symbol
|
||||
//! instances, tweens), [`shape`] the shape records' styles and straight and curved edges, and
|
||||
//! [`doc`] maps them into the AniCraft model the way the XFL importer maps Animate's (ADR 0096).
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod archive;
|
||||
pub mod cfb;
|
||||
pub mod doc;
|
||||
pub mod records;
|
||||
|
||||
+488
-20
@@ -310,25 +310,21 @@ fn synthetic_contents() -> Vec<u8> {
|
||||
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(&9u32.to_le_bytes()); // its item id
|
||||
c.push(0x00); // a graphic
|
||||
c.extend_from_slice(&[0u8; 8]);
|
||||
c
|
||||
}
|
||||
|
||||
/// A minimal page stream: the item prologue, then two layer records — each the constant
|
||||
/// layer anchor, the marker, then the name (stored bottom-first).
|
||||
/// A minimal page stream: two layers (stored bottom-first), each with one empty keyframe.
|
||||
fn synthetic_page() -> Vec<u8> {
|
||||
let utf16 = |s: &str| -> Vec<u8> { s.encode_utf16().flat_map(|c| c.to_le_bytes()).collect() };
|
||||
let anchor = [0x00u8, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x0B];
|
||||
let mut d = records::ITEM_PROLOGUE.to_vec();
|
||||
d.extend_from_slice(&[0x08, 0x00]);
|
||||
d.extend_from_slice(b"CPicPage");
|
||||
for name in ["b", "a"] {
|
||||
d.extend_from_slice(&anchor);
|
||||
d.extend_from_slice(&[0xFF, 0xFE, 0xFF, name.len() as u8]);
|
||||
d.extend_from_slice(&utf16(name));
|
||||
d.extend_from_slice(&[0u8; 16]);
|
||||
}
|
||||
d
|
||||
let mut w = Ar::new();
|
||||
w.page(|w| {
|
||||
for name in ["b", "a"] {
|
||||
w.layer(name, 0, None, |w| w.frame(&[], &FrameSpec { duration: 1, ..FrameSpec::default() }, |_| {}));
|
||||
}
|
||||
});
|
||||
w.out
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -337,7 +333,7 @@ fn a_synthetic_legacy_document_opens_with_its_scenes_and_layers() {
|
||||
let payloads = vec![
|
||||
("Contents", synthetic_contents()),
|
||||
("P 1 1", synthetic_page()),
|
||||
("S 9 100", b"no records".to_vec()),
|
||||
("Symbol 9", one_frame_stream(&[])),
|
||||
];
|
||||
let bytes = write(&payloads);
|
||||
let (document, report) = doc::import(&bytes).expect("the synthetic legacy document opens");
|
||||
@@ -346,8 +342,8 @@ fn a_synthetic_legacy_document_opens_with_its_scenes_and_layers() {
|
||||
// Layers come bottom-first in the stream; the timeline is top-first.
|
||||
let names: Vec<&str> = document.scenes[0].timeline.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["a", "b"]);
|
||||
// The structure-only open reports what stayed for the record-level decode.
|
||||
assert!(report.skipped.is_empty(), "a stream with no known records skips nothing: {:?}", report.skipped);
|
||||
// Everything in it decoded: nothing to report.
|
||||
assert!(report.skipped.is_empty(), "{:?}", report.skipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -465,9 +461,9 @@ fn synthetic_shape_record() -> Vec<u8> {
|
||||
d
|
||||
}
|
||||
|
||||
fn library_shapes(stream: Vec<u8>) -> (Vec<std::sync::Arc<anicraft_doc::Element>>, super::Report) {
|
||||
fn library_shapes(record: Vec<u8>) -> (Vec<std::sync::Arc<anicraft_doc::Element>>, super::Report) {
|
||||
use super::doc;
|
||||
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", synthetic_page()), ("Symbol 9", stream)];
|
||||
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", synthetic_page()), ("Symbol 9", one_frame_stream(&record_body(&record)))];
|
||||
let (document, report) = doc::import(&write(&payloads)).expect("opens");
|
||||
let elements = document.library.iter().find(|s| s.name == "UFO mask")
|
||||
.map(|symbol| symbol.timeline.layers[0].keyframes[0].elements.clone())
|
||||
@@ -475,6 +471,25 @@ fn library_shapes(stream: Vec<u8>) -> (Vec<std::sync::Arc<anicraft_doc::Element>
|
||||
(elements, report)
|
||||
}
|
||||
|
||||
/// A shape record's body (from its matrix to the edge list's end), as a keyframe holds it.
|
||||
fn record_body(record: &[u8]) -> Vec<u8> {
|
||||
let start = records::ITEM_PROLOGUE.len() + 6 + 9 + 15;
|
||||
// Up to the edge list's end when it decodes (the tail after it is the library object's).
|
||||
let end = super::shape::find_all(record).first().map_or(record.len(), |r| r.end);
|
||||
record.get(start..end).map(<[u8]>::to_vec).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// An item stream of one layer with one keyframe whose raw artwork is `body`.
|
||||
fn one_frame_stream(body: &[u8]) -> Vec<u8> {
|
||||
let mut w = Ar::new();
|
||||
w.page(|w| {
|
||||
w.layer("artwork", 0, None, |w| {
|
||||
w.frame(body, &FrameSpec { duration: 1, ..FrameSpec::default() }, |_| {});
|
||||
});
|
||||
});
|
||||
w.out
|
||||
}
|
||||
|
||||
fn shape_of(element: &anicraft_doc::Element) -> &anicraft_doc::Shape {
|
||||
match &element.kind {
|
||||
anicraft_doc::ElementKind::Shape(shape) => shape,
|
||||
@@ -670,7 +685,8 @@ fn a_shape_record_cut_short_anywhere_never_panics_and_never_half_draws() {
|
||||
let (elements, report) = library_shapes(good[..cut].to_vec());
|
||||
if cut < full_end {
|
||||
assert!(elements.is_empty(), "cut at {cut}: a partial record drew {} shapes", elements.len());
|
||||
if cut > records::ITEM_PROLOGUE.len() + 6 + 9 {
|
||||
// (A cut before the body's start leaves the keyframe an empty body: nothing lost.)
|
||||
if cut > records::ITEM_PROLOGUE.len() + 6 + 9 + 15 {
|
||||
assert!(!report.skipped.is_empty(), "cut at {cut}: the left-out shape is counted");
|
||||
}
|
||||
} else {
|
||||
@@ -678,3 +694,455 @@ fn a_shape_record_cut_short_anywhere_never_panics_and_never_half_draws() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Timelines: an independent writer for the item streams' object graph (ADR 0096), written from
|
||||
// the decoded grammar (`crate::archive`), never from corpus bytes.
|
||||
|
||||
/// Writes an item stream: the `01` byte, then objects the way the format numbers them (classes
|
||||
/// and objects share one count from 1; a new class is declared by name, a known one referenced
|
||||
/// as `0x8000 | n`, an object written before as `n`).
|
||||
struct Ar {
|
||||
out: Vec<u8>,
|
||||
classes: Vec<(&'static str, u16)>,
|
||||
count: u16,
|
||||
}
|
||||
|
||||
/// What a keyframe record carries besides its artwork and objects.
|
||||
#[derive(Clone, Default)]
|
||||
struct FrameSpec {
|
||||
duration: u16,
|
||||
/// 0 none, 1 classic, 2 shape.
|
||||
tween: u8,
|
||||
ease: i16,
|
||||
label: &'static str,
|
||||
comment: bool,
|
||||
/// Custom ease anchors for the `all` group: (in, anchor, out) points.
|
||||
ease_all: Vec<[f64; 6]>,
|
||||
script: &'static str,
|
||||
}
|
||||
|
||||
/// A symbol instance as written.
|
||||
#[derive(Clone)]
|
||||
struct InstSpec {
|
||||
class: &'static str,
|
||||
item: u16,
|
||||
matrix: [i32; 6],
|
||||
/// The transformation point placed on the stage, in twips.
|
||||
point: (i32, i32),
|
||||
first_frame: u16,
|
||||
loop_mode: u16,
|
||||
/// (style, A mul, A add, R mul, R add, G mul, G add, B mul, B add, percent, tint RGBA)
|
||||
color: (u8, [i16; 8], i16, [u8; 4]),
|
||||
blend: u8,
|
||||
flag: u8,
|
||||
persistent: Vec<(&'static str, &'static str)>,
|
||||
}
|
||||
|
||||
impl Default for InstSpec {
|
||||
fn default() -> Self {
|
||||
InstSpec {
|
||||
class: "CPicSymbol",
|
||||
item: 9,
|
||||
matrix: [65536, 0, 0, 65536, 0, 0],
|
||||
point: (0, 0),
|
||||
first_frame: 0,
|
||||
loop_mode: 0,
|
||||
color: (0, [256, 0, 256, 0, 256, 0, 256, 0], 0, [255, 255, 255, 255]),
|
||||
blend: 1,
|
||||
flag: 0,
|
||||
persistent: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Ar {
|
||||
fn new() -> Ar {
|
||||
Ar { out: vec![0x01], classes: Vec::new(), count: 1 }
|
||||
}
|
||||
fn u16(&mut self, v: u16) {
|
||||
self.out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn i32(&mut self, v: i32) {
|
||||
self.out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
fn string(&mut self, s: &str) {
|
||||
let units: Vec<u16> = s.encode_utf16().collect();
|
||||
self.out.extend_from_slice(&[0xFF, 0xFE, 0xFF]);
|
||||
if units.len() < 0xFF {
|
||||
self.out.push(units.len() as u8);
|
||||
} else {
|
||||
self.out.push(0xFF);
|
||||
self.u16(units.len() as u16);
|
||||
}
|
||||
for u in units {
|
||||
self.u16(u);
|
||||
}
|
||||
}
|
||||
/// An object's tag; returns the object's number.
|
||||
fn tag(&mut self, class: &'static str) -> u16 {
|
||||
if let Some(&(_, n)) = self.classes.iter().find(|(c, _)| *c == class) {
|
||||
self.u16(0x8000 | n);
|
||||
} else {
|
||||
self.out.extend_from_slice(&[0xFF, 0xFF, 0x01, 0x00]);
|
||||
self.u16(class.len() as u16);
|
||||
self.out.extend_from_slice(class.as_bytes());
|
||||
self.classes.push((class, self.count));
|
||||
self.count += 1;
|
||||
}
|
||||
self.count += 1;
|
||||
self.count - 1
|
||||
}
|
||||
/// A `CPic*` object's head, its children, then its base fields.
|
||||
fn object(&mut self, class: &'static str, flag: u8, point: Option<(i32, i32)>, word: u16, kind: u8, children: impl FnOnce(&mut Ar)) -> u16 {
|
||||
let n = self.tag(class);
|
||||
self.out.extend_from_slice(&[0x04, flag]);
|
||||
children(self);
|
||||
self.out.extend_from_slice(&[0x00, 0x00]);
|
||||
let (x, y) = point.unwrap_or((i32::MIN, i32::MIN));
|
||||
self.i32(x);
|
||||
self.i32(y);
|
||||
self.u16(word);
|
||||
self.out.push(kind);
|
||||
n
|
||||
}
|
||||
fn page(&mut self, layers: impl FnOnce(&mut Ar)) {
|
||||
self.object("CPicPage", 0, None, 0, 0x07, layers);
|
||||
self.out.extend_from_slice(&[0x02, 0x00, 0x01, 0x00, 0, 0, 0, 0]);
|
||||
self.i32(0); // no ruler guides
|
||||
}
|
||||
/// A layer; `parent` is the layer it sits under, written in place (as the first child of a
|
||||
/// folder has it).
|
||||
fn layer(&mut self, name: &str, kind: u8, parent: Option<Parent>, frames: impl FnOnce(&mut Ar)) -> u16 {
|
||||
let n = self.object("CPicLayer", 0, None, 0, 0x0B, frames);
|
||||
self.layer_fields(name, kind, parent);
|
||||
n
|
||||
}
|
||||
fn layer_fields(&mut self, name: &str, kind: u8, parent: Option<Parent>) {
|
||||
self.string(name);
|
||||
self.out.extend_from_slice(&[0, 0, 1]); // not current, not hidden, locked
|
||||
self.i32(-1);
|
||||
self.out.extend_from_slice(&[0x4F, 0xFF, 0x4F, 0xFF]);
|
||||
self.i32(0);
|
||||
self.i32(1);
|
||||
self.out.push(kind);
|
||||
match parent {
|
||||
None => self.u16(0),
|
||||
Some(Parent::Inline(name, kind)) => {
|
||||
self.object("CPicLayer", 0, None, 0, 0x0B, |_| {});
|
||||
self.layer_fields(name, kind, None);
|
||||
}
|
||||
}
|
||||
self.out.extend_from_slice(&[0x01, 0x00]);
|
||||
}
|
||||
/// A keyframe: its objects, its raw artwork (a shape body), then its fields.
|
||||
fn frame(&mut self, body: &[u8], spec: &FrameSpec, objects: impl FnOnce(&mut Ar)) {
|
||||
self.object("CPicFrame", 0, None, 0, 0x03, objects);
|
||||
if body.is_empty() {
|
||||
self.empty_shape();
|
||||
} else {
|
||||
self.out.extend_from_slice(body);
|
||||
}
|
||||
self.i32(0); // no cubic hints
|
||||
self.out.push(0x18);
|
||||
self.u16(spec.duration);
|
||||
self.out.extend_from_slice(&[spec.tween, 0x06]);
|
||||
self.out.extend_from_slice(&spec.ease.to_le_bytes());
|
||||
self.u16(0); // no sound
|
||||
self.u16(0); // no envelope
|
||||
self.u16(1); // loops
|
||||
self.out.push(0); // sync
|
||||
self.i32(0);
|
||||
self.i32(0x3FFF_FFFF);
|
||||
self.u16(0xFFFF);
|
||||
self.string(spec.label);
|
||||
self.out.extend_from_slice(&[4, 0, 0, 0, 1, 0, 0, 0, 0x33, 0x0D, 0, 0, 0, 0, 0, 0]);
|
||||
self.string(spec.script);
|
||||
self.out.extend_from_slice(&[0; 8]);
|
||||
self.i32(spec.comment as i32);
|
||||
self.u16(0); // no shape-tween cache
|
||||
self.out.extend_from_slice(&[0; 4]);
|
||||
self.u16(0); // no hints
|
||||
self.string("");
|
||||
for v in [1, 0, 0, 1, (!spec.ease_all.is_empty()) as i32] {
|
||||
self.i32(v);
|
||||
}
|
||||
if !spec.ease_all.is_empty() {
|
||||
for group in 0..6 {
|
||||
if group < 5 {
|
||||
self.i32(0);
|
||||
continue;
|
||||
}
|
||||
self.i32(spec.ease_all.len() as i32);
|
||||
for a in &spec.ease_all {
|
||||
for v in a {
|
||||
self.out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A shape body without edges: the identity matrix, no styles.
|
||||
fn empty_shape(&mut self) {
|
||||
for v in [65536, 0, 0, 65536, 0, 0] {
|
||||
self.i32(v);
|
||||
}
|
||||
self.out.push(0x05);
|
||||
self.i32(0);
|
||||
self.u16(0);
|
||||
self.u16(0);
|
||||
self.out.push(0x00);
|
||||
}
|
||||
fn instance(&mut self, spec: &InstSpec) {
|
||||
self.object(spec.class, spec.flag, Some(spec.point), 0, 0x13, |_| {});
|
||||
for v in spec.matrix {
|
||||
self.i32(v);
|
||||
}
|
||||
self.u16(spec.first_frame);
|
||||
self.u16(spec.loop_mode);
|
||||
self.out.push(1);
|
||||
let (style, chans, percent, tint) = spec.color;
|
||||
for v in chans {
|
||||
self.out.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
self.out.extend_from_slice(&[style, 0]);
|
||||
self.out.extend_from_slice(&percent.to_le_bytes());
|
||||
self.out.extend_from_slice(&tint);
|
||||
self.string("");
|
||||
self.u16(spec.item);
|
||||
self.out.extend_from_slice(&[0, 0, 0]);
|
||||
if spec.persistent.is_empty() {
|
||||
self.out.push(0);
|
||||
} else {
|
||||
self.out.push(1);
|
||||
self.i32(1);
|
||||
self.i32(spec.persistent.len() as i32);
|
||||
for (k, v) in &spec.persistent {
|
||||
self.out.push(0x05);
|
||||
self.string(k);
|
||||
self.string(v);
|
||||
}
|
||||
}
|
||||
self.out.extend_from_slice(&[0, 0, spec.blend, 0, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
enum Parent {
|
||||
/// The parent layer, written in place.
|
||||
Inline(&'static str, u8),
|
||||
}
|
||||
|
||||
/// The rectangle's body (from `synthetic_shape_record`).
|
||||
fn rectangle_body() -> Vec<u8> {
|
||||
record_body(&synthetic_shape_record())
|
||||
}
|
||||
|
||||
/// A scene's page: a folder written in place as its first child's parent, a guide, a layer
|
||||
/// with a classic tween, a comment and a name label, a zero-length frame and a scaled,
|
||||
/// tinted, single-frame instance with a moved transformation point; then the folder's own
|
||||
/// place in the stack (a back-reference) and a top layer.
|
||||
fn rich_page() -> (Vec<u8>, InstSpec) {
|
||||
let inst = InstSpec {
|
||||
// Scale 1.25 and −0.5, a 30° rotation's b and c, translation (100.5, −20.25) px.
|
||||
matrix: [81920, 32768, -32768, -32768, 2010, -405],
|
||||
point: (2010 + 200, -405 + 100),
|
||||
first_frame: 4,
|
||||
loop_mode: 2,
|
||||
color: (2, [256, 0, 128, 0, 128, 0, 128, 0], 50, [255, 0, 0, 255]),
|
||||
blend: 7,
|
||||
flag: 0x04,
|
||||
persistent: vec![("rigData", "{\"id\":1}")],
|
||||
..InstSpec::default()
|
||||
};
|
||||
let mut w = Ar::new();
|
||||
let rect = rectangle_body();
|
||||
let i2 = inst.clone();
|
||||
let mut folder = 0u16;
|
||||
w.page(|w| {
|
||||
// Bottom first: a layer inside a folder (the folder written in place as its parent).
|
||||
w.layer("in folder", 0, Some(Parent::Inline("folder", 3)), |w| {
|
||||
w.frame(&rect, &FrameSpec { duration: 10, ..FrameSpec::default() }, |_| {});
|
||||
});
|
||||
// The folder was the last object written.
|
||||
folder = w.count - 1;
|
||||
w.u16(folder); // the folder's own place in the stack: a back-reference
|
||||
w.layer("animation", 0, None, |w| {
|
||||
w.frame(&[], &FrameSpec { duration: 0, ..FrameSpec::default() }, |_| {}); // dropped
|
||||
w.frame(&[], &FrameSpec { duration: 3, tween: 1, ease: -50, label: "start", ..FrameSpec::default() }, |w| w.instance(&i2));
|
||||
w.frame(&[], &FrameSpec { duration: 7, label: "note to self", comment: true, ease_all: vec![[0.0, 0.0, 0.0, 0.0, 0.25, 0.1], [0.75, 0.9, 1.0, 1.0, 1.0, 1.0]], tween: 2, ..FrameSpec::default() }, |w| {
|
||||
w.instance(&InstSpec { class: "CPicSprite", ..InstSpec::default() });
|
||||
});
|
||||
});
|
||||
w.layer("guide", 1, None, |w| w.frame(&[], &FrameSpec { duration: 10, script: "stop();", ..FrameSpec::default() }, |_| {}));
|
||||
});
|
||||
(w.out, inst)
|
||||
}
|
||||
|
||||
/// A movie-clip instance's settings after its common fields, in a layout not decoded: a
|
||||
/// version byte, the frame actions' header, two strings, then component data.
|
||||
fn sprite_extras(w: &mut Ar) {
|
||||
w.out.push(0x08);
|
||||
w.out.extend_from_slice(&[4, 0, 0, 0, 1, 0, 0, 0, 0x42, 0x57, 0, 0, 0, 0, 0, 0]);
|
||||
w.string("");
|
||||
w.string("");
|
||||
w.out.extend_from_slice(&[2, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0]);
|
||||
w.string("<component metaDataFetched='true'/>");
|
||||
}
|
||||
|
||||
fn rich_document() -> (Vec<u8>, InstSpec) {
|
||||
let (page, inst) = rich_page();
|
||||
// The movie clip in `rich_page` carries its extras: rewrite it with them in place.
|
||||
let page = with_sprite_extras(page);
|
||||
let mut symbol = Ar::new();
|
||||
let rect = rectangle_body();
|
||||
symbol.page(|w| {
|
||||
w.layer("artwork", 0, None, |w| {
|
||||
w.frame(&rect, &FrameSpec { duration: 2, ..FrameSpec::default() }, |_| {});
|
||||
w.frame(&[], &FrameSpec { duration: 3, ..FrameSpec::default() }, |_| {});
|
||||
});
|
||||
});
|
||||
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", page), ("Symbol 9", symbol.out)];
|
||||
(write(&payloads), inst)
|
||||
}
|
||||
|
||||
/// `page` with a movie clip's extra settings after the sprite instance's common fields.
|
||||
fn with_sprite_extras(page: Vec<u8>) -> Vec<u8> {
|
||||
let name = b"CPicSprite";
|
||||
let Some(at) = page.windows(name.len()).position(|w| w == name) else { return page };
|
||||
// The sprite's common fields end with its blend byte and two zero bytes: 15 bytes of base,
|
||||
// 24 of matrix, 4, 1, 16, 1, 1, 2, 4, the empty name (4), the item (2), 3 + 1 + 1 + 1 + 1 + 2.
|
||||
let end = at + name.len() + 15 + 24 + 4 + 1 + 16 + 1 + 1 + 2 + 4 + 4 + 2 + 3 + 1 + 1 + 1 + 1 + 2;
|
||||
let mut extras = Ar::new();
|
||||
extras.out.clear();
|
||||
sprite_extras(&mut extras);
|
||||
let mut out = page[..end].to_vec();
|
||||
out.extend_from_slice(&extras.out);
|
||||
out.extend_from_slice(&page[end..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn scene(doc: &anicraft_doc::Document) -> &anicraft_doc::Timeline {
|
||||
&doc.scenes[0].timeline
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_synthetic_timeline_decodes_its_layers_keyframes_tweens_and_instances() {
|
||||
use anicraft_doc::{BlendMode, ColorEffect, ElementKind, LayerKind, LoopMode, TweenKind};
|
||||
let (bytes, inst) = rich_document();
|
||||
let (doc, report) = super::doc::import(&bytes).expect("the synthetic document opens");
|
||||
let tl = scene(&doc);
|
||||
// Top first: the guide, the animation, the folder, the layer in it.
|
||||
let names: Vec<&str> = tl.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["guide", "animation", "folder", "in folder"]);
|
||||
let kinds: Vec<LayerKind> = tl.layers.iter().map(|l| l.kind).collect();
|
||||
assert_eq!(kinds, [LayerKind::Guide, LayerKind::Normal, LayerKind::Folder, LayerKind::Normal]);
|
||||
assert_eq!(tl.layers[3].parent, Some(tl.layers[2].id), "the layer sits in the folder");
|
||||
assert!(tl.layers[2].keyframes.is_empty(), "a folder holds no frames");
|
||||
assert!(tl.layers[0].locked && tl.layers[0].visible);
|
||||
// The animation's keyframes: the zero-length record dropped, the rest one after another.
|
||||
let anim = &tl.layers[1];
|
||||
let spans: Vec<(u32, u32)> = anim.keyframes.iter().map(|k| (k.start, k.duration)).collect();
|
||||
assert_eq!(spans, [(0, 3), (3, 7)]);
|
||||
let first = &anim.keyframes[0];
|
||||
assert_eq!(first.label, "start");
|
||||
let tween = first.tween.as_ref().expect("a classic tween");
|
||||
assert_eq!(tween.kind, TweenKind::Classic);
|
||||
assert_eq!(tween.easing, anicraft_doc::Easing::Classic(-50.0));
|
||||
let second = &anim.keyframes[1];
|
||||
assert_eq!(second.label, "", "a comment is not a label");
|
||||
let shape_tween = second.tween.as_ref().expect("a shape tween");
|
||||
assert_eq!(shape_tween.kind, TweenKind::Shape);
|
||||
let anicraft_doc::Easing::CubicBezier(x1, y1, x2, y2) = shape_tween.easing else { panic!("the custom ease's one segment: {:?}", shape_tween.easing) };
|
||||
assert!(close(x1, 0.25) && close(y1, 0.1) && close(x2, 0.75) && close(y2, 0.9), "{:?}", shape_tween.easing);
|
||||
// The instance: its symbol, matrix, loop, first frame, colour, blend and moved point.
|
||||
let e = &first.elements[0];
|
||||
let ElementKind::Symbol { symbol, loop_mode, first_frame, blend, pivot, .. } = &e.kind else { panic!("an instance: {:?}", e.kind) };
|
||||
assert_eq!(doc.symbol(*symbol).map(|s| s.name.as_str()), Some("UFO mask"));
|
||||
let want = [1.25, 0.5, -0.5, -0.5, 100.5, -20.25];
|
||||
for (got, want) in e.transform.m.iter().zip(want) {
|
||||
assert!((got - want).abs() < 1e-4, "{:?}", e.transform.m);
|
||||
}
|
||||
assert_eq!((*loop_mode, *first_frame, *blend), (LoopMode::SingleFrame, 4, BlendMode::Difference));
|
||||
let placed = e.transform.apply(pivot.expect("a moved transformation point"));
|
||||
assert!((placed.x - (inst.point.0 as f32 / 20.0)).abs() < 1e-3 && (placed.y - (inst.point.1 as f32 / 20.0)).abs() < 1e-3, "{placed:?}");
|
||||
let ColorEffect::Tint { color, amount } = e.color else { panic!("a tint: {:?}", e.color) };
|
||||
assert!((amount - 0.5).abs() < 1e-6 && color.r == 1.0 && color.g == 0.0);
|
||||
// The movie clip after the tween: placed, its extra settings skipped.
|
||||
assert!(matches!(second.elements[0].kind, ElementKind::Symbol { loop_mode: LoopMode::Loop, .. }));
|
||||
// The raw artwork of the layer in the folder: the rectangle, merging (ADR 0042).
|
||||
let raw = &tl.layers[3].keyframes[0].elements;
|
||||
assert_eq!(raw.len(), 1);
|
||||
assert!(matches!(&raw[0].kind, ElementKind::Shape(s) if s.merge));
|
||||
// The library symbol has its own timeline now, not just its first shape.
|
||||
let sym = doc.library.iter().find(|s| s.name == "UFO mask").expect("the symbol");
|
||||
let spans: Vec<(u32, u32)> = sym.timeline.layers[0].keyframes.iter().map(|k| (k.start, k.duration)).collect();
|
||||
assert_eq!(spans, [(0, 2), (2, 3)]);
|
||||
// The report: what was left out, by kind.
|
||||
assert_eq!(report.skipped.get("frame comments"), Some(&1), "{:?}", report.skipped);
|
||||
assert_eq!(report.skipped.get("frame scripts (decode pending)"), Some(&1), "{:?}", report.skipped);
|
||||
assert_eq!(report.skipped.get("movie clip and button settings (scripts, component data; left out)"), Some(&1), "{:?}", report.skipped);
|
||||
assert_eq!(report.kept.get("symbol instances"), Some(&2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_of_a_kind_not_decoded_is_skipped_and_its_siblings_still_place() {
|
||||
use anicraft_doc::ElementKind;
|
||||
let mut w = Ar::new();
|
||||
w.page(|w| {
|
||||
w.layer("notes", 0, None, |w| {
|
||||
w.frame(&[], &FrameSpec { duration: 5, ..FrameSpec::default() }, |w| {
|
||||
// Two objects of a class this pass doesn't decode (a text, in a made-up
|
||||
// layout), then an instance.
|
||||
for _ in 0..2 {
|
||||
w.object("CPicText", 0, None, 0, 0x0D, |_| {});
|
||||
for v in [65536, 0, 0, 65536, 40, 60] {
|
||||
w.i32(v);
|
||||
}
|
||||
w.string("hello, world");
|
||||
w.out.extend_from_slice(&[0x0C, 0x80, 0x02, 0x05, 0x41, 0x00, 0x00, 0x80]);
|
||||
}
|
||||
w.instance(&InstSpec::default());
|
||||
});
|
||||
});
|
||||
});
|
||||
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", w.out), ("Symbol 9", one_frame_stream(&rectangle_body()))];
|
||||
let (doc, report) = super::doc::import(&write(&payloads)).expect("opens");
|
||||
let k = &scene(&doc).layers[0].keyframes[0];
|
||||
assert_eq!((k.start, k.duration), (0, 5));
|
||||
assert_eq!(k.elements.len(), 1);
|
||||
assert!(matches!(k.elements[0].kind, ElementKind::Symbol { .. }));
|
||||
assert_eq!(report.skipped.get("texts (decode pending)"), Some(&2), "{:?}", report.skipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeline_cut_short_or_damaged_anywhere_never_panics() {
|
||||
let (bytes, _) = rich_page();
|
||||
let page = with_sprite_extras(bytes);
|
||||
for cut in 0..page.len() {
|
||||
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", page[..cut].to_vec())];
|
||||
let (doc, _) = super::doc::import(&write(&payloads)).expect("a damaged timeline still opens the document");
|
||||
assert_eq!(doc.scenes.len(), 1);
|
||||
}
|
||||
// Every byte flipped, one at a time.
|
||||
for at in 1..page.len() {
|
||||
let mut bad = page.clone();
|
||||
bad[at] ^= 0xA5;
|
||||
let payloads = vec![("Contents", synthetic_contents()), ("P 1 1", bad)];
|
||||
assert!(super::doc::import(&write(&payloads)).is_ok(), "flip at {at}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_object_graph_refuses_what_it_cannot_number() {
|
||||
use super::archive::parse;
|
||||
assert!(parse(&[]).is_err());
|
||||
assert!(parse(&[0x02]).is_err(), "the stream's first byte");
|
||||
// A back-reference to an object never written.
|
||||
assert!(parse(&[0x01, 0x05, 0x00]).is_err());
|
||||
// A class reference to a number that is no class.
|
||||
assert!(parse(&[0x01, 0x07, 0x80, 0x04, 0x00]).is_err());
|
||||
// The root must be a page.
|
||||
let mut w = Ar::new();
|
||||
w.layer("x", 0, None, |_| {});
|
||||
assert!(parse(&w.out).is_err());
|
||||
}
|
||||
+277
-4
@@ -62,8 +62,8 @@ fn expected_layers(name: &str) -> Option<Vec<&str>> {
|
||||
"mademoiselle-legacy.fla" => vec!["notes", "character"],
|
||||
"magnebot-legacy.fla" => vec!["notes", "character"],
|
||||
"rabbit-legacy.fla" => vec!["notes", "character", "poses"],
|
||||
// The audio layer's sound record embeds the sound's file name behind the same
|
||||
// anchor as a layer name; the record-level decode pass will tell them apart.
|
||||
// The twin has one more layer, named after the audio's sound file (the timeline
|
||||
// differential below checks every layer exactly).
|
||||
"movietemplate-legacy.fla" => {
|
||||
vec!["notes", "audio", "sound 1", "sound 2", "maracas", "video", "frame counter", "field guide / mask", "fade in / out", "FX", "camera"]
|
||||
}
|
||||
@@ -88,8 +88,7 @@ fn the_corpus_opens_with_the_twins_scenes_and_layers() {
|
||||
assert_eq!(doc.scenes[0].name, "Scene 1", "{}", path.display());
|
||||
let got: Vec<&str> = doc.scenes[0].timeline.layers.iter().map(|l| l.name.as_str()).collect();
|
||||
if name == "movietemplate-legacy.fla" {
|
||||
// The real layers are all present, top-first, with the sound-name phantom
|
||||
// possibly among them.
|
||||
// These layers are all present, top-first, with the sound-named one among them.
|
||||
for real in &want_layers {
|
||||
assert!(got.contains(real), "{}: layer {real:?} missing from {got:?}", path.display());
|
||||
}
|
||||
@@ -315,3 +314,277 @@ fn the_corpus_decodes_curved_shapes_edge_for_edge_like_the_twins() {
|
||||
assert!(curved >= 1500, "expected curved shapes among them, got {curved}");
|
||||
eprintln!("{matched} decoded shapes match their twins edge for edge ({curved} with curves)");
|
||||
}
|
||||
|
||||
/// The XML of a twin's member: from its zip package, or its extracted folder.
|
||||
fn twin_member(path: &std::path::Path, member: &str) -> Option<Vec<u8>> {
|
||||
if path.is_dir() {
|
||||
return std::fs::read(path.join(member)).ok();
|
||||
}
|
||||
let bytes = std::fs::read(path).ok()?;
|
||||
let archive = craft_xfl::Archive::open(&bytes).ok()?;
|
||||
archive.read(member).ok().flatten()
|
||||
}
|
||||
|
||||
fn twin_members(path: &std::path::Path) -> Vec<String> {
|
||||
if path.is_dir() {
|
||||
let mut out = Vec::new();
|
||||
let mut dirs = vec![path.to_path_buf()];
|
||||
while let Some(dir) = dirs.pop() {
|
||||
for entry in std::fs::read_dir(&dir).expect("twin lists").flatten() {
|
||||
let p = entry.path();
|
||||
if p.is_dir() {
|
||||
dirs.push(p);
|
||||
} else if let Ok(rel) = p.strip_prefix(path) {
|
||||
out.push(rel.to_string_lossy().replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
let bytes = std::fs::read(path).expect("twin reads");
|
||||
let archive = craft_xfl::Archive::open(&bytes).expect("twin opens");
|
||||
archive.names().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// One keyframe as compared: its span and its symbol instances (library name, matrix).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct KeyCmp {
|
||||
start: u32,
|
||||
duration: u32,
|
||||
/// "motion" (classic) or "shape".
|
||||
tween: Option<&'static str>,
|
||||
instances: Vec<(String, [f32; 6])>,
|
||||
/// Each instance's loop mode and first frame.
|
||||
playback: Vec<(anicraft_doc::LoopMode, u32)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct LayerCmp {
|
||||
name: String,
|
||||
keys: Vec<KeyCmp>,
|
||||
}
|
||||
|
||||
fn local(name: &str) -> &str {
|
||||
name.rsplit(':').next().unwrap_or(name)
|
||||
}
|
||||
|
||||
fn kids<'a>(el: &'a craft_xml::El, name: &'a str) -> impl Iterator<Item = &'a craft_xml::El> + 'a {
|
||||
el.elements().filter(move |e| local(&e.name) == name)
|
||||
}
|
||||
|
||||
/// A twin `DOMTimeline` as compared: layers top-first, folders without frames.
|
||||
fn twin_timeline(tl: &craft_xml::El) -> Vec<LayerCmp> {
|
||||
let mut out = Vec::new();
|
||||
for layers in kids(tl, "layers") {
|
||||
for l in kids(layers, "DOMLayer") {
|
||||
let folder = l.attr("layerType") == Some("folder");
|
||||
let mut keys = Vec::new();
|
||||
for frames in kids(l, "frames").filter(|_| !folder) {
|
||||
for f in kids(frames, "DOMFrame") {
|
||||
let start = f.attr("index").and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
let duration = f.attr("duration").and_then(|v| v.parse().ok()).unwrap_or(1);
|
||||
let tween = match f.attr("tweenType") {
|
||||
Some("motion") => Some("motion"),
|
||||
Some("shape") => Some("shape"),
|
||||
_ => None,
|
||||
};
|
||||
let mut instances = Vec::new();
|
||||
let mut playback = Vec::new();
|
||||
for els in kids(f, "elements") {
|
||||
for e in kids(els, "DOMSymbolInstance") {
|
||||
let name = e.attr("libraryItemName").unwrap_or("");
|
||||
let name = name.rsplit('/').next().unwrap_or(name).to_string();
|
||||
let m = kids(e, "matrix").flat_map(|m| kids(m, "Matrix")).next();
|
||||
let g = |k: &str, d: f32| m.and_then(|m| m.attr(k)).and_then(|v| v.parse::<f32>().ok()).unwrap_or(d);
|
||||
instances.push((name, [g("a", 1.0), g("b", 0.0), g("c", 0.0), g("d", 1.0), g("tx", 0.0), g("ty", 0.0)]));
|
||||
let lm = match e.attr("loop") {
|
||||
Some("play once" | "play once reverse") => anicraft_doc::LoopMode::PlayOnce,
|
||||
Some("single frame") => anicraft_doc::LoopMode::SingleFrame,
|
||||
_ => anicraft_doc::LoopMode::Loop,
|
||||
};
|
||||
playback.push((lm, e.attr("firstFrame").and_then(|v| v.parse().ok()).unwrap_or(0)));
|
||||
}
|
||||
}
|
||||
keys.push(KeyCmp { start, duration, tween, instances, playback });
|
||||
}
|
||||
}
|
||||
out.push(LayerCmp { name: l.attr("name").unwrap_or("").to_string(), keys });
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// An imported timeline as compared.
|
||||
fn legacy_timeline(doc: &anicraft_doc::Document, tl: &anicraft_doc::Timeline) -> Vec<LayerCmp> {
|
||||
tl.layers.iter().map(|l| LayerCmp {
|
||||
name: l.name.clone(),
|
||||
keys: l.keyframes.iter().map(|k| KeyCmp {
|
||||
start: k.start,
|
||||
duration: k.duration,
|
||||
tween: k.tween.as_ref().map(|t| if t.kind == anicraft_doc::TweenKind::Shape { "shape" } else { "motion" }),
|
||||
instances: k.elements.iter().filter_map(|e| match &e.kind {
|
||||
anicraft_doc::ElementKind::Symbol { symbol, .. } => Some((doc.symbol(*symbol).map_or(String::new(), |s| s.name.clone()), e.transform.m)),
|
||||
_ => None,
|
||||
}).collect(),
|
||||
playback: k.elements.iter().filter_map(|e| match &e.kind {
|
||||
anicraft_doc::ElementKind::Symbol { loop_mode, first_frame, .. } => Some((*loop_mode, *first_frame)),
|
||||
_ => None,
|
||||
}).collect(),
|
||||
}).collect(),
|
||||
}).collect()
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
struct Tally {
|
||||
timelines: usize,
|
||||
timelines_same_layers: usize,
|
||||
layers: usize,
|
||||
layers_same_keys: usize,
|
||||
keyframes: usize,
|
||||
instances: usize,
|
||||
instances_same: usize,
|
||||
tweens_same: usize,
|
||||
playback_same: usize,
|
||||
mismatches: Vec<String>,
|
||||
}
|
||||
|
||||
fn compare(tag: &str, legacy: &[LayerCmp], twin: &[LayerCmp], t: &mut Tally) {
|
||||
t.timelines += 1;
|
||||
let names = |ls: &[LayerCmp]| ls.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
|
||||
if names(legacy) != names(twin) {
|
||||
t.mismatches.push(format!("{tag}: layers {:?} vs twin {:?}", names(legacy), names(twin)));
|
||||
return;
|
||||
}
|
||||
t.timelines_same_layers += 1;
|
||||
for (a, b) in legacy.iter().zip(twin) {
|
||||
t.layers += 1;
|
||||
let spans = |l: &LayerCmp| l.keys.iter().map(|k| (k.start, k.duration)).collect::<Vec<_>>();
|
||||
if spans(a) != spans(b) {
|
||||
t.mismatches.push(format!("{tag} / {}: keyframes {:?} vs twin {:?}", a.name, spans(a), spans(b)));
|
||||
continue;
|
||||
}
|
||||
t.layers_same_keys += 1;
|
||||
for (ka, kb) in a.keys.iter().zip(&b.keys) {
|
||||
t.keyframes += 1;
|
||||
if ka.tween == kb.tween {
|
||||
t.tweens_same += 1;
|
||||
} else if t.mismatches.len() < 400 {
|
||||
t.mismatches.push(format!("{tag} / {} @{}: tween {:?} vs twin {:?}", a.name, ka.start, ka.tween, kb.tween));
|
||||
}
|
||||
if ka.playback.len() == kb.playback.len() {
|
||||
for (pa, pb) in ka.playback.iter().zip(&kb.playback) {
|
||||
if pa == pb {
|
||||
t.playback_same += 1;
|
||||
} else if t.mismatches.len() < 400 {
|
||||
t.mismatches.push(format!("{tag} / {} @{}: loop/first frame {pa:?} vs twin {pb:?}", a.name, ka.start));
|
||||
}
|
||||
}
|
||||
}
|
||||
t.instances += kb.instances.len().max(ka.instances.len());
|
||||
if ka.instances.len() != kb.instances.len() {
|
||||
t.mismatches.push(format!("{tag} / {} @{}: {} instances vs twin {}", a.name, ka.start, ka.instances.len(), kb.instances.len()));
|
||||
continue;
|
||||
}
|
||||
for ((na, ma), (nb, mb)) in ka.instances.iter().zip(&kb.instances) {
|
||||
let close = (0..4).all(|i| (ma[i] - mb[i]).abs() <= 0.01) && (4..6).all(|i| (ma[i] - mb[i]).abs() <= 0.05);
|
||||
if na == nb && close {
|
||||
t.instances_same += 1;
|
||||
} else if t.mismatches.len() < 400 {
|
||||
t.mismatches.push(format!("{tag} / {} @{}: {na} {ma:?} vs twin {nb} {mb:?}", a.name, ka.start));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_corpus_timelines_match_the_twins_keyframe_for_keyframe() {
|
||||
let Some(dir) = corpus() else { return };
|
||||
let mut all = Tally::default();
|
||||
let mut lines = Vec::new();
|
||||
for (legacy, twin) in TWINS {
|
||||
let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin));
|
||||
if !legacy_path.exists() || !twin_path.exists() {
|
||||
continue;
|
||||
}
|
||||
let data = std::fs::read(&legacy_path).expect("legacy reads");
|
||||
let (doc, _report) = anicraft_fla::import(&data).unwrap_or_else(|e| panic!("{legacy}: {e}"));
|
||||
let mut t = Tally::default();
|
||||
// The scenes, in order.
|
||||
let dom = twin_member(&twin_path, "DOMDocument.xml").expect("DOMDocument.xml");
|
||||
let dom = craft_xfl::document::Document::parse(&dom).expect("twin parses");
|
||||
let scenes: Vec<&craft_xml::El> = dom.root().descendants().filter(|e| local(&e.name) == "DOMTimeline").collect();
|
||||
for (scene, tl) in doc.scenes.iter().zip(scenes) {
|
||||
compare(&format!("{legacy}:{}", scene.name), &legacy_timeline(&doc, &scene.timeline), &twin_timeline(tl), &mut t);
|
||||
}
|
||||
// Library symbols with a unique name in the twin.
|
||||
let mut by_stem: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
|
||||
for m in twin_members(&twin_path).into_iter().filter(|m| m.starts_with("LIBRARY/") && m.ends_with(".xml")) {
|
||||
let stem = m.rsplit('/').next().unwrap_or(&m).trim_end_matches(".xml").to_string();
|
||||
by_stem.entry(stem).or_default().push(m);
|
||||
}
|
||||
for symbol in &doc.library {
|
||||
let Some([member]) = by_stem.get(&symbol.name).map(Vec::as_slice) else { continue };
|
||||
let Some(xml) = twin_member(&twin_path, member) else { continue };
|
||||
let Ok(x) = craft_xfl::document::Document::parse(&xml) else { continue };
|
||||
let Some(tl) = x.root().descendants().find(|e| local(&e.name) == "DOMTimeline") else { continue };
|
||||
compare(&format!("{legacy}:{}", symbol.name), &legacy_timeline(&doc, &symbol.timeline), &twin_timeline(tl), &mut t);
|
||||
}
|
||||
lines.push(format!(
|
||||
"{legacy}: timelines {}/{} same layers, layers {}/{} same keyframes, tweens {}/{} keyframes, instances {}/{} same name and matrix, {}/{} same loop and first frame",
|
||||
t.timelines_same_layers, t.timelines, t.layers_same_keys, t.layers, t.tweens_same, t.keyframes, t.instances_same, t.instances, t.playback_same, t.instances
|
||||
));
|
||||
all.tweens_same += t.tweens_same;
|
||||
all.playback_same += t.playback_same;
|
||||
all.timelines += t.timelines;
|
||||
all.timelines_same_layers += t.timelines_same_layers;
|
||||
all.layers += t.layers;
|
||||
all.layers_same_keys += t.layers_same_keys;
|
||||
all.keyframes += t.keyframes;
|
||||
all.instances += t.instances;
|
||||
all.instances_same += t.instances_same;
|
||||
all.mismatches.extend(t.mismatches);
|
||||
}
|
||||
for l in &lines {
|
||||
eprintln!("{l}");
|
||||
}
|
||||
eprintln!(
|
||||
"all: timelines {}/{}, layers {}/{}, tweens {}/{} keyframes, instances {}/{} (loop and first frame {}/{})",
|
||||
all.timelines_same_layers, all.timelines, all.layers_same_keys, all.layers, all.tweens_same, all.keyframes, all.instances_same, all.instances, all.playback_same, all.instances
|
||||
);
|
||||
for m in all.mismatches.iter().take(40) {
|
||||
eprintln!(" {m}");
|
||||
}
|
||||
assert!(all.timelines >= 300, "expected the corpus's ~330 timelines, compared {}", all.timelines);
|
||||
assert_eq!(all.timelines_same_layers, all.timelines, "every timeline has the twin's layers");
|
||||
assert_eq!(all.layers_same_keys, all.layers, "every layer has the twin's keyframes");
|
||||
assert_eq!(all.instances_same, all.instances, "every instance has the twin's symbol and matrix");
|
||||
assert_eq!(all.tweens_same, all.keyframes, "every keyframe has the twin's tween kind");
|
||||
assert_eq!(all.playback_same, all.instances, "every instance has the twin's loop mode and first frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_corpus_stage_matches_the_twins() {
|
||||
let Some(dir) = corpus() else { return };
|
||||
let mut checked = 0;
|
||||
for (legacy, twin) in TWINS {
|
||||
let (legacy_path, twin_path) = (dir.join(legacy), dir.join(twin));
|
||||
if !legacy_path.exists() || !twin_path.exists() {
|
||||
continue;
|
||||
}
|
||||
let (doc, _) = anicraft_fla::import(&std::fs::read(&legacy_path).expect("reads")).expect("imports");
|
||||
let dom = twin_member(&twin_path, "DOMDocument.xml").expect("DOMDocument.xml");
|
||||
let dom = craft_xfl::document::Document::parse(&dom).expect("parses");
|
||||
let r = dom.root();
|
||||
let num = |k: &str, d: f32| r.attr(k).and_then(|v| v.parse::<f32>().ok()).unwrap_or(d);
|
||||
assert_eq!((doc.stage.width, doc.stage.height), (num("width", 550.0) as u32, num("height", 400.0) as u32), "{legacy}");
|
||||
assert!((doc.stage.fps - num("frameRate", 24.0)).abs() < 0.01, "{legacy}: {}", doc.stage.fps);
|
||||
if let Some(bg) = r.attr("backgroundColor") {
|
||||
let want = u32::from_str_radix(bg.trim_start_matches('#'), 16).expect("hex");
|
||||
let got = ((doc.stage.background.r * 255.0).round() as u32) << 16 | ((doc.stage.background.g * 255.0).round() as u32) << 8 | (doc.stage.background.b * 255.0).round() as u32;
|
||||
assert_eq!(got, want, "{legacy}: background");
|
||||
}
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked >= 6);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
# ADR 0096: Legacy Flash import — the compound binary container
|
||||
|
||||
Date: 2026-11-16 · Status: accepted — the container (Stage 1) and the structure pass
|
||||
(scenes, layers, library; Stage 2 part 1) are implemented; record-payload decode continues
|
||||
Date: 2026-11-16 · Status: accepted — the container (Stage 1), shapes and the timelines
|
||||
(scenes, layers, keyframes, instances, tweens, library symbols) are implemented; text, media,
|
||||
scripts and filters continue
|
||||
|
||||
## Context
|
||||
|
||||
@@ -24,8 +25,9 @@ follow-on work tracked in `openspec/changes/add-legacy-fla-import/`.
|
||||
|
||||
2. **Record streams read as data first.** Observation on real files establishes the
|
||||
stream layout: a 5-byte prologue per stream family (`Contents`: `3F 01 00 00 00`,
|
||||
`Media`: `03 05 60 01 58`, library items: `01 FF FF 01 00`), then records whose names
|
||||
are 16-bit little-endian length-prefixed ASCII: `CPicPage → CPicLayer → CPicFrame`
|
||||
`Media`: `03 05 60 01 58`, library items: `01 FF FF 01 00`), then an object graph
|
||||
framed the way MFC's `CArchive` writes objects (its documented behaviour, see below),
|
||||
whose class names are 16-bit little-endian length-prefixed ASCII: `CPicPage → CPicLayer → CPicFrame`
|
||||
(structure), `CPicShape`, `CPicSymbol`, `CPicText`, `CPicSprite`, `CPicButton`,
|
||||
`CPicMorphShape` (+ `CMorphSegment`/`CMorphCurve`/`CMorphHintItem`), `CPicBitmap`,
|
||||
`CMediaBits`, `CMediaSound`, `CQTAudioSettings`, `CDocumentPage`, `CColorDef`,
|
||||
@@ -72,17 +74,56 @@ follow-on work tracked in `openspec/changes/add-legacy-fla-import/`.
|
||||
in the corpus (3197, 2201 of them curved) matches its twin's XFL edges, styles and
|
||||
matrix. (An earlier reading took the edge unit for half-pixels; it is half-twips — the
|
||||
"UFO mask" fixture is 10.9 × 11.2 px.) Fill regions are rebuilt per style as the XFL
|
||||
importer does. Library symbols show each item's first shape record; the other records
|
||||
are placed by the frame pass, so the stage stays empty until placements land. Bitmap
|
||||
fills and stroke kinds (dashed, dotted, hairline) are not yet located.
|
||||
- **What stays open**: frame records (durations are u16 LE near keyframes; the exact
|
||||
keyframe record layout is not yet mapped), tweens, text, bitmaps
|
||||
and sounds — each counted in the report's `skipped` per kind, and a sound file's name
|
||||
inside a frame currently reads as an extra layer (the record-level pass will tell them
|
||||
apart). Committed fixtures stay synthetic; the CC BY-NC-SA corpus runs via
|
||||
`ANICRAFT_FLA_CORPUS`.
|
||||
importer does. Bitmap fills and stroke kinds (dashed, dotted, hairline) are not yet
|
||||
located.
|
||||
- **Timelines** (`crates/fla/src/archive.rs` holds the full grammar): every item stream is a
|
||||
`01` byte and one object graph. Objects are tagged as MFC's `CArchive` tags them — `FF FF`,
|
||||
schema, length and name to declare a class; `0x8000 | n` for an object of class `n`; a
|
||||
bare `n` for an object written before; `00 00` for none — with classes and objects sharing
|
||||
one count. Every `CPic*` object starts with `04`, a flag byte, its children up to `00 00`,
|
||||
two i32 (a point in twips, `0x80000000` for none), a u16 and a kind byte. A page's
|
||||
children are its layers (bottom-first); a layer's are its keyframes, then its name,
|
||||
current/hidden/locked bytes, colour (RGBA), outline, type (0 normal, 1 guide, 3 folder,
|
||||
4 mask) and its parent layer as an object reference (a folder is written in place as its
|
||||
first child's parent and later back-referenced at its own place in the stack); a
|
||||
keyframe's children are its objects, then its raw artwork (a shape body + cubic hints),
|
||||
then `18`, the u16 duration, the tween word (low byte none/classic/shape, high byte flags),
|
||||
the i16 ease, the sound block, the label, the frame actions, the label kind (1 comment),
|
||||
the shape tween's cache and hints (objects), and six custom ease curves (position,
|
||||
rotation, scale, colour, filters, all) when flagged. An instance (`CPicSymbol`,
|
||||
`CPicSprite` movie clip, `CPicButton`) holds the matrix, first frame, loop mode, colour
|
||||
effect (A, R, G, B multipliers in 1/256 and offsets, style, percent, tint), name, the u16
|
||||
**library item id from `Contents`** (not the stream number), persistent data, filter count
|
||||
and blend (SWF numbering); its base point is the transformation point already placed by
|
||||
the matrix. A `CPicShape` object is a drawing object (base u16 1), a loose shape (flag
|
||||
bit 0) or a group (members as children). `Contents` gives each library item's u32 id
|
||||
and symbol type after its label, and the stage (rectangle in twips, background, 16.16
|
||||
frame rate) in the document properties.
|
||||
- **Skipping what isn't decoded.** Texts, bitmaps, a movie clip's or button's extra
|
||||
settings and anything newer are skipped to where their parent continues — its own end
|
||||
(`00 00` and its base with its kind byte) or the next sibling, confirmed by parsing that
|
||||
sibling — counting class declarations inside the skipped bytes so later class numbers
|
||||
stay right. A keyframe whose artwork doesn't decode keeps its timing (its fields are found
|
||||
by trial parse). Scan bytes, trial parses, nesting and object counts are capped per
|
||||
stream; a timeline that doesn't decode falls back to the structure-only reading.
|
||||
- **Mapping** mirrors the XFL importer: folders hold no frames, zero-length frame records
|
||||
are dropped (the twins don't have them), raw shapes merge (ADR 0042), comments are
|
||||
reported, classic and shape tweens keep their eases (shape tweens are rebuilt by the
|
||||
engine; the stored morph cache and hints are not used), movie clips and buttons loop.
|
||||
A moved transformation point becomes the instance's pivot (ADR 0111).
|
||||
- **Verified differentially** against all 9 pairs: 337/337 timelines have the twins' layers,
|
||||
1628/1628 layers their keyframes (index and duration), 6993/6993 keyframes their tween
|
||||
kind, 4457/4457 instances their library item, matrix, loop mode and first frame; the
|
||||
stage matches on all pairs; rendered frames of the movie template and the character rigs
|
||||
match their twins' apart from text and dotted strokes.
|
||||
- **What stays open**: text, bitmaps, sounds, frame and button scripts, filters (an
|
||||
instance with filters loses its blend mode too), dashed/dotted strokes, instance names
|
||||
on buttons, library folders — each counted in the report's `skipped` per kind. Committed
|
||||
fixtures stay synthetic; the CC BY-NC-SA corpus runs via `ANICRAFT_FLA_CORPUS`.
|
||||
|
||||
## References
|
||||
|
||||
- Microsoft `[MS-CFB]`: Compound File Binary Format specification (public).
|
||||
- Microsoft's MFC documentation of `CArchive` object serialization (`CArchive::WriteObject`,
|
||||
`CRuntimeClass` schemas): the public description of the object framing.
|
||||
- The PR's task list and the local corpus notes (not committed; EDAP samples are CC BY-NC-SA).
|
||||
Reference in new issue
Block a user