Files
isaac-port/notes/systems/anm2_parser.md
T

31 KiB

isaac-ng.exe (Repentance+ 1.9.7.17) — ANM2 parser decompilation

Target: 0x40ed50 (AnmCache::LoadFile), the frame-expansion helpers 0x414e00 / 0x415170, and what they call. Annotated dumps: parse.asm (0x40ed50-0x413b40) and interp.asm (0x414e00-0x4155c2). Labels were added to labels.json. Addresses in [brackets] are the evidence for each claim.


0. Who calls it (load path)

  • 0x40ed50 is __thiscall on the global AnmCache map 0xc78ee0. It takes 2 stack args, (const std::string& path, uint32 hash), and ends with ret 8. If hash==0, it is computed as 0xa159d0(path.c_str()) [0x40ee02]. Callers:
    • 0x40ddf9, inside AnmCache::Get 0x40db90. That function is called from lua_Load (0x40bd83) and lua_Reload (0x40beab). It builds the candidate path for each content/mod directory (vector 0xc798b8..0xc798bc, strncpy_s/strcat_s), hashes it, and looks it up in the cache map (0x416490). It calls the parser when there is no entry. It also calls it when there is an entry whose byte flag +0 is set and 0xa17180(path) returns non-zero (reload). After that it copies the cache data into the Sprite (0x40de78...).
    • 0x40ec3f, inside AnmCache::Preload(const char*) 0x40ea50. This is the same lookup, done by C-string.
  • Flow inside the parser:
    1. 0x8f5ad0 resolves the path. 0xa178d0 opens the file. On failure it logs "ERROR Could not open %s\n" at level 1 and returns [0x40edee]. The cache entry is not touched.
    2. entry = cacheMap[hash] (0x414500 → 0x4158b0, value at node+0x14).
    3. entry->Clear() (0x40d850, which frees every array), then entry->byte0 = 0 [0x40ee25-0x40ee32].
    4. It reads the whole file into buf = alloc(size+1) and adds a NUL. It then runs rapidxml in-situ (doc at ebp-0x26638, 0x413b90 ctor, 0x4155d0 parse).

XML access is rapidxml: node +0x18 first_node, +0x20 first_attribute, +0x2c next_sibling. Attributes are +0 name, +4 value, +0x10 parent, +0x18 next_attribute (the next attribute is used only when parent != 0). A NULL name or value is read as "" (0xc71640).

  • 0x413c70 = first_node(name). It compares sizes, then bytes, and returns 0 if the node is missing.
  • 0x413bf0 = first_attribute(name). With name==0 it returns the first attribute.

No element is optional. The code never checks a first_node result for NULL. It always reads [node+0x18] immediately. So a missing AnimatedActor, Content, Spritesheets, Layers, Nulls, Events, Animations, RootAnimation, LayerAnimations, NullAnimations or Triggers crashes with a NULL deref. The child-name lookups inside <Animation> are inlined loops [0x410261, 0x410e02, 0x4122e3, 0x413472]. Each ends in xor edi,edi; mov edi,[edi+0x18].

Child elements are never checked by tag name. Every child of <Spritesheets>, <Layers>, <Nulls>, <Events>, <RootAnimation>, <LayerAnimation>, <Triggers> and so on is processed whatever its tag is. Animations are iterated from first_node("Animation") along next_sibling [0x40fc0f, 0x4136ab]. Siblings after the first <Animation> are not filtered by name either. Attribute matching is an exact, case-sensitive strcmp. Unknown attributes are ignored.

Value converters (inlined everywhere)

  • int: atoi(value). Unparsable text gives 0.
  • float: (float)atof(value) (fstp dword).
  • scale: f = (float)atof(v); f = f / 100.0f. This is done on x87 as fld f; fdiv dword 100.0; fstp. It is bit-identical to a single-precision f/100.0f.
  • color: the same, but / 255.0f (constant 0xbaaae4 = 255.0). This applies to both tints and offsets.
  • bool (Loop, Visible, Interpolated) [0x4100b6-0x410186, 0x411586-0x411602]:
    bool ParseBool(std::string s) { if (s.empty()) return false;
        if (s == "true") return true; if (s == "True") return true; return atoi(s.c_str()) != 0; }
    
    So "1" and "TRUE"-like numbers work, and "false", "FALSE" and "" give false.

1. Data structures

1.1 Cache entry (AnmData, value of the AnmCache map, at map node + 0x14)

off type meaning
+0x00 u8 flag. The parser clears it to 0 [0x40ee32]. The caller reloads when it is set.
+0x04 LayerInfo* new[] with a count cookie at ptr-4 [0x40f3e3-0x40f4eb]
+0x08 int layerCount [0x40f4f7]
+0x0c AnimationData* new[] with a cookie [0x4136fe-0x4139de]
+0x10 int animationCount [0x4139e1]
+0x14 std::string* null names, new[] with a cookie. Only set if nullCount>0 [0x40f7fe]
+0x18 int nullCount [0x40f813]
+0x1c std::string* event names, new[] with a cookie. Only set if eventCount>0 [0x40fb2e]
+0x20 int eventCount [0x40fb46]
+0x24 std::string DefaultAnimation [0x40fbf4]. Not reset by Clear(), so on a reload without the attribute the old value stays.

The spritesheet table is not stored. Spritesheet paths live only in a 64-entry local array (ebp-0x16a0) and are copied into each layer (LayerInfo.+0x20). The Sprite object (+0x80 layerCount, +0x8c eventNames, ... in CONTEXT.md) is a separate object filled from this entry by 0x40db90.

1.2 LayerInfo (0x38) — ctor 0x40d140

off type field
+0x00 int Id
+0x04 int SpritesheetId
+0x08 std::string Name
+0x20 std::string resolved spritesheet path (copy of spritesheetPath[SpritesheetId])

1.3 AnimationData (0x13c) — ctor 0x40bec0

off type field / ctor default
+0x000 std::string Name
+0x018 LayerAnimation* new[] with a cookie (NULL if 0)
+0x01c int layerAnimCount
+0x020 NullAnimation* new[] with a cookie (NULL if 0)
+0x024 int nullAnimCount
+0x028 Trigger* plain new with no cookie (NULL if 0)
+0x02c int triggerCount
+0x030 int FrameNum (ctor -1; the parser always writes it, default 0)
+0x034 bool Loop (default false)
+0x038 int[64] layerId → layer-animation index (ctor fills with -1, see §2.9)
+0x138 int index of this animation in file order [0x41022e]

There are no root frames in AnimationData. RootAnimation is baked into the layer and null frames at load time (§3.3).

1.4 LayerAnimation (0x10) — ctor 0x40c1e0

off type field / default
+0x0 int LayerId (default -1)
+0x4 AnimationFrame* frames (plain new, NULL if 0 frames)
+0x8 int frameCount (count after expansion and root splitting)
+0xc bool Visible (default true)

1.5 NullAnimation (0x10) — ctor 0x40c210 (zeroes only +8/+0xc)

off type field / default
+0x0 int NullId (no default: stale or uninitialized, see §2.10)
+0x4 bool Visible (no default)
+0x8 NullFrame* frames (plain new, NULL if 0)
+0xc int frameCount

1.6 AnimationFrame (0x6c) — ctor inlined [0x40fdfe]

off type XML attr conversion
+0x00 float XCrop atof
+0x04 float YCrop atof
+0x08 float Width atof
+0x0c float Height atof
+0x10 float XPosition atof
+0x14 float YPosition atof
+0x18 float XScale atof/100
+0x1c float YScale atof/100
+0x20 float XPivot atof
+0x24 float YPivot atof
+0x28 int Delay atoi (after expansion: 1 for interpolated sub-frames, see §3)
+0x2c bool Visible ParseBool
+0x30 Color (0x2c) see 1.8
+0x5c float Rotation atof, degrees, no conversion
+0x60 bool Interpolated ParseBool
+0x64 int startFrame (inclusive) computed
+0x68 int endFrame (exclusive; = start of the next frame) computed

Correction to CONTEXT.md: +0x68 is the end frame (start + length). The runtime AdvanceLayerPosition 0x408b90 advances while frame >= (float)frames[idx].end(+0x68), so CONTEXT's "cumulative startFrame" is really the end tick. +0x64 holds the start.

ctor zeroes +0x00..+0x24 and sets the Color to tint (1,1,1,1) with the rest 0 (0x407170), and +0x60 = 0. +0x28 Delay, +0x2c Visible, +0x5c Rotation, +0x64 and +0x68 are not initialized.

1.7 NullFrame (0x54) — used for null frames AND root frames; ctor inlined [0x40fc50]

off type XML attr conversion
+0x00 float XPosition atof
+0x04 float YPosition atof
+0x08 int Delay atoi
+0x0c bool Visible ParseBool
+0x10 float XScale atof/100
+0x14 float YScale atof/100
+0x18 Color (0x2c)
+0x44 float Rotation atof
+0x48 bool Interpolated ParseBool
+0x4c int startFrame (inclusive) computed
+0x50 int endFrame (exclusive) computed

ctor zeroes +0, +4, +0x10, +0x14, runs Color(), and sets +0x48=0. +0x08, +0x0c, +0x44, +0x4c and +0x50 are uninitialized. Correction to CONTEXT.md: +0x50 is the end frame, not the start. +0x4c is the start.

1.8 Color (0x2c) — 0x407170 ctor, 0x4071f0 copy

float tint[4] (RGBA, default 1), float colorize[4] (default 0), float offset[3] (RGB, default 0).

  • +0x00..+0x0c RedTint/GreenTint/BlueTint/AlphaTint, each /255.
  • +0x10..+0x1c colorize. The parser never writes it, so it is always 0.
  • +0x20..+0x28 RedOffset/GreenOffset/BlueOffset, each /255.

So in an AnimationFrame the offsets are at +0x50/+0x54/+0x58. In a NullFrame they are at +0x38/+0x3c/+0x40.

1.9 Trigger (8)

int EventId (+0), int AtFrame (+4). Both use atoi. There are no defaults (see §2.11).


2. Parser pseudocode (0x40ed50)

void AnmCache::LoadFile(const std::string& path, uint32 hash)
{
    std::string resolved = ResolvePath(path);                         // 0x8f5ad0
    File* f = FileSystem::Open(resolved.c_str(), 0);                  // 0xa178d0
    if (!f) { KAGE_LogMessage(1, "ERROR Could not open %s\n", path.c_str()); return; }
    if (!hash) hash = HashString(path.c_str());                       // 0xa159d0
    AnmData& d = s_cache[hash]; d.Clear(); d.flag = 0;
    size_t n = f->Size(); char* text = Alloc(n+1); f->Read(text,1,n); text[n]=0; f->Close(1);
    rapidxml::xml_document doc; doc.parse(text);
    xml_node* actor   = doc.first_node("AnimatedActor");
    xml_node* content = actor->first_node("Content");

2.1 Spritesheets [0x40eec2-0x40f01d]

    std::string sheetPath[64];                 // local only
    char pathBuf[260];                         // ebp-0x120, NOT cleared between elements
    int sheetCount = 0;
    for (xml_node* e = content->first_node("Spritesheets")->first_node(); e; e = e->next_sibling()) {
        int id = 64;                                                   // default = invalid
        for (attr a : e->attributes()) {
            if (a.name == "Path") ResolveRelativePath(pathBuf, path.c_str(), a.value); // 0x67f670
            else if (a.name == "Id") id = atoi(a.value);
        }
        if (id >= 64 || id != sheetCount)      // signed compare: jge 0x40 / jne
            Log(0x10, "%s: invalid spritesheet id %d\n", path.c_str(), id);
        sheetPath[id] = pathBuf;               // written even when invalid (out-of-bounds if id>=64 or <0)
        ++sheetCount;
    }

0x67f670 is not fully reversed. It turns \ into /, splits on /, takes the directory of the .anm2 path, appends the relative path and handles ".." (string 0xb1ceb8), then strncpys up to 0x104 chars into pathBuf. The resulting path is relative to the .anm2 file's directory. If an element has no Path attribute, the previous element's path is reused because the buffer is stale. An element with no attributes at all also logs "invalid spritesheet id 64".

2.2 Layers [0x40f052-0x40f4f7]

    LayerInfo layer[64]; int layerCount = 0;
    for (e : content->first_node("Layers")->children) {
        std::string name; int id = 64; int sheet = -1;
        for (a : e->attributes()) {
            if (a.name=="Name") name = a.value;
            else if (a.name=="Id") id = atoi(a.value);
            else if (a.name=="SpritesheetId") sheet = atoi(a.value);
        }
        if (id >= 64 || id != layerCount) Log(0x10, "%s: invalid layer id %d\n", path, id);
        if (sheet < 0 || sheet >= sheetCount) Log(0x10, "%s: invalid spritesheet id %d\n", path, sheet);
        layer[id].spritesheetPath = sheetPath[sheet];    // unchecked index (sheet=-1 reads OOB)
        layer[id].id = id; layer[id].spritesheetId = sheet; layer[id].name = name;
        ++layerCount;
    }
    if (layerCount == 0) Log(0x10, "%s: no layers\n", path);   // only a log, parsing continues
    d.layers = new LayerInfo[layerCount]; copy layer[0..layerCount-1]; d.layerCount = layerCount;

An element with no attributes skips straight to the error with id=64 and sheet=-1 [0x40f0b2→0x40f26a].

2.3 Nulls [0x40f514-0x40f813]

    std::string nullName[64]; int nullCount = 0;
    for (e : content->first_node("Nulls")->children) {
        int id = 64; std::string name;
        for (a) { if (a.name=="Id") id = atoi(v); else if (a.name=="Name") name = v; }
        if (id >= 64 || id != nullCount) Log(0x10, "%s: invalid Null ID %d\n", path, id);
        nullName[id] = name; ++nullCount;
    }
    if (nullCount) d.nullNames = new std::string[nullCount] (copy); d.nullCount = nullCount;

2.4 Events [0x40f839-0x40fb46] — maximum 16 events

    std::string eventName[16]; int eventCount = 0;
    for (e : content->first_node("Events")->children) {
        int id = 16; std::string name;
        for (a) { if (a.name=="Id") id = atoi(v); else if (a.name=="Name") name = v; }
        if (id >= 16 || id != eventCount) Log(0x10, "%s: invalid Event ID %d\n", path, id);
        eventName[id] = name; ++eventCount;
    }
    if (eventCount) d.eventNames = new std::string[eventCount]; d.eventCount = eventCount;

Event IDs are 0..15. The runtime 32-bit bts masks therefore only ever use bits 0..15. Trigger EventIds are not validated against eventCount.

2.5 Animations header [0x40fb5a-0x40fc14]

    AnimationData anim[256];       // local, ctor 0x40bec0. There is NO "too many animations" check (>256 overflows the stack)
    int animCount = 0;
    xml_node* anims = actor->first_node("Animations");
    for (a : anims->attributes()) if (a.name=="DefaultAnimation") d.defaultAnimation = a.value;
    xml_node* animNode = anims->first_node("Animation");
    // 6 scratch buffers of 5000 frames, allocated ONCE and reused for every animation:
    NullFrame*      A = new NullFrame[5000];   // ebp-0x26698  root frames
    NullFrame*      B = new NullFrame[5000];   // ebp-0x26668  scratch for root interpolation
    NullFrame*      C = new NullFrame[5000];   // ebp-0x2669c  null frames
    NullFrame*      D = new NullFrame[5000];   // ebp-0x26694  scratch / output for nulls
    AnimationFrame* E = new AnimationFrame[5000]; // ebp-0x26670 layer frames
    AnimationFrame* F = new AnimationFrame[5000]; // ebp-0x2668c scratch / output for layers

2.6 Per animation [0x40ff10-0x410269]

    for (; animNode; animNode = animNode->next_sibling()) {
        std::string name; int frameNum = 0; bool loop = false;
        for (a : animNode->attributes()) {
            if (a.name=="Name") name = v;
            else if (a.name=="FrameNum") frameNum = atoi(v);
            else if (a.name=="Loop") loop = ParseBool(v);
        }
        AnimationData& an = anim[animCount]; an.index(+0x138) = animCount; ++animCount;
        an.name = name; an.frameNum = frameNum; an.loop = loop;

FrameNum is only stored. The parser does not use it to clamp or pad frames.

2.7 RootAnimation [0x410261-0x410ddc]

        xml_node* root = FindChild(animNode, "RootAnimation");        // crash if missing
        int rootCount = 0, t = 0;
        for (xml_node* fr = root->first_node(); fr; fr = fr->next_sibling()) {
            if (rootCount >= 5000) Log(0x10, "%s: too many root frames\n", path);   // continues anyway (overflow)
            NullFrame& f = A[rootCount++];
            float tint[4] = {1,1,1,1}, off[3] = {0,0,0};               // reset for every frame
            for (a : fr->attributes()) switch(name):
                XPosition: f.x = atof;  YPosition: f.y = atof;  Delay: f.delay = atoi;
                Visible: f.visible = ParseBool;  XScale: f.sx = atof/100; YScale: f.sy = atof/100;
                RedTint/GreenTint/BlueTint/AlphaTint: tint[i] = atof/255;
                RedOffset/GreenOffset/BlueOffset: off[i] = atof/255;
                Rotation: f.rot = atof;  Interpolated: f.interp = ParseBool;
            f.color.tint = tint; f.color.offset = off;                 // colorize untouched
            f.start = t; f.end = t + f.delay; t = f.end;               // [0x410daa]
        }
        InterpolateNullFrames(A, &rootCount, B);                       // 0x414e00, result in place in A

Missing-attribute defaults: only tint (1) and offset (0) are reset for each frame. Every other field keeps whatever the reused buffer slot held. For a never-used slot that is: x, y, sx, sy = 0 (so a missing XScale means scale 0), interp=false, and delay, visible and rot uninitialized heap memory. Otherwise it is the value from a previous animation, or the expanded output that 0x414e00 memcpy'd into that slot. Real .anm2 files always write every attribute. For a reimplementation: use defaults of pos 0, scale 1, delay 1, visible true, rot 0, interp false, and note the difference. The same is true for layer and null frames (buffers E and C).

2.8 LayerAnimations [0x410de4-0x4122c2]

        LayerAnimation la[64];            // ctor per animation: id=-1, frames=0, count=0, visible=true
        int laCount = 0;
        for (xml_node* ln = FindChild(animNode,"LayerAnimations")->first_node(); ln; ln = ln->next_sibling()) {
            if (laCount >= 64) Log(0x10, "%s: too many animation layers\n", path);  // continues (overflow)
            LayerAnimation& L = la[laCount++];
            for (a) { if (a.name=="LayerId") L.layerId = atoi(v); else if (a.name=="Visible") L.visible = ParseBool(v); }
            int n = 0, t = 0;
            for (xml_node* fr = ln->first_node(); fr; fr = fr->next_sibling()) {
                if (n >= 5000) Log(0x10, "%s: too many animation frames\n", path);
                AnimationFrame& f = E[n++];
                float tint[4]={1,1,1,1}, off[3]={0,0,0};
                attrs: XPosition(+0x10) YPosition(+0x14) XPivot(+0x20) YPivot(+0x24) Width(+8) Height(+0xc)
                       XScale(+0x18,/100) YScale(+0x1c,/100) Delay(+0x28,atoi) Visible(+0x2c)
                       XCrop(+0) YCrop(+4) Red/Green/Blue/AlphaTint(/255) Red/Green/BlueOffset(/255)
                       Rotation(+0x5c) Interpolated(+0x60)
                f.color.tint = tint; f.color.offset = off;
                f.start = t; f.end = t + f.delay; t = f.end;          // [0x411db2]
            }
            InterpolateLayerFrames(E, &n, F);                          // 0x415170, result in place in E
            // ---- root-frame adjustment (bakes RootAnimation into the layer), §3.3 ----
            int out = ApplyRoot<AnimationFrame>(E, n, A, rootCount, F); // [0x411df1-0x4121a1]
            if (out) { L.frames = new AnimationFrame[out]; copy F[0..out-1]; }
            L.frameCount = out;
        }
        if (laCount) {
            an.layerAnims = new LayerAnimation[laCount] (copy id, visible, frames, count);
            an.layerAnimCount = laCount;
            for (i = 0; i < laCount; ++i) an.layerMap[an.layerAnims[i].layerId] = i;   // [0x4122a0] unchecked index
        } else an.layerAnimCount = 0;

LayerId is not validated against layerCount or against 0..63. layerMap[id] with id=-1 writes into +0x34 (Loop). id ≥ 64 writes past the array into +0x138 and beyond. Two LayerAnimations with the same LayerId: the last one wins in the map.

2.9 Note on layerMap (+0x38)

The map is rebuilt at the end (§2.12) in a temporary and swapped into the final array. So it is the final map that counts:

  • For animation index ≥1, the slots that are not referenced are -1, because they come from the swapped-out ctor-initialized element.
  • For animation 0, the slots that are not referenced are uninitialized stack memory [0x41384f-0x413957; nothing initializes ebp-0x267c0]. Reimplement as "-1 everywhere, then map[layerId]=index".

2.10 NullAnimations [0x4122c5-0x413477]

        NullAnimation na[64];            // ctor per animation only zeroes frames/count; NullId and Visible keep stale stack values
        int naCount = 0;
        for (nn : FindChild(animNode,"NullAnimations")->children) {
            if (naCount >= 64) Log(0x10, "%s: too many null layers\n", path);
            NullAnimation& N = na[naCount++];
            for (a) { if (a.name=="NullId") N.nullId = atoi(v); else if (a.name=="Visible") N.visible = ParseBool(v); }
            int n = 0, t = 0;
            for (fr : nn->children) {
                if (n >= 5000) Log(0x10, "%s: too many null frames\n", path);
                NullFrame& f = C[n++];
                // same attribute set and conversions as root frames (§2.7)
                f.start = t; f.end = t + f.delay; t = f.end;          // [0x412fd8]
            }
            InterpolateNullFrames(C, &n, D);                           // 0x414e00
            int out = ApplyRoot<NullFrame>(C, n, A, rootCount, D);    // [0x413017-0x41334a]
            if (out) { N.frames = new NullFrame[out]; copy D[0..out-1]; }
            N.frameCount = out;
        }
        if (naCount) an.nullAnims = new NullAnimation[naCount] (copy nullId, visible, frames, count);
        an.nullAnimCount = naCount;

NullId is not validated, and there is no null map.

2.11 Triggers [0x413472-0x4136a2] — maximum 128 (0x80)

        Trigger tr[128]; int tc = 0;     // local array NOT reset per animation or per trigger
        for (te : FindChild(animNode,"Triggers")->children) {
            if (tc >= 128) Log(0x10, "%s: too many triggers\n", path);   // continues (overflow)
            Trigger& T = tr[tc++];
            for (a) { if (a.name=="EventId") T.eventId = atoi(v); else if (a.name=="AtFrame") T.atFrame = atoi(v); }
        }
        if (tc) { an.triggers = new Trigger[tc]; copy; }
        an.triggerCount = tc;
    } // next animation

AtFrame is the raw tick number. There is no conversion and it is not checked against FrameNum.

2.12 Finish [0x4136f0-0x413b37]

    d.anims = new AnimationData[animCount];   // ctor 0x40bec0
    for (i...) { tmp = copy of anim[i] with map rebuilt (§2.9); swap(d.anims[i], tmp); }
    d.animCount = animCount;
    free A..F; destroy local arrays; destroy the xml document; free the text buffer.
}

Limits summary

limit value behaviour when exceeded
spritesheets id < 64 and id == index "%s: invalid spritesheet id %d" (level 0x10), still stored at [id]
layers id < 64 and id == index "%s: invalid layer id %d"
layer→spritesheet 0 ≤ id < sheetCount "%s: invalid spritesheet id %d"
no layers count == 0 "%s: no layers"
nulls id < 64 and id == index "%s: invalid Null ID %d"
events id < 16 and id == index "%s: invalid Event ID %d"
animations 256 (stack array) no check
root frames / anim 5000 "%s: too many root frames" (when count ≥5000 before adding)
layer anims / anim 64 "%s: too many animation layers"
frames / layer anim 5000 "%s: too many animation frames"
null anims / anim 64 "%s: too many null layers"
frames / null anim 5000 "%s: too many null frames"
expanded frames 5000 "too many frames after interpolation\n" (checked as i+1 ≥ 5000, where i is the source index, not the output count; see §3)
root-adjusted frames 5000 "%s: too many frames after interpolation/root frame adjustment"
triggers / anim 128 "%s: too many triggers"
Every check only logs and keeps going. None of them stops parsing or clamps a value (in the original that means memory corruption).

3. Frame expansion

Both helpers use a custom calling convention: ecx = frames (in/out), edx = int* count (in/out), one stack arg scratch (caller cleans). They write the output to scratch, then memcpy(frames, scratch, out*size) and set *count = out [0x415131, 0x41559b]. Interpolation is pre-baked at load time. Each interpolated keyframe becomes delay one-tick frames.

3.1 0x415170 InterpolateLayerFrames (AnimationFrame)

void InterpolateLayerFrames(AnimationFrame* src, int* count, AnimationFrame* dst) {
    int out = 0, tick = 0;
    for (unsigned i = 0; i < (unsigned)*count; ++i) {
        AnimationFrame& a = src[i];
        if (i != *count - 1 && a.interpolated) {            // last frame is never interpolated
            if (i + 1 >= 5000) Log(0x10, "too many frames after interpolation\n");
            AnimationFrame& b = src[i+1];
            float t = 0.0f;
            float step = 1.0f / (float)a.delay;              // cvtdq2ps + divss
            for (int k = 0; k < a.delay; ++k) {              // delay <= 0: emits nothing, tick not advanced
                AnimationFrame& o = dst[out++];
                o.xcrop=a.xcrop; o.ycrop=a.ycrop; o.width=a.width; o.height=a.height;   // NOT interpolated
                o.x  = (b.x  - a.x ) * t + a.x;              // subss, mulss, addss (no FMA)
                o.y  = (b.y  - a.y ) * t + a.y;
                o.sx = (b.sx - a.sx) * t + a.sx;
                o.sy = (b.sy - a.sy) * t + a.sy;
                o.pivotX = a.pivotX; o.pivotY = a.pivotY;    // NOT interpolated
                o.delay = 1;
                o.visible = a.visible;
                o.color = Color::Lerp(a.color, b.color, t);  // 0x6832e0
                o.rotation = LerpAngleDeg(a.rotation, b.rotation, t); // 0x6828b0
                o.interpolated = a.interpolated;             // true
                o.start = tick; o.end = tick + 1; ++tick;
                t = step + t;                                // accumulated in float, NOT k/delay
            }
        } else {
            AnimationFrame& o = dst[out++];
            o = a;                                           // full copy
            o.start = tick; o.end = tick + a.delay; tick += a.delay;
        }
    }
    memcpy(src, dst, out * 0x6c); *count = out;
}

3.2 0x414e00 InterpolateNullFrames (NullFrame, used for root and null frames)

This is the same algorithm on the NullFrame fields.

  • Interpolated: x, y, sx, sy (lerp), color (Color::Lerp), rotation (LerpAngleDeg).
  • Copied from a: visible, interpolated. delay=1, start=tick, end=tick+1.
  • A non-interpolated frame is a full copy with start=tick, end=tick+delay.
  • The overflow check is the same i+1 >= 5000 [0x414e63].

Color::Lerp 0x6832e0(out, a, b, t): for all 11 floats (tint RGBA, colorize RGBA, offset RGB), out = a*(1-t) + b*t. (1-t) is computed once as a float.

LerpAngleDeg 0x6828b0(a, b, t) (all single precision. fmodf = 0x499d20 = (float)fmod((double)x,(double)y)):

static float Wrap(float x) { if (fabsf(x) > 360.f) x = fmodf(x, 360.f);
                             if (x > 180.f) x -= 360.f; else if (x < -180.f) x += 360.f; return x; }
float LerpAngleDeg(float a, float b, float t) {
    a = Wrap(a); b = Wrap(b);
    if (fabsf(b - a) > 180.f) { if (b > a) a += 360.f; else b += 360.f; }
    return Wrap((b - a) * t + a);
}

All comparisons are strict. Because Wrap is applied, interpolated sub-frames carry rotation normalized to [-180,180] (for example a keyframe at 270° comes out as -90° at t=0). Non-interpolated frames keep their raw rotation.

3.3 Root-frame adjustment (inlined twice: layers [0x411df1-0x41219a], nulls [0x413017-0x413343])

After interpolation, each layer or null track is re-timed against the (interpolated) root track A[0..rootCount). Every frame is split wherever a root frame boundary falls inside it, and each piece is multiplied by the root frame that is active during that piece:

template<class Fr>   // Fr = AnimationFrame or NullFrame
int ApplyRoot(Fr* src, int n, const NullFrame* root, int rootCount, Fr* dst) {
    int out = 0, g = 0, r = 0;                 // g = global tick, r = current root index
    for (int i = 0; i < n; ++i) {
        Fr& s = src[i];
        s.start = g;                           // overwrites start
        for (int k = 0; k < s.delay; ++k) {    // delay <= 0: no output
            ++g;                               // g = tick index + 1
            int prev = r; bool emit = false;
            if (r + 1 < rootCount) {
                while (g >= root[r].end) { ++r; if (r + 1 >= rootCount) break; }
                if (r > prev) emit = true;     // the root frame ends on this tick
            }
            if (!emit && k == s.delay - 1) emit = true;      // last tick of the source frame
            if (!emit) continue;
            if (out >= 5000) Log(0x10, "%s: too many frames after interpolation/root frame adjustment\n", path);
            const NullFrame& R = root[prev];   // root frame active during this piece (index BEFORE advancing)
            Fr& o = dst[out++];
            o = s;                             // includes s.start (start of this piece) and s.delay (NOT updated)
            o.x = o.x * R.sx + R.x;            // mulss then addss
            o.y = R.sy * o.y + R.y;
            o.visible = o.visible && R.visible;
            o.sx = o.sx * R.sx;  o.sy = R.sy * o.sy;
            o.color *= R.color;                // 0x6831c0
            o.rotation = R.rotation + o.rotation;
            o.end = g;                         // piece ends here
            s.start = g;                       // next piece of this source frame starts here
        }
    }
    return out;
}
  • The root transform does not rotate the position around the root. Pivot, crop and size are unchanged. The pieces' delay field keeps the source delay, so only start/end are correct afterwards. The runtime uses end.
  • When a track outlasts the root animation, the last root frame stays in effect (r is capped at rootCount-1).
  • rootCount == 0: the inner test is skipped and root[0] is still applied. That is a stale or uninitialized slot of buffer A, so the original's behaviour is undefined. A reimplementation should use the identity transform.

Color::operator= 0x6831c0 (this = frame color, other = root color):*

tint[i] = other.tint[i] * tint[i];                          // i = 0..3
if (other.colorize.r + other.colorize.g + other.colorize.b != 0) {
    if (colorize.r + colorize.g + colorize.b == 0) colorize = other.colorize;   // copy all 4
    else for (i<4) colorize[i] = (colorize[i] + other.colorize[i]) * 0.5f;
}
offset[i] = other.offset[i] + offset[i];                    // i = 0..2

(The parser always leaves colorize at 0, so only the tint multiply and offset add matter for .anm2 data.)


4. Uncertainties

  • 0x67f670 (spritesheet path resolution) was skimmed, not fully decompiled. It joins the directory of the .anm2 path with the relative path, handles \→/ and .., and truncates to 0x104.
  • 0x8f5ad0 (initial path resolution / mod redirect) and 0xa178d0 (file open) were not examined beyond their role.
  • What the cache-entry byte +0 means (it is cleared here, and the caller's reload test reads it) was not traced fully.
  • The rapidxml parse flags were not examined. Entity decoding and whitespace handling follow rapidxml's defaults for whatever flags 0x4155d0 was instantiated with.