# AnmCache + ANM2 (Sprite) lifecycle — isaac-ng.exe (Repentance+ 1.9.7.17) All addresses are VA (ImageBase 0x400000). "Confirmed" means read directly from asm; "guess" marks naming/semantics I inferred but did not prove. The XML parser itself (0x40ed50) is out of scope; only its interface is given. Note: several labels in labels.json are misleading. `lua_Load`, `lua_Reload`, `lua_Reset`, `lua_ReplaceSpritesheet`, `lua_LoadGraphics` are **native ANM2 member functions**. The Sprite Lua table (0x867200..) points straight at them, and they have hundreds of native callers (Load 0x40bd50 has 369 call sites). --------------------------------------------------------------------------------------------------------------------- ## 0. Helpers referenced | addr | meaning | |---|---| | 0xa159d0 | `uint32 HashPath(const char* s /*ecx*/)`: djb2, case-folded and slash-normalised (below) | | 0xa68490 | `uint64 GetTimeNs()` = QPC / QPF * 1e9 (constant at 0xbaa8b0 = 1e9) | | 0xa16060 | `std::vector FileSystem::GetMountPrefixes()` (below) | | 0xa17180 | `char* FileSystem::ResolvePath(const char*)` (this = 0xc379e0). Returns a heap string or NULL | | 0x40ccd0 | `std::string::assign(const char*, size_t)` | | 0x40cf50 | `std::string` copy-ctor | | 0x40d040 | `std::string` dtor (0x40bf20 is a jmp thunk to it) | | 0x40cae0 | `bool StrEqual(const char* a/*ecx*/, size_t la/*edx*/, const char* b, size_t lb)` | | 0xa0f4e0 | tracked `operator new(size /*ecx*/)` | | 0xa648b0 | tracked alloc/free: `fastcall(bool isFree /*cl*/, void* p /*edx*/, size_t sz, int 0)` | | 0xaef5c4 / 0xaef638 | MSVC `eh vector constructor iterator` / `eh vector destructor iterator` | | 0xaef15c | sized `operator delete(p, size)` | | 0x416490 | `std::map::_Find_lower_bound` for g_AnmCache.files | | 0x416440 | same, for g_AnmCache.textures | | 0x414500 | `files.operator[](key)`: returns `&node->value` (node+0x14). Calls try_emplace 0x4158b0 | | 0x414440 | `textures.operator[](key)` | | 0x415d20 / 0x414d60 | `files.erase(node)` / `textures.erase(it)` | | 0x414a80 | map iterator `operator++` | **Tracked free.** Every block has its size at `p-4`. Freeing does `MemStats* s = g_memStats(0xc7de78) ? g_memStats+0x30 : &g_fallbackStat(0xc7f618); s->bytes(u64) -= *(u32*)(p-4); free(p-4);`. ```cpp uint32 HashPath(const char* s) { // 0xa159d0 if (!s) return 0; uint32 h = 5381; for (; *s; ++s) { uint8 c = *s; if ((uint8)(c - 'A') <= 25) c += 0x20; // tolower (ASCII only) if (c == '\\') c = '/'; h = h * 33 + c; } return h; } std::vector FileSystem::GetMountPrefixes() { // 0xa16060 (static, sret) std::vector v; // g_FileSystem(0xc379e0)+8 : std::vector mounts (begin 0xc379e8, end 0xc379ec) for (int i = mounts.size() - 1; i >= 0; --i) { // NOTE: reverse order (last-mounted first) strncmp(mounts[i]->name, "", 0); // dead call, result ignored (literal in binary) v.push_back(mounts[i]->name /* Mount+0xc, const char* */); } return v; } ``` --------------------------------------------------------------------------------------------------------------------- ## 1. AnmCache ### 1.1 Globals (one static "AnmCache" object, dtor at 0x40d240, static init 0x401140) | addr | type | name | |---|---|---| | 0xc78ee0 | `std::map` (`_Myhead` @0xc78ee0, `_Mysize` @0xc78ee4) | `g_AnmCache.files` | | 0xc78ee8 | `std::map` (head/size; node size 0x1c) | `g_AnmCache.textures` | | 0xc798b8 | `std::vector` (begin/end/cap @ b8/bc/c0) | `s_mountPrefixes` (filled lazily) | | 0xc79c40 | `uint64` | `s_totalAnm2LoadMs` | | 0xc78da4 | `std::vector` (begin/end/cap @ a4/a8/ac) | heap-sprite pool, deleted in ~AnmCache. One push site at 0x960c97, which also stores to 0xc72214 | The map comparator is plain `uint32 <`. MSVC tree node: left@0, parent@4, right@8, color@0xc, isnil@0xd, value@0x10. ### 1.2 `files` node layout (node size 0x54, confirmed by try_emplace 0x4158b0 init and erase `delete(node,0x54)`) ``` node+0x10 uint32 key // HashPath(prefix + path) node+0x14 AnmFileData data (0x3c bytes) ─┐ node+0x50 int refCount ─┘ value = {data, refCount} (0x40 bytes) ``` `AnmFileData` (offsets relative to data = node+0x14; ANM2 copy targets in the right column): | off | type | meaning | copied to ANM2 | |---|---|---|---| | +0x00 | bool | `needsReload`(?) flag. try_emplace and ParseAnm2 only ever write 0. Load re-parses if it is set and the file resolves. I never saw it set to 1 (**uncertain**) | – | | +0x04 | LayerInfo* (count-prefixed new[], stride 0x38) | layers | ANM2 builds LayerState[] from it | | +0x08 | uint | layerCount | +0x80 | | +0x0c | AnimationData* (new[], stride 0x13c) | animations | +0x74 | | +0x10 | uint | animationCount | +0x78 | | +0x14 | std::string* (new[], stride 0x18) | null names | +0x84 | | +0x18 | uint | nullCount | +0x88 | | +0x1c | std::string* (new[], stride 0x18) | event names | +0x8c | | +0x20 | uint | eventCount | +0x90 | | +0x24 | std::string | default animation name | +0x18 (assign) | `LayerInfo` (0x38). Its dtor 0x40db70 destroys strings at +8 and +0x20. `+0x00 int`, `+0x04 int` (probably layerId and spritesheetId; the parser agent should confirm), `+0x08 std::string name`, `+0x20 std::string spritesheetPath` (fully resolved image path that LayerState copies). `AnimationData` (0x13c) begins with `+0x00 std::string name`. Its new[] dtor is just the string dtor. Other fields are as in CONTEXT.md (+0x18 layerAnims, +0x1c count, +0x20 nullAnims, +0x24 count, +0x28 triggers, +0x2c count, +0x30 FrameNum, +0x34 Loop, +0x38 int layerIdToLayerAnimIdx[]). ### 1.3 Cache key: how a path is looked up (identical loop in Load / AddRef / RemoveRef / Preload / texture Has / Release) ```cpp static bool FindEntry(const char* path, Node*& out, uint32& keyOut) { if (s_mountPrefixes.size() < 1) // lazy init s_mountPrefixes = FileSystem::GetMountPrefixes(); // move-assign (0x4149d0 = vector dtor) out = files.head; keyOut = 0; for (const char* prefix : s_mountPrefixes) { char buf[256]; strncpy_s(buf, 256, prefix, 256); strcat_s (buf, 256, path); keyOut = HashPath(buf); Node* n = files.lower_bound(keyOut); out = (n != head && !(keyOut < n->key)) ? n : head; if (out != head) break; // first prefix that hits wins } return out != head; } ``` - The key is **djb2(lowercase, '\\'→'/', mountPrefix + path)**. Nothing is appended. - If nothing matches, `keyOut` is the hash for the **last** prefix tried. That is mount[0], the first-mounted one, because GetMountPrefixes reverses the list. That is the key a newly parsed file is stored under. - If there are no mounts at all, keyOut stays 0. ParseAnm2 then substitutes HashPath(path), but Load re-looks up key 0, so Load reports "failed to load" (edge case, faithful). ### 1.4 `void AnmCache::Load(const std::string& path, ANM2* spr)` — 0x40db90 Static. Args are on the stack (`ret 8`) and ecx is unused. Callers: ANM2::Load 0x40bd83, ANM2::Reload 0x40beab. ```cpp void AnmCache::Load(const std::string& path, ANM2* spr) { if (path.size() == 0) return; // no timing either uint64 t0ms = GetTimeNs() / 1000000; Node* n; uint32 key; FindEntry(path.c_str(), n, key); char* resolved = FileSystem::ResolvePath(&g_FileSystem /*0xc379e0*/, path.c_str()); if (n == files.head || (n->data.needsReload && resolved != nullptr)) { ParseAnm2(&files, path, key); // 0x40ed50, see 1.10 n = files.lower_bound(key); if (n == head || key < n->key) n = head; } if (resolved) TrackedFree(resolved); if (n == files.head) { KAGE_LogMessage(1, "AnmCache failed to load %s\n", path.c_str()); } else { AnmFileData& d = n->data; // --- rebuild per-layer runtime state --- if (spr->layerStates) delete[] spr->layerStates; // eh-vector-dtor, LayerState::~LayerState 0x407a60 uint cnt = d.layerCount; if (cnt) { spr->layerStates = new LayerState[cnt]; // operator new(cnt*0xa0+4) 0xa0f4e0, count prefix, // ctor 0x4081d0 per element for (uint i = 0; i < d.layerCount; ++i) { spr->layerStates[i].Init(&d.layers[i]); // 0x408310 spr->layerStates[i].owner = spr; // +4 } cnt = d.layerCount; } // QUIRK: if cnt==0, layerStates was deleted but NOT nulled (dangling, would double-free on Reset). spr->layerCount = cnt; // +0x80 spr->animations = d.animations; // +0x74 (shared, not copied!) spr->animCount = d.animationCount; // +0x78 spr->nullNames = d.nullNames; // +0x84 spr->nullCount = d.nullCount; // +0x88 spr->eventNames = d.eventNames; // +0x8c spr->eventCount = d.eventCount; // +0x90 if (&spr->defaultAnimation != &d.defaultAnimation) spr->defaultAnimation.assign(d.defaultAnimation); // +0x18 } uint64 t1ms = GetTimeNs() / 1000000; s_totalAnm2LoadMs += t1ms - t0ms; // 0xc79c40 (timing covers cache hits too) } ``` The sprite only borrows pointers into the cache entry. The refCount (AddRef/RemoveRef) is what keeps an entry alive through `Clear()`. ### 1.5 `void AnmCache::AddRef(const std::string& path)` — 0x40e110 (static, `ret 4`) ```cpp if (FindEntry(path.c_str(), n, key)) ++n->refCount; // node+0x50 else KAGE_LogMessage(1, "[warn] AnmCache: cannot add reference to %s\n", path.c_str()); ``` Callers: ANM2 copy-ctor (0x407866), ANM2::Load, ANM2::Reload. ### 1.6 `void AnmCache::RemoveRef(const std::string& path)` — 0x40e2b0 (static, `ret 4`) ```cpp if (FindEntry(path.c_str(), n, key)) { if (n->refCount == 0) KAGE_LogMessage(0x10, "cannot remove reference at RefCount 0\n"); // level 0x10 = error/assert if (n->refCount != 0) --n->refCount; } else KAGE_LogMessage(1, "[warn] AnmCache: cannot remove reference to %s\n", path.c_str()); ``` Callers: ANM2::Reset 0x407f3d, ANM2::Load 0x40bd60, plus 5 others elsewhere. ### 1.7 `void AnmCache::Clear()` — 0x40e470 (static) Removes only unreferenced entries: ```cpp for (it = files.begin(); it != files.end(); ) { if (it->refCount == 0) { KAGE_LogMessage(1, "AnmCache: Clear %u.\n", it->key); it->data.Clear(); // 0x40d850 Node* victim = it; ++it; files.erase(victim); // 0x415d20, then ~string(node+0x38), delete(node,0x54) } else ++it; } ``` Callers: 0x68fd57, 0x8f8c6f, 0x9b248f (level/stage transitions; not identified further). ### 1.8 `void AnmFileData::Clear()` — 0x40d850 (thiscall, this = node+0x14) ```cpp delete[] layers; layers = nullptr; layerCount = 0; // eh-vec-dtor 0x40db70, size cnt*0x38+4 for (uint a = 0; a < animationCount; ++a) { AnimationData& A = animations[a]; for (uint i = 0; i < A.layerAnimCount; ++i) TrackedFree(A.layerAnims[i].frames); // +4 delete[] A.layerAnims; // stride 0x10, trivial dtor 0x40c200 for (uint i = 0; i < A.nullAnimCount; ++i) TrackedFree(A.nullAnims[i].frames); // +8 delete[] A.nullAnims; TrackedFree(A.triggers); // +0x28 } delete[] animations; animations = nullptr; animationCount = 0; // dtor = ~string(name) delete[] nullNames; nullNames = nullptr; nullCount = 0; delete[] eventNames; eventNames = nullptr; eventCount = 0; // needsReload (+0) and defaultAnimation (+0x24) are NOT touched here ``` ### 1.9 `void AnmCache::LogMemoryUsage()` — 0x40d4c0 (static) Called once, from the stats dump 0x6f4170. That routine is called from 0x9b7680. Just before the call it logs `"Total entity spawn time: %llu ms"` and `"Total ANM2 loading time: " << s_totalAnm2LoadMs << " ms"` (0x6f4257) through an ostringstream. ```cpp uint32 bytes = 0, entries = 0; for (auto& [key, v] : files) { const AnmFileData& d = v.data; bytes += d.animationCount * 0x13c; for (uint a = 0; a < d.animationCount; ++a) { const AnimationData& A = d.animations[a]; bytes += A.layerAnimCount * 0x10; for (i) bytes += A.layerAnims[i].frameCount * 0x6c; // LayerAnimation+8 bytes += A.nullAnimCount * 0x10; for (i) bytes += A.nullAnims[i].frameCount * 0x54; // NullAnimation+0xc bytes += A.triggerCount * 8; } bytes += (d.nullCount + d.eventCount) * 0x18 + d.layerCount * 0x38 + 0x40; // 0x40 = sizeof(value) ++entries; } KAGE_LogMessage(1, "AnmCache memory usage: %u bytes in %u entries.\n", bytes, entries); ``` (The asm is an SSE4.1 `pmulld` vectorisation of these loops. Sums are 32-bit.) ### 1.10 `ParseAnm2` interface — 0x40ed50 (decompiled by the other agent) `void __thiscall AnmCache::ParseFile(std::map* files /*=0xc78ee0*/, const std::string& path, uint32 key)`, `ret 8`. - It first resolves `path` through `(*(Game**)0xc7169c)+0x2a6c0 -> 0x8f5ad0(&tmpStr, path)` (probably mod-override path resolution) and opens it with `FileSystem(0xc37a10)::Open(0xa178d0)(resolved, 0)`. On failure it logs `"ERROR Could not open %s\n"` and returns **without creating an entry**. - `if (key == 0) key = HashPath(path.c_str());` - `AnmFileData* d = &files[key]` (operator[] 0x414500, which creates the node with refCount 0). Then `d->Clear(); d->needsReload = 0;` - It reads the whole file through the file vtable (+4 size, +0x14 read, +0 close/delete) into a NUL-terminated buffer and runs rapidxml. Then it fills d->layers/+0x8 (0x40f4eb), nulls +0x14/+0x18 (0x40f7fe), events +0x1c/+0x20 (0x40fb2e), defaultAnimation +0x24 (0x40fbf4), animations +0xc/+0x10 (0x4139de). - On a re-parse (reload) the refCount is kept, because operator[] returns the existing node. ### 1.11 Preload — `void AnmCache::Preload(const char* path)` — 0x40ea50 (static, `ret 4`) Called from the entity-config preloader 0x69ba90 (with the entity's anm2 path at config+0x74). The same routine logs "Preload sound %d." for sounds. ```cpp if (!*path) return; uint32 key; Node* n; if (!FindEntry(path, n, key)) { ParseFile(&files, std::string(path), key); if (!FindEntry-by-key(key, n)) return; // plain lower_bound with the same key } for (uint i = 0; i < n->data.layerCount; ++i) { const char* img = n->data.layers[i].spritesheetPath.c_str(); // LayerInfo+0x20 if (!TextureCache::Has(img)) { Graphics_Prepare(*(void**)0xc71678); // 0x6fd350, unidentified (context/manager getter) TexturePtr t = LoadImage(img); // 0x9588a0(&out, path) TextureCache::Add(t); // 0x40e520 } } // refCount is NOT incremented by preload ``` ### 1.12 Texture side of the cache (`textures` map @0xc78ee8; node: key@0x10, TexturePtr@0x14 {obj,ctrl}) - `bool TextureCache::Has(const char* name)`, 0x40e5d0: FindEntry-style prefix loop, but on `textures`. - `void TextureCache::Add(TexturePtr t /*by value, 8 bytes*/)`, 0x40e520, `ret 8`: `if (t) { const char* nm = t->name44 ? t->name44 : (t->name40 ? t->name40 : "unknown"); textures[HashPath(nm)] = t; }`, then releases the by-value arg. The key here has **no prefix**, so the texture's own name (+0x44) must already contain the mount prefix for Has/Release to match. (Guess.) - `void TextureCache::Release(const char* name)`, 0x40e740: finds the entry with the prefix loop. If found and `ctrl==NULL || useCount(u16 @ctrl+4) <= 2` (read under the ctrl+8 lock, vfuncs +0xc lock(-1) / +0x10 unlock), it resets the pointer (0x40c7f0(0)) and erases the entry. - `void TextureCache::Purge()`, 0x40e910: the same `<= 2` rule applied to every texture entry. 14 callers. - `void TextureCache::Preload(const char* name)`, 0x40ea10: `if (!Has(name)) Add(LoadImage(name));` `TexturePtr` is a KAGE intrusive/shared smart pointer `{T* obj; RefCtrl* ctrl}`. The ctrl vtable has +4 = TryAddRef, returning bool, and +0xc = Release, returning true when the object dies. When Release returns true, the global deleter hook `(*(void(**)(TexturePtr*))0xc7163c)(&sp)` is called. Helpers: copy-ctor 0x40c550, assign 0x40c3b0, dtor 0x40c440, `reset(raw)` 0x40c7f0 / ctor-from-raw 0x40c4a0 (both allocate a new 0x18-byte ctrl block with vtable 0xb1a6e0). ### 1.13 `AnmCache::~AnmCache()` — 0x40d240 (this = 0xc78ee0; called from 0x9ab8db and the atexit thunk 0xb1522e) 1. For each `ANM2*` in the pool vector 0xc78da4: inlined `~ANM2` (Reset, free the 4 AnimationState arrays, 2 strings), then `delete(p, 0x114)`. Then the pool is cleared. 2. `data.Clear()` for **every** file entry, with no refcount check. Then the tree is destroyed (0x415ae0) and the head is reset. 3. Every texture pointer is released, the tree is destroyed (0x415800) and the head is reset. --------------------------------------------------------------------------------------------------------------------- ## 2. ANM2 (Sprite) — object layout, sizeof = 0x114 The size is confirmed by `operator=(ANM2)` using `ret 0x114` (by-value param) and by `delete(p, 0x114)` in 0x40d240. | off | type | field | init (ctor+Reset) | source / evidence | |---|---|---|---|---| | 0x000 | std::string | filename | "" | Load assigns it. AddRef/RemoveRef receive `this` as `const std::string&`. GetFilename 0x4312e0 copies it | | 0x018 | std::string | defaultAnimation | "" | GetDefaultAnimationName/GetDefaultAnimation 0x4a5cf0 returns &+0x18 | | 0x030 | AnimationState (0x20) | main | owner=this | | | 0x050 | AnimationState (0x20) | overlay | owner=this | RemoveOverlay 0x40ac60 = `overlay.SetAnimationData(nullptr)` | | 0x070 | bool | overlayRenderFirst | 0 | SetOverlayRenderPriority 0x431300. Render 0x40a0d0 draws the overlay before main if set | | 0x074 | AnimationData* | animations (borrowed from cache) | 0 | | | 0x078 | uint | animationCount | 0 | PlayRandom uses `rand % +0x78` | | 0x07c | LayerState* | layerStates (count-prefixed new[], stride 0xa0) | 0 | | | 0x080 | uint | layerCount | 0 | GetLayerCount 0x440e40 | | 0x084 | std::string* | nullNames (borrowed) | 0 | | | 0x088 | uint | nullCount | 0 | | | 0x08c | std::string* | eventNames (borrowed) | 0 | | | 0x090 | uint | eventCount | 0 | | | 0x094 | Vector (2 floats) | Offset | Vector::Zero (0xc7b640) | Lua Offset: get 0x49cb40 (`&+0x94`), set 0x456340 | | 0x09c | Vector | Scale | Vector::One (0xc3793c) | Lua Scale: get 0x417200, set 0x420170 | | 0x0a4 | float | Rotation | 0 | Lua Rotation: get 0x417210, set 0x43ee80 | | 0x0a8 | ColorMod (0x2c: Tint RGBA, Colorize RGBA, Offset RGB) | Color | {1,1,1,1, 0,0,0,0, 0,0,0} | Lua Color: get 0x407410, set 0x4073d0 | | 0x0d4 | ColorMod-shaped (0x2c) | **unknown** (second colour) | Reset: {1,1,1,**0**, 0,0,0,0, 0,0,0} (ctor writes alpha 1.0, then Reset overwrites it with 0) | copied/swapped like Color. Not exposed to Lua and not read in 0x409120..0x40a0d0 (**uncertain**) | | 0x100 | bool | FlipX | 0 | get 0x407420 / set 0x435c60 | | 0x101 | bool | FlipY | 0 | get 0x407430 / set 0x505b50 | | 0x104 | float | PlaybackSpeed | 1.0 | get 0x456360 / set 0x440e50 | | 0x108 | bool | **unknown** | 0 | only copied/swapped/reset in this module | | 0x109 | bool | loaded | 0 | IsLoaded 0x420160. Render returns early if 0 | | 0x10c | int | shadowLayerIndex | -1 | set by Load to the layer named exactly "shadow" (last match wins) | | 0x110 | uint32 | renderFlags | 0 | OR-ed with LayerState+0x8c at render time (0x4091eb, 0x409a63, 0x409cc0). Load sets 0x400 if any layer name starts with '*' and 0x800 if any null name starts with '*'. At render, bit 4 means "draw only if debug global 0xc7977e", bit 2 is some crop/clip path | ### 2.1 AnimationState (0x20) — confirmed ``` +0x00 ANM2* owner +0x04 AnimationData* anim +0x08 int* layerFrameIdx (anim->layerAnimCount entries) +0x0c int* nullFrameIdx (anim->nullAnimCount entries) +0x10 float frame (-1.0f after SetAnimationData) +0x14 bool playing +0x18 u32 eventsThisUpdate +0x1c u32 eventsSinceStart ``` ### 2.2 LayerState (0xa0) — per layer, in ANM2+0x7c | off | type | field (name = guess unless noted) | Init(LayerInfo*) 0x408310 value | |---|---|---|---| | 0x00 | const LayerInfo* | info (cache-owned; name = info+8) | arg | | 0x04 | ANM2* | owner (set by the creator) | – | | 0x08 | std::string | spritesheetPath (confirmed; ReplaceSpritesheet edits it) | info ? info->spritesheetPath(+0x20) : "" | | 0x20 | u32 x4 | texture sampler/wrap params (two pairs pushed to the texture through vfunc +0x44 and +0x48 in GetTexture) | copy of globals 0xc3799c..0xc379a8 | | 0x30 | bool | graphicsLoaded (confirmed: LoadGraphics skips if set, ReplaceSpritesheet clears it) | 0 (the dword write clears 0x30..0x33) | | 0x31 | bool | cleared by LoadGraphics (dirty flag?) | 0 | | 0x32,0x33 | bool | copied only (flipX/flipY?) | 0 | | 0x34 | Vector | size/scale | Vector::One | | 0x3c | float | rotation | 0 | | 0x40 | Vector | position/offset | Vector::Zero | | 0x48 | ColorMod (0x2c) | color | default ColorMod | | 0x74 | bool | visible | 1 | | 0x78 | int | blend: mode/flags | 0 | | 0x7c | int | blend: RGB src factor | `(g_0xc798e4 & 4) ? 1 : 6` (ONE if premultiplied, else SRC_ALPHA) | | 0x80 | int | blend: RGB dst factor | 7 (ONE_MINUS_SRC_ALPHA) | | 0x84 | int | blend: alpha src | 1 | | 0x88 | int | blend: alpha dst | 7 | | 0x8c | u32 | renderFlags (OR-ed with ANM2+0x110). '*'-prefixed layers get `|= 5` | 0 | | 0x90 | Vector | crop offset? | Vector::Zero | | 0x98 | TexturePtr {obj @0x98, ctrl @0x9c} | spritesheet texture (confirmed) | reset(nullptr) | LayerState functions: - ctor 0x4081d0: zeroes the string and the fields listed, uses the same defaults, then `Init(nullptr)`. - dtor 0x407a60: releases the TexturePtr at +0x98 and destroys the string at +8. It does **not** call TextureCache::Release. - `TexturePtr GetTexture() const`, 0x408590 (sret): if a texture is present, it pushes +0x20/+0x24 to `tex->vfunc[0x44]` when they differ from tex+0x30/+0x34, and +0x28/+0x2c to `tex->vfunc[0x48]` when they differ from tex+0x38/+0x3c. Then it returns a copy. - `void SetTexture(TexturePtr t /*by value*/)`, 0x408640: `if (t) memcpy(&+0x20, t.obj+0x30, 16); texture = t;` --------------------------------------------------------------------------------------------------------------------- ## 3. ANM2 lifecycle — pseudocode ### 3.1 ctor `ANM2::ANM2()` — 0x4074c0 (170 callers) ```cpp ANM2::ANM2() { filename = ""; defaultAnimation = ""; main.owner = this; main.layerFrameIdx = main.nullFrameIdx = nullptr; main.SetAnimationData(nullptr); overlay.owner = this; overlay.layerFrameIdx = overlay.nullFrameIdx = nullptr; overlay.SetAnimationData(nullptr); offset = {0,0}; /* +0x94/+0x98 */ scale(+0x9c/+0xa0) = {0,0}; // overwritten by Reset color(+0xa8) = ColorMod{1,1,1,1, 0,0,0,0, 0,0,0}; color2(+0xd4) = ColorMod{1,1,1,1, 0,0,0,0, 0,0,0}; layerStates = nullptr; // +0x7c Reset(); // 0x407f10 sets the real defaults } ``` ### 3.2 `void ANM2::Reset()` — 0x407f10 (Lua `Sprite:Reset`, also used by the dtor and operator=) ```cpp void ANM2::Reset() { if (filename.size()) AnmCache::RemoveRef(filename); filename.clear(); main.SetAnimationData(nullptr); overlay.SetAnimationData(nullptr); defaultAnimation.clear(); animations = nullptr; animationCount = 0; delete[] layerStates; layerStates = nullptr; layerCount = 0; // ~LayerState each nullNames = nullptr; nullCount = 0; eventNames = nullptr; eventCount = 0; offset = Vector::Zero; // 0xc7b640 scale = Vector::One; // 0xc3793c rotation = 0.0f; color = ColorMod{1,1,1,1, 0,0,0,0, 0,0,0}; color2 = ColorMod{1,1,1,0, 0,0,0,0, 0,0,0}; // note alpha 0 (literal) flipX = flipY = false; // word write at +0x100 playbackSpeed = 1.0f; unk108 = false; loaded = false; // word write at +0x108 overlayRenderFirst = false; // +0x70 shadowLayerIndex = -1; renderFlags = 0; } ``` ### 3.3 dtor `ANM2::~ANM2()` — 0x408170 (also used by many EH unwind funclets) ```cpp ANM2::~ANM2() { Reset(); overlay.~AnimationState(); main.~AnimationState(); defaultAnimation.~string(); filename.~string(); } ``` ### 3.4 copy-ctor `ANM2::ANM2(const ANM2& o)` — 0x407690 (`ret 4`, 40 callers) ```cpp ANM2::ANM2(const ANM2& o) : filename(o.filename), defaultAnimation(o.defaultAnimation), main(this, o.main), overlay(this, o.overlay) // AnimationState copy 0x4086e0 { overlayRenderFirst = o.overlayRenderFirst; animations = o.animations; animationCount = o.animationCount; layerStates = nullptr; layerCount = o.layerCount; nullNames = o.nullNames; nullCount = o.nullCount; eventNames = o.eventNames; eventCount = o.eventCount; offset = {0,0}; // QUIRK: Offset is NOT copied (literal zero stores at 0x407767/0x407771) scale = o.scale; rotation = o.rotation; color = o.color; color2 = o.color2; flipX = o.flipX; flipY = o.flipY; playbackSpeed = o.playbackSpeed; unk108 = o.unk108; loaded = o.loaded; shadowLayerIndex = o.shadowLayerIndex; renderFlags = 0; // QUIRK: not copied if (loaded) AnmCache::AddRef(filename); layerStates = new LayerState[o.layerCount]; // ctor 0x4081d0 each for (uint i = 0; i < o.layerCount; ++i) { LayerState& d = layerStates[i]; const LayerState& s = o.layerStates[i]; d.info = s.info; d.spritesheetPath = s.spritesheetPath; d.texture = s.GetTexture(); // 0x408590 + assign 0x40c3b0 d.b30 = s.b30; d.b31 = s.b31; d.b32 = s.b32; d.b33 = s.b33; d.size = s.size; d.rotation = s.rotation; d.pos = s.pos; // +0x34..+0x44 d.color = s.color; // +0x48 (0x2c) d.visible = s.visible; // +0x74 memcpy(&d.blendMode, &s.blendMode, 0x1c); // +0x78..+0x94 (blend x5, flags, crop vector) d.owner = this; // +0x20..+0x2c sampler params keep the Init(nullptr) defaults } } ``` `AnimationState::AnimationState(ANM2* owner, const AnimationState& s)`, 0x4086e0, `ret 8`: copies anim and makes a deep copy of both index arrays (`operator new(count*4)`, memcpy) using `anim->layerAnimCount/nullAnimCount`. Then it copies frame, playing and both masks. ### 3.5 `ANM2& ANM2::operator=(ANM2 tmp /*by value*/)` — 0x407e90 (`ret 0x114`, copy-and-swap) ```cpp ANM2& ANM2::operator=(ANM2 tmp) { swap(*this, tmp); /* inline ~ANM2(tmp) */ tmp.Reset(); ...; return *this; } ``` `void swap(ANM2& a /*ecx*/, ANM2& b /*edx*/)`, 0x407ae0, fastcall. It swaps: filename, defaultAnimation (raw 0x18-byte swap), main and overlay **except owner** (+4..+0x1c), +0x74..+0x90, scale, rotation, color, color2, flipX, flipY, playbackSpeed, +0x108, loaded, shadowLayerIndex, renderFlags. It does **not** swap +0x70 (overlayRenderFirst) or +0x94 (Offset). Afterwards it re-points `layerStates[i].owner` in both objects. Net effect of `a = b`: `a` keeps its own Offset and overlayRenderFirst, and its renderFlags become 0 (from the copy-ctor). ### 3.6 `void ANM2::Load(const std::string& path, bool loadGraphics)` — 0x40bd50 (`ret 8`) ```cpp void ANM2::Load(const std::string& path, bool loadGraphics) { if (filename.size()) AnmCache::RemoveRef(filename); if (this != (ANM2*)&path) filename.assign(path); AnmCache::Load(path, this); // fills animations/layerStates/... (see 1.4) AnmCache::AddRef(path); if (loadGraphics) LoadGraphics(); main.SetAnimationData(nullptr); overlay.SetAnimationData(nullptr); loaded = true; // QUIRK: set even when the cache load failed shadowLayerIndex = -1; for (uint i = 0; i < layerCount; ++i) { const char* nm = layerStates[i].info ? layerStates[i].info->name.c_str() : ""; if (strcmp(nm, "shadow") == 0) shadowLayerIndex = i; else if (nm[0] == '*') { layerStates[i].renderFlags |= 5; renderFlags |= 0x400; } } for (uint i = 0; i < nullCount; ++i) if (nullNames[i].c_str()[0] == '*') renderFlags |= 0x800; } ``` (The AnimationStates are reset only **after** AnmCache::Load has replaced `animations`. Before that they briefly hold pointers into the old data.) ### 3.7 `void ANM2::Reload()` — 0x40bea0 (Lua only; no native callers) ```cpp void ANM2::Reload() { if (filename.size()) { AnmCache::Load(filename, this); AnmCache::AddRef(filename); // QUIRK: no matching RemoveRef, so each Reload leaks one ref LoadGraphics(); } // anim states, loaded flag and shadow index are NOT touched } ``` ### 3.8 `bool ANM2::ReplaceSpritesheet(int layer, const std::string& path)` — 0x40bf30 (`ret 8`) ```cpp bool ANM2::ReplaceSpritesheet(int layer, const std::string& path) { if (layer < 0 || layer >= (int)layerCount) return false; LayerState& ls = layerStates[layer]; if (StrEqual(ls.spritesheetPath, path)) return false; // unchanged ls.spritesheetPath = path; ls.graphicsLoaded = false; // +0x30 return true; // texture loads on the next LoadGraphics() } ``` ### 3.9 `void ANM2::LoadGraphics(/*unused 4-byte arg*/)` — 0x40c000 (`ret 4`; 0x40bff0 is the Lua/zero-arg thunk that pushes garbage) ```cpp void ANM2::LoadGraphics() { for (uint i = 0; i < layerCount; ++i) { LayerState& ls = layerStates[i]; if (ls.graphicsLoaded) continue; TexturePtr tex = LoadImage(ls.spritesheetPath.c_str()); // 0x9588a0(&tex, path) bool ok = tex.obj && tex.obj->vfunc0(); // IsValid/IsLoaded if (ok) TextureCache::Add(tex); // 0x40e520 (by-value copy) TexturePtr old = ls.GetTexture(); // 0x408590 if (old.obj) { const char* oldName = old.obj->name44; // tex+0x44 ls.SetTexture(TexturePtr(nullptr)); // 0x40c4a0 + 0x408640 TextureCache::Release(oldName); // 0x40e740 (evicts if useCount <= 2) } ls.SetTexture(tex); // set even if !ok ls.graphicsLoaded = ok; // +0x30 ls.b31 = false; // +0x31 } } ``` --------------------------------------------------------------------------------------------------------------------- ## 4. AnimationState: what happens when an animation is set ### 4.1 `void AnimationState::SetAnimationData(AnimationData* a)` — 0x408830 (`ret 4`; ~60 callers) Used by Reset, Load, RemoveOverlay, and SetAnimation(name, reset=true). ```cpp void AnimationState::SetAnimationData(AnimationData* a) { anim = a; if (layerFrameIdx) { KageFree(layerFrameIdx); layerFrameIdx = nullptr; } // 0xa648b0(cl=1) if (nullFrameIdx) { KageFree(nullFrameIdx); nullFrameIdx = nullptr; } if (anim) { if (anim->layerAnimCount) { // +0x1c layerFrameIdx = (int*)KageAlloc(anim->layerAnimCount * 4); // 0xa648b0(cl=0) memset(layerFrameIdx, 0xFF, anim->layerAnimCount * 4); // all -1 } if (anim->nullAnimCount) { // +0x24 (only checked if anim != null) nullFrameIdx = (int*)KageAlloc(anim->nullAnimCount * 4); memset(nullFrameIdx, 0xFF, anim->nullAnimCount * 4); } } frame = -1.0f; playing = false; eventsThisUpdate = 0; eventsSinceStart = 0; } ``` The arrays are sized by the **animation's** layer-animation and null-animation counts, not by the sprite's layer/null counts. Rendering maps sprite layer id → layer-anim index through `anim->layerIdToLayerAnimIdx[id]` (+0x38). ### 4.2 `void AnimationState::ChangeAnimationKeepFrame(AnimationData* a)` — 0x408970 (`ret 4`) Used by SetAnimation(name, reset=false) 0x40a678 and by SetOverlayAnimation 0x40ab98. ```cpp void AnimationState::ChangeAnimationKeepFrame(AnimationData* a) { int oldL = anim ? anim->layerAnimCount : 0, newL = a ? a->layerAnimCount : 0; int oldN = anim ? anim->nullAnimCount : 0, newN = a ? a->nullAnimCount : 0; if (oldL != newL) { if (newL <= 0) { if (layerFrameIdx) { KageFree(layerFrameIdx); layerFrameIdx = nullptr; } } else { int* p = (int*)KageAlloc(newL * 4); memset(p, 0xFF, newL * 4); if (oldL > 0) memcpy(p, layerFrameIdx, oldL * 4); // QUIRK: copies OLD count, overflows if oldL > newL if (layerFrameIdx) TrackedFree(layerFrameIdx); layerFrameIdx = p; } } if (oldN != newN) { if (newN <= 0) { if (nullFrameIdx) { KageFree(nullFrameIdx); nullFrameIdx = nullptr; } } else { int* p = (int*)KageAlloc(newN * 4); memset(p, 0xFF, newN * 4); if (oldN > 0) memcpy(p, nullFrameIdx, oldN * 4); if (nullFrameIdx) { TrackedFree(nullFrameIdx); nullFrameIdx = nullptr; } layerFrameIdx = p; // !!! BUG IN BINARY (0x408b6a): the new NULL array is stored into // layerFrameIdx (leaking the layer array). nullFrameIdx ends NULL. } } anim = a; // frame / playing / event masks are preserved } ``` (Re-check 0x408b63..0x408b6d if you doubt this. The store really is `mov [esi+8], ebx`.) ### 4.3 Callers that select an animation - `bool ANM2::SetAnimation(const char* name, bool reset)`, 0x40a5d0 (`ret 8`). The Lua wrapper 0x40a5b0 takes a std::string. It does a linear `strcmp` over `animations[0..animationCount)` on `AnimationData::name` (+0). If nothing matches it logs `"[warn] no animation named %s\n"` and returns false. Otherwise it calls `reset ? main.SetAnimationData(&animations[i]) : main.ChangeAnimationKeepFrame(&animations[i])` and returns true. SetOverlayAnimation 0x40aaf0 does the same on `overlay`. - `void ANM2::Play(const char* name, bool force)`, 0x40a380 (Lua 0x40a360): `if (force || !main.anim || strcmp(main.anim->name, name) || (!main.anim->loop && !main.playing)) { if (SetAnimation(name, true)) { main.Rewind(); main.playing = true; } }` PlayRandom 0x40a2b0 (`animations[seed % animationCount]`) and the index variant 0x40a400 (`"[warn] Animation index out of range!"`) follow the same pattern. - `void AnimationState::Rewind()`, 0x40a1b0: `frame = 0; eventsThisUpdate = eventsSinceStart = 0; FireTriggersAtCurrentFrame(); fill layerFrameIdx[0..layerAnimCount) and nullFrameIdx[0..nullAnimCount) with 0;` - `Stop` 0x40a910: `if (main.anim) main.playing = false;` --------------------------------------------------------------------------------------------------------------------- ## 5. Open questions / uncertainty 1. `AnmFileData+0 needsReload`: the only writes I found set it to 0 (node creation, ParseAnm2). It may be set elsewhere, for example when a mod is toggled. I did not scan the whole binary for byte writes to node+0x14. 2. ANM2 +0xd4 (0x2c-byte colour struct whose Reset alpha is 0) and +0x108 (bool): purpose unknown. Neither is read in the 0x401000..0x41d000 module. Look at entity render code outside it. 3. LayerState +0x20..+0x2c (texture param pairs), +0x31..+0x33, +0x78..+0x94: names are guesses from defaults and the Repentance+ LayerState API (blend factors 1/6/7 match GL enum ordinals ONE/SRC_ALPHA/ONE_MINUS_SRC_ALPHA). 4. LayerInfo +0/+4 ints: likely layerId and spritesheetId. The parser decomp should confirm. 5. TextureCache key mismatch: Add uses the unprefixed `tex->name`, while Has/Release use `prefix+name`. This only works if the texture name already includes the mount prefix (not verified). 6. Mount prefix strings come from `Mount+0xc` in FileSystem 0xc379e0+8. Their actual values (e.g. "resources/") were not observed at runtime.