notes/systems: keep the anm2 and rooms decompilation write-ups the src/ ports retired
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e35ad1316f
commit
d5c7b29bad
5 files changed
+1753
-1
No files matched your search
@@ -0,0 +1,635 @@
|
||||
# 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<const char*> 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<uint32,..>::_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<const char*> FileSystem::GetMountPrefixes() { // 0xa16060 (static, sret)
|
||||
std::vector<const char*> v;
|
||||
// g_FileSystem(0xc379e0)+8 : std::vector<Mount*> 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<uint32, AnmCacheEntry>` (`_Myhead` @0xc78ee0, `_Mysize` @0xc78ee4) | `g_AnmCache.files` |
|
||||
| 0xc78ee8 | `std::map<uint32, TexturePtr>` (head/size; node size 0x1c) | `g_AnmCache.textures` |
|
||||
| 0xc798b8 | `std::vector<const char*>` (begin/end/cap @ b8/bc/c0) | `s_mountPrefixes` (filled lazily) |
|
||||
| 0xc79c40 | `uint64` | `s_totalAnm2LoadMs` |
|
||||
| 0xc78da4 | `std::vector<ANM2*>` (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<uint32,AnmCacheEntry>* 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.
|
||||
@@ -0,0 +1,537 @@
|
||||
# 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`)
|
||||
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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 `strncpy`s 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]
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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**
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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)**
|
||||
```cpp
|
||||
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]
|
||||
```cpp
|
||||
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)
|
||||
```cpp
|
||||
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)`):
|
||||
```cpp
|
||||
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:
|
||||
```cpp
|
||||
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):**
|
||||
```cpp
|
||||
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.
|
||||
@@ -0,0 +1,326 @@
|
||||
# isaac-ng.exe (Rep+ 1.9.7.17) — RoomConfig stage table, .stb loading, mod room merging
|
||||
|
||||
Covers: RoomConfig construction, stages.xml parsing, when stages are loaded, mod room merging,
|
||||
variant-range bookkeeping, and the only XML room parser (--load-room). The per-room
|
||||
binary reader (ReadRoom 0x82aea0) is in CONTEXT_rooms.md and is not repeated here.
|
||||
Labels for everything below are in labels.json.
|
||||
|
||||
Conventions: `Game* g = *(Game**)0xc71678`; `ModManager* mm = *(char**)0xc7169c + 0x2a6c0`.
|
||||
`difficulty = g+0x269c8` (0 normal, 1 hard, 2 greed, 3 greedier).
|
||||
`ResolveContentPath` 0x8f5ad0 = mm->ResolveContentPath(out, relPath). It checks each enabled mod's
|
||||
`resources-dlc3/<rel>`, then `resources/<rel>`, falls back to the vanilla rel path, and caches by path hash.
|
||||
|
||||
## 1. Layout
|
||||
|
||||
```
|
||||
struct Game { ... RoomConfig roomConfig @ +0x18910 (size 0x1e28, ends at +0x1a738) ... }
|
||||
|
||||
struct RoomConfig { // ctor inlined in Game::ctor 0x6f1020 @0x6f1184..
|
||||
RoomConfigStage stages[37]; // +0x0000, stride 0xc4 (eh-vector ctor 0x828f00 / dtor 0x8295e0, count 0x25)
|
||||
/* +0x1c54 */ void* curses_begin, *curses_end, *curses_cap; // std::vector (curses.xml, 0x82bf00) – not analysed
|
||||
/* +0x1c60 */ struct { int id; std::string name; } curseTable[16]; // 0x1c each, ctor 0x829650 – likely curses, unverified
|
||||
/* +0x1e20 */ std::list<RoomConfigRoom> generatedRooms; // node 0x64 = next,prev + 0x5c Room; size @+0x1e24
|
||||
// cleared by 0x82d320 "delete %d generated rooms." from Level::Init
|
||||
};
|
||||
|
||||
struct RoomConfigStage { // 0xc4, ctor 0x828f00
|
||||
/* +0x00 */ int id; // NOT initialised by the ctor; only set when stages.xml has the <stage>
|
||||
/* +0x04 */ std::string name; // "name" attribute ("#BASEMENT_NAME"; '#' => localised, see 0x829500)
|
||||
/* +0x1c */ std::string playerSpot; // bossgfxroot + "playerspot"
|
||||
/* +0x34 */ std::string bossSpot; // bossgfxroot + "bossspot"
|
||||
/* +0x4c */ std::string suffix; // "suffix"
|
||||
/* +0x64 */ RoomConfigMode modes[2]; // [0] normal/hard, [1] greed/greedier (eh-vector ctor 0x828b60, dtor 0x829260)
|
||||
/* +0xbc */ int music; // atoi("music")
|
||||
/* +0xc0 */ int backdrop; // atoi("backdrop")
|
||||
};
|
||||
|
||||
struct RoomConfigMode { // 0x2c, ctor 0x828b60, Clear 0x828c00
|
||||
/* +0x00 */ std::string file; // root/greedroot + "path" (still ".xml"; turned into ".stb" at load time)
|
||||
/* +0x18 */ RoomConfigRoom* rooms; // new[] with count cookie at rooms[-1] (4 bytes), stride 0x5c
|
||||
/* +0x1c */ uint32_t count;
|
||||
/* +0x20 */ std::map<int /*room type*/, VariantRanges*> variantsByType; // MSVC map: head @+0x20, size @+0x24
|
||||
/* +0x28 */ bool loaded;
|
||||
};
|
||||
|
||||
struct VariantRanges { Interval* head; }; // malloc'd 4 bytes (0x828e50)
|
||||
struct Interval { uint32_t lo, hi; Interval* next; }; // 0xc bytes (tracked malloc 0x10 incl. size header);
|
||||
// sorted ascending, disjoint, inclusive [lo,hi]
|
||||
```
|
||||
|
||||
Room field corrections to CONTEXT_rooms.md, confirmed by the Lua binding table at 0x86bee8..0x86bfe9:
|
||||
`+0x30 = InitialWeight` and `+0x34 = Weight` (the current, mutable weight). CONTEXT_rooms.md had these
|
||||
two swapped. ReadRoom writes the same value to both. Every reset copies +0x30 into +0x34
|
||||
(0x82aa27, 0x745195, 0x7516f7). Other Lua names: +0 StageID, +4 Mode, +8 Type, +0xc Variant,
|
||||
+0x58 OriginalVariant, +0x10 Subtype, +0x14 Name, +0x2c Difficulty, +0x44 SpawnCount, +0x46 Width,
|
||||
+0x47 Height, +0x48 Shape. Doors and Spawns are getters. +0x50 and +0x54 are still unknown: they
|
||||
are zeroed in the ctor 0x828b20, are not written by load or merge, have no Lua binding, and are
|
||||
not set by the XML parser.
|
||||
|
||||
## 2. stages.xml → stage table
|
||||
|
||||
### Who calls it
|
||||
- `Game::LoadConfigXmls` 0x6f4740 runs once per Game object. It is called from app init 0x952410
|
||||
(right after `new Game` 0x6f1020 at 0x952837) and from 0x959720 (also right after `new Game`).
|
||||
It does `roomConfig.LoadStagesXml(ResolveContentPath("stages.xml"))` at 0x6f4829, then curses.xml, and so on.
|
||||
- `0x6f3c00` (called at 0x9b24d8 from 0x9b23a0, the "Lua is resetting!" path, i.e. a mod enable/disable reload)
|
||||
re-parses stages.xml at 0x6f3ca0. After that, `ModManager::LoadModCurses` 0x8f86c0 runs at 0x9b2508.
|
||||
- The game resolves stages.xml through ResolveContentPath, so **one mod can replace the whole
|
||||
stages.xml** (`<mod>/resources[-dlc3]/stages.xml`). The game does not merge stages.xml files from several mods.
|
||||
|
||||
### RoomConfig::LoadStagesXml 0x82b2f0 (thiscall, ret 4)
|
||||
```cpp
|
||||
bool RoomConfig::LoadStagesXml(const char* path) {
|
||||
File* f = FileSystem::Open(0xc37a10, path, 0); if (!f) return false;
|
||||
size_t n = f->Size(); char* buf = new_tracked(n+1); f->Read(buf,1,n); buf[n]=0; f->Close(1);
|
||||
rapidxml::xml_document doc; doc.parse(buf);
|
||||
xml_node* root = doc.first_node("stages");
|
||||
std::string roomsRoot = attr(root,"root") ?: "rooms/"; // 0x82b3d9 / default 0x82b3f6
|
||||
std::string greedRoot = attr(root,"greedroot") ?: "rooms/greed/"; // 0x82b43c / default 0x82b459
|
||||
std::string bossGfxRoot = attr(root,"bossgfxroot")->value(); // 0x82b49c: NO null check (crashes if missing)
|
||||
int id; // [ebp-0x10188]; NOT reset per <stage>, so a missing id reuses the previous one
|
||||
for (xml_node* n = root->first_node("stage"); n; n = n->next_sibling /*[+0x2c], any sibling, no name filter*/) {
|
||||
RoomConfigStage tmp; // strings + modes re-constructed per node (0x82b503..0x82b5c9)
|
||||
tmp.music = 0; tmp.backdrop = 0;
|
||||
for (attr a : n->attributes) { // strcmp chain, unknown attributes ignored
|
||||
if (a=="id") id = atoi(v);
|
||||
else if (a=="name") tmp.name = v;
|
||||
else if (a=="path") { tmp.modes[0].file = roomsRoot + v; // 0x82b727
|
||||
tmp.modes[1].file = greedRoot + v; } // 0x82b79c (ALWAYS both)
|
||||
else if (a=="playerspot") tmp.playerSpot = bossGfxRoot + v;
|
||||
else if (a=="bossspot") tmp.bossSpot = bossGfxRoot + v;
|
||||
else if (a=="music") tmp.music = atoi(v);
|
||||
else if (a=="backdrop") tmp.backdrop = atoi(v);
|
||||
else if (a=="suffix") tmp.suffix = v;
|
||||
}
|
||||
tmp.id = id;
|
||||
this->stages[id] = tmp; // 0x82bd60 operator=, NO bounds check on id (array has 37 entries)
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
`RoomConfigStage::operator=` 0x82bd60 copies everything. That includes `modes[i].rooms`, `count`,
|
||||
`loaded` and a deep copy of the variant map (0x82e720). The temporary has rooms=null,
|
||||
count=0, loaded=false, so **re-parsing stages.xml "unloads" every stage that appears in the XML**.
|
||||
The old room arrays are not freed and leak. Lazy loading then reloads them on next use. Stages
|
||||
missing from the XML keep their earlier state. On a fresh Game their `file` is empty and
|
||||
LoadStageBinary returns false at once (0x82aac2).
|
||||
|
||||
So a stage's file names are `modes[0].file = "rooms/" + path` and `modes[1].file = "rooms/greed/" + path`,
|
||||
for example "rooms/01.Basement.xml" and "rooms/greed/01.Basement.xml". The loader later turns these into ".stb".
|
||||
|
||||
Vanilla stage ids (taken from a mod's copy of vanilla stages.xml in mods/stageapi15_*/resources/stages.xml; the packed
|
||||
vanilla file was not extracted): 0 Special Rooms, 1-17 the normal chapters, 24 The Shop, 25 Ultra Greed, 26 The Void
|
||||
(path "01.Basement.xml" in that copy; a "26.The Void_ex.stb" exists in resources/rooms), 27-33 Downpour..Corpse,
|
||||
35 Home, 36 Backwards. 18-23 are commented out in that copy. 34 is not present.
|
||||
Uncertain: whether the vanilla packed stages.xml differs.
|
||||
|
||||
## 3. LoadStageBinary 0x82aa40 (summary of what it does around the per-room reader)
|
||||
|
||||
```cpp
|
||||
bool RoomConfig::LoadStageBinary(int stageId, int mode /*-1 => difficulty>=2 ? 1 : 0*/) {
|
||||
Stage& s = stages[stageId]; Mode& m = s.modes[mode];
|
||||
if (m.file.empty()) return false; // 0x82aac2
|
||||
Log("[RoomConfig] load stage %d: %s (mode %d)\n", s.id, s.GetDisplayName(), mode);
|
||||
std::string stb = m.file.substr(0, m.file.size()-3) + "stb"; // 0x82ab59..0x82ab8a
|
||||
File* f = FileSystem::Open(ResolveContentPath(stb), 0); // a mod's resources/ can REPLACE the vanilla .stb
|
||||
if (!f) return false; // no Clear and loaded stays false, so it retries next call
|
||||
m.Clear(); // 0x828c00: frees entries, spawns, rooms[], interval lists, map; loaded=false
|
||||
if (read32(f) != 'STB1') return false; // 0x82aca1 (file is not closed here: leak)
|
||||
m.count = read32(f);
|
||||
if (m.count) {
|
||||
Log("allocate %d rooms.\n", m.count);
|
||||
m.rooms = new RoomConfigRoom[m.count]; // ctor 0x828b20
|
||||
for (i = 0; i < m.count; i++) {
|
||||
ReadRoom(&m, i, stageId, f); // 0x82aea0
|
||||
m.rooms[i].mode = mode;
|
||||
m.GetVariantRanges(m.rooms[i].type)->Insert(m.rooms[i].variant); // return value ignored (duplicates allowed in vanilla)
|
||||
switch (stageId) { // table 0x82ae78
|
||||
case 1: case 2: case 3: if (variant==603 || variant==716) flags |= 4; break;
|
||||
case 29: case 30: if (type==1 && subtype==31) flags |= 2; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
f->Close(1);
|
||||
mm->LoadModRooms(stageId, mode); // 0x8f8040, see section 5
|
||||
m.loaded = true; return true;
|
||||
}
|
||||
```
|
||||
|
||||
## 4. When stages get loaded (lazy, per floor, and never unloaded except by a stages.xml re-parse)
|
||||
|
||||
There is no load-all at startup. Every caller uses the same idiom: `if (!m.loaded) LoadStageBinary(id, mode); else for each room: weight(+0x34) = initialWeight(+0x30);`.
|
||||
That idiom is factored as `RoomConfig::LoadOrResetStage` 0x82a9c0 and inlined at other sites. So **every
|
||||
level init resets all weights of the stages it uses**.
|
||||
|
||||
Callers of LoadStageBinary:
|
||||
| site | function | stage / mode |
|
||||
|---|---|---|
|
||||
| 0x745179 | Level::Init 0x744940 | LevelStage==12 (Void): stages 1..17 except 13, mode derived (-1 logic) |
|
||||
| 0x74523a | Level::Init | otherwise `GetStageID(levelStage, stageType, -1)` (0x82d030), mode derived |
|
||||
| 0x74532e | Level::Init | non-greed, StageType 4/5 (alt path), and (LevelStage==4, or LevelStage==3 with curse bit 2 = Labyrinth): **stage 29 (Mines)** is also loaded, mode derived. The LevelStage 1..6 && g+0x2654c&0x10000 case skips this (likely the Ascent flag, unverified). |
|
||||
| 0x7453e7 (via 0x82a9c0) | Level::Init | non-greed normal generation path: **stage 0 (Special Rooms)** with mode -1, then 0x740e10 (layout gen). Home (LS13), the 0x10000 path, `g+0x26584==0x2c`, and LS9 go to dedicated generators (0x74de30 / 0x742ef0 / 0x7508c0 / 0x74a500) and do NOT load stage 0 here. |
|
||||
| 0x745427 | Level::Init | greed/greedier: **stage 0, mode 1** ("rooms/greed/00.Special Rooms.stb"), then 0x743550 (greed layout) |
|
||||
| 0x7516d8, 0x751ca6 | 0x751650 (reached from 0x7515c0 when Level+0x1830c != 2) | **stage 35 (Home), mode 0 always**. Probably building dimension 2 (Death Certificate area); unverified. |
|
||||
| 0x82c76e | RoomConfig::GetRoomByStageTypeAndVariant 0x82c720 | lazy load of any (stageId, mode) on lookup |
|
||||
| 0x82cebe | RoomConfig::GetRooms 0x82ce40 | lazy load on filtered query |
|
||||
|
||||
`Mode` is always derived the same way: `mode==-1 ? (difficulty==2||difficulty==3) : mode`.
|
||||
|
||||
`RoomConfig::GetStageID` 0x82d030 (ecx=LevelStage, edx=StageType, [esp+4]=mode/-1, cdecl):
|
||||
```cpp
|
||||
greed = (mode==-1) ? (game && difficulty in {2,3}) : (mode==1);
|
||||
if (greed) {
|
||||
if (ls==7) return 25; if (ls==6) return 24; if (ls==5) return 14;
|
||||
if (st==4) return ls*2+25; if (st==5) return ls*2+26;
|
||||
return 3*ls - 2 + st; // ls1:1..3, ls2:4..6, ls3:7..9, ls4:10..12
|
||||
}
|
||||
if (ls==13) return 35;
|
||||
if (ls < 9) { c = ls-1;
|
||||
if (st==4) return (c & ~1) + 27; // 27,29,31,33
|
||||
if (st==5) return (c>>1)*2 + 28; // 28,30,32,34
|
||||
return (c>>1)*3 + st + 1; } // 1..12
|
||||
if (ls==9) return st==4 ? 36 : 13;
|
||||
if (ls==12) return 26;
|
||||
return (ls-3)*2 + st; // ls10: 14/15, ls11: 16/17
|
||||
```
|
||||
|
||||
Lookups:
|
||||
- `GetRoomByStageTypeAndVariant(stageId,type,variant,mode)` 0x82c720 (ret 0x10) does a linear scan and returns the **first**
|
||||
room with `type==t && variant(+0xc)==v`. Vanilla rooms come first, then mods in merge order. If nothing matches it
|
||||
logs "[warn] StageID %d Room type %d, variant %d not found!" and returns null.
|
||||
- `GetRooms(out vector<Room*>, stageId, type, shape(13=any), minVariant, maxVariant, minDifficulty, maxDifficulty,
|
||||
const uint32* requiredDoors, subtype(-1=any), mode)` 0x82ce40 (ret 0x2c) filters with
|
||||
`type==` and `shape==/13` and `minV<=variant<=maxV` (unsigned) and `minD<=difficulty<=maxD` (signed) and
|
||||
`(doorMask & *req)==*req` and `subtype==/-1`. It also drops rooms with `flags&0x80` (the entity-4500 rooms) unless
|
||||
`g+0x1bbd8` (a std::map<int,...>) contains key 79 (0x82cf69..0x82cfa4; what that map is was not determined).
|
||||
|
||||
## 5. Mod room merging — ModManager::LoadModRooms 0x8f8040 (thiscall this=mm, ret 8)
|
||||
|
||||
```cpp
|
||||
void ModManager::LoadModRooms(int stageId, int mode) {
|
||||
if (!g_Game) return;
|
||||
for (Mod* mod : this->mods /* vector<Mod*> at this+0 / +4, list order */) {
|
||||
if (!mod->enabled /* +0xfd */) continue;
|
||||
Mode& m = g->roomConfig.stages[stageId].modes[mode];
|
||||
Log("[ModManager] load stage %d: %s (mode %d)\n", stage.id, stage.GetDisplayName(), mode);
|
||||
std::string rel = m.file.substr(0, size-3) + "stb"; // e.g. "rooms/01.Basement.stb", "rooms/greed/01.Basement.stb"
|
||||
std::string path = mod->GetContentPath(rel); // 0x8f99c0, see below
|
||||
if (!FileSystem::ResolvePath(0xc379e0, path)) continue; // silently skip when the mod has no such file
|
||||
File* f = FileSystem::Open(0xc37a10, path, 0);
|
||||
if (!f) { Log("[ModManager] Failed to open room config files %s!\n", path); continue; }
|
||||
if (read32(f) != 'STB1') { Log("[ModManager] bad room config header in %s!\n", path); return; }
|
||||
// NB: returns from the WHOLE function (0x8f8315 -> 0x8f864e -> exit). Later mods are not merged,
|
||||
// the file is not closed, and the caller still sets loaded=true.
|
||||
uint32 oldCount = m.count; uint32 n = read32(f);
|
||||
if (n) {
|
||||
Log("reallocate %d rooms.\n", n); // logs the ADDED count, not the total
|
||||
RoomConfigRoom* nr = new RoomConfigRoom[oldCount + n]; // ctor 0x828b20, count cookie
|
||||
for (i < oldCount) memberwise copy rooms[i] -> nr[i]; // shallow: spawns ptr copied; name string deep-copied
|
||||
delete[] m.rooms; // eh-vector dtor 0x6ef3e0 destroys only the name string
|
||||
m.rooms = nr; m.count = oldCount + n;
|
||||
}
|
||||
for (i = oldCount; i < m.count; i++) {
|
||||
ReadRoom(&m, i, stageId, f); // 0x82aea0: sets variant(+0xc) = originalVariant(+0x58) = file value
|
||||
Room& r = m.rooms[i];
|
||||
r.mode = mode;
|
||||
VariantRanges* vr = m.GetVariantRanges(r.type);
|
||||
uint32 v = r.variant;
|
||||
if (!vr->Insert(v)) { // variant already used for this type -> reassign
|
||||
Interval* first = vr->head; Interval* nx = first->next;
|
||||
if (nx && nx->lo + 2 == first->hi) { // AS COMPILED (0x8f857d..0x8f8585): effectively never true
|
||||
v = nx->lo + 1; // because lists are sorted and disjoint. It looks like
|
||||
first->next = nx->next; first->hi = nx->hi; free(nx);// the intended check was "first->hi + 2 == nx->lo" (fill a 1-wide gap).
|
||||
} else {
|
||||
first->hi++; v = first->hi; // 0x8f85b4: extend the LOWEST interval by one
|
||||
}
|
||||
r.variant = v; // +0x58 OriginalVariant keeps the file value
|
||||
}
|
||||
}
|
||||
// NB: the vanilla per-stage flag fixups (flags|=4 / |=2) are NOT applied to mod rooms.
|
||||
f->Close(1);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Mod path builder `Mod::GetContentPath(out, rel)` 0x8f99c0. `mod+0x48` is `<moddir>/content/` (set at 0x8f6d6e)
|
||||
and `mod+0x30` is `<moddir>/resources/` (0x8f6cda).
|
||||
1. Try `mod+0x48` minus its trailing '/', plus `"-dlc3/"` plus rel, i.e. **`<moddir>/content-dlc3/rooms/<file>.stb`**. If
|
||||
`FileSystem::ResolvePath` finds it, return it.
|
||||
2. Otherwise return **`<moddir>/content/rooms/<file>.stb`** without checking that it exists; the merge checks.
|
||||
|
||||
Only `.stb` files are tried. No mod `.xml` room file is ever read. Greed mode looks under
|
||||
`content/rooms/greed/`, because the mode file already contains the greedroot.
|
||||
|
||||
Consequences and semantics for a reimplementation:
|
||||
- Merge is **append-only**. Vanilla rooms are never replaced by mod content files. Full replacement only happens
|
||||
through `resources/rooms/X.stb` (ResolveContentPath in LoadStageBinary).
|
||||
- **OriginalVariant (+0x58)** is always the variant stored in the .stb. **Variant (+0xc)** equals it unless a mod
|
||||
room collided with an already-registered (type, variant), in which case it is remapped as above.
|
||||
- Collision detection uses the per-type interval set, which contains every vanilla variant (inserted
|
||||
unconditionally during the vanilla load) and every variant from earlier mod rooms and earlier mods.
|
||||
- Remap rule as compiled: new variant = `++head.hi`, where head is the lowest interval of that type. Because
|
||||
the "merge with next interval" branch is dead, once the gap after the first interval is used up, the next
|
||||
collision produces `head.hi == next.lo`. **That gives a duplicate variant** (equal to an existing room's
|
||||
variant), and the intervals stay overlapping or adjacent from then on. A faithful port should keep this quirk.
|
||||
Example: vanilla type 1 has variants {0..5, 7..9}. Mod rooms colliding three times get 6, then 7 (duplicate of
|
||||
vanilla 7), then 8 (duplicate), and so on. A non-colliding mod variant is inserted normally and merges ranges.
|
||||
- GetRoomByStageTypeAndVariant returns the first match, so a duplicated variant resolves to the earlier
|
||||
(vanilla) room.
|
||||
- A room array reallocation moves all earlier Room objects. This is safe only because it happens inside the
|
||||
load, before anything holds Room pointers.
|
||||
|
||||
## 6. Variant ranges (0x828e50 / 0x829290)
|
||||
|
||||
```cpp
|
||||
VariantRanges* RoomConfigMode::GetVariantRanges(int type) { // 0x828e50, thiscall ret 4
|
||||
auto it = variantsByType.lower_bound(type); // 0x416440
|
||||
if (it != end && !(type < it->key)) return it->value;
|
||||
VariantRanges* r = (VariantRanges*)tracked_malloc(4); r->head = nullptr;
|
||||
variantsByType.emplace_hint(it, type, r); // 0x5cca10
|
||||
return r;
|
||||
}
|
||||
bool VariantRanges::Insert(uint32 v) { // 0x829290, thiscall ret 4; unsigned compares
|
||||
if (!head) { head = new Interval{v,v,nullptr}; return true; }
|
||||
Interval* prev = nullptr;
|
||||
for (Interval* cur = head; cur; prev = cur, cur = cur->next) {
|
||||
if (v < cur->lo) {
|
||||
if (v == cur->lo - 1) {
|
||||
if (prev && prev->hi + 1 == v) { prev->hi = cur->hi; prev->next = cur->next; free(cur); } // bridge
|
||||
else cur->lo = v;
|
||||
return true;
|
||||
}
|
||||
if (prev && prev->hi + 1 == v) { prev->hi = v; return true; }
|
||||
Interval* n = new Interval{v,v,cur}; (prev ? prev->next : head) = n; return true;
|
||||
}
|
||||
if (v <= cur->hi) return false; // already present
|
||||
}
|
||||
// ran past the last interval (prev = last)
|
||||
if (v == prev->hi + 1) { prev->hi = v; return true; }
|
||||
prev->next = new Interval{v,v,nullptr}; return true;
|
||||
}
|
||||
```
|
||||
Queried only in LoadStageBinary (0x82ad79/0x82ad8a; result ignored) and LoadModRooms (0x8f854b/0x8f8565;
|
||||
used for collision handling). Mode::Clear 0x828c00 and the stage copy 0x82bd60 (deep copy via 0x82e720) also
|
||||
touch it. No other reader was found (not exhaustively searched; callers of 0x828e50/0x829290 are only those two).
|
||||
|
||||
## 7. XML room files
|
||||
|
||||
The game has exactly one XML room parser: `RoomConfig::LoadRoomFromXmlFile` 0x829710, which calls
|
||||
`RoomConfigRoom::ParseXml` 0x829af0. It parses a **single** `<room>` element from a file into a function-local
|
||||
static Room (0xc80e48). Its only caller is `Game::Start` 0x6f7750 @0x6f7a8f, used when the start
|
||||
parameter string is non-empty. That string comes from the **`--load-room=`** command-line option (string
|
||||
0xb7e12c, used at 0x9aaf03), alongside `--set-stage=` / `--set-stage-type=`. The path is opened directly
|
||||
(FileSystem::Open, no ResolveContentPath).
|
||||
Attributes read: room `type variant subtype name difficulty weight(->+0x30 and +0x34) width height shape flags(->+0x4c)`;
|
||||
`<door x y exists="true|True">`; `<spawn x y>` with `<entity type variant subtype weight>`.
|
||||
None of this is used for stage loading. Stage room data is .stb only, for both vanilla and mods.
|
||||
|
||||
## Uncertainties
|
||||
- Stage +0 `id` for stages missing from stages.xml is never written by the ctor. It is probably zero (Game is
|
||||
likely zero-allocated), but this is not verified.
|
||||
- 0x751650: the "dimension 2 / Death Certificate" meaning is inferred. The stage 35 mode 0 load is certain.
|
||||
- The `g+0x2654c & 0x10000` flag is assumed to be the Ascent/backwards state. The `g+0x26584 == 0x2c` branch was not identified.
|
||||
- Ordering of `ModManager.mods` (the vector at mm+0) was not analysed. Merge follows that order.
|
||||
- The vanilla packed stages.xml was not read. The attribute set and defaults above come from the code. The id list comes
|
||||
from a mod's copy of the vanilla file.
|
||||
- Room +0x50/+0x54 are still unknown.
|
||||
@@ -0,0 +1,254 @@
|
||||
# isaac-ng.exe (Rep+ 1.9.7.17) — how room-config (.stb) data is consumed
|
||||
|
||||
All addresses are VAs (ImageBase 0x400000). Struct layouts are from CONTEXT_rooms.md. One correction comes first.
|
||||
|
||||
## 0. Correction: weight fields
|
||||
`ReadRoom` (0x82afe1..0x82aff0) writes the same float to both +0x30 and +0x34. The rest of the code shows which is which:
|
||||
* **+0x30 = InitialWeight** (never written at runtime; it is the source for every reset)
|
||||
* **+0x34 = Weight** (the runtime value; GetRandomRoom reads it for sums and multiplies it by 0.1 after a pick)
|
||||
|
||||
So CONTEXT_rooms.md has the two names swapped.
|
||||
|
||||
Global layout used below: `Game* g = [0xc71678]`. `g+0` is the Level (`+0 stage`, `+4 stageType`, `+0xc curses`), `g+0x18300` is `Room*`, `g+0x18910` is `RoomConfig` (embedded), and `g+0x1bbd8` is the seed-effects `std::set<int>`. `g+0x269c8` is difficulty (2/3 = greed/greedier, which gives mode 1).
|
||||
`RoomConfig`: `+stageId*0xc4` is the stage (37 stages, 0..36). `+0x1e20` is `std::list<Room>*` of generated rooms (node 0x64 = next, prev, Room@+8), and `+0x1e24` is its count.
|
||||
|
||||
Mode resolution, used everywhere (for example 0x82c738 and 0x82ce84): `if (mode == -1) mode = (g && (g->difficulty==2 || g->difficulty==3)) ? 1 : 0;`. If `!stageMode.loaded` (+0x28), it calls LoadStageBinary first.
|
||||
|
||||
## 1. RNG class (0x7e8fe0 / 0x7e9020 / 0x7e9080 / 0x7e90f0)
|
||||
```cpp
|
||||
struct RNG { u32 seed; u32 s1, s2, s3; }; // 0x10 bytes
|
||||
static const u32 kShifts[81][3] @0xb1f4c8; // listed below
|
||||
void RNG::SetSeed(u32 seed, u32 idx) { // 0x7e8fe0
|
||||
this->seed = seed; idx = min(idx, 80u); // (idx==0 -> 0)
|
||||
s1,s2,s3 = kShifts[idx];
|
||||
}
|
||||
u32 RNG::Next() { // 0x7e90f0 ("RNG Seed is zero!" + int3 if seed==0)
|
||||
u32 x = seed; x ^= x >> s1; x ^= x << s2; x ^= x >> s3; return seed = x;
|
||||
}
|
||||
u32 RNG::RandomInt(u32 n) { u32 x = Next(); return n ? x % n : 0; } // 0x7e9020
|
||||
float RNG::RandomFloat() { return (float)(double)Next() * 2.3283062e-10f; } // 0x7e9080
|
||||
// float conversion: cvtdq2pd + (x>>31 ? 4294967296.0 : 0) [table 0xbacb00] -> cvtpd2ps -> mulss 0x2f7ffffe
|
||||
```
|
||||
`kShifts` (index: s1,s2,s3):
|
||||
```
|
||||
0:(1,3,10) 1:(1,5,16) 2:(1,5,19) 3:(1,9,29) 4:(1,11,6) 5:(1,11,16) 6:(1,19,3) 7:(1,21,20) 8:(1,27,27)
|
||||
9:(2,5,15) 10:(2,5,21) 11:(2,7,7) 12:(2,7,9) 13:(2,7,25) 14:(2,9,15) 15:(2,15,17) 16:(2,15,25) 17:(2,21,9)
|
||||
18:(3,1,14) 19:(3,3,26) 20:(3,3,28) 21:(3,3,29) 22:(3,5,20) 23:(3,5,22) 24:(3,5,25) 25:(3,7,29) 26:(3,13,7)
|
||||
27:(3,23,25) 28:(3,25,24) 29:(3,27,11) 30:(4,3,17) 31:(4,3,27) 32:(4,5,15) 33:(5,3,21) 34:(5,7,22) 35:(5,9,7)
|
||||
36:(5,9,28) 37:(5,9,31) 38:(5,13,6) 39:(5,15,17) 40:(5,17,13) 41:(5,21,12) 42:(5,27,8) 43:(5,27,21) 44:(5,27,25)
|
||||
45:(5,27,28) 46:(6,1,11) 47:(6,3,17) 48:(6,17,9) 49:(6,21,7) 50:(6,21,13) 51:(7,1,9) 52:(7,1,18) 53:(7,1,25)
|
||||
54:(7,13,25) 55:(7,17,21) 56:(7,25,12) 57:(7,25,20) 58:(8,7,23) 59:(8,9,23) 60:(9,5,14) 61:(9,5,25) 62:(9,11,19)
|
||||
63:(9,21,16) 64:(10,9,21) 65:(10,9,25) 66:(11,7,12) 67:(11,7,16) 68:(11,17,13) 69:(11,21,13) 70:(12,9,23)
|
||||
71:(13,3,17) 72:(13,3,27) 73:(13,5,19) 74:(13,17,15) 75:(14,1,15) 76:(14,13,15) 77:(15,1,29) 78:(17,15,20)
|
||||
79:(17,15,23) 80:(17,15,26)
|
||||
```
|
||||
Inlined RNGs often load a triplet straight from the table (`movq xmm0,[0xb1f4c8+idx*12]`). This gives `idx = (addr-0xb1f4c8)/12`.
|
||||
|
||||
## 2. RoomConfig::GetRandomRoom — 0x82c7d0 (thiscall, ret 0x30)
|
||||
```cpp
|
||||
Room* RoomConfig::GetRandomRoom(u32 seed, bool reduceWeight, int stageId, int type, int shape /*13 = any*/,
|
||||
u32 minVariant, u32 maxVariant, int minDifficulty, int maxDifficulty,
|
||||
const std::bitset<8>* requiredDoors, int subtype /*-1 = any*/, int mode /*-1 = auto*/)
|
||||
{
|
||||
// (a) Curse of the Giant (LevelCurse bit 0x80). 0x82c846..0x82c8e4
|
||||
u32 curses = (g->level.curses /*g+0xc*/ | g+0x26550 | Seeds_ForcedCurses() /*0x6f9400*/) & ~Seeds_PreventedCurses() /*0x6f95a0*/;
|
||||
if (curses & 0x80) {
|
||||
RNG r{seed, kShifts[17]}; // (2,21,9)
|
||||
if ((r.Next() & 1) == 0) {
|
||||
Room* g2 = GetRandomSplitRoom(seed, reduceWeight, stageId, type, shape, minV, maxV, minD, maxD, requiredDoors, subtype, mode); // 0x82d880
|
||||
if (g2) return g2;
|
||||
}
|
||||
}
|
||||
// (b) Candidate collection. 0x82c8ec..0x82ca03
|
||||
std::vector<Room*> all;
|
||||
if (g->level.stage == 12 /*Void*/ && stageId != 0 && stageId != 35 /*Home*/) {
|
||||
for (int s = 1; s <= 17; ++s) { if (s == 13) continue; // skip Blue Womb
|
||||
auto v = CollectRooms(s, type, shape, minV, maxV, minD, /*maxD*/ 20, requiredDoors, subtype, mode);
|
||||
all.insert(all.end(), v.begin(), v.end()); } // NOTE: the requested stageId is ignored; maxDifficulty is forced to 20
|
||||
} else
|
||||
all = CollectRooms(stageId, type, shape, minV, maxV, minD, maxD, requiredDoors, subtype, mode); // 0x82ce40
|
||||
// (c) Sums. 0x82ca21..0x82caa5 (float, accumulated in vector order)
|
||||
float total = 0, exactSum = 0; std::vector<Room*> exact;
|
||||
for (Room* r : all) {
|
||||
total += r->Weight /*+0x34*/;
|
||||
if (requiredDoors->any() /*0x6da750*/ && r->doorMask /*+0x38*/ == requiredDoors->to_ulong()) {
|
||||
exact.push_back(r); exactSum += r->Weight; }
|
||||
}
|
||||
if (!(total > 0.0f)) { // comiss 0,total ; jb => fail when 0 >= total (also when empty)
|
||||
KAGE_LogMessage(1, "[warn] GetRandomRoom: unable to find matching room ... RequiredDoors %s, Subtype %d, returning NULL",
|
||||
seed, stageId, type, shape, minV, maxV, minD, maxD, requiredDoors->to_string() /*0x752c30*/, subtype);
|
||||
return nullptr;
|
||||
}
|
||||
// (d) Weighted pick. 0x82cba4..0x82cd9a
|
||||
RNG rng{seed, kShifts[7]}; // (1,21,20)
|
||||
u32 r1 = rng.Next(); float f1 = toFloat(r1); // RandomFloat math
|
||||
float exactChance = (exactSum / total) * 9.99f; // 0x411fd70a
|
||||
Room* pick = nullptr;
|
||||
if (!exact.empty()) {
|
||||
u32 r2 = rng.Next(); float f2 = toFloat(r2); // 2nd draw is only consumed when exact is non-empty
|
||||
if (exactChance > f2) { // comiss xmm4,xmm0 ; jbe
|
||||
float target = f1 * exactSum, acc = 0;
|
||||
for (Room* r : exact) { acc += r->Weight; if (acc > target) { pick = r; break; } }
|
||||
goto done; // NOTE: if not found -> NULL, with no fallback to `all`
|
||||
}
|
||||
}
|
||||
{ float target = f1 * total, acc = 0;
|
||||
for (Room* r : all) { acc += r->Weight; if (acc > target) { pick = r; break; } } }
|
||||
done:
|
||||
if (pick && reduceWeight)
|
||||
pick->Weight = maxss(1e-7f /*0x33d6bf95*/, pick->Weight * 0.1f /*0x3dcccccd*/); // 0x82cd7c
|
||||
return pick; // may be NULL when float rounding means acc never exceeds target
|
||||
}
|
||||
```
|
||||
Notes:
|
||||
* Every comparison is strict `acc > target` (`comiss acc,target; ja`).
|
||||
* A room's weight goes into the sums as it currently is, so weights already reduced earlier in the run take part.
|
||||
* "exact" means the room's door mask is exactly the requested set. CollectRooms only requires the requested doors to be a subset. This makes rooms that fit the doors exactly much more likely: they are chosen with probability `min(1, 9.99*exactSum/total)`.
|
||||
* Fallback when nothing matches: it logs the warning and returns NULL. There is no retry inside the function. Callers retry, for example the wrapper below.
|
||||
|
||||
### CollectRooms — 0x82ce40 (thiscall, ret 0x2c, returns vector by out-ptr)
|
||||
```cpp
|
||||
for (u32 i = 0; i < m.count; ++i) { Room* r = &m.rooms[i]; // m = stage(stageId).modes[mode]
|
||||
if (r->type != type) continue;
|
||||
if (shape != 13 && r->shape /*+0x48*/ != shape) continue; // 13 = ROOMSHAPE_NUM acts as a wildcard
|
||||
if (r->variant < minVariant || r->variant > maxVariant) continue; // unsigned compare (jb/ja)
|
||||
if (r->difficulty < minDifficulty || r->difficulty > maxDifficulty) continue; // signed (jl/jg)
|
||||
if ((r->doorMask & *requiredDoors) != *requiredDoors) continue; // must have all the required doors (superset allowed)
|
||||
if (subtype != -1 && r->subtype != subtype) continue;
|
||||
if (Seeds.contains(79 /*0x4f*/) && (r->flags /*+0x4c*/ & 0x80)) continue; // flag 0x80 = room contains a 4500.0 entity (pressure plate)
|
||||
out.push_back(r);
|
||||
}
|
||||
```
|
||||
The weight is not filtered here, so rooms with weight 0 are collected but can never be picked (they add 0 to the sums). The value 79 is a SeedEffect id. Its name was not checked; it is probably the "no pressure plates"-style seed.
|
||||
|
||||
### Wrapper 0x82cdd0 (ret 0x34, 13 stack args)
|
||||
`r = GetRandomRoom(a1 seed, a2 reduce, a3 stageId, a5 type, a6 shape, 0, 0xFFFFFFFF, a9 minD, a10 maxD, a11 doors, a12 subtype, -1)`. If that returns NULL, it repeats the call with `stageId = a4` (fallback stage).
|
||||
Args a7, a8 and a13 appear unused (uncertain). Called from 16 sites in Level generation (0x7392c7, 0x73a3df, ...).
|
||||
|
||||
### Curse of the Giant split rooms — 0x82d880 (same signature as GetRandomRoom)
|
||||
This path is only taken if `type == 1` and `shape != 13`, and the split table `0xb1f494[shape]` must be non-empty. Each table entry is 32 bytes: `{shapeA, offXA, offYA, doorsA, shapeB, offXB, offYB, doorsB}`:
|
||||
```
|
||||
4(IH): {1,0,0,8, 1,0,1,2} 5(IIV):{3,0,0,8, 3,0,1,2} 6(1x2? per enum 6): {1,0,0,4, 1,1,0,1} 7: {2,0,0,4, 2,1,0,1}
|
||||
8(2x2): {4,0,0,0x44,4,1,0,0x11} {6,0,0,0x88,6,0,1,0x22} {9,0,0,3,1,0,0,0xc} {10,0,0,0x24,1,1,0,9} {11,0,0,0x18,1,0,1,6} {12,0,0,0xc0,1,0,1,3}
|
||||
9: {1,0,1,4,4,1,0,0x10} {1,1,0,8,6,0,1,0x20} 10: {4,0,0,0x40,1,1,1,1} {1,0,0,8,6,0,1,2}
|
||||
11: {1,0,0,4,4,1,0,1} {6,0,0,0x80,1,1,1,2} 12: {4,0,0,4,1,1,0,1} {6,0,0,8,1,0,1,2}
|
||||
```
|
||||
The function works like this:
|
||||
1. `RNG rng{seed, kShifts[55]}` and `e = table[rng.RandomInt(count)]`.
|
||||
2. Each required door d (0..7) is remapped into each half. If `offY>0 && d∈{4,6}` or `offX>0 && d∈{5,7}`, then `d -= 4`. The door is kept only if it is valid for the half's shape (valid-door mask per shape is at 0xb1f894: `[0,0xf,5,0xa,0x5f,0xa,0xaf,5,0xff,0xff,0xff,0xff,0xff]`). The result is OR-ed into `doorsA` / `doorsB`.
|
||||
3. `sA = next(rng.seed)` with (7,17,21), and `A = GetRandomRoom(sA, reduce, stageId, 1, shapeA, minV, maxV, minD, maxD, &doorsA, subtype, mode)`.
|
||||
4. `sB = next(sA)`, and B is picked the same way with `shapeB`.
|
||||
5. If both are found, it returns `0x82d4a0(A, B, shape)`. That function builds a merged Room and appends it to the `RoomConfig+0x1e20` generated list (count at +0x1e24). Otherwise it returns NULL.
|
||||
|
||||
### GetRoomByStageTypeAndVariant — 0x82c720 (thiscall, ret 0x10)
|
||||
```cpp
|
||||
Room* RoomConfig::GetRoomByStageTypeAndVariant(int stageId, int type, int variant, int mode /*-1 auto*/) {
|
||||
// mode resolve + lazy load
|
||||
for (u32 i = 0; i < m.count; ++i) if (m.rooms[i].type == type && m.rooms[i].variant == variant) return &m.rooms[i];
|
||||
KAGE_LogMessage(1, "[warn] StageID %d Room type %d, variant %d not found!\n", stageId, type, variant);
|
||||
return nullptr;
|
||||
}
|
||||
```
|
||||
It does a linear scan, returns the first match and ignores subtype.
|
||||
|
||||
### GetStageID — 0x82d030 (ecx=levelStage, edx=stageType, [esp+4]=mode; caller cleans)
|
||||
This maps LevelStage and StageType to the stb id.
|
||||
* **Greed** (`mode==1`, or `mode==-1` with greed difficulty):
|
||||
* stage 7 → 25 and stage 6 → 24 (`stage+18`); stage 5 → 14 (`stage+9`).
|
||||
* Otherwise: type 4 → `2*stage+25`, type 5 → `2*stage+26`, else `3*stage-2+type`.
|
||||
* **Normal**:
|
||||
* stage 13 → 35 (Home).
|
||||
* stage < 9: with `n = stage-1`, type 4 → `(n&~1)+27`, type 5 → `(n>>1)*2+28`, else `(n>>1)*3+type+1`.
|
||||
* stage 9 → 13, or 36 when type 4.
|
||||
* stage 12 → 26.
|
||||
* Otherwise → `(stage-3)*2+type` (10 → 14/15, 11 → 16/17).
|
||||
|
||||
## 3. RoomConfig::Spawn::PickEntry — 0x82d290 (thiscall on Spawn, 1 float arg, ret 4)
|
||||
```cpp
|
||||
const Entry* Spawn::PickEntry(float r /*[0,1)*/) const {
|
||||
float target = r * sumWeights; // +0xc
|
||||
float acc = 0;
|
||||
for (u8 i = 0; i < entryCount /*+8*/; ++i) { // u8 counter
|
||||
acc += entries[i].weight; // +8 of 0xc-byte Entry
|
||||
if (acc > target) return &entries[i]; // comiss; ja (strict)
|
||||
}
|
||||
KAGE_LogMessage(1, "[warn] RoomConfig::Spawn::PickEntry did not terminate properly. Picking first entry: (%d, %d, %d, %f)\n",
|
||||
entries[0].type, entries[0].variant, entries[0].subtype, (double)entries[0].weight);
|
||||
return &entries[0];
|
||||
}
|
||||
```
|
||||
Callers always check `entryCount > 0` before calling it.
|
||||
|
||||
## 4. Runtime Weight (+0x34) modification and reset
|
||||
* **Reduced**: only in GetRandomRoom when `reduceWeight` is true (0x82cd72..0x82cd95): `w = max(1e-7, w*0.1)`. No other writer was found in native code. Lua exposes the `Weight` / `InitialWeight` properties (strings 0xb6a14c / 0xb735c4, used by bindings near 0x86be2d / 0x86bf71); I did not check whether they are writable.
|
||||
* **Reset (`Weight = InitialWeight` for every room of a stage/mode)**:
|
||||
* `RoomConfig::ResetStageWeights(stageId, mode)` at **0x82a9c0**. If the stage is not loaded it calls LoadStageBinary instead, which also gives fresh weights. Otherwise it loops over the rooms.
|
||||
* **Level::Init 0x744940** (log "Level::Init m_Stage %d, m_StageType %d Seed %u"), right after `ClearGeneratedRooms()` (call at 0x74510c):
|
||||
* Level stage 12 (Void) resets stb 1..17 except 13, both loaded and mode-resolved (0x74511c..0x7451cb).
|
||||
* Any other stage resets `GetStageID(stage, stageType, -1)` (0x7451dc..0x74526c).
|
||||
* Additionally, if stageType is 4/5 and (stage==4, or stage==3 with Labyrinth curse bit 2 set), it resets stb 29 (Mines; 0x7452af..0x745362).
|
||||
* Not greed: unless stage==13/the specific level-gen cases (stage 13, stage≤6 with g+0x2654c&0x10000, challenge g+0x26584==0x2c, stage 9), it calls `ResetStageWeights(0 /*special rooms*/, -1)` at 0x7453e7 and then generates (0x740e10).
|
||||
* Greed: it resets stb 0 inline (0x7453f9..0x74545a) and then calls 0x743550.
|
||||
* So the **special-room (stb 0) weights are reset on each normal level init**, except on Home (stage 13), Blue Womb (stage 9), challenge 0x2c, and stage≤6 with the g+0x2654c&0x10000 flag. Those go to the dedicated generators 0x74de30, 0x74a500, 0x7508c0 and 0x742ef0, and whether those reset stb 0 was not checked.
|
||||
* **Home generation 0x751650**: resets or loads stb 35 (mode 0).
|
||||
* **0x6fa0c0** (called from the shutdown path 0x9ab84a; probably Game::Exit/end-of-run): resets every loaded stage, 37 stages × 2 modes (0x6fa3c5..0x6fa41a).
|
||||
* **Generated rooms**: `RoomConfig::ClearGeneratedRooms` at **0x82d320** logs `"delete %d generated rooms.\n"` with count `+0x1e24`. For each list node it frees every Spawn's entries (`Room+0x40`/`+0x44`) and the spawn array, destroys the name string, frees the 0x64-byte node, and resets the list and count. It is called from Level::Init (0x74510c) and from 0x7477e5. Generated rooms are created by the Giant-curse merge (0x82d4a0 → 0x82de80 list insert).
|
||||
|
||||
## 5. From Room spawns to entities (high level)
|
||||
`Room::Init(RoomConfig::Room* cfg, RoomDescriptor* desc)` at **0x7f2800** (thiscall on `g+0x18300`, called from 0x73e8a2). Grid width is `Room+0xc` and height is `Room+0x10`. The grid-entity pointer array is `Room+0x24 + idx*4`, with indices up to 0x1bf (448 cells).
|
||||
|
||||
**Pass 1, pre-scan (0x7f319a..0x7f3339).**
|
||||
* It logs `"SpawnRNG seed: %u"` with `desc+0x5c` (SpawnSeed), then builds an RNG from that seed with kShifts[11] (2,7,7).
|
||||
* For each spawn i: `rng.Next()`, `f = toFloat`; if entryCount > 0 it calls `e = PickEntry(f)`.
|
||||
* It switches on `e->type` in 825..970 (table 0x7f7928/0x7f7908) and sets room or descriptor flags.
|
||||
* Type **970** (room-config meta entity) is handled by variant:
|
||||
* variant 0 → `desc+0x44 |= 0x200`
|
||||
* variant 1 → by subtype: 20 / 11 → local flags; 10 → `desc+0x44 |= 0x1000`; 0..3 → `Room+0x7460/0x7464 = table 0xc5d0e8[subtype]` (a direction vector)
|
||||
* variant 3 → `desc+0x44 |= 0x2000`
|
||||
* variant 4 → uses the grid position (0x7f342d)
|
||||
* Types 825/907, 829, 876/918, 882, 905 and 919 have their own cases.
|
||||
|
||||
**Pass 2, real spawn (0x7f39b3..0x7f3aff).** It restarts from the same `desc+0x5c` seed, so pass 1 and pass 2 make identical picks.
|
||||
```cpp
|
||||
RNG rng{desc->spawnSeed, kShifts[11]};
|
||||
for (u16 i = 0; i < cfg->spawnCount; ++i) {
|
||||
Spawn& s = cfg->spawns[i];
|
||||
u32 seed = rng.Next(); float f = toFloat(seed); // advanced even if entryCount==0
|
||||
int gridIdx = (s.x + 1) + (s.y + 1) * room->width; // stb x,y are relative to the inner area (no walls)
|
||||
if (s.entryCount == 0) continue;
|
||||
const Entry* e = s.PickEntry(f);
|
||||
if (!desc->set80.contains(gridIdx)) // std::set<int> at RoomDescriptor+0x80 (probably removed/restricted grid indices; meaning unverified)
|
||||
room->SpawnEntry(gridIdx, e, seed, false, false); // 0x7ed310
|
||||
}
|
||||
```
|
||||
**`Room::SpawnEntry(gridIdx, Entry*, seed, bool, bool)`** at **0x7ed310** (ret 0x14).
|
||||
* It copies the entry, then calls 0x7ec100 (entry transform/replacement; likely where MC_PRE_ROOM_ENTITY_SPAWN and stage replacements happen; unverified).
|
||||
* The per-entity seed RNG uses kShifts[35] (5,9,7).
|
||||
* Position of a grid index: `x = (idx % w)*40 + 40`, `y = (idx / w)*40 + 120` (0x7ee4dc, 0x815cef).
|
||||
* **type < 1000** spawns an entity via `Game::Spawn(type, variant, pos, Vector0, nullptr, subtype, seed)` (0x428b20). Special cases:
|
||||
* 970 (0x3ca) spawns nothing (returns true; 0x7ed936)
|
||||
* 969 (0x3c9) is special-cased (0x7ed93c)
|
||||
* 999 (0x3e7), 965 (0x3c5) and 911 (0x38f) are also special-cased
|
||||
* **type ≥ 1000** creates a grid entity: `CreateGridEntity(gridType, gridIdx)` (0x70b2e0), then `grid->variant = v`, then `Init(seed)` (0x709db0). The stb-to-GridEntityType mapping (0x7ede09..0x7ee64d):
|
||||
* 1000..1011: jump table at 0x7ee6a0 (1000 → ROCK 2, etc.)
|
||||
* 1300 → special case
|
||||
* 1400..1501: table at 0x7ee700 (fire places/poops → 14 POOP with variants, `desc+0x50++`)
|
||||
* 1900 → 3 (BLOCK)
|
||||
* 1901..1940: table at 0x7ee790 (10, 8, 9, 24 …)
|
||||
* 1999 → 15
|
||||
* 3000..3009: table at 0x7ee7c8; 3000 → PIT 7, `desc+0x54++`
|
||||
* 4000 → 11 (LOCK)
|
||||
* 4500 → 20 (PRESSURE_PLATE)
|
||||
* 5000 → 21 (STATUE) var 0; 5001 → 21 var 1
|
||||
* 6000/6001 → 7 (also 0x7ed9a4)
|
||||
* 6100 → 23 (TELEPORTER)
|
||||
* 9000 → 17 (TRAPDOOR) var 0; 9100 → 18 (CRAWLSPACE); 10000 → 19 (GRAVITY)
|
||||
* anything else → 1 (DECORATION)
|
||||
* 0x815ae0 is a separate re-spawn routine (shop restock for room types 2/22). It uses the same grid-index and position math and spawns only 5.150 entries, plus a 1000.15 poof.
|
||||
|
||||
## Uncertainties
|
||||
* The 0x82cdd0 argument meanings (a7, a8, a13 unused) were not checked against callers.
|
||||
* SeedEffect 79 has not been named. `g+0x26550` is assumed to be extra curses.
|
||||
* The meaning of `RoomDescriptor+0x80` and of the 0x7ec100 transform.
|
||||
* 0x6fa0c0 being "end of run". Its only direct caller is in the shutdown path, so a reset between runs in the same session may happen only through Level::Init. That means non-current stages and stb 0 in some flows keep their reduced weights.
|
||||
* The 0x82d4a0 merge internals (how the spawn offsets and doors are combined) were not decoded.
|
||||
Reference in new issue
Block a user