diff --git a/src/Offsets.h b/src/Offsets.h index 1c4b9ccd..ecfd9eae 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -13586,6 +13586,11 @@ enum Offsets { FUN_M2SCENE_COPY_MODEL = 0x00707400, // M2SceneDraw — `__thiscall(scene, pass)`; the bake draws 0 then 1. FUN_M2SCENE_DRAW = 0x00708900, + // The scene's clock, uint32 milliseconds: M2SceneAdvance (0x007074B0, + // `__thiscall(scene, ms)`, nothing for 0) passes +0x0C + ms to SetTime + // (0x00707490), which stores it here. A Model frame's update (slot 14, + // 0x0076D7F0) advances its scene by the truncated ms of each frame. + OFF_M2SCENE_TIME = 0x0C, // The world's object pick (0x00480A50, Ghidra): EnableRayHits, then // SetHitTestMode on each candidate and its children (0x00480D90), then // RayHit with retry 1, the ray in view space (the device view of the diff --git a/src/model/Scene.cpp b/src/model/Scene.cpp index f5dacfe6..2035bb31 100644 --- a/src/model/Scene.cpp +++ b/src/model/Scene.cpp @@ -71,6 +71,11 @@ // stops the scene clock: the frame's update runs without Model's // M2SceneAdvance, so every actor holds its pose. // +// ClassicAPI extensions on that clock: GetSceneTime, and After / NewTimer / +// NewTicker, C_Timer's queue and handles with deadlines in scene seconds, +// fired from the update right after the clock moves. A paused or hidden +// scene's clock stands still, and so do its timers. +// // XML: `drawLayer`, `fogNear` and `fogFar` (clamped at 0, as Model's loader // clamps them) and (FUN_XML_READ_COLOR, which arms the fog), after // the frame's own loader, and . Retail's @@ -118,6 +123,7 @@ #include "gx/Device.h" #include "model/Camera.h" #include "model/M2.h" +#include "time/Timer.h" #include "xml/FrameLoad.h" #include @@ -163,6 +169,9 @@ struct Fields { World::Backdrop *world; // SetWorldModel, owned, or null bool playWorldModelSounds; // SetPlayWorldModelSounds Actor *listener; // SetSoundListenerActor, or null; the frame owns its actors + // GetSceneTime: the seconds the M2 scene's clock has advanced since the + // frame was made, summed from each update's change so it never wraps. + double clock; }; constexpr size_t kObjectSize = Offsets::MODEL_FRAME_SIZE + sizeof(Fields); @@ -793,6 +802,7 @@ void Destroy(void *frame) { f.actors = nullptr; World::Free(f.world); f.world = nullptr; + Time::Timer::CancelOwned(frame); } Frame::Subclass::Class @@ -868,10 +878,18 @@ void __fastcall OnFrameUpdate(void *self, void *, float elapsedSec) { if (actor->model != nullptr && M2::Parent(actor->model) == nullptr && M2::IsLoaded(actor->model, 0, 0)) World::Settle(*world, *actor->ambience, self, actor->model, elapsedSec); } + void *m2Scene = Model::Pane::Scene(self); + const uint32_t before = m2Scene != nullptr ? Game::Read(m2Scene, Offsets::OFF_M2SCENE_TIME) : 0; if (F(self).paused) FrameBase(Offsets::VTBL_FRAME_ON_FRAME_UPDATE)(self, nullptr, elapsedSec); else g_class.Base(Offsets::VTBL_FRAME_ON_FRAME_UPDATE)(self, nullptr, elapsedSec); + // The scene's timers run on its clock, once it has moved this frame. + if (m2Scene != nullptr) { + const uint32_t advancedMs = Game::Read(m2Scene, Offsets::OFF_M2SCENE_TIME) - before; + F(self).clock += advancedMs / 1000.0; + } + Time::Timer::Fire(self, F(self).clock); // By index: an actor's script may create another. std::vector &actors = *F(self).actors; for (size_t i = 0; i < actors.size(); ++i) @@ -961,6 +979,7 @@ void *__fastcall CreateModelScene(void *parent) { f.world = nullptr; f.playWorldModelSounds = false; f.listener = nullptr; + f.clock = 0.0; InitLight(frame); InitFog(frame); InstallCamera(frame); @@ -1147,6 +1166,27 @@ int __fastcall Script_SetPaused(void *L) { return 0; } +int __fastcall Script_GetSceneTime(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + Game::Lua::PushNumber(L, F(frame).clock); + return 1; +} + +template +int __fastcall Script_Timer(void *L) { + static constexpr const char *kUsage[] = { + "Usage: scene:After(seconds, callback)", + "Usage: local cbObject = scene:NewTimer(seconds, callback)", + "Usage: local cbObject = scene:NewTicker(seconds, callback [, iterations])", + }; + void *frame = Self(L); + if (frame == nullptr) + return 0; + return Time::Timer::Script(L, 2, frame, F(frame).clock, kind, kUsage[static_cast(kind)]); +} + int __fastcall Script_Project3DPointTo2D(void *L) { void *frame = Self(L); if (frame == nullptr || !NumberArgs(L, 2, 3, Game::Lua::ObjectDisplayName(frame), @@ -1623,6 +1663,10 @@ const Game::Lua::FrameMethodEntry g_methods[] = { {"SetDrawLayer", &Script_SetDrawLayer}, {"GetDrawLayer", &Script_GetDrawLayer}, {"SetPaused", &Script_SetPaused}, + {"GetSceneTime", &Script_GetSceneTime}, + {"After", &Script_Timer}, + {"NewTimer", &Script_Timer}, + {"NewTicker", &Script_Timer}, {"SetGroundTerrain", &Script_SetGroundTerrain}, {"GetGroundTerrain", &Script_GetGroundTerrain}, {"SetWorldModel", &Script_SetWorldModel}, @@ -1758,6 +1802,28 @@ const Game::Doc::Field kFarFogRet[] = {Req("far", "number")}; const Game::Doc::Function kSetDrawLayer{"Sets the layer the scene draws in.", kLayerArg, {}}; const Game::Doc::Function kGetDrawLayer{"Returns the layer the scene draws in.", {}, kLayerRets}; const Game::Doc::Function kSetPaused{"Stops or restarts the actors' animations.", kPausedArgs, {}}; +const Game::Doc::Field kSceneTimeRet[] = {Req("seconds", "number")}; +const Game::Doc::Function kGetSceneTime{ + "Returns the seconds that the clock of the scene has run since the scene was made. The clock " + "stops while the scene is paused or hidden. The actors' animations use this clock.", + {}, kSceneTimeRet, nullptr, true}; +const Game::Doc::Field kTimerArgs[] = {Req("seconds", "number", "On the clock of the scene."), + Req("callback", "function")}; +const Game::Doc::Field kTickerArgs[] = {Req("seconds", "number", "On the clock of the scene."), + Req("callback", "function"), + Opt("iterations", "number", nullptr, "Without it, the ticker runs until it is cancelled.")}; +const Game::Doc::Field kTimerRet[] = { + Req("cbObject", "table", "Cancel() stops the timer. IsCancelled() returns true when the timer has stopped.")}; +const Game::Doc::Function kAfter{ + "Calls the callback once, after the clock of the scene has run for the seconds. As C_Timer.After, " + "on the clock of the scene.", + kTimerArgs, {}, nullptr, true}; +const Game::Doc::Function kNewTimer{ + "As scene:After, and returns a handle that can cancel the timer.", kTimerArgs, kTimerRet, nullptr, true}; +const Game::Doc::Function kNewTicker{ + "Calls the callback each time the clock of the scene runs for the seconds. As C_Timer.NewTicker, " + "on the clock of the scene.", + kTickerArgs, kTimerRet, nullptr, true}; const Game::Doc::Field kGroundTerrainArg[] = { Opt("terrainTypeID", "number", nullptr, "A TerrainType.dbc row: 0 Dirt, 1 Metallic, 2 Stone, 3 Snow, 4 Wood, 5 Grass, 6 Leaves, 7 " @@ -1963,6 +2029,10 @@ const Game::Doc::Method g_methodDocs[] = { {"SetDrawLayer", &kSetDrawLayer}, {"GetDrawLayer", &kGetDrawLayer}, {"SetPaused", &kSetPaused}, + {"GetSceneTime", &kGetSceneTime}, + {"After", &kAfter}, + {"NewTimer", &kNewTimer}, + {"NewTicker", &kNewTicker}, {"SetAllowOverlappedModels", &kSetAllowOverlappedModels}, {"GetAllowOverlappedModels", &kGetAllowOverlappedModels}, {"SetGroundTerrain", &kSetGroundTerrain}, diff --git a/src/time/Timer.cpp b/src/time/Timer.cpp index 1e7e8e9a..2ebd4644 100644 --- a/src/time/Timer.cpp +++ b/src/time/Timer.cpp @@ -11,6 +11,8 @@ // You should have received a copy of the GNU General Public License along with // ClassicAPI. If not, see . +#include "time/Timer.h" + #include "Game.h" #include "tick/WorldTick.h" @@ -40,6 +42,9 @@ namespace Time::Timer { // the new entry is appended after this tick's snapshot. A // callback that cancels another pending timer is also safe; we // re-check the cancel flag inside the fire pass. +// - Owners (Timer.h): a ModelScene's timers share the queue, the +// handles and the callback storage, with deadlines on the scene's +// clock; the scene fires its own, the WorldTick only C_Timer's. namespace { @@ -47,7 +52,8 @@ constexpr double TIMER_MIN_PERIOD = 0.0001; // tickers with period<=0 would tigh struct Entry { int id; - double deadline; // seconds since clock start, absolute + const void *owner; // null = C_Timer; else the object whose clock this is on + double deadline; // seconds on the owner's clock, absolute double period; // 0 = one-shot; >0 = ticker period int iterationsLeft; // -1 = infinite; 0 = mark for removal; >0 = countdown bool cancelled; @@ -56,11 +62,11 @@ struct Entry { std::vector g_timers; int g_nextID = 1; -// The earliest deadline of a live timer: a frame before it has nothing to -// fire and returns at once. Scheduling lowers it; the sweep at the end of a +// The earliest deadline of a live C_Timer timer: a frame before it has +// nothing to fire and returns at once. Scheduling lowers it; the sweep at the end of a // firing frame recomputes it. A timer cancelled first only costs one early // pass that fires nothing. -double g_nextDeadline = 0.0; +double g_nextDeadline = HUGE_VAL; // IDs due this frame (Tick pass 1), kept for its capacity. std::vector g_toFire; @@ -157,24 +163,21 @@ void PushCancelHandle(void *L, int id) { Game::Lua::SetTable(L, -3); } -// ----- Tick: fire ready timers ----------------------------------------- +// ----- Fire ready timers ----------------------------------------------- -void Tick() { +void FireDue(const void *owner, double now) { if (g_timers.empty()) return; - const double now = Now(); - if (now < g_nextDeadline) - return; void *L = Game::Lua::State(); if (L == nullptr) return; - // Pass 1: snapshot IDs of timers due to fire. Walking by index - // would invalidate on re-entrant scheduling; capture IDs and + // Pass 1: snapshot IDs of the owner's timers due to fire. Walking by + // index would invalidate on re-entrant scheduling; capture IDs and // re-lookup inside the fire pass. g_toFire.clear(); for (const auto &t : g_timers) { - if (!t.cancelled && t.iterationsLeft != 0 && t.deadline <= now) + if (t.owner == owner && !t.cancelled && t.iterationsLeft != 0 && t.deadline <= now) g_toFire.push_back(t.id); } @@ -218,7 +221,7 @@ void Tick() { } // Pass 3: sweep cancelled entries and release their registry refs, in - // one compacting pass, and find the next deadline among the rest. + // one compacting pass, and find the next C_Timer deadline among the rest. size_t keep = 0; g_nextDeadline = HUGE_VAL; for (const Entry &t : g_timers) { @@ -226,29 +229,37 @@ void Tick() { ReleaseCallback(L, t.id); continue; } - if (t.deadline < g_nextDeadline) + if (t.owner == nullptr && t.deadline < g_nextDeadline) g_nextDeadline = t.deadline; g_timers[keep++] = t; } g_timers.resize(keep); } +void Tick() { + const double now = Now(); + if (now < g_nextDeadline) + return; + FireDue(nullptr, now); +} + // ----- Scheduling -------------------------------------------------------- -int Schedule(void *L, int callbackStackIdx, double seconds, double period, - int iterations) { +int Schedule(void *L, int callbackStackIdx, const void *owner, double now, double seconds, + double period, int iterations) { const int id = g_nextID++; Game::Lua::PushValue(L, callbackStackIdx); StoreCallback(L, id); Entry e{}; e.id = id; - e.deadline = Now() + (seconds < 0 ? 0 : seconds); + e.owner = owner; + e.deadline = now + (seconds < 0 ? 0 : seconds); e.period = period; e.iterationsLeft = iterations; e.cancelled = false; g_timers.push_back(e); - if (g_timers.size() == 1 || e.deadline < g_nextDeadline) + if (owner == nullptr && e.deadline < g_nextDeadline) g_nextDeadline = e.deadline; return id; } @@ -256,50 +267,17 @@ int Schedule(void *L, int callbackStackIdx, double seconds, double period, // ----- Lua surface ------------------------------------------------------- int __fastcall Script_C_Timer_After(void *L) { - if (!Game::Lua::IsNumber(L, 1) || - Game::Lua::Type(L, 2) != Game::Lua::TYPE_FUNCTION) { - Game::Lua::Error(L, "Usage: C_Timer.After(seconds, callback)"); - return 0; - } - const double seconds = Game::Lua::ToNumber(L, 1); - Schedule(L, 2, seconds, /*period=*/0.0, /*iterations=*/1); - return 0; + return Script(L, 1, nullptr, Now(), Kind::After, "Usage: C_Timer.After(seconds, callback)"); } int __fastcall Script_C_Timer_NewTimer(void *L) { - if (!Game::Lua::IsNumber(L, 1) || - Game::Lua::Type(L, 2) != Game::Lua::TYPE_FUNCTION) { - Game::Lua::Error(L, - "Usage: local cbObject = C_Timer.NewTimer(seconds, callback)"); - return 0; - } - const double seconds = Game::Lua::ToNumber(L, 1); - const int id = Schedule(L, 2, seconds, /*period=*/0.0, /*iterations=*/1); - PushCancelHandle(L, id); - return 1; + return Script(L, 1, nullptr, Now(), Kind::NewTimer, + "Usage: local cbObject = C_Timer.NewTimer(seconds, callback)"); } int __fastcall Script_C_Timer_NewTicker(void *L) { - if (!Game::Lua::IsNumber(L, 1) || - Game::Lua::Type(L, 2) != Game::Lua::TYPE_FUNCTION) { - Game::Lua::Error(L, - "Usage: local cbObject = C_Timer.NewTicker(seconds, callback [, iterations])"); - return 0; - } - double seconds = Game::Lua::ToNumber(L, 1); - if (seconds < TIMER_MIN_PERIOD) - seconds = TIMER_MIN_PERIOD; - int iterations = -1; // infinite by default - if (Game::Lua::IsNumber(L, 3)) { - const double v = Game::Lua::ToNumber(L, 3); - if (v >= 1.0) - iterations = static_cast(v); - // negative / zero / non-numeric → keep -1 (infinite), matching - // modern WoW's behavior where omitted iterations means forever. - } - const int id = Schedule(L, 2, seconds, /*period=*/seconds, iterations); - PushCancelHandle(L, id); - return 1; + return Script(L, 1, nullptr, Now(), Kind::NewTicker, + "Usage: local cbObject = C_Timer.NewTicker(seconds, callback [, iterations])"); } void RegisterLuaFunctions() { @@ -310,6 +288,50 @@ void RegisterLuaFunctions() { } // namespace +int Script(void *L, int first, const void *owner, double now, Kind kind, const char *usage) { + if (!Game::Lua::IsNumber(L, first) || Game::Lua::Type(L, first + 1) != Game::Lua::TYPE_FUNCTION) { + Game::Lua::Error(L, "%s", usage); + return 0; + } + double seconds = Game::Lua::ToNumber(L, first); + if (kind != Kind::NewTicker) { + const int id = Schedule(L, first + 1, owner, now, seconds, /*period=*/0.0, /*iterations=*/1); + if (kind == Kind::After) + return 0; + PushCancelHandle(L, id); + return 1; + } + if (seconds < TIMER_MIN_PERIOD) + seconds = TIMER_MIN_PERIOD; + int iterations = -1; // infinite by default + if (Game::Lua::IsNumber(L, first + 2)) { + const double v = Game::Lua::ToNumber(L, first + 2); + if (v >= 1.0) + iterations = static_cast(v); + // negative / zero / non-numeric → keep -1 (infinite), matching + // modern WoW's behavior where omitted iterations means forever. + } + const int id = Schedule(L, first + 1, owner, now, seconds, /*period=*/seconds, iterations); + PushCancelHandle(L, id); + return 1; +} + +void Fire(const void *owner, double now) { FireDue(owner, now); } + +void CancelOwned(const void *owner) { + void *L = Game::Lua::State(); + size_t keep = 0; + for (const Entry &t : g_timers) { + if (t.owner == owner) { + if (L != nullptr) + ReleaseCallback(L, t.id); + continue; + } + g_timers[keep++] = t; + } + g_timers.resize(keep); +} + // Cancel every pending timer and release its Lua registry callback before a // /reload (or logout) resets the Lua state. Otherwise g_timers would carry // entries whose "ClassicAPI.Timer.N" registry callbacks died with the reset: @@ -323,6 +345,7 @@ void PrepareForReload() { ReleaseCallback(L, t.id); g_timers.clear(); g_nextID = 1; + g_nextDeadline = HUGE_VAL; } static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; diff --git a/src/time/Timer.h b/src/time/Timer.h new file mode 100644 index 00000000..2576f437 --- /dev/null +++ b/src/time/Timer.h @@ -0,0 +1,38 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +namespace Time::Timer { + +// The C_Timer queue, shared with other clocks. Each timer has an owner: +// null for C_Timer (its own clock, fired from the WorldTick), or an object +// with a clock of its own, which fires its timers itself with Fire(owner, +// now) and drops them with CancelOwned(owner). Deadlines are in the owner's +// seconds. Handles and callbacks are C_Timer's. + +enum class Kind { After, NewTimer, NewTicker }; + +// The body of C_Timer.After / NewTimer / NewTicker with the seconds at stack +// index `first` (the callback, then the ticker's iterations, after it), on +// `owner`'s clock at `now`. Raises `usage` on bad arguments. Returns the +// count of Lua results. +int Script(void *L, int first, const void *owner, double now, Kind kind, const char *usage); + +// Runs `owner`'s timers that are due at `now`, in the order they were made. +void Fire(const void *owner, double now); + +// Drops `owner`'s timers; their handles answer IsCancelled true. +void CancelOwned(const void *owner); + +} // namespace Time::Timer