// See anm2.hpp. Build with SSE floats and no FMA contraction to keep float results identical to the // game: e.g. `g++ -O2 -msse2 -mfpmath=sse -ffp-contract=off`. #include "anm2.hpp" #include #include #include #include #include #include #include namespace anm2 { // ============================================================================================= // Logging // ============================================================================================= static LogFn g_log = [](int level, const std::string& msg) { std::fprintf(stderr, "[%x] %s", level, msg.c_str()); }; void SetLogger(LogFn fn) { g_log = std::move(fn); } static void Log(int level, const char* fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); std::vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); if (g_log) g_log(level, buf); } // ============================================================================================= // Minimal XML DOM (the game uses rapidxml in-situ with default flags; .anm2 only needs elements // and attributes). Lookups by name are exact and case-sensitive like rapidxml's. // ============================================================================================= namespace xml { struct Attr { std::string name, value; }; struct Node { std::string name; std::vector attrs; std::vector children; const Node* child(const char* n) const { // rapidxml first_node(name) 0x413c70 for (auto& c : children) if (c.name == n) return &c; return nullptr; } }; class Parser { public: explicit Parser(const std::string& s) : s_(s) {} bool parse(Node& doc) { doc.name.clear(); return parseChildren(doc, /*top=*/true); } private: const std::string& s_; size_t p_ = 0; bool eof() const { return p_ >= s_.size(); } void ws() { while (!eof() && (unsigned char)s_[p_] <= ' ') ++p_; } bool starts(const char* t) const { return s_.compare(p_, std::strlen(t), t) == 0; } bool skipPast(const char* t) { size_t q = s_.find(t, p_); if (q == std::string::npos) { p_ = s_.size(); return false; } p_ = q + std::strlen(t); return true; } static bool nameChar(char c) { return !((unsigned char)c <= ' ' || c == '/' || c == '>' || c == '=' || c == '<' || c == '?' || c == '!'); } static void appendUtf8(std::string& o, unsigned long cp) { if (cp < 0x80) o += char(cp); else if (cp < 0x800) { o += char(0xC0 | (cp >> 6)); o += char(0x80 | (cp & 0x3F)); } else if (cp < 0x10000) { o += char(0xE0 | (cp >> 12)); o += char(0x80 | ((cp >> 6) & 0x3F)); o += char(0x80 | (cp & 0x3F)); } else { o += char(0xF0 | (cp >> 18)); o += char(0x80 | ((cp >> 12) & 0x3F)); o += char(0x80 | ((cp >> 6) & 0x3F)); o += char(0x80 | (cp & 0x3F)); } } static std::string decode(const std::string& v) { // rapidxml default: decode entities in attr values std::string o; for (size_t i = 0; i < v.size(); ++i) { if (v[i] != '&') { o += v[i]; continue; } size_t semi = v.find(';', i); if (semi == std::string::npos) { o += v[i]; continue; } std::string e = v.substr(i + 1, semi - i - 1); if (e == "amp") o += '&'; else if (e == "lt") o += '<'; else if (e == "gt") o += '>'; else if (e == "quot") o += '"'; else if (e == "apos") o += '\''; else if (!e.empty() && e[0] == '#') { unsigned long cp = (e.size() > 1 && e[1] == 'x') ? std::strtoul(e.c_str() + 2, nullptr, 16) : std::strtoul(e.c_str() + 1, nullptr, 10); appendUtf8(o, cp); } else { o += v[i]; continue; } i = semi; } return o; } bool parseChildren(Node& parent, bool top) { for (;;) { size_t lt = s_.find('<', p_); if (lt == std::string::npos) { p_ = s_.size(); return top; } p_ = lt; if (starts(""); continue; } if (starts(""); continue; } if (starts(""); continue; } if (starts(""); continue; } if (starts(""); return !top; } ++p_; Node n; while (!eof() && nameChar(s_[p_])) n.name += s_[p_++]; if (n.name.empty()) return false; // "expected element name" for (;;) { ws(); if (eof()) return false; if (s_[p_] == '/') { p_ += 2; parent.children.push_back(std::move(n)); break; } if (s_[p_] == '>') { ++p_; if (!parseChildren(n, false)) return false; parent.children.push_back(std::move(n)); break; } Attr a; while (!eof() && nameChar(s_[p_])) a.name += s_[p_++]; if (a.name.empty()) return false; // "expected attribute name" ws(); if (eof() || s_[p_] != '=') return false; ++p_; ws(); if (eof() || (s_[p_] != '"' && s_[p_] != '\'')) return false; char q = s_[p_++]; size_t e = s_.find(q, p_); if (e == std::string::npos) return false; a.value = decode(s_.substr(p_, e - p_)); p_ = e + 1; n.attrs.push_back(std::move(a)); } } } }; } // namespace xml // ============================================================================================= // Value converters (inlined everywhere in 0x40ed50) // ============================================================================================= static int ToInt(const std::string& v) { return std::atoi(v.c_str()); } static float ToFloat(const std::string& v) { return (float)std::atof(v.c_str()); } static float ToScale(const std::string& v) { float f = ToFloat(v); return f / 100.0f; } static float ToColor(const std::string& v) { float f = ToFloat(v); return f / 255.0f; } static bool ToBool(const std::string& v) { // 0x4100b6 if (v.empty()) return false; if (v == "true" || v == "True") return true; return std::atoi(v.c_str()) != 0; } // fmodf as the game does it: 0x499d20 = (float)fmod((double)x, (double)y) static float FmodF(float x, float y) { return (float)std::fmod((double)x, (double)y); } // Spritesheet path resolver 0x67f670 (approximation; only skimmed): '\' -> '/', path is relative // to the .anm2's directory, ".." pops a directory, result truncated to 0x104 chars. static std::string ResolveRelativePath(const std::string& anmPath, const std::string& rel) { auto split = [](std::string s) { for (char& c : s) if (c == '\\') c = '/'; std::vector parts; std::string cur; for (char c : s) { if (c == '/') { if (!cur.empty()) parts.push_back(cur); cur.clear(); } else cur += c; } if (!cur.empty()) parts.push_back(cur); return parts; }; std::vector dir = split(anmPath); if (!dir.empty()) dir.pop_back(); // drop file name for (auto& part : split(rel)) { if (part == "..") { if (!dir.empty()) dir.pop_back(); } else if (part != ".") dir.push_back(part); } std::string out = (!anmPath.empty() && (anmPath[0] == '/' || anmPath[0] == '\\')) ? "/" : ""; for (size_t i = 0; i < dir.size(); ++i) { if (i) out += '/'; out += dir[i]; } if (out.size() > 0x104) out.resize(0x104); return out; } // ============================================================================================= // Color helpers // ============================================================================================= Color LerpColor(const Color& a, const Color& b, float t) { // 0x6832e0: a*(1-t) + b*t, all 11 floats float it = 1.0f - t; Color o; for (int i = 0; i < 4; ++i) o.tint[i] = a.tint[i] * it + b.tint[i] * t; for (int i = 0; i < 4; ++i) o.colorize[i] = a.colorize[i] * it + b.colorize[i] * t; for (int i = 0; i < 3; ++i) o.offset[i] = a.offset[i] * it + b.offset[i] * t; return o; } void MulColor(Color& self, const Color& other) { // 0x6831c0 for (int i = 0; i < 4; ++i) self.tint[i] = other.tint[i] * self.tint[i]; if (other.colorize[0] + other.colorize[1] + other.colorize[2] != 0.0f) { if (self.colorize[0] + self.colorize[1] + self.colorize[2] == 0.0f) for (int i = 0; i < 4; ++i) self.colorize[i] = other.colorize[i]; else for (int i = 0; i < 4; ++i) self.colorize[i] = (self.colorize[i] + other.colorize[i]) * 0.5f; } for (int i = 0; i < 3; ++i) self.offset[i] = other.offset[i] + self.offset[i]; } static float WrapAngle(float x) { if (std::fabs(x) > 360.0f) x = FmodF(x, 360.0f); if (x > 180.0f) x -= 360.0f; else if (x < -180.0f) x += 360.0f; return x; } float LerpAngleDeg(float a, float b, float t) { // 0x6828b0 a = WrapAngle(a); b = WrapAngle(b); if (std::fabs(b - a) > 180.0f) { if (b > a) a += 360.0f; else b += 360.0f; } return WrapAngle((b - a) * t + a); } // ============================================================================================= // Load-time interpolation: every interpolated keyframe (except the last) is expanded into `delay` // one-tick frames. Nothing is interpolated at runtime. // ============================================================================================= void InterpolateLayerFrames(std::vector& src) { // 0x415170 std::vector dst; dst.reserve(src.size()); int tick = 0; const unsigned count = (unsigned)src.size(); for (unsigned i = 0; i < count; ++i) { const AnimationFrame& a = src[i]; if (i != count - 1 && a.interpolated) { if (i + 1 >= (unsigned)kMaxFrames) Log(0x10, "too many frames after interpolation\n"); const AnimationFrame& b = src[i + 1]; float t = 0.0f; const float step = 1.0f / (float)a.delay; for (int k = 0; k < a.delay; ++k) { // delay <= 0 emits nothing AnimationFrame o; o.xCrop = a.xCrop; o.yCrop = a.yCrop; o.width = a.width; o.height = a.height; o.x = (b.x - a.x) * t + a.x; o.y = (b.y - a.y) * t + a.y; o.xScale = (b.xScale - a.xScale) * t + a.xScale; o.yScale = (b.yScale - a.yScale) * t + a.yScale; o.xPivot = a.xPivot; o.yPivot = a.yPivot; o.delay = 1; o.visible = a.visible; o.color = LerpColor(a.color, b.color, t); o.rotation = LerpAngleDeg(a.rotation, b.rotation, t); o.interpolated = a.interpolated; o.start = tick; o.end = tick + 1; ++tick; dst.push_back(o); t = step + t; // accumulated, not k/delay } } else { AnimationFrame o = a; o.start = tick; o.end = tick + a.delay; tick += a.delay; dst.push_back(o); } } src.swap(dst); } void InterpolateNullFrames(std::vector& src) { // 0x414e00 std::vector dst; dst.reserve(src.size()); int tick = 0; const unsigned count = (unsigned)src.size(); for (unsigned i = 0; i < count; ++i) { const NullFrame& a = src[i]; if (i != count - 1 && a.interpolated) { if (i + 1 >= (unsigned)kMaxFrames) Log(0x10, "too many frames after interpolation\n"); const NullFrame& b = src[i + 1]; float t = 0.0f; const float step = 1.0f / (float)a.delay; for (int k = 0; k < a.delay; ++k) { NullFrame o; o.x = (b.x - a.x) * t + a.x; o.y = (b.y - a.y) * t + a.y; o.xScale = (b.xScale - a.xScale) * t + a.xScale; o.yScale = (b.yScale - a.yScale) * t + a.yScale; o.delay = 1; o.visible = a.visible; o.color = LerpColor(a.color, b.color, t); o.rotation = LerpAngleDeg(a.rotation, b.rotation, t); o.interpolated = a.interpolated; o.start = tick; o.end = tick + 1; ++tick; dst.push_back(o); t = step + t; } } else { NullFrame o = a; o.start = tick; o.end = tick + a.delay; tick += a.delay; dst.push_back(o); } } src.swap(dst); } // ============================================================================================= // RootAnimation baking (inlined twice in the parser: layers 0x411df1, nulls 0x413017). // Each track frame is cut wherever a root-frame boundary falls inside it; each piece gets the // transform of the root frame active during it. Pieces keep the source `delay` (only start/end are // updated) - the runtime only uses start/end. // ============================================================================================= template static std::vector ApplyRoot(std::vector& src, const std::vector& root, const std::string& path) { std::vector dst; const int rootCount = (int)root.size(); NullFrame identity; // ORIGINAL: with 0 root frames it applies stale scratch slot root[0] (undefined) int g = 0, r = 0; for (Fr& s : src) { s.start = g; for (int k = 0; k < s.delay; ++k) { ++g; const 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; // a root frame ended on this tick } if (!emit && k == s.delay - 1) emit = true; // last tick of the source frame if (!emit) continue; if ((int)dst.size() >= kMaxFrames) Log(0x10, "%s: too many frames after interpolation/root frame adjustment\n", path.c_str()); const NullFrame& R = rootCount ? root[prev] : identity; Fr o = s; o.x = o.x * R.xScale + R.x; o.y = R.yScale * o.y + R.y; o.visible = o.visible && R.visible; o.xScale = o.xScale * R.xScale; o.yScale = R.yScale * o.yScale; MulColor(o.color, R.color); o.rotation = R.rotation + o.rotation; o.end = g; dst.push_back(o); s.start = g; } } return dst; } // ============================================================================================= // Frame attribute readers. Only tint (1) and offset (0) are reset per frame in the original; any // other missing attribute keeps whatever was left in a reused 5000-entry scratch buffer. // Here missing attributes take the struct defaults instead (pos 0, scale 1, delay 1, visible, rot 0). // ============================================================================================= static void ReadNullFrame(const xml::Node& fr, NullFrame& f) { float tint[4] = {1, 1, 1, 1}, off[3] = {0, 0, 0}; for (auto& a : fr.attrs) { const std::string& n = a.name; const std::string& v = a.value; if (n == "XPosition") f.x = ToFloat(v); else if (n == "YPosition") f.y = ToFloat(v); else if (n == "Delay") f.delay = ToInt(v); else if (n == "Visible") f.visible = ToBool(v); else if (n == "XScale") f.xScale = ToScale(v); else if (n == "YScale") f.yScale = ToScale(v); else if (n == "RedTint") tint[0] = ToColor(v); else if (n == "GreenTint") tint[1] = ToColor(v); else if (n == "BlueTint") tint[2] = ToColor(v); else if (n == "AlphaTint") tint[3] = ToColor(v); else if (n == "RedOffset") off[0] = ToColor(v); else if (n == "GreenOffset") off[1] = ToColor(v); else if (n == "BlueOffset") off[2] = ToColor(v); else if (n == "Rotation") f.rotation = ToFloat(v); else if (n == "Interpolated") f.interpolated = ToBool(v); } for (int i = 0; i < 4; ++i) f.color.tint[i] = tint[i]; for (int i = 0; i < 3; ++i) f.color.offset[i] = off[i]; } static void ReadLayerFrame(const xml::Node& fr, AnimationFrame& f) { float tint[4] = {1, 1, 1, 1}, off[3] = {0, 0, 0}; for (auto& a : fr.attrs) { const std::string& n = a.name; const std::string& v = a.value; if (n == "XPosition") f.x = ToFloat(v); else if (n == "YPosition") f.y = ToFloat(v); else if (n == "XPivot") f.xPivot = ToFloat(v); else if (n == "YPivot") f.yPivot = ToFloat(v); else if (n == "Width") f.width = ToFloat(v); else if (n == "Height") f.height = ToFloat(v); else if (n == "XScale") f.xScale = ToScale(v); else if (n == "YScale") f.yScale = ToScale(v); else if (n == "Delay") f.delay = ToInt(v); else if (n == "Visible") f.visible = ToBool(v); else if (n == "XCrop") f.xCrop = ToFloat(v); else if (n == "YCrop") f.yCrop = ToFloat(v); else if (n == "RedTint") tint[0] = ToColor(v); else if (n == "GreenTint") tint[1] = ToColor(v); else if (n == "BlueTint") tint[2] = ToColor(v); else if (n == "AlphaTint") tint[3] = ToColor(v); else if (n == "RedOffset") off[0] = ToColor(v); else if (n == "GreenOffset") off[1] = ToColor(v); else if (n == "BlueOffset") off[2] = ToColor(v); else if (n == "Rotation") f.rotation = ToFloat(v); else if (n == "Interpolated") f.interpolated = ToBool(v); } for (int i = 0; i < 4; ++i) f.color.tint[i] = tint[i]; for (int i = 0; i < 3; ++i) f.color.offset[i] = off[i]; } // Required child lookup. ORIGINAL: never NULL-checked; a missing element crashes the game. static const xml::Node* Need(const xml::Node* parent, const char* name, const std::string& path) { const xml::Node* n = parent ? parent->child(name) : nullptr; if (!n) Log(0x10, "%s: missing <%s> (the original crashes here)\n", path.c_str(), name); return n; } // ============================================================================================= // AnmCache::LoadFile 0x40ed50 // ============================================================================================= bool ParseAnm2(const std::string& path, const std::string& text, AnmData& d) { d = AnmData{}; // entry->Clear() (ORIGINAL: defaultAnimation survives Clear(); see notes) xml::Node doc; if (!xml::Parser(text).parse(doc)) { Log(0x10, "%s: XML parse error\n", path.c_str()); return false; } const xml::Node* actor = Need(&doc, "AnimatedActor", path); const xml::Node* content = Need(actor, "Content", path); if (!content) return false; // ---- Spritesheets (not stored; each layer receives a copy of its sheet's path) ---- // Children are never filtered by tag name. const xml::Node* sheets = Need(content, "Spritesheets", path); if (!sheets) return false; std::string sheetPath[kMaxLayers]; std::string pathBuf; // ORIGINAL: char[260] not cleared between elements -> a Path-less sheet reuses the previous one int sheetCount = 0; for (auto& e : sheets->children) { int id = kMaxLayers; for (auto& a : e.attrs) { if (a.name == "Path") pathBuf = ResolveRelativePath(path, a.value); else if (a.name == "Id") id = ToInt(a.value); } if (id >= kMaxLayers || id != sheetCount) Log(0x10, "%s: invalid spritesheet id %d\n", path.c_str(), id); if (id >= 0 && id < kMaxLayers) sheetPath[id] = pathBuf; // ORIGINAL: stored at [id] unchecked ++sheetCount; } // ---- Layers ---- const xml::Node* layers = Need(content, "Layers", path); if (!layers) return false; LayerInfo layer[kMaxLayers]; int layerCount = 0; for (auto& e : layers->children) { std::string name; int id = kMaxLayers; int sheet = -1; for (auto& a : e.attrs) { if (a.name == "Name") name = a.value; else if (a.name == "Id") id = ToInt(a.value); else if (a.name == "SpritesheetId") sheet = ToInt(a.value); } if (id >= kMaxLayers || id != layerCount) Log(0x10, "%s: invalid layer id %d\n", path.c_str(), id); if (sheet < 0 || sheet >= sheetCount) Log(0x10, "%s: invalid spritesheet id %d\n", path.c_str(), sheet); if (id >= 0 && id < kMaxLayers) { LayerInfo& L = layer[id]; L.spritesheetPath = (sheet >= 0 && sheet < kMaxLayers) ? sheetPath[sheet] : std::string(); L.id = id; L.spritesheetId = sheet; L.name = name; } ++layerCount; } if (layerCount == 0) Log(0x10, "%s: no layers\n", path.c_str()); // only logged for (int i = 0; i < layerCount && i < kMaxLayers; ++i) d.layers.push_back(layer[i]); // ---- Nulls ---- const xml::Node* nulls = Need(content, "Nulls", path); if (!nulls) return false; std::string nullName[kMaxLayers]; int nullCount = 0; for (auto& e : nulls->children) { int id = kMaxLayers; std::string name; for (auto& a : e.attrs) { if (a.name == "Id") id = ToInt(a.value); else if (a.name == "Name") name = a.value; } if (id >= kMaxLayers || id != nullCount) Log(0x10, "%s: invalid Null ID %d\n", path.c_str(), id); if (id >= 0 && id < kMaxLayers) nullName[id] = name; ++nullCount; } for (int i = 0; i < nullCount && i < kMaxLayers; ++i) d.nullNames.push_back(nullName[i]); // ---- Events (max 16) ---- const xml::Node* events = Need(content, "Events", path); if (!events) return false; std::string eventName[kMaxEvents]; int eventCount = 0; for (auto& e : events->children) { int id = kMaxEvents; std::string name; for (auto& a : e.attrs) { if (a.name == "Id") id = ToInt(a.value); else if (a.name == "Name") name = a.value; } if (id >= kMaxEvents || id != eventCount) Log(0x10, "%s: invalid Event ID %d\n", path.c_str(), id); if (id >= 0 && id < kMaxEvents) eventName[id] = name; ++eventCount; } for (int i = 0; i < eventCount && i < kMaxEvents; ++i) d.eventNames.push_back(eventName[i]); // ---- Animations ---- const xml::Node* anims = Need(actor, "Animations", path); if (!anims) return false; for (auto& a : anims->attrs) if (a.name == "DefaultAnimation") d.defaultAnimation = a.value; // Iteration starts at first_node("Animation") and then follows next_sibling WITHOUT a name check. size_t firstAnim = anims->children.size(); for (size_t i = 0; i < anims->children.size(); ++i) if (anims->children[i].name == "Animation") { firstAnim = i; break; } for (size_t ai = firstAnim; ai < anims->children.size(); ++ai) { const xml::Node& an = anims->children[ai]; if ((int)d.animations.size() >= kMaxAnimations) Log(0x10, "%s: more than %d animations (the original overflows its stack here)\n", path.c_str(), kMaxAnimations); AnimationData A; for (auto& a : an.attrs) { if (a.name == "Name") A.name = a.value; else if (a.name == "FrameNum") A.frameNum = ToInt(a.value); else if (a.name == "Loop") A.loop = ToBool(a.value); } A.index = (int)d.animations.size(); // RootAnimation const xml::Node* rootNode = Need(&an, "RootAnimation", path); std::vector root; if (rootNode) { int t = 0; for (auto& fr : rootNode->children) { if ((int)root.size() >= kMaxFrames) Log(0x10, "%s: too many root frames\n", path.c_str()); NullFrame f; ReadNullFrame(fr, f); f.start = t; f.end = t + f.delay; t = f.end; root.push_back(f); } } InterpolateNullFrames(root); // LayerAnimations if (const xml::Node* las = Need(&an, "LayerAnimations", path)) { for (auto& ln : las->children) { if ((int)A.layerAnims.size() >= kMaxLayers) Log(0x10, "%s: too many animation layers\n", path.c_str()); LayerAnimation L; for (auto& a : ln.attrs) { if (a.name == "LayerId") L.layerId = ToInt(a.value); else if (a.name == "Visible") L.visible = ToBool(a.value); } std::vector frames; int t = 0; for (auto& fr : ln.children) { if ((int)frames.size() >= kMaxFrames) Log(0x10, "%s: too many animation frames\n", path.c_str()); AnimationFrame f; ReadLayerFrame(fr, f); f.start = t; f.end = t + f.delay; t = f.end; frames.push_back(f); } InterpolateLayerFrames(frames); L.frames = ApplyRoot(frames, root, path); A.layerAnims.push_back(std::move(L)); } // map[LayerId] = index; last duplicate wins. // ORIGINAL: unchecked; LayerId -1 overwrites Loop (+0x34), >=64 writes past the array. for (int i = 0; i < (int)A.layerAnims.size(); ++i) { int id = A.layerAnims[i].layerId; if (id >= 0 && id < kMaxLayers) A.layerMap[id] = i; } } // NullAnimations (no id validation, no map) if (const xml::Node* nas = Need(&an, "NullAnimations", path)) { for (auto& nn : nas->children) { if ((int)A.nullAnims.size() >= kMaxLayers) Log(0x10, "%s: too many null layers\n", path.c_str()); NullAnimation N; for (auto& a : nn.attrs) { if (a.name == "NullId") N.nullId = ToInt(a.value); else if (a.name == "Visible") N.visible = ToBool(a.value); } std::vector frames; int t = 0; for (auto& fr : nn.children) { if ((int)frames.size() >= kMaxFrames) Log(0x10, "%s: too many null frames\n", path.c_str()); NullFrame f; ReadNullFrame(fr, f); f.start = t; f.end = t + f.delay; t = f.end; frames.push_back(f); } InterpolateNullFrames(frames); N.frames = ApplyRoot(frames, root, path); A.nullAnims.push_back(std::move(N)); } } // Triggers (max 128; EventId and AtFrame are raw ints, never validated) if (const xml::Node* trs = Need(&an, "Triggers", path)) { for (auto& te : trs->children) { if ((int)A.triggers.size() >= kMaxTriggers) Log(0x10, "%s: too many triggers\n", path.c_str()); Trigger T; // ORIGINAL: local array not reset -> missing attrs keep a previous trigger's values for (auto& a : te.attrs) { if (a.name == "EventId") T.eventId = ToInt(a.value); else if (a.name == "AtFrame") T.atFrame = ToInt(a.value); } A.triggers.push_back(T); } } d.animations.push_back(std::move(A)); } return true; } bool LoadAnm2File(const std::string& path, AnmData& out) { std::ifstream f(path, std::ios::binary); if (!f) { Log(1, "ERROR Could not open %s\n", path.c_str()); return false; } std::stringstream ss; ss << f.rdbuf(); return ParseAnm2(path, ss.str(), out); } // ============================================================================================= // AnimationState // ============================================================================================= static int FloorToInt(float f) { // floor() on the double, stored back to float, then cvttss2si float fl = (float)std::floor((double)f); return (int)fl; } int AnimationState::FindEvent(const char* name) const { if (!anim_) Log(0x10, "AnimationData is NULL\n"); // logged, not returned const AnmData* d = owner_->data_; if (!d) return -1; for (size_t i = 0; i < d->eventNames.size(); ++i) if (std::strcmp(d->eventNames[i].c_str(), name) == 0) return (int)i; return -1; } // 0x408830: hard reset. Index arrays are reallocated to the new animation's sizes and filled // with -1, frame = -1.0f, not playing, both event masks cleared. void AnimationState::SetAnimationData(const AnimationData* a) { anim_ = a; layerFrameIdx_.assign(a ? a->layerAnims.size() : 0, -1); nullFrameIdx_.assign(a ? a->nullAnims.size() : 0, -1); frame_ = -1.0f; playing_ = false; eventsThisUpdate_ = 0; eventsSinceStart_ = 0; } // 0x408970: switch animation, keep frame / playing / masks / existing per-track indices. // ORIGINAL BUGS (not reproduced): // * it memcpy's the OLD layer count into the NEW index array -> heap overflow when the new animation // has fewer layer-anims; // * when the null-anim count changes to a non-zero value, the new null array is stored into the // LAYER slot (`mov [esi+8], ebx` @0x408b6a) and the null slot is left NULL -> the next Update // dereferences NULL. I.e. Sprite:SetAnimation(name, false) between animations with different // non-zero null counts crashes the game. void AnimationState::ChangeAnimationKeepFrame(const AnimationData* a) { size_t nl = a ? a->layerAnims.size() : 0, nn = a ? a->nullAnims.size() : 0; if (layerFrameIdx_.size() != nl) layerFrameIdx_.resize(nl, -1); if (nullFrameIdx_.size() != nn) nullFrameIdx_.resize(nn, -1); anim_ = a; } // 0x408c90. Exact float equality between the current frame and AtFrame. Both masks get the bit; // `bts reg, id` means bit (eventId & 31). void AnimationState::FireTriggersAtCurrentFrame() { if (!anim_) { Log(0x10, "AnimationData is NULL\n"); return; } // ORIGINAL: continues and crashes for (const Trigger& t : anim_->triggers) { if ((float)t.atFrame == frame_) { eventsThisUpdate_ |= 1u << (t.eventId & 31); eventsSinceStart_ |= 1u << (t.eventId & 31); } } } // 0x40a1b0 void AnimationState::Rewind() { frame_ = 0.0f; eventsThisUpdate_ = 0; eventsSinceStart_ = 0; FireTriggersAtCurrentFrame(); // events on frame 0 fire immediately on Play for (int& i : layerFrameIdx_) i = 0; for (int& i : nullFrameIdx_) i = 0; } // 0x408b90: move forward while the current keyframe has ended. Never moves backward. void AnimationState::AdvanceLayerPosition(int i, float t) { if (!anim_ || i < 0 || i >= (int)anim_->layerAnims.size()) { Log(0x10, "id out of bounds\n"); return; } const auto& frames = anim_->layerAnims[i].frames; int& idx = layerFrameIdx_[i]; while (idx >= 0 && idx + 1 < (int)frames.size() && t >= (float)frames[idx].end) ++idx; } // 0x408c10 void AnimationState::AdvanceNullLayerPosition(int i, float t) { if (!anim_ || i < 0 || i >= (int)anim_->nullAnims.size()) { Log(0x10, "id out of bounds\n"); return; } const auto& frames = anim_->nullAnims[i].frames; int& idx = nullFrameIdx_[i]; while (idx >= 0 && idx + 1 < (int)frames.size() && t >= (float)frames[idx].end) ++idx; } // 0x408d00: step one whole frame at a time up to `target`, firing triggers on every integer frame // passed. eventsThisUpdate is cleared first, so it reflects only frames crossed by this call. void AnimationState::AdvancePosition(int target) { int cur = FloorToInt(frame_); if (target < cur) Log(0x10, "Animation::AdvancePosition cannot go backward (new: %d, cur: %d)\n", target, cur); const float t = (float)target; eventsThisUpdate_ = 0; while (t > frame_) { frame_ = (float)std::floor((double)frame_) + 1.0f; FireTriggersAtCurrentFrame(); } for (int i = 0; i < (int)anim_->layerAnims.size(); ++i) AdvanceLayerPosition(i, t); for (int i = 0; i < (int)anim_->nullAnims.size(); ++i) AdvanceNullLayerPosition(i, t); } // 0x409030 void AnimationState::Update() { if (!anim_ || !playing_) return; // NB: event masks are NOT cleared while stopped const float oldFrame = frame_; const float newFrame = frame_ + owner_->playbackSpeed; const int nf = FloorToInt(newFrame); if (nf >= anim_->frameNum) { if (anim_->loop) { // Frames between the old position and FrameNum-1 are NOT stepped through (only matters // for speed > 1), and the fractional overshoot is dropped. Rewind(); return; } int last = anim_->frameNum - 1; if (last >= FloorToInt(oldFrame)) AdvancePosition(last); playing_ = false; // frame_ stays at FrameNum-1 (an integer) return; } AdvancePosition(nf); // with speed < 0 this logs "cannot go backward" and fires nothing frame_ = newFrame; // keep the fractional part } // 0x408e00: jump directly to a frame. Clamped to just below FrameNum; triggers fire only if the // clamped frame equals AtFrame exactly. eventsSinceStart is NOT cleared. Track indices are reset to 0 // and advanced to the UNCLAMPED value. void AnimationState::SetFrame(float f) { float maxF = std::nextafterf((float)anim_->frameNum, 0.0f); frame_ = (maxF < f) ? maxF : f; // minss eventsThisUpdate_ = 0; FireTriggersAtCurrentFrame(); for (int i = 0; i < (int)anim_->layerAnims.size(); ++i) { layerFrameIdx_[i] = 0; AdvanceLayerPosition(i, f); } for (int i = 0; i < (int)anim_->nullAnims.size(); ++i) { nullFrameIdx_[i] = 0; AdvanceNullLayerPosition(i, f); } } // 0x408ef0 / 0x40a7e0: layerId goes through layerMap. void AnimationState::SetLayerFrame(int layerId, int frame) { const AnmData* d = owner_->data_; if (!anim_) return; if (layerId < 0 || !d || layerId >= (int)d->layers.size()) { Log(0x10, "LayerId out of bounds\n"); return; } int la = (layerId < kMaxLayers) ? anim_->layerMap[layerId] : -1; if (la < 0 || la >= (int)anim_->layerAnims.size()) { Log(0x10, "id out of bounds\n"); return; // ORIGINAL: logs, then writes layerFrameIdx[-1] = 0 anyway } layerFrameIdx_[la] = 0; AdvanceLayerPosition(la, (float)frame); } // 0x408fc0: index is the null-ANIMATION index (no map), bounds-checked against the sprite's null count. void AnimationState::SetNullLayerFrame(int i, int frame) { const AnmData* d = owner_->data_; if (i < 0 || !d || i >= (int)d->nullNames.size()) Log(0x10, "layerId out of bounds\n"); if (!anim_ || i < 0 || i >= (int)anim_->nullAnims.size()) { Log(0x10, "id out of bounds\n"); return; } nullFrameIdx_[i] = 0; AdvanceNullLayerPosition(i, (float)frame); } bool AnimationState::IsEventTriggered(const char* name) const { // 0x40add0 int i = FindEvent(name); return i >= 0 && (eventsThisUpdate_ & (1u << i)) != 0; } bool AnimationState::WasEventTriggered(const char* name) const { // 0x40ae70 int i = FindEvent(name); return i >= 0 && (eventsSinceStart_ & (1u << i)) != 0; } // 0x40af10: nearest trigger frame strictly after the current frame (truncated, not floored), or -1. int AnimationState::NextEventTrigger(const char* name) const { int ev = FindEvent(name); if (ev < 0) return -1; int best = -1, bestDist = -1; const int cur = (int)frame_; // cvttss2si for (const Trigger& t : anim_->triggers) { if (t.eventId != ev) continue; int dist = t.atFrame - cur; if (dist > 0 && (bestDist < 0 || dist < bestDist)) { best = t.atFrame; bestDist = dist; } } return best; } const AnimationFrame* AnimationState::GetLayerFrame(int layerId) const { // 0x40a220 if (!anim_) { Log(0x10, "AnimationData is NULL\n"); return nullptr; } const AnmData* d = owner_->data_; if (layerId < 0 || !d || layerId >= (int)d->layers.size()) Log(0x10, "LayerId out of bounds\n"); // ORIGINAL quirk: the second bounds test is `layerId > layerCount` (jg), i.e. off by one. if (layerId < 0 || layerId >= kMaxLayers || !d || layerId > (int)d->layers.size()) return nullptr; int la = anim_->layerMap[layerId]; if (la < 0 || la >= (int)anim_->layerAnims.size()) return nullptr; int fi = layerFrameIdx_[la]; const auto& fr = anim_->layerAnims[la].frames; if (fi < 0 || fi >= (int)fr.size()) return nullptr; return &fr[fi]; } const NullFrame* AnimationState::GetNullFrameByID(int nullId) const { // 0x40ac70: first match with a valid index if (!anim_) { Log(0x10, "AnimationData is NULL\n"); return nullptr; } for (size_t i = 0; i < anim_->nullAnims.size(); ++i) { const NullAnimation& n = anim_->nullAnims[i]; int fi = nullFrameIdx_[i]; if (n.nullId == nullId && fi >= 0 && fi < (int)n.frames.size()) return &n.frames[fi]; } return nullptr; } const NullFrame* AnimationState::GetNullFrame(const char* name) const { // 0x40ace0 const AnmData* d = owner_->data_; if (!d) return nullptr; for (size_t i = 0; i < d->nullNames.size(); ++i) if (std::strcmp(d->nullNames[i].c_str(), name) == 0) return GetNullFrameByID((int)i); return nullptr; } // ============================================================================================= // Sprite (ANM2) // ============================================================================================= void Sprite::Load(const AnmData* data) { data_ = data; // ORIGINAL: borrowed pointers into the AnmCache entry main_.SetAnimationData(nullptr); overlay_.SetAnimationData(nullptr); loaded_ = true; // ORIGINAL: set even if the cache load failed } void Sprite::Reset() { main_.SetAnimationData(nullptr); overlay_.SetAnimationData(nullptr); data_ = nullptr; playbackSpeed = 1.0f; overlayRenderFirst = false; loaded_ = false; } // 0x409100: both states advance with the same PlaybackSpeed. void Sprite::Update() { if (!loaded_) return; main_.Update(); overlay_.Update(); } const AnimationData* Sprite::FindAnimation(const char* name) const { if (data_) for (const AnimationData& a : data_->animations) if (std::strcmp(a.name.c_str(), name) == 0) return &a; return nullptr; } // 0x40a5d0 / 0x40aaf0 bool Sprite::SetAnimation(const char* name, bool reset) { const AnimationData* a = FindAnimation(name); if (!a) { Log(1, "[warn] no animation named %s\n", name); return false; } if (reset) main_.SetAnimationData(a); else main_.ChangeAnimationKeepFrame(a); return true; } bool Sprite::SetOverlayAnimation(const char* name, bool reset) { const AnimationData* a = FindAnimation(name); if (!a) { Log(1, "[warn] no animation named %s\n", name); return false; } if (reset) overlay_.SetAnimationData(a); else overlay_.ChangeAnimationKeepFrame(a); return true; } // Shared logic of Play / PlayOverlay / PlayRandom / PlayIndex. Without `force`, playing the // animation that is already current does nothing if it is non-looping (even when it has finished), // or if it is looping and still playing. A stopped looping animation restarts. static bool ShouldRestart(const AnimationState& s, const char* name, bool force) { if (force || !s.anim()) return true; if (std::strcmp(s.anim()->name.c_str(), name) != 0) return true; if (!s.anim()->loop) return false; return !s.playing(); } void Sprite::Play(const char* name, bool force) { // 0x40a380 if (!ShouldRestart(main_, name, force)) return; if (SetAnimation(name, true)) { main_.Rewind(); main_.setPlaying(true); } } void Sprite::PlayOverlay(const char* name, bool force) { // 0x40a940 if (!ShouldRestart(overlay_, name, force)) return; if (SetOverlayAnimation(name, true)) { overlay_.Rewind(); overlay_.setPlaying(true); } } void Sprite::PlayRandom(uint32_t seed) { // 0x40a2b0: animation index = seed % count (unsigned) if (!data_ || data_->animations.empty()) { Log(1, "[warn] PlayRandom: no animations\n"); return; } const char* name = data_->animations[seed % (uint32_t)data_->animations.size()].name.c_str(); if (!ShouldRestart(main_, name, false)) return; if (SetAnimation(name, true)) { main_.Rewind(); main_.setPlaying(true); } } void Sprite::PlayIndex(int index) { // 0x40a400 if (!data_ || index < 0 || index >= (int)data_->animations.size()) { Log(1, "[warn] Animation index out of range!\n"); return; } const char* name = data_->animations[index].name.c_str(); if (!ShouldRestart(main_, name, false)) return; if (SetAnimation(name, true)) { main_.Rewind(); main_.setPlaying(true); } } // 0x40a6e0: selects (hard reset), jumps, and STOPS the main animation. void Sprite::SetFrame(const char* name, int frame) { if (!SetAnimation(name, true) || !main_.anim()) return; main_.SetFrame((float)frame); main_.setPlaying(false); } void Sprite::SetFrame(float frame) { if (main_.anim()) main_.SetFrame(frame); } // 0x40a740 (keeps playing) void Sprite::SetLastFrame() { // 0x40a760: does not stop playback if (main_.anim()) main_.AdvancePosition(main_.anim()->frameNum - 1); } int Sprite::GetFrame() const { return main_.anim() ? FloorToInt(main_.frame()) : -1; } // 0x40a780 void Sprite::Stop() { if (main_.anim()) main_.setPlaying(false); } // 0x40a910 bool Sprite::IsPlaying(const char* name) const { // 0x40a4d0 if (!main_.anim() || !main_.playing()) return false; return name[0] == 0 || std::strcmp(main_.anim()->name.c_str(), name) == 0; } bool Sprite::IsFinished(const char* name) const { // 0x40a550 if (!main_.anim()) return name[0] == 0; if (main_.playing()) return false; return name[0] == 0 || std::strcmp(main_.anim()->name.c_str(), name) == 0; } // 0x40b030 / 0x40b090: main state only (Repentogon adds overlay variants). bool Sprite::IsEventTriggered(const char* name) const { return main_.anim() && main_.IsEventTriggered(name); } bool Sprite::WasEventTriggered(const char* name) const { return main_.anim() && main_.WasEventTriggered(name); } void Sprite::SetLayerFrame(int layerId, int frame) { if (main_.anim()) main_.SetLayerFrame(layerId, frame); } // 0x40abf0: unlike SetFrame(name, frame), does NOT stop the overlay. void Sprite::SetOverlayFrame(const char* name, int frame) { if (!SetOverlayAnimation(name, true) || !overlay_.anim()) return; overlay_.SetFrame((float)frame); } void Sprite::SetOverlayFrame(int frame) { if (overlay_.anim()) overlay_.SetFrame((float)frame); } // 0x40ac30 int Sprite::GetOverlayFrame() const { return overlay_.anim() ? (int)overlay_.frame() : -1; } // 0x40ac50: truncates void Sprite::StopOverlay() { if (overlay_.anim()) overlay_.setPlaying(false); } // 0x40a9c0 void Sprite::RemoveOverlay() { overlay_.SetAnimationData(nullptr); } // 0x40ac60 bool Sprite::IsOverlayPlaying(const char* name) const { // 0x40a9f0 if (!overlay_.anim() || !overlay_.playing()) return false; return name[0] == 0 || std::strcmp(overlay_.anim()->name.c_str(), name) == 0; } bool Sprite::IsOverlayFinished(const char* name) const { // 0x40aa70 if (!overlay_.anim()) return name[0] == 0; if (overlay_.playing()) return false; return name[0] == 0 || std::strcmp(overlay_.anim()->name.c_str(), name) == 0; } } // namespace anm2