diff --git a/Config/DefaultEngine.ini b/Config/DefaultEngine.ini index 71ea000..9e2cf2d 100644 --- a/Config/DefaultEngine.ini +++ b/Config/DefaultEngine.ini @@ -1,6 +1,6 @@ [/Script/EngineSettings.GameMapsSettings] -GameDefaultMap=/Game/Maps/L_LuaDemo -EditorStartupMap=/Game/Maps/L_LuaDemo +GameDefaultMap=/Game/Maps/L_Bootstrap +EditorStartupMap=/Game/Maps/L_Bootstrap GlobalDefaultGameMode=/Script/UnrealLuaDemo.LuaGameModeBase GameInstanceClass=/Script/UnrealLuaDemo.LuaGameInstance diff --git a/Config/DefaultGame.ini b/Config/DefaultGame.ini index fab42f4..79164e0 100644 --- a/Config/DefaultGame.ini +++ b/Config/DefaultGame.ini @@ -104,6 +104,8 @@ bSkipMovies=False +IniSectionDenylist=/Script/AndroidFileServerEditor.AndroidFileServerRuntimeSettings +DirectoriesToAlwaysCook=(Path="/NNEDenoiser") +DirectoriesToAlwaysCook=(Path="/Game/Generated") ++DirectoriesToAlwaysCook=(Path="/Game/Maps") ++DirectoriesToAlwaysCook=(Path="/Game/UI") bRetainStagedDirectory=False CustomStageCopyHandler= diff --git a/Content/Generated/DA_LuaBundle.uasset b/Content/Generated/DA_LuaBundle.uasset index 2e37f08..4f68dc2 100644 Binary files a/Content/Generated/DA_LuaBundle.uasset and b/Content/Generated/DA_LuaBundle.uasset differ diff --git a/Content/Maps/L_Bootstrap.umap b/Content/Maps/L_Bootstrap.umap new file mode 100644 index 0000000..42e27dc Binary files /dev/null and b/Content/Maps/L_Bootstrap.umap differ diff --git a/Content/Maps/L_LuaDemo.umap b/Content/Maps/L_LuaDemo.umap deleted file mode 100644 index a7f2796..0000000 Binary files a/Content/Maps/L_LuaDemo.umap and /dev/null differ diff --git a/Content/UI/Textures/T_MiniSettingsIcon.uasset b/Content/UI/Textures/T_MiniSettingsIcon.uasset new file mode 100644 index 0000000..46e073e Binary files /dev/null and b/Content/UI/Textures/T_MiniSettingsIcon.uasset differ diff --git a/Content/UI/WBP_MiniSettings.uasset b/Content/UI/WBP_MiniSettings.uasset new file mode 100644 index 0000000..fb72d8d Binary files /dev/null and b/Content/UI/WBP_MiniSettings.uasset differ diff --git a/Script/lua/Framework/Bootstrap.lua b/Script/lua/Framework/Bootstrap.lua deleted file mode 100644 index e65e1c4..0000000 --- a/Script/lua/Framework/Bootstrap.lua +++ /dev/null @@ -1,55 +0,0 @@ -local ____exports = __module.env -local Log = __MODULE__.Import("Framework.Log", __module) -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -local HotReload = __MODULE__.Import("Framework.HotReload", __module) -function ____exports.Shutdown() - Log.Info("Lua GameFramework shutting down...") - EventBus.Clear() - ____exports.GameInstance = nil - ____exports.IsInitialized = false - _G.GameFramework = nil -end -____exports.Version = "0.2.0" ---- --- @module_data -____exports.IsInitialized = false ---- --- @module_data -____exports.GameInstance = nil -function ____exports.Init(gameInstance) - ____exports.GameInstance = gameInstance - ____exports.IsInitialized = true - _G.GameFramework = { - Log = Log, - EventBus = EventBus, - HotReload = HotReload, - Bootstrap = {Version = ____exports.Version, Init = ____exports.Init, Shutdown = ____exports.Shutdown}, - GameInstance = gameInstance - } - Log.Info("Lua GameFramework initialized (version=%s, Lua=%s)", ____exports.Version, _VERSION) -end -function __module.StashData(env, to) - local ____has = to.__has__ - if not ____has then - ____has = {} - to.__has__ = ____has - end - to.IsInitialized = ____exports.IsInitialized - ____has.IsInitialized = true - to.GameInstance = ____exports.GameInstance - ____has.GameInstance = true -end -function __module.RestoreData(env, from) - local ____has = from.__has__ - if not ____has then - return - end - if ____has.IsInitialized then - ____exports.IsInitialized = from.IsInitialized - end - if ____has.GameInstance then - ____exports.GameInstance = from.GameInstance - end -end -function __module.UpdateImports() -end diff --git a/Script/lua/Framework/EventBus.lua b/Script/lua/Framework/EventBus.lua deleted file mode 100644 index 6f4a109..0000000 --- a/Script/lua/Framework/EventBus.lua +++ /dev/null @@ -1,122 +0,0 @@ -local ____exports = __module.env ---- --- @module_data -local Listeners = {} -function ____exports.On(eventName, callback, owner) - assert( - type(eventName) == "string", - "EventBus.On: eventName must be a string" - ) - assert( - type(callback) == "function", - "EventBus.On: callback must be a function" - ) - local list = Listeners[eventName] - if not list then - list = {} - Listeners[eventName] = list - end - do - local i = 0 - while i < #list do - local entry = list[i + 1] - if entry.callback == callback and entry.owner == owner then - return - end - i = i + 1 - end - end - list[#list + 1] = {callback = callback, owner = owner} -end -function ____exports.Off(eventName, callback, owner) - local list = Listeners[eventName] - if not list then - return - end - do - local i = #list - 1 - while i >= 0 do - local entry = list[i + 1] - if entry.callback == callback and (owner == nil or entry.owner == owner) then - table.remove(list, i + 1) - end - i = i - 1 - end - end -end -function ____exports.OffAllForOwner(owner) - if owner == nil then - return - end - for _, list in pairs(Listeners) do - if list ~= nil then - do - local i = #list - 1 - while i >= 0 do - if list[i + 1].owner == owner then - table.remove(list, i + 1) - end - i = i - 1 - end - end - end - end -end -function ____exports.Emit(eventName, ...) - local list = Listeners[eventName] - if not list then - return - end - local snapshot = {} - do - local i = 0 - while i < #list do - snapshot[i + 1] = list[i + 1] - i = i + 1 - end - end - do - local i = 0 - while i < #snapshot do - local entry = snapshot[i + 1] - local ok - local err - if entry.owner ~= nil then - ok, err = pcall(entry.callback, entry.owner, ...) - else - ok, err = pcall(entry.callback, ...) - end - if not ok then - print(string.format( - "[UnrealLuaDemo][ERROR] EventBus(%s): %s", - eventName, - tostring(err) - )) - end - i = i + 1 - end - end -end -function ____exports.Clear() - Listeners = {} -end -function __module.StashData(env, to) - local ____has = to.__has__ - if not ____has then - ____has = {} - to.__has__ = ____has - end - to.Listeners = Listeners - ____has.Listeners = true -end -function __module.RestoreData(env, from) - local ____has = from.__has__ - if not ____has then - return - end - if ____has.Listeners then - Listeners = from.Listeners - end -end -function __module.UpdateImports() -end diff --git a/Script/lua/Framework/HotReload.lua b/Script/lua/Framework/HotReload.lua deleted file mode 100644 index e38c272..0000000 --- a/Script/lua/Framework/HotReload.lua +++ /dev/null @@ -1,76 +0,0 @@ -local ____exports = __module.env -local Log = __MODULE__.Import("Framework.Log", __module) -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -____exports.EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload" -____exports.EVENT_AFTER_RELOAD = "Framework.AfterHotReload" -local function CollectLoadedHotReloadModules() - local modules = {} - if __MODULE__ == nil then - return modules - end - for name in pairs(__MODULE__.AllLoadedModules()) do - if type(name) == "string" and name ~= "Framework.HotReload" and ((string.match(name, "^Game%.")) ~= nil or (string.match(name, "^Framework%.")) ~= nil) then - modules[#modules + 1] = name - end - end - table.sort(modules) - return modules -end ---- 单文件热更指定模块(完全基于 Lib/Module.lua 的 __MODULE__.ReimportSafely,零入侵 UnLua)。 -function ____exports.ReloadModule(moduleName) - if type(moduleName) ~= "string" or moduleName == "" then - return false, "Invalid module name" - end - if __MODULE__ == nil then - return false, "__MODULE__ runtime is not initialized" - end - if __MODULE__.GetModuleByName(moduleName) == nil then - Log.Warn("Module '%s' is not loaded yet, skipping hot-reload.", moduleName) - return false, "Module not loaded: " .. moduleName - end - Log.Info("Hot-reloading module via __MODULE__: %s", moduleName) - EventBus.Emit(____exports.EVENT_BEFORE_RELOAD, moduleName) - local ok, err = __MODULE__.ReimportSafely(moduleName) - if not ok then - Log.Error( - "__MODULE__.ReimportSafely('%s') failed: %s", - moduleName, - tostring(err) - ) - return false, err - end - EventBus.Emit(____exports.EVENT_AFTER_RELOAD, moduleName) - Log.Info("Successfully hot-reloaded module: %s", moduleName) - return true -end ---- 批量热更所有已加载的业务/框架模块(Game.* / Framework.*)。 -function ____exports.ReloadAll() - local managedModules = CollectLoadedHotReloadModules() - Log.Info("Triggering HotReload via __MODULE__ (modules=%d)...", #managedModules) - EventBus.Emit(____exports.EVENT_BEFORE_RELOAD, "*") - local allOk = true - do - local i = 0 - while i < #managedModules do - local modName = managedModules[i + 1] - local ok, err = __MODULE__.ReimportSafely(modName) - if not ok then - Log.Error( - "__MODULE__.ReimportSafely('%s') failed: %s", - modName, - tostring(err) - ) - allOk = false - end - i = i + 1 - end - end - EventBus.Emit(____exports.EVENT_AFTER_RELOAD, "*") - Log.Info( - "HotReload completed (ok=%s).", - tostring(allOk) - ) - return allOk -end -function __module.UpdateImports() -end diff --git a/Script/lua/Framework/Log.lua b/Script/lua/Framework/Log.lua deleted file mode 100644 index 333cdd8..0000000 --- a/Script/lua/Framework/Log.lua +++ /dev/null @@ -1,31 +0,0 @@ -local ____exports = __module.env ---- --- @noSelfInFile -local TAG = "[UnrealLuaDemo]" -local function FormatMessage(level, fmt, ...) - local args = {...} - local fmtStr = tostring(fmt) - local msg - if #args > 0 then - local ok, formatted = pcall( - string.format, - fmtStr, - table.unpack(args) - ) - msg = ok and formatted or fmtStr - else - msg = fmtStr - end - return string.format("%s[%s] %s", TAG, level, msg) -end -function ____exports.Info(fmt, ...) - print(FormatMessage("INFO", fmt, ...)) -end -function ____exports.Warn(fmt, ...) - print(FormatMessage("WARN", fmt, ...)) -end -function ____exports.Error(fmt, ...) - print(FormatMessage("ERROR", fmt, ...)) -end -function __module.UpdateImports() -end diff --git a/Script/lua/Game/LuaCharacter.lua b/Script/lua/Game/LuaCharacter.lua deleted file mode 100644 index f2d0447..0000000 --- a/Script/lua/Game/LuaCharacter.lua +++ /dev/null @@ -1,13 +0,0 @@ -local ____exports = __module.env -local Log = __MODULE__.Import("Framework.Log", __module) -function ____exports.OnBeginPlay(_character) - Log.Info("LuaCharacter.OnBeginPlay()") -end -function ____exports.OnEndPlay(_character, endPlayReason) - Log.Info( - "LuaCharacter.OnEndPlay(reason=%s)", - tostring(endPlayReason) - ) -end -function __module.UpdateImports() -end diff --git a/Script/lua/Game/LuaDemoActor.lua b/Script/lua/Game/LuaDemoActor.lua deleted file mode 100644 index 406a373..0000000 --- a/Script/lua/Game/LuaDemoActor.lua +++ /dev/null @@ -1,330 +0,0 @@ -local ____lualib = require("lualib_bundle") -local __TS__New = ____lualib.__TS__New -local ____exports = __module.env -local Log = __MODULE__.Import("Framework.Log", __module) -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -local HotReload = __MODULE__.Import("Framework.HotReload", __module) -local globalPingCount, globalReloadCount -____exports.DEMO_VERSION = "v1" ---- 目标旋转速度(度/秒,直接驱动方块自转速度,热更后下一帧立即生效) -____exports.ACTOR_SPIN_SPEED = 60 ---- 当前展示配色(热更修改颜色值与名称后,__module.OnReimport 立即刷新方块材质与 3D 文本) -____exports.DEMO_COLORS = { - { - Name = "Cyan", - R = 0.08, - G = 0.78, - B = 0.95, - A = 1 - }, - { - Name = "Gold", - R = 0.98, - G = 0.72, - B = 0.12, - A = 1 - }, - { - Name = "Magenta", - R = 0.92, - G = 0.22, - B = 0.65, - A = 1 - }, - { - Name = "Lime", - R = 0.25, - G = 0.9, - B = 0.35, - A = 1 - }, - { - Name = "Orange", - R = 0.98, - G = 0.42, - B = 0.14, - A = 1 - } -} ---- --- @noSelf -local function MakeLinearColor(c) - return UE.FLinearColor(c.R, c.G, c.B, c.A) -end ---- --- @noSelf -local function IsActorAlive(actor) - if actor == nil then - return false - end - if UE ~= nil and UE.UKismetSystemLibrary ~= nil and UE.UKismetSystemLibrary.IsValid ~= nil then - return UE.UKismetSystemLibrary.IsValid(actor) - end - return true -end -____exports.DemoActorController = __TS__DefineClass("DemoActorController", __module) -local DemoActorController = ____exports.DemoActorController -DemoActorController.name = "DemoActorController" -function DemoActorController.prototype.____constructor(self, actor) - self.elapsedTime = 0 - self.textRefreshTimer = 0 - self.tickCount = 0 - self.pingCount = 0 - self.reloadCount = 0 - self.colorIndex = 0 - self.hasLoggedTick = false - self.actor = actor - self._tmpDeltaRot = UE.FRotator(0, 0, 0) -end -function DemoActorController.prototype.IsValid(self) - return IsActorAlive(self.actor) -end -function DemoActorController.prototype.GetSpinSpeed(self) - return ____exports.ACTOR_SPIN_SPEED -end -function DemoActorController.prototype.GetCurrentColor(self) - return ____exports.DEMO_COLORS[self.colorIndex + 1] or ____exports.DEMO_COLORS[1] -end -function DemoActorController.prototype.OnBeginPlay(self) - EventBus.On("Demo.Ping", self.OnDemoPing, self) - EventBus.On(HotReload.EVENT_AFTER_RELOAD, self.OnAfterHotReload, self) - self:ApplyCurrentColor() - self:RefreshStatusText() - Log.Info( - "LuaDemoActor.OnBeginPlay() ready! version=%s speed=%.1f color=%s Lua=%s", - ____exports.DEMO_VERSION, - self:GetSpinSpeed(), - self:GetCurrentColor().Name, - _VERSION - ) - local msg = string.format( - "[UnLua Demo] Pure-TS Actor active (%s | Speed=%.0f | Color=%s) - [Space] Ping, [R] HotReload", - ____exports.DEMO_VERSION, - self:GetSpinSpeed(), - self:GetCurrentColor().Name - ) - UE.UKismetSystemLibrary.PrintString( - self.actor, - msg, - true, - true, - UE.FLinearColor(0.2, 1, 0.4, 1), - 8 - ) -end -function DemoActorController.prototype.OnTick(self, deltaSeconds) - self.elapsedTime = self.elapsedTime + deltaSeconds - self.tickCount = self.tickCount + 1 - if not self.hasLoggedTick then - self.hasLoggedTick = true - Log.Info( - "LuaDemoActor.OnTick() first tick verified (dt=%.4f, speed=%.1f)", - deltaSeconds, - self:GetSpinSpeed() - ) - end - local yawDelta = self:GetSpinSpeed() * deltaSeconds - local pitchDelta = yawDelta * 0.35 - self._tmpDeltaRot.Pitch = pitchDelta - self._tmpDeltaRot.Yaw = yawDelta - self._tmpDeltaRot.Roll = 0 - self.actor:AddCubeLocalRotation(self._tmpDeltaRot) - local zOffset = math.sin(self.elapsedTime * (self.actor.BobFrequency or 2)) * (self.actor.BobAmplitude or 25) - self.actor:SetCubeVerticalOffset(zOffset) - self.textRefreshTimer = self.textRefreshTimer + deltaSeconds - if self.textRefreshTimer >= 0.2 then - self.textRefreshTimer = 0 - self:RefreshStatusText() - end -end -function DemoActorController.prototype.OnDemoPing(self, sourceName) - self.pingCount = self.pingCount + 1 - globalPingCount = globalPingCount + 1 - self.colorIndex = (self.colorIndex + 1) % #____exports.DEMO_COLORS - local colorEntry = self:ApplyCurrentColor() - self:RefreshStatusText() - local msg = string.format( - "[UnLua Demo] Ping #%d from %s -> Cube color: %s (Speed=%.0f)", - self.pingCount, - tostring(sourceName), - colorEntry.Name, - self:GetSpinSpeed() - ) - Log.Info(msg) - UE.UKismetSystemLibrary.PrintString( - self.actor, - msg, - true, - true, - MakeLinearColor(colorEntry), - 3 - ) -end -function DemoActorController.prototype.OnAfterHotReload(self, moduleName) - self.reloadCount = self.reloadCount + 1 - globalReloadCount = globalReloadCount + 1 - self:ApplyCurrentColor() - self:RefreshStatusText() - local msg = string.format( - "[UnLua Demo] HotReload #%d applied! target=%s | version=%s | Speed=%.0f | Color=%s", - self.reloadCount, - tostring(moduleName), - ____exports.DEMO_VERSION, - self:GetSpinSpeed(), - self:GetCurrentColor().Name - ) - Log.Info(msg) - UE.UKismetSystemLibrary.PrintString( - self.actor, - msg, - true, - true, - UE.FLinearColor(1, 0.85, 0.2, 1), - 4 - ) -end -function DemoActorController.prototype.ResetToPrimaryColor(self) - self.colorIndex = 0 -end -function DemoActorController.prototype.ApplyCurrentColor(self) - local colorEntry = self:GetCurrentColor() - self.actor:SetCubeColor(MakeLinearColor(colorEntry)) - return colorEntry -end -function DemoActorController.prototype.RefreshStatusText(self) - local colorEntry = self:GetCurrentColor() - local text = string.format( - "Pure-TS Actor (%s | %s)\nSpeed: %.0f deg/s | Color: %s\nTime: %.1fs | Pings: %d | Reloads: %d\n[Space] Ping | [R] HotReload", - _VERSION, - ____exports.DEMO_VERSION, - self:GetSpinSpeed(), - colorEntry.Name, - self.elapsedTime, - self.pingCount, - self.reloadCount - ) - self.actor:SetStatusText(text) -end -function DemoActorController.prototype.OnEndPlay(self, _endPlayReason) - EventBus.OffAllForOwner(self) - Log.Info("LuaDemoActor.OnEndPlay(ticks=%d, pings=%d)", self.tickCount, self.pingCount) -end ---- --- @module_data -local activeControllers = {} ---- --- @module_data -globalPingCount = 0 ---- --- @module_data -globalReloadCount = 0 ---- --- @noSelf -local function GetActorKey(actor) - if actor.GetName ~= nil then - return actor:GetName() - end - return tostring(actor) -end ---- --- @noSelf -function ____exports.OnBeginPlay(actor) - local key = GetActorKey(actor) - local old = activeControllers[key] - if old ~= nil then - old:OnEndPlay(0) - end - local ctrl = __TS__New(____exports.DemoActorController, actor) - activeControllers[key] = ctrl - ctrl:OnBeginPlay() -end ---- --- @noSelf -function ____exports.OnTick(actor, deltaSeconds) - local ctrl = activeControllers[GetActorKey(actor)] - if ctrl ~= nil then - ctrl:OnTick(deltaSeconds) - end -end ---- --- @noSelf -function ____exports.OnEndPlay(actor, endPlayReason) - local key = GetActorKey(actor) - local ctrl = activeControllers[key] - if ctrl ~= nil then - ctrl:OnEndPlay(endPlayReason) - activeControllers[key] = nil - end -end ---- --- @noSelf -function ____exports.GetGlobalStats() - return { - pings = globalPingCount, - reloads = globalReloadCount, - version = ____exports.DEMO_VERSION, - spinSpeed = ____exports.ACTOR_SPIN_SPEED, - primaryColor = ____exports.DEMO_COLORS[1].Name - } -end ---- --- @noSelf -function ____exports.GetActiveControllerCount() - local count = 0 - for _, ctrl in pairs(activeControllers) do - if ctrl ~= nil then - count = count + 1 - end - end - return count -end -__module.OnReimport = function() - for key, ctrl in pairs(activeControllers) do - if ctrl ~= nil then - if ctrl:IsValid() then - ctrl:ResetToPrimaryColor() - ctrl:ApplyCurrentColor() - ctrl:RefreshStatusText() - else - activeControllers[key] = nil - end - end - end - Log.Info( - "Game.LuaDemoActor OnReimport applied! version=%s speed=%.1f color=%s activeActors=%d", - ____exports.DEMO_VERSION, - ____exports.ACTOR_SPIN_SPEED, - ____exports.DEMO_COLORS[1].Name, - ____exports.GetActiveControllerCount() - ) -end -function __module.StashData(env, to) - local ____has = to.__has__ - if not ____has then - ____has = {} - to.__has__ = ____has - end - to.activeControllers = activeControllers - ____has.activeControllers = true - to.globalPingCount = globalPingCount - ____has.globalPingCount = true - to.globalReloadCount = globalReloadCount - ____has.globalReloadCount = true -end -function __module.RestoreData(env, from) - local ____has = from.__has__ - if not ____has then - return - end - if ____has.activeControllers then - activeControllers = from.activeControllers - end - if ____has.globalPingCount then - globalPingCount = from.globalPingCount - end - if ____has.globalReloadCount then - globalReloadCount = from.globalReloadCount - end -end -function __module.UpdateImports() -end diff --git a/Script/lua/Game/LuaGameInstance.lua b/Script/lua/Game/LuaGameInstance.lua deleted file mode 100644 index 073bdc8..0000000 --- a/Script/lua/Game/LuaGameInstance.lua +++ /dev/null @@ -1,13 +0,0 @@ -local ____exports = __module.env -local Bootstrap = __MODULE__.Import("Framework.Bootstrap", __module) -local Log = __MODULE__.Import("Framework.Log", __module) -function ____exports.OnInit(gameInstance) - Bootstrap.Init(gameInstance) - Log.Info("LuaGameInstance.OnInit()") -end -function ____exports.OnShutdown(_gameInstance) - Log.Info("LuaGameInstance.OnShutdown()") - Bootstrap.Shutdown() -end -function __module.UpdateImports() -end diff --git a/Script/lua/Game/LuaGameMode.lua b/Script/lua/Game/LuaGameMode.lua deleted file mode 100644 index 55313d3..0000000 --- a/Script/lua/Game/LuaGameMode.lua +++ /dev/null @@ -1,21 +0,0 @@ -local ____exports = __module.env -local Log = __MODULE__.Import("Framework.Log", __module) -function ____exports.OnBeginPlay(gameMode) - Log.Info("LuaGameMode.OnBeginPlay() - Demo scene started") - UE.UKismetSystemLibrary.PrintString( - gameMode, - "[UnLua Demo] LuaGameMode initialized (Pure TS Callback Mode)!", - true, - true, - UE.FLinearColor(0.3, 0.85, 1, 1), - 5 - ) -end -function ____exports.OnEndPlay(_gameMode, endPlayReason) - Log.Info( - "LuaGameMode.OnEndPlay(reason=%s)", - tostring(endPlayReason) - ) -end -function __module.UpdateImports() -end diff --git a/Script/lua/Game/LuaPlayerController.lua b/Script/lua/Game/LuaPlayerController.lua deleted file mode 100644 index 57e5094..0000000 --- a/Script/lua/Game/LuaPlayerController.lua +++ /dev/null @@ -1,23 +0,0 @@ -local ____exports = __module.env -local Log = __MODULE__.Import("Framework.Log", __module) -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -local HotReload = __MODULE__.Import("Framework.HotReload", __module) -function ____exports.OnBeginPlay(_pc) - Log.Info("LuaPlayerController.OnBeginPlay() - Ready for [Space]=Ping, [R]=HotReload") -end -function ____exports.OnDemoPingPressed(_pc) - Log.Info("LuaPlayerController.OnDemoPingPressed() -> Emitting Demo.Ping") - EventBus.Emit("Demo.Ping", "LuaPlayerController") -end -function ____exports.OnDemoHotReloadPressed(_pc) - Log.Info("LuaPlayerController.OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()") - HotReload.ReloadAll() -end -function ____exports.OnEndPlay(_pc, endPlayReason) - Log.Info( - "LuaPlayerController.OnEndPlay(reason=%s)", - tostring(endPlayReason) - ) -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua b/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua deleted file mode 100644 index 688f76b..0000000 --- a/Script/lua/Tests/Extra/HotReloadAndFrameworkTest.lua +++ /dev/null @@ -1,170 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) -local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance -local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -local Bootstrap = __MODULE__.Import("Framework.Bootstrap", __module) -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -local HotReload = __MODULE__.Import("Framework.HotReload", __module) -local LuaDemoActor = __MODULE__.Import("Game.LuaDemoActor", __module) -function ____exports.RunHotReloadAndFrameworkTests() - Suite( - "Extra.FrameworkAndHotReload", - function() - Test( - "EventBus: dedup, owner dispatch, mid-emit unsubscribe, OffAllForOwner and error isolation", - function() - EventBus.Clear() - local received = {} - local ownerA = { - tag = "A", - OnEvent = function(self, msg) - received[#received + 1] = (self.tag .. ":") .. msg - end - } - local ownerB = { - tag = "B", - OnEvent = function(self, msg) - received[#received + 1] = (self.tag .. ":") .. msg - EventBus.Off("Test.Ping", self.OnEvent, self) - end - } - EventBus.On("Test.Ping", ownerA.OnEvent, ownerA) - EventBus.On("Test.Ping", ownerA.OnEvent, ownerA) - EventBus.On("Test.Ping", ownerB.OnEvent, ownerB) - EventBus.On( - "Test.Ping", - function() - error("intentional listener error") - end - ) - local afterErrorCalled = false - EventBus.On( - "Test.Ping", - function() - afterErrorCalled = true - end - ) - EventBus.Emit("Test.Ping", "hello") - AssertArrayEqual(received, {"A:hello", "B:hello"}) - AssertTrue(afterErrorCalled) - EventBus.Emit("Test.Ping", "world") - AssertArrayEqual(received, {"A:hello", "B:hello", "A:world"}) - EventBus.OffAllForOwner(ownerA) - EventBus.Emit("Test.Ping", "ignored") - AssertArrayEqual(received, {"A:hello", "B:hello", "A:world"}) - EventBus.Clear() - end - ) - Test( - "Bootstrap Init/Shutdown lifecycle and _G.GameFramework registration", - function() - local fakeGI = CreateBoundInstance({}, "ULuaGameInstance") - Bootstrap.Init(fakeGI) - AssertTrue(Bootstrap.IsInitialized) - AssertEqual(Bootstrap.GameInstance, fakeGI) - AssertNotNil(_G.GameFramework) - Bootstrap.Shutdown() - AssertFalse(Bootstrap.IsInitialized) - AssertNil(Bootstrap.GameInstance) - AssertNil(_G.GameFramework) - end - ) - Test( - "HotReload.ReloadModule validates arguments and emits Before/After events", - function() - EventBus.Clear() - local badOk, badErr = HotReload.ReloadModule("") - AssertFalse(badOk) - AssertEqual(badErr, "Invalid module name") - local order = {} - EventBus.On( - HotReload.EVENT_BEFORE_RELOAD, - function(modName) - order[#order + 1] = "before:" .. modName - end - ) - EventBus.On( - HotReload.EVENT_AFTER_RELOAD, - function(modName) - order[#order + 1] = "after:" .. modName - end - ) - local ok = HotReload.ReloadModule("Framework.Log") - AssertTrue(ok) - AssertArrayEqual(order, {"before:Framework.Log", "after:Framework.Log"}) - EventBus.Clear() - end - ) - Test( - "LuaDemoActor full integration: pure TS callback BeginPlay, Tick, Ping color cycle, HotReload & EndPlay cleanup", - function() - ResetMockState() - EventBus.Clear() - local lastStatusText = "" - local colorApplyCount = 0 - local rotationAddCount = 0 - local lastVerticalOffset = 0 - local fakeActor = CreateBoundInstance( - {}, - "ALuaDemoActor", - { - SpinSpeed = 90, - BobAmplitude = 20, - BobFrequency = 2, - SetStatusText = function(self, text) - lastStatusText = text - end, - SetCubeColor = function(self, _color) - colorApplyCount = colorApplyCount + 1 - end, - AddCubeLocalRotation = function(self, _delta) - rotationAddCount = rotationAddCount + 1 - end, - SetCubeVerticalOffset = function(self, zOffset) - lastVerticalOffset = zOffset - end - } - ) - LuaDemoActor.OnBeginPlay(fakeActor) - AssertEqual(colorApplyCount, 1) - AssertTrue((string.find(lastStatusText, "Pings: 0", 1, true)) ~= nil) - AssertTrue((string.find(lastStatusText, "Speed: 60", 1, true)) ~= nil) - LuaDemoActor.OnTick(fakeActor, 0.25) - AssertEqual(rotationAddCount, 1) - AssertTrue(lastVerticalOffset ~= 0) - EventBus.Emit("Demo.Ping", "TestSuite") - AssertEqual(colorApplyCount, 2) - AssertTrue((string.find(lastStatusText, "Pings: 1", 1, true)) ~= nil) - EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "Game.LuaDemoActor") - AssertEqual(colorApplyCount, 3) - AssertTrue((string.find(lastStatusText, "Reloads: 1", 1, true)) ~= nil) - LuaDemoActor.OnEndPlay(fakeActor, UE.EEndPlayReason.Destroyed) - EventBus.Emit("Demo.Ping", "AfterEndPlay") - AssertEqual(colorApplyCount, 3) - EventBus.Clear() - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual - CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance - ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -end diff --git a/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua b/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua deleted file mode 100644 index f8ac861..0000000 --- a/Script/lua/Tests/Extra/LifecycleAndMemoryTest.lua +++ /dev/null @@ -1,104 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) -local AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime -local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance -local GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState -local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -local LifecycleSafetyActor = require("Tests.Extra.LifecycleSafetyActor") -function ____exports.RunLifecycleAndMemoryTests() - Suite( - "Extra.LifecycleAndMemorySafety", - function() - Test( - "multiple @unlua instances maintain isolated state (no shared class-table arrays)", - function() - ResetMockState() - EventBus.Clear() - local cls = LifecycleSafetyActor - local a = CreateBoundInstance(cls, "AActor") - local b = CreateBoundInstance(cls, "AActor") - a:ReceiveBeginPlay() - b:ReceiveBeginPlay() - a:PushItem("only_in_a") - b:PushItem("only_in_b") - AssertArrayEqual( - a:GetItems(), - {"only_in_a"} - ) - AssertArrayEqual( - b:GetItems(), - {"only_in_b"} - ) - a:ReceiveEndPlay(UE.EEndPlayReason.Destroyed) - b:ReceiveEndPlay(UE.EEndPlayReason.Destroyed) - EventBus.Clear() - end - ) - Test( - "paired cleanup on ReceiveEndPlay prevents leaked EventBus, Delegate, Timer & manual Ref", - function() - ResetMockState() - EventBus.Clear() - local actor = CreateBoundInstance(LifecycleSafetyActor, "AActor") - local asset = UE.UObject.Load("/Game/Data/DA_Config.DA_Config") - local weak = UE.FWeakObjectPtr(actor) - actor:ReceiveBeginPlay() - actor:HoldManualRef(asset) - AssertEqual( - GetMockState().manualRefs[asset], - 1 - ) - EventBus.Emit("Lifecycle.Broadcast", "msg1") - actor.OnTakeAnyDamage:Broadcast( - actor, - 25, - nil, - nil, - nil - ) - AdvanceMockTime(1) - AssertEqual( - actor:GetReceivedEvents(), - 3 - ) - AssertTrue(weak:IsValid()) - actor:ReceiveEndPlay(UE.EEndPlayReason.Destroyed) - actor:K2_DestroyActor() - AssertFalse(actor.OnTakeAnyDamage:IsBound()) - AssertFalse(weak:IsValid()) - AssertNil(weak:Get()) - AssertNil(GetMockState().manualRefs[asset]) - EventBus.Emit("Lifecycle.Broadcast", "msg2") - AdvanceMockTime(3) - AssertEqual( - actor:GetReceivedEvents(), - 3 - ) - EventBus.Clear() - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual - AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime - CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance - GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState - ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -end diff --git a/Script/lua/Tests/Extra/LifecycleSafetyActor.lua b/Script/lua/Tests/Extra/LifecycleSafetyActor.lua deleted file mode 100644 index 53d66cf..0000000 --- a/Script/lua/Tests/Extra/LifecycleSafetyActor.lua +++ /dev/null @@ -1,54 +0,0 @@ -local EventBus = __MODULE__.Import("Framework.EventBus") -local LifecycleSafetyActor = UnLua.Class() -function LifecycleSafetyActor.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.items = {} - self.receivedEvents = 0 - EventBus.On("Lifecycle.Broadcast", self.OnBroadcast, self) - self.OnTakeAnyDamage:Add(self, self.OnDamaged) - self.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate({self, self.OnHeartbeat}, 1, true) -end -function LifecycleSafetyActor.PushItem(self, item) - self.items[#self.items + 1] = item -end -function LifecycleSafetyActor.GetItems(self) - return self.items -end -function LifecycleSafetyActor.HoldManualRef(self, asset) - self.keptRef = asset - UnLua.Ref(asset) -end -function LifecycleSafetyActor.OnBroadcast(self, tag) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.receivedEvents = self.receivedEvents + 1 - self.items[#self.items + 1] = tag -end -function LifecycleSafetyActor.OnDamaged(self, _DamagedActor, Damage, _DamageType, _InstigatedBy, _DamageCauser) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.receivedEvents = self.receivedEvents + 1 - self.items[#self.items + 1] = "dmg:" .. tostring(Damage) -end -function LifecycleSafetyActor.OnHeartbeat(self) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.receivedEvents = self.receivedEvents + 1 -end -function LifecycleSafetyActor.GetReceivedEvents(self) - return self.receivedEvents -end -function LifecycleSafetyActor.ReceiveEndPlay(self, EndPlayReason) - EventBus.OffAllForOwner(self) - self.OnTakeAnyDamage:Remove(self, self.OnDamaged) - UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(self, self.timerHandle) - if self.keptRef ~= nil then - UnLua.Unref(self.keptRef) - self.keptRef = nil - end - self.Overridden.ReceiveEndPlay(self, EndPlayReason) -end -return LifecycleSafetyActor diff --git a/Script/lua/Tests/Extra/Lua54PitfallsTest.lua b/Script/lua/Tests/Extra/Lua54PitfallsTest.lua deleted file mode 100644 index 72aaa8d..0000000 --- a/Script/lua/Tests/Extra/Lua54PitfallsTest.lua +++ /dev/null @@ -1,178 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertNear = M__Tests_Harness_TestRunner.AssertNear -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local function EscapeLuaPattern(literal) - local escaped = string.gsub(literal, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1") - return escaped -end -local function DeepCloneTable(src, seen) - if type(src) ~= "table" then - return src - end - local visited = seen or ({}) - local existing = visited[src] - if existing ~= nil then - return existing - end - local copy = {} - visited[src] = copy - for k, v in pairs(src) do - copy[DeepCloneTable(k, visited)] = DeepCloneTable(v, visited) - end - return copy -end -function ____exports.RunLua54PitfallsTests() - Suite( - "Extra.Lua54PitfallsAndEdgeCases", - function() - Test( - "Lua truthiness vs JS: explicit checks for 0 and empty string, ?? vs ||", - function() - local zero = 0 - local empty = "" - AssertTrue(zero == 0) - AssertTrue(empty == "") - local ____AssertTrue_1 = AssertTrue - local ____temp_0 - if zero then - ____temp_0 = true - else - ____temp_0 = false - end - ____AssertTrue_1(____temp_0) - local ____AssertTrue_3 = AssertTrue - local ____temp_2 - if empty then - ____temp_2 = true - else - ____temp_2 = false - end - ____AssertTrue_3(____temp_2) - local optZero = 0 - local optEmpty = "" - local optFalse = false - local optNil = nil - AssertEqual(optZero or 100, 0) - AssertEqual(optEmpty or "fallback", "") - local ____AssertEqual_5 = AssertEqual - local ____optFalse_4 = optFalse - if ____optFalse_4 == nil then - ____optFalse_4 = true - end - ____AssertEqual_5(____optFalse_4, false) - AssertEqual(optNil or 100, 100) - end - ) - Test( - "Lua 5.4 UTF-8 character counting for CJK game text vs byte length", - function() - local cnText = "你好UE5世界" - AssertEqual(#cnText, 15) - local charCount = utf8.len(cnText) - AssertEqual(charCount, 7) - local codes = {utf8.codepoint(cnText, 1, -1)} - AssertEqual(#codes, 7) - AssertEqual(codes[1], 20320) - AssertEqual(codes[3], 85) - end - ) - Test( - "Lua pattern magic character escaping for literal search & replace", - function() - local raw = "Item[Epic]+10 (50.5%)" - local escaped = EscapeLuaPattern("[Epic]+10 (50.5%)") - local startIdx = string.find(raw, escaped) - AssertTrue(startIdx ~= nil) - local replaced = string.gsub( - raw, - EscapeLuaPattern("(50.5%)"), - "(100%%)" - ) - AssertEqual(replaced, "Item[Epic]+10 (100%)") - end - ) - Test( - "0-based TS array vs 1-based UE.TArray interop without sparse holes", - function() - local tsArr = {"first", "second", "third"} - local ueArr = UE.TArray(UE.FString) - do - local i = 0 - while i < #tsArr do - ueArr:Add(tsArr[i + 1]) - i = i + 1 - end - end - AssertEqual( - ueArr:Length(), - #tsArr - ) - AssertEqual( - ueArr:Get(1), - tsArr[1] - ) - AssertEqual( - ueArr:Get(3), - tsArr[3] - ) - local dense = {10, 20, 30, 40} - local removeIdx = 1 - dense[removeIdx + 1] = dense[#dense] - table.remove(dense) - AssertEqual(#dense, 3) - AssertArrayEqual(dense, {10, 40, 30}) - end - ) - Test( - "deep clone plain tables safely including circular references", - function() - local original = {name = "Root", tags = {"a", "b"}} - original.selfRef = original - local cloned = DeepCloneTable(original) - AssertEqual(cloned.name, "Root") - AssertArrayEqual(cloned.tags, {"a", "b"}) - AssertTrue(cloned ~= original) - AssertTrue(cloned.tags ~= original.tags) - AssertEqual(cloned.selfRef, cloned) - local ____cloned_tags_6 = cloned.tags - ____cloned_tags_6[#____cloned_tags_6 + 1] = "c" - AssertEqual(#original.tags, 2) - AssertEqual(#cloned.tags, 3) - end - ) - Test( - "zero-GC hot-path Tick simulation with cached FVector/FRotator (10,000 frames)", - function() - local pos = UE.FVector(0, 0, 0) - local vel = UE.FVector(10, 20, -5) - local dt = 0.016 - do - local frame = 0 - while frame < 10000 do - pos.X = pos.X + vel.X * dt - pos.Y = pos.Y + vel.Y * dt - pos.Z = pos.Z + vel.Z * dt - frame = frame + 1 - end - end - AssertNear(pos.X, 1600, 0.1) - AssertNear(pos.Y, 3200, 0.1) - AssertNear(pos.Z, -800, 0.1) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertNear = M__Tests_Harness_TestRunner.AssertNear - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -end diff --git a/Script/lua/Tests/Gameplay/BehaviorTree.lua b/Script/lua/Tests/Gameplay/BehaviorTree.lua deleted file mode 100644 index ac48134..0000000 --- a/Script/lua/Tests/Gameplay/BehaviorTree.lua +++ /dev/null @@ -1,129 +0,0 @@ -local ____exports = __module.env -____exports.BTCondition = __TS__DefineClass("BTCondition", __module) -local BTCondition = ____exports.BTCondition -BTCondition.name = "BTCondition" -function BTCondition.prototype.____constructor(self, check) - self.check = check -end -function BTCondition.prototype.Tick(self, ctx) - return self.check(ctx) and 0 or 1 -end -function BTCondition.prototype.Reset(self) -end -____exports.BTAction = __TS__DefineClass("BTAction", __module) -local BTAction = ____exports.BTAction -BTAction.name = "BTAction" -function BTAction.prototype.____constructor(self, action) - self.action = action -end -function BTAction.prototype.Tick(self, ctx) - return self.action(ctx) -end -function BTAction.prototype.Reset(self) -end -____exports.BTSequence = __TS__DefineClass("BTSequence", __module) -local BTSequence = ____exports.BTSequence -BTSequence.name = "BTSequence" -function BTSequence.prototype.____constructor(self, children) - self.runningIndex = 0 - self.children = children -end -function BTSequence.prototype.Tick(self, ctx) - while self.runningIndex < #self.children do - local status = self.children[self.runningIndex + 1]:Tick(ctx) - if status == 2 then - return 2 - end - if status == 1 then - self:Reset() - return 1 - end - self.runningIndex = self.runningIndex + 1 - end - self:Reset() - return 0 -end -function BTSequence.prototype.Reset(self) - self.runningIndex = 0 - do - local i = 0 - while i < #self.children do - self.children[i + 1]:Reset() - i = i + 1 - end - end -end -____exports.BTSelector = __TS__DefineClass("BTSelector", __module) -local BTSelector = ____exports.BTSelector -BTSelector.name = "BTSelector" -function BTSelector.prototype.____constructor(self, children) - self.runningIndex = 0 - self.children = children -end -function BTSelector.prototype.Tick(self, ctx) - while self.runningIndex < #self.children do - local status = self.children[self.runningIndex + 1]:Tick(ctx) - if status == 2 then - return 2 - end - if status == 0 then - self:Reset() - return 0 - end - self.runningIndex = self.runningIndex + 1 - end - self:Reset() - return 1 -end -function BTSelector.prototype.Reset(self) - self.runningIndex = 0 - do - local i = 0 - while i < #self.children do - self.children[i + 1]:Reset() - i = i + 1 - end - end -end -____exports.BTInverter = __TS__DefineClass("BTInverter", __module) -local BTInverter = ____exports.BTInverter -BTInverter.name = "BTInverter" -function BTInverter.prototype.____constructor(self, child) - self.child = child -end -function BTInverter.prototype.Tick(self, ctx) - local st = self.child:Tick(ctx) - if st == 0 then - return 1 - end - if st == 1 then - return 0 - end - return 2 -end -function BTInverter.prototype.Reset(self) - self.child:Reset() -end -____exports.BTCooldown = __TS__DefineClass("BTCooldown", __module) -local BTCooldown = ____exports.BTCooldown -BTCooldown.name = "BTCooldown" -function BTCooldown.prototype.____constructor(self, child, cooldownSeconds) - self.lastSuccessTime = -9999 - self.child = child - self.cooldownSeconds = cooldownSeconds -end -function BTCooldown.prototype.Tick(self, ctx) - if ctx.time - self.lastSuccessTime < self.cooldownSeconds then - return 1 - end - local st = self.child:Tick(ctx) - if st == 0 then - self.lastSuccessTime = ctx.time - end - return st -end -function BTCooldown.prototype.Reset(self) - self.child:Reset() -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua b/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua deleted file mode 100644 index 72895ea..0000000 --- a/Script/lua/Tests/Gameplay/BuffAndAttributeSystem.lua +++ /dev/null @@ -1,179 +0,0 @@ -local ____exports = __module.env -____exports.AttributeAndBuffComponent = __TS__DefineClass("AttributeAndBuffComponent", __module) -local AttributeAndBuffComponent = ____exports.AttributeAndBuffComponent -AttributeAndBuffComponent.name = "AttributeAndBuffComponent" -function AttributeAndBuffComponent.prototype.____constructor(self, initialStats) - self.baseStats = {} - self.buffs = {} - self.listeners = {} - for k, v in pairs(initialStats) do - self.baseStats[k] = v - end -end -function AttributeAndBuffComponent.prototype.OnAttributeChanged(self, cb) - self.listeners[#self.listeners + 1] = cb -end -function AttributeAndBuffComponent.prototype.GetBase(self, attr) - return self.baseStats[attr] or 0 -end -function AttributeAndBuffComponent.prototype.SetBase(self, attr, val) - local clamped = val - if attr == "HP" then - clamped = math.max( - 0, - math.min( - val, - self:GetFinal("MaxHP") - ) - ) - end - self.baseStats[attr] = clamped - self:Notify( - attr, - self:GetFinal(attr) - ) -end -function AttributeAndBuffComponent.prototype.GetFinal(self, attr) - local baseVal = self.baseStats[attr] or 0 - local flat = 0 - local pct = 0 - do - local i = 0 - while i < #self.buffs do - do - local b = self.buffs[i + 1] - local mods = b.spec.modifiers - if mods == nil then - goto __continue10 - end - do - local j = 0 - while j < #mods do - do - local m = mods[j + 1] - if m.attr ~= attr then - goto __continue13 - end - if m.op == 0 then - flat = flat + m.value * b.stacks - else - pct = pct + m.value * b.stacks - end - end - ::__continue13:: - j = j + 1 - end - end - end - ::__continue10:: - i = i + 1 - end - end - return (baseVal + flat) * (1 + pct) -end -function AttributeAndBuffComponent.prototype.ApplyBuff(self, spec) - local policy = spec.stackPolicy or 0 - local maxStacks = spec.maxStacks or 1 - do - local i = 0 - while i < #self.buffs do - local existing = self.buffs[i + 1] - if existing.spec.id == spec.id then - if policy == 2 then - return - end - existing.remaining = spec.duration - if policy == 1 and existing.stacks < maxStacks then - existing.stacks = existing.stacks + 1 - end - return - end - i = i + 1 - end - end - self.buffs[#self.buffs + 1] = {spec = spec, stacks = 1, remaining = spec.duration, tickAccumulator = 0} -end -function AttributeAndBuffComponent.prototype.RemoveBuff(self, buffId) - do - local i = #self.buffs - 1 - while i >= 0 do - if self.buffs[i + 1].spec.id == buffId then - table.remove(self.buffs, i + 1) - return true - end - i = i - 1 - end - end - return false -end -function AttributeAndBuffComponent.prototype.GetBuffStacks(self, buffId) - do - local i = 0 - while i < #self.buffs do - if self.buffs[i + 1].spec.id == buffId then - return self.buffs[i + 1].stacks - end - i = i + 1 - end - end - return 0 -end -function AttributeAndBuffComponent.prototype.Tick(self, dt) - do - local i = #self.buffs - 1 - while i >= 0 do - local b = self.buffs[i + 1] - b.remaining = b.remaining - dt - if b.spec.tickInterval ~= nil and b.spec.tickInterval > 0 and b.spec.hpPerTick ~= nil then - b.tickAccumulator = b.tickAccumulator + dt - while b.tickAccumulator >= b.spec.tickInterval do - b.tickAccumulator = b.tickAccumulator - b.spec.tickInterval - local delta = b.spec.hpPerTick * b.stacks - self:SetBase( - "HP", - self:GetBase("HP") + delta - ) - end - end - if b.remaining <= 0 then - table.remove(self.buffs, i + 1) - end - i = i - 1 - end - end -end -function AttributeAndBuffComponent.prototype.ApplyDamageFrom(self, attacker, skillMultiplier, isCrit, critMultiplier) - if critMultiplier == nil then - critMultiplier = 1.5 - end - local atk = attacker:GetFinal("Attack") - local def = math.max( - 0, - self:GetFinal("Defense") - ) - local raw = atk * skillMultiplier * (isCrit and critMultiplier or 1) - local mitigated = math.floor(raw * (100 / (100 + def)) + 0.5) - local nextHp = math.max( - 0, - self:GetBase("HP") - mitigated - ) - self:SetBase("HP", nextHp) - return { - rawDamage = raw, - mitigatedDamage = mitigated, - isCrit = isCrit, - targetHpAfter = nextHp, - targetKilled = nextHp <= 0 - } -end -function AttributeAndBuffComponent.prototype.Notify(self, attr, val) - do - local i = 0 - while i < #self.listeners do - self.listeners[i + 1](attr, val) - i = i + 1 - end - end -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua b/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua deleted file mode 100644 index fdfdc08..0000000 --- a/Script/lua/Tests/Gameplay/CoroutineTaskRunner.lua +++ /dev/null @@ -1,127 +0,0 @@ -local ____exports = __module.env -____exports.CoroutineTaskRunner = __TS__DefineClass("CoroutineTaskRunner", __module) -local CoroutineTaskRunner = ____exports.CoroutineTaskRunner -CoroutineTaskRunner.name = "CoroutineTaskRunner" -function CoroutineTaskRunner.prototype.____constructor(self) - self.nextId = 1 - self.tasks = {} -end -function CoroutineTaskRunner.prototype.Start(self, body, owner) - local ____self_0, ____nextId_1 = self, "nextId" - local ____self_nextId_2 = ____self_0[____nextId_1] - ____self_0[____nextId_1] = ____self_nextId_2 + 1 - local id = ____self_nextId_2 - local co = coroutine.create(body) - local task = {id = id, co = co, owner = owner, cancelled = false} - self.tasks[#self.tasks + 1] = task - self:StepTask(task) - return id -end -function CoroutineTaskRunner.prototype.Cancel(self, taskId) - do - local i = 0 - while i < #self.tasks do - if self.tasks[i + 1].id == taskId and not self.tasks[i + 1].cancelled then - self.tasks[i + 1].cancelled = true - return true - end - i = i + 1 - end - end - return false -end -function CoroutineTaskRunner.prototype.Tick(self, dt) - local snapshot = {} - do - local i = 0 - while i < #self.tasks do - snapshot[i + 1] = self.tasks[i + 1] - i = i + 1 - end - end - do - local i = 0 - while i < #snapshot do - do - local task = snapshot[i + 1] - if task.cancelled or coroutine.status(task.co) == "dead" then - task.cancelled = true - goto __continue12 - end - if task.owner ~= nil and not UE.UKismetSystemLibrary.IsValid(task.owner) then - task.cancelled = true - goto __continue12 - end - local cmd = task.pending - if cmd == nil then - self:StepTask(task) - elseif cmd.kind == "wait_seconds" then - cmd.remaining = cmd.remaining - dt - if cmd.remaining <= 0 then - task.pending = nil - self:StepTask(task) - end - elseif cmd.kind == "wait_until" then - if cmd.predicate() then - task.pending = nil - self:StepTask(task) - end - end - end - ::__continue12:: - i = i + 1 - end - end - do - local i = #self.tasks - 1 - while i >= 0 do - local t = self.tasks[i + 1] - if t.cancelled or coroutine.status(t.co) == "dead" then - table.remove(self.tasks, i + 1) - end - i = i - 1 - end - end -end -function CoroutineTaskRunner.prototype.GetActiveTaskCount(self) - local count = 0 - do - local i = 0 - while i < #self.tasks do - local t = self.tasks[i + 1] - if not t.cancelled and coroutine.status(t.co) ~= "dead" then - count = count + 1 - end - i = i + 1 - end - end - return count -end -function CoroutineTaskRunner.prototype.StepTask(self, task) - if task.cancelled or coroutine.status(task.co) == "dead" then - return - end - local ok, yielded = coroutine.resume(task.co) - if not ok then - task.cancelled = true - error("CoroutineTaskRunner error: " .. tostring(yielded)) - end - if coroutine.status(task.co) == "dead" then - task.cancelled = true - elseif yielded ~= nil then - task.pending = yielded - end -end -function CoroutineTaskRunner.WaitSeconds(seconds) - local cmd = {kind = "wait_seconds", remaining = seconds} - coroutine.yield(cmd) -end -function CoroutineTaskRunner.WaitUntil(predicate) - if predicate() then - return - end - local cmd = {kind = "wait_until", predicate = predicate} - coroutine.yield(cmd) -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Gameplay/FSM.lua b/Script/lua/Tests/Gameplay/FSM.lua deleted file mode 100644 index cb71aa7..0000000 --- a/Script/lua/Tests/Gameplay/FSM.lua +++ /dev/null @@ -1,87 +0,0 @@ -local ____exports = __module.env -____exports.StateMachine = __TS__DefineClass("StateMachine", __module) -local StateMachine = ____exports.StateMachine -StateMachine.name = "StateMachine" -function StateMachine.prototype.____constructor(self, ctx) - self.states = {} - self.transitions = {} - self.currentState = nil - self.stateElapsed = 0 - self.paused = false - self.history = {} - self.ctx = ctx -end -function StateMachine.prototype.RegisterState(self, id, handler) - self.states[id] = handler -end -function StateMachine.prototype.AddTransition(self, from, to, condition) - self.transitions[#self.transitions + 1] = {from = from, to = to, condition = condition} -end -function StateMachine.prototype.Start(self, initialState) - if self.states[initialState] == nil then - return false - end - self.currentState = initialState - self.stateElapsed = 0 - self.history[#self.history + 1] = initialState - local handler = self.states[initialState] - if handler and handler.OnEnter then - handler.OnEnter(self.ctx, nil) - end - return true -end -function StateMachine.prototype.ChangeState(self, nextState) - if self.currentState == nextState or self.states[nextState] == nil then - return false - end - local prev = self.currentState - if prev ~= nil then - local prevHandler = self.states[prev] - if prevHandler and prevHandler.OnExit then - prevHandler.OnExit(self.ctx, nextState) - end - end - self.currentState = nextState - self.stateElapsed = 0 - self.history[#self.history + 1] = nextState - local nextHandler = self.states[nextState] - if nextHandler and nextHandler.OnEnter then - nextHandler.OnEnter(self.ctx, prev) - end - return true -end -function StateMachine.prototype.Update(self, dt) - if self.paused or self.currentState == nil then - return - end - self.stateElapsed = self.stateElapsed + dt - do - local i = 0 - while i < #self.transitions do - local tr = self.transitions[i + 1] - if (tr.from == "*" or tr.from == self.currentState) and tr.to ~= self.currentState and tr.condition(self.ctx) then - self:ChangeState(tr.to) - break - end - i = i + 1 - end - end - local handler = self.states[self.currentState] - if handler and handler.OnUpdate then - handler.OnUpdate(self.ctx, dt) - end -end -function StateMachine.prototype.SetPaused(self, paused) - self.paused = paused -end -function StateMachine.prototype.GetCurrentState(self) - return self.currentState -end -function StateMachine.prototype.GetStateElapsed(self) - return self.stateElapsed -end -function StateMachine.prototype.GetHistory(self) - return self.history -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Gameplay/GameplaySuite.lua b/Script/lua/Tests/Gameplay/GameplaySuite.lua deleted file mode 100644 index db27b64..0000000 --- a/Script/lua/Tests/Gameplay/GameplaySuite.lua +++ /dev/null @@ -1,515 +0,0 @@ -local ____lualib = require("lualib_bundle") -local __TS__New = ____lualib.__TS__New -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertNear = M__Tests_Harness_TestRunner.AssertNear -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) -local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance -local M__Tests_Gameplay_FSM = __MODULE__.Import("Tests.Gameplay.FSM", __module) -local StateMachine = M__Tests_Gameplay_FSM.StateMachine -local M__Tests_Gameplay_ObjectPool = __MODULE__.Import("Tests.Gameplay.ObjectPool", __module) -local ObjectPool = M__Tests_Gameplay_ObjectPool.ObjectPool -local M__Tests_Gameplay_TimerScheduler = __MODULE__.Import("Tests.Gameplay.TimerScheduler", __module) -local TimerScheduler = M__Tests_Gameplay_TimerScheduler.TimerScheduler -local CooldownTracker = M__Tests_Gameplay_TimerScheduler.CooldownTracker -local M__Tests_Gameplay_BuffAndAttributeSystem = __MODULE__.Import("Tests.Gameplay.BuffAndAttributeSystem", __module) -local AttributeAndBuffComponent = M__Tests_Gameplay_BuffAndAttributeSystem.AttributeAndBuffComponent -local M__Tests_Gameplay_InventorySystem = __MODULE__.Import("Tests.Gameplay.InventorySystem", __module) -local InventorySystem = M__Tests_Gameplay_InventorySystem.InventorySystem -local M__Tests_Gameplay_CoroutineTaskRunner = __MODULE__.Import("Tests.Gameplay.CoroutineTaskRunner", __module) -local CoroutineTaskRunner = M__Tests_Gameplay_CoroutineTaskRunner.CoroutineTaskRunner -local M__Tests_Gameplay_BehaviorTree = __MODULE__.Import("Tests.Gameplay.BehaviorTree", __module) -local BTAction = M__Tests_Gameplay_BehaviorTree.BTAction -local BTCondition = M__Tests_Gameplay_BehaviorTree.BTCondition -local BTCooldown = M__Tests_Gameplay_BehaviorTree.BTCooldown -local BTInverter = M__Tests_Gameplay_BehaviorTree.BTInverter -local BTSelector = M__Tests_Gameplay_BehaviorTree.BTSelector -local BTSequence = M__Tests_Gameplay_BehaviorTree.BTSequence -function ____exports.RunGameplayTests() - Suite( - "Gameplay.Systems", - function() - Test( - "FSM: state lifecycle, conditional transitions, pause and history", - function() - local ctx = {speed = 0, hp = 100, log = {}} - local fsm = __TS__New(StateMachine, ctx) - fsm:RegisterState( - "Idle", - { - OnEnter = function(c) - c.log[#c.log + 1] = "Enter:Idle" - end, - OnExit = function(c) - c.log[#c.log + 1] = "Exit:Idle" - end - } - ) - fsm:RegisterState( - "Run", - { - OnEnter = function(c) - c.log[#c.log + 1] = "Enter:Run" - end, - OnUpdate = function(c, dt) - c.log[#c.log + 1] = "Run:" .. tostring(math.floor(dt * 100)) - end - } - ) - fsm:RegisterState( - "Dead", - {OnEnter = function(c) - c.log[#c.log + 1] = "Enter:Dead" - end} - ) - fsm:AddTransition( - "Idle", - "Run", - function(c) return c.speed > 0 end - ) - fsm:AddTransition( - "Run", - "Idle", - function(c) return c.speed == 0 end - ) - fsm:AddTransition( - "*", - "Dead", - function(c) return c.hp <= 0 end - ) - AssertTrue(fsm:Start("Idle")) - AssertEqual( - fsm:GetCurrentState(), - "Idle" - ) - ctx.speed = 300 - fsm:Update(0.1) - AssertEqual( - fsm:GetCurrentState(), - "Run" - ) - fsm:SetPaused(true) - ctx.hp = 0 - fsm:Update(0.1) - AssertEqual( - fsm:GetCurrentState(), - "Run" - ) - fsm:SetPaused(false) - fsm:Update(0.1) - AssertEqual( - fsm:GetCurrentState(), - "Dead" - ) - AssertArrayEqual( - fsm:GetHistory(), - {"Idle", "Run", "Dead"} - ) - end - ) - Test( - "ObjectPool: prewarm, acquire/reuse, maxCapacity cap and reset hooks", - function() - local pool = __TS__New( - ObjectPool, - { - factory = function() return {active = false, damage = 0} end, - onAcquire = function(b) - b.active = true - b.damage = 10 - end, - onRelease = function(b) - b.active = false - b.damage = 0 - end, - maxCapacity = 2 - } - ) - pool:Prewarm(2) - AssertEqual( - pool:GetIdleCount(), - 2 - ) - AssertEqual( - pool:GetTotalCreated(), - 2 - ) - local b1 = pool:Acquire() - local b2 = pool:Acquire() - local b3 = pool:Acquire() - AssertTrue(b1.active) - AssertEqual(b1.damage, 10) - AssertEqual( - pool:GetActiveCount(), - 3 - ) - AssertEqual( - pool:GetTotalCreated(), - 3 - ) - pool:Release(b1) - pool:Release(b2) - pool:Release(b3) - AssertFalse(b1.active) - AssertEqual( - pool:GetActiveCount(), - 0 - ) - AssertEqual( - pool:GetIdleCount(), - 2 - ) - local reused = pool:Acquire() - AssertEqual( - pool:GetTotalCreated(), - 3 - ) - AssertTrue(reused.active) - end - ) - Test( - "TimerScheduler & CooldownTracker: one-shot, repeat, self-cancel, timeScale and cooldowns", - function() - local scheduler = __TS__New(TimerScheduler) - local events = {} - scheduler:ScheduleOnce( - 0.5, - function() - events[#events + 1] = "once" - end - ) - local repId = scheduler:ScheduleRepeat( - 0.25, - function(id) - events[#events + 1] = "rep#" .. tostring(id) - end, - 3 - ) - local selfCancelCount = 0 - scheduler:ScheduleRepeat( - 0.2, - function(id) - selfCancelCount = selfCancelCount + 1 - if selfCancelCount == 2 then - scheduler:Cancel(id) - end - end - ) - scheduler:Tick(0.5) - AssertEqual(selfCancelCount, 2) - AssertEqual(#events, 3) - scheduler:SetPaused(repId, true) - scheduler:Tick(1) - AssertEqual(#events, 3) - scheduler:SetPaused(repId, false) - scheduler:SetTimeScale(0.5) - scheduler:Tick(0.5) - AssertEqual(#events, 4) - AssertEqual( - scheduler:GetActiveCount(), - 0 - ) - local cd = __TS__New(CooldownTracker) - AssertTrue(cd:IsReady("Fireball")) - cd:StartCooldown("Fireball", 5) - AssertFalse(cd:IsReady("Fireball")) - cd:Tick(2) - AssertNear( - cd:GetRemaining("Fireball"), - 3 - ) - cd:ReduceCooldown("Fireball", 3.5) - AssertTrue(cd:IsReady("Fireball")) - AssertEqual( - cd:GetRemaining("Fireball"), - 0 - ) - end - ) - Test( - "BuffAndAttributeSystem: flat/percent modifiers, stacking, DoT tick and damage mitigation", - function() - local hero = __TS__New(AttributeAndBuffComponent, {MaxHP = 200, HP = 200, Attack = 50, Defense = 0}) - local boss = __TS__New(AttributeAndBuffComponent, {MaxHP = 500, HP = 500, Attack = 40, Defense = 100}) - local furyBuff = { - id = "Fury", - duration = 5, - maxStacks = 3, - stackPolicy = 1, - modifiers = {{attr = "Attack", op = 0, value = 10}, {attr = "Attack", op = 1, value = 0.2}} - } - hero:ApplyBuff(furyBuff) - hero:ApplyBuff(furyBuff) - AssertEqual( - hero:GetBuffStacks("Fury"), - 2 - ) - AssertNear( - hero:GetFinal("Attack"), - 98 - ) - local dmg = boss:ApplyDamageFrom(hero, 1, true, 1.5) - AssertEqual(dmg.mitigatedDamage, 74) - AssertEqual(dmg.targetHpAfter, 426) - AssertFalse(dmg.targetKilled) - boss:ApplyBuff({id = "Poison", duration = 3.1, tickInterval = 1, hpPerTick = -15}) - boss:Tick(2.5) - AssertEqual( - boss:GetBase("HP"), - 396 - ) - boss:Tick(1) - AssertEqual( - boss:GetBase("HP"), - 381 - ) - AssertEqual( - boss:GetBuffStacks("Poison"), - 0 - ) - end - ) - Test( - "InventorySystem: stack merge, split, swap, consume, filter and serialize/deserialize", - function() - local inv = __TS__New(InventorySystem, 4) - inv:RegisterItemDef({ - itemId = "potion_hp", - name = "Health Potion", - category = "Consumable", - rarity = 0, - maxStack = 10 - }) - inv:RegisterItemDef({ - itemId = "sword_excalibur", - name = "Excalibur", - category = "Weapon", - rarity = 3, - maxStack = 1 - }) - AssertEqual( - inv:AddItem("potion_hp", 25), - 0 - ) - AssertEqual( - inv:GetItemCount("potion_hp"), - 25 - ) - AssertEqual( - inv:GetUsedSlotCount(), - 3 - ) - AssertEqual( - inv:AddItem("sword_excalibur", 2), - 1 - ) - AssertEqual( - inv:GetItemCount("sword_excalibur"), - 1 - ) - AssertTrue(inv:ConsumeItem("potion_hp", 12)) - AssertEqual( - inv:GetItemCount("potion_hp"), - 13 - ) - AssertNil(inv:GetSlot(2)) - AssertTrue(inv:SplitSlot(0, 2, 4)) - AssertEqual( - inv:GetSlot(0).count, - 6 - ) - AssertEqual( - inv:GetSlot(2).count, - 4 - ) - AssertTrue(inv:SwapSlots(0, 3)) - AssertEqual( - inv:GetSlot(0).itemId, - "sword_excalibur" - ) - AssertEqual( - #inv:FilterByCategory("Weapon"), - 1 - ) - AssertEqual( - #inv:FilterByCategory("Consumable"), - 3 - ) - local saved = inv:Serialize() - local restored = __TS__New(InventorySystem, 1) - restored:Deserialize(saved) - AssertEqual( - restored:GetItemCount("potion_hp"), - 13 - ) - AssertEqual( - restored:GetSlot(0).itemId, - "sword_excalibur" - ) - end - ) - Test( - "CoroutineTaskRunner: WaitSeconds, WaitUntil and UObject destroy auto-cancellation", - function() - local runner = __TS__New(CoroutineTaskRunner) - local trace = {} - local doorOpened = false - runner:Start(function() - trace[#trace + 1] = "start" - CoroutineTaskRunner.WaitSeconds(0.5) - trace[#trace + 1] = "after_delay" - CoroutineTaskRunner.WaitUntil(function() return doorOpened end) - trace[#trace + 1] = "entered_room" - end) - AssertArrayEqual(trace, {"start"}) - runner:Tick(0.3) - AssertArrayEqual(trace, {"start"}) - runner:Tick(0.3) - AssertArrayEqual(trace, {"start", "after_delay"}) - runner:Tick(1) - AssertArrayEqual(trace, {"start", "after_delay"}) - doorOpened = true - runner:Tick(0.016) - AssertArrayEqual(trace, {"start", "after_delay", "entered_room"}) - AssertEqual( - runner:GetActiveTaskCount(), - 0 - ) - local world = _G.__UE_TEST_WORLD - local ownerActor = world ~= nil and world:SpawnActor( - UE.AActor.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - ) or CreateBoundInstance({}, "AActor") - local postDestroyExecuted = false - runner:Start( - function() - CoroutineTaskRunner.WaitSeconds(1) - postDestroyExecuted = true - end, - ownerActor - ) - ownerActor:K2_DestroyActor() - runner:Tick(2) - AssertFalse(postDestroyExecuted) - AssertEqual( - runner:GetActiveTaskCount(), - 0 - ) - end - ) - Test( - "BehaviorTree: Selector/Sequence/Cooldown/Inverter with Running resumption", - function() - local log = {} - local castProgress = 0 - local castUltimate = __TS__New( - BTCooldown, - __TS__New( - BTSequence, - { - __TS__New( - BTCondition, - function(ctx) return ctx.bb.mana >= 50 end - ), - __TS__New( - BTAction, - function(ctx) - castProgress = castProgress + ctx.dt - if castProgress < 1 then - log[#log + 1] = "casting" - return 2 - end - castProgress = 0 - ctx.bb.mana = ctx.bb.mana - 50 - log[#log + 1] = "ult_fired" - return 0 - end - ) - } - ), - 5 - ) - local basicAttack = __TS__New( - BTSequence, - { - __TS__New( - BTInverter, - __TS__New( - BTCondition, - function(ctx) return ctx.bb.stunned == true end - ) - ), - __TS__New( - BTAction, - function() - log[#log + 1] = "basic_attack" - return 0 - end - ) - } - ) - local root = __TS__New(BTSelector, {castUltimate, basicAttack}) - local ctx = {dt = 0.5, time = 0, bb = {mana = 60, stunned = false}} - AssertEqual( - root:Tick(ctx), - 2 - ) - ctx.time = 0.5 - AssertEqual( - root:Tick(ctx), - 0 - ) - AssertEqual(ctx.bb.mana, 10) - ctx.time = 1 - AssertEqual( - root:Tick(ctx), - 0 - ) - ctx.time = 1.5 - ctx.bb.stunned = true - AssertEqual( - root:Tick(ctx), - 1 - ) - AssertArrayEqual(log, {"casting", "ult_fired", "basic_attack"}) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertNear = M__Tests_Harness_TestRunner.AssertNear - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual - CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance - StateMachine = M__Tests_Gameplay_FSM.StateMachine - ObjectPool = M__Tests_Gameplay_ObjectPool.ObjectPool - TimerScheduler = M__Tests_Gameplay_TimerScheduler.TimerScheduler - CooldownTracker = M__Tests_Gameplay_TimerScheduler.CooldownTracker - AttributeAndBuffComponent = M__Tests_Gameplay_BuffAndAttributeSystem.AttributeAndBuffComponent - InventorySystem = M__Tests_Gameplay_InventorySystem.InventorySystem - CoroutineTaskRunner = M__Tests_Gameplay_CoroutineTaskRunner.CoroutineTaskRunner - BTAction = M__Tests_Gameplay_BehaviorTree.BTAction - BTCondition = M__Tests_Gameplay_BehaviorTree.BTCondition - BTCooldown = M__Tests_Gameplay_BehaviorTree.BTCooldown - BTInverter = M__Tests_Gameplay_BehaviorTree.BTInverter - BTSelector = M__Tests_Gameplay_BehaviorTree.BTSelector - BTSequence = M__Tests_Gameplay_BehaviorTree.BTSequence -end diff --git a/Script/lua/Tests/Gameplay/InventorySystem.lua b/Script/lua/Tests/Gameplay/InventorySystem.lua deleted file mode 100644 index 4b0d60c..0000000 --- a/Script/lua/Tests/Gameplay/InventorySystem.lua +++ /dev/null @@ -1,160 +0,0 @@ -local ____exports = __module.env -____exports.InventorySystem = __TS__DefineClass("InventorySystem", __module) -local InventorySystem = ____exports.InventorySystem -InventorySystem.name = "InventorySystem" -function InventorySystem.prototype.____constructor(self, capacity) - self.defs = {} - self.slots = {} - self.capacity = capacity -end -function InventorySystem.prototype.RegisterItemDef(self, def) - self.defs[def.itemId] = def -end -function InventorySystem.prototype.AddItem(self, itemId, amount) - local def = self.defs[itemId] - if def == nil or amount <= 0 then - return amount - end - local remaining = amount - do - local i = 0 - while i < self.capacity and remaining > 0 do - local slot = self.slots[i] - if slot ~= nil and slot.itemId == itemId and slot.count < def.maxStack then - local space = def.maxStack - slot.count - local add = math.min(space, remaining) - slot.count = slot.count + add - remaining = remaining - add - end - i = i + 1 - end - end - do - local i = 0 - while i < self.capacity and remaining > 0 do - if self.slots[i] == nil then - local add = math.min(def.maxStack, remaining) - self.slots[i] = {itemId = itemId, count = add} - remaining = remaining - add - end - i = i + 1 - end - end - return remaining -end -function InventorySystem.prototype.ConsumeItem(self, itemId, amount) - if amount <= 0 or self:GetItemCount(itemId) < amount then - return false - end - local remaining = amount - do - local i = self.capacity - 1 - while i >= 0 and remaining > 0 do - local slot = self.slots[i] - if slot ~= nil and slot.itemId == itemId then - local take = math.min(slot.count, remaining) - slot.count = slot.count - take - remaining = remaining - take - if slot.count <= 0 then - self.slots[i] = nil - end - end - i = i - 1 - end - end - return true -end -function InventorySystem.prototype.SwapSlots(self, slotA, slotB) - if slotA < 0 or slotA >= self.capacity or slotB < 0 or slotB >= self.capacity then - return false - end - local tmp = self.slots[slotA] - self.slots[slotA] = self.slots[slotB] - self.slots[slotB] = tmp - return true -end -function InventorySystem.prototype.SplitSlot(self, fromSlot, toSlot, splitCount) - if fromSlot < 0 or fromSlot >= self.capacity or toSlot < 0 or toSlot >= self.capacity or fromSlot == toSlot then - return false - end - local src = self.slots[fromSlot] - if src == nil or self.slots[toSlot] ~= nil then - return false - end - if splitCount <= 0 or splitCount >= src.count then - return false - end - src.count = src.count - splitCount - self.slots[toSlot] = {itemId = src.itemId, count = splitCount} - return true -end -function InventorySystem.prototype.GetItemCount(self, itemId) - local total = 0 - do - local i = 0 - while i < self.capacity do - local slot = self.slots[i] - if slot ~= nil and slot.itemId == itemId then - total = total + slot.count - end - i = i + 1 - end - end - return total -end -function InventorySystem.prototype.GetSlot(self, index) - return self.slots[index] -end -function InventorySystem.prototype.GetUsedSlotCount(self) - local used = 0 - do - local i = 0 - while i < self.capacity do - if self.slots[i] ~= nil then - used = used + 1 - end - i = i + 1 - end - end - return used -end -function InventorySystem.prototype.FilterByCategory(self, category) - local out = {} - do - local i = 0 - while i < self.capacity do - local slot = self.slots[i] - if slot ~= nil then - local def = self.defs[slot.itemId] - if def ~= nil and def.category == category then - out[#out + 1] = slot - end - end - i = i + 1 - end - end - return out -end -function InventorySystem.prototype.Serialize(self) - local copiedSlots = {} - do - local i = 0 - while i < self.capacity do - local s = self.slots[i] - if s ~= nil then - copiedSlots[i] = {itemId = s.itemId, count = s.count} - end - i = i + 1 - end - end - return {capacity = self.capacity, slots = copiedSlots} -end -function InventorySystem.prototype.Deserialize(self, data) - self.capacity = data.capacity - self.slots = {} - for idx, s in pairs(data.slots) do - self.slots[idx] = {itemId = s.itemId, count = s.count} - end -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Gameplay/ObjectPool.lua b/Script/lua/Tests/Gameplay/ObjectPool.lua deleted file mode 100644 index a445b5f..0000000 --- a/Script/lua/Tests/Gameplay/ObjectPool.lua +++ /dev/null @@ -1,60 +0,0 @@ -local ____exports = __module.env -____exports.ObjectPool = __TS__DefineClass("ObjectPool", __module) -local ObjectPool = ____exports.ObjectPool -ObjectPool.name = "ObjectPool" -function ObjectPool.prototype.____constructor(self, options) - self.idle = {} - self.activeCount = 0 - self.totalCreated = 0 - self.factory = options.factory - self.onAcquire = options.onAcquire - self.onRelease = options.onRelease - self.maxCapacity = options.maxCapacity or 64 -end -function ObjectPool.prototype.Prewarm(self, count) - local target = math.min(count, self.maxCapacity) - while #self.idle < target do - self.totalCreated = self.totalCreated + 1 - self.idle[#self.idle + 1] = self.factory() - end -end -function ObjectPool.prototype.Acquire(self) - local obj - if #self.idle > 0 then - obj = table.remove(self.idle) - else - self.totalCreated = self.totalCreated + 1 - obj = self.factory() - end - self.activeCount = self.activeCount + 1 - if self.onAcquire then - self.onAcquire(obj) - end - return obj -end -function ObjectPool.prototype.Release(self, obj) - if self.activeCount > 0 then - self.activeCount = self.activeCount - 1 - end - if self.onRelease then - self.onRelease(obj) - end - if #self.idle < self.maxCapacity then - self.idle[#self.idle + 1] = obj - end -end -function ObjectPool.prototype.Clear(self) - self.idle = {} - self.activeCount = 0 -end -function ObjectPool.prototype.GetIdleCount(self) - return #self.idle -end -function ObjectPool.prototype.GetActiveCount(self) - return self.activeCount -end -function ObjectPool.prototype.GetTotalCreated(self) - return self.totalCreated -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Gameplay/TimerScheduler.lua b/Script/lua/Tests/Gameplay/TimerScheduler.lua deleted file mode 100644 index 494f5d6..0000000 --- a/Script/lua/Tests/Gameplay/TimerScheduler.lua +++ /dev/null @@ -1,158 +0,0 @@ -local ____exports = __module.env -____exports.TimerScheduler = __TS__DefineClass("TimerScheduler", __module) -local TimerScheduler = ____exports.TimerScheduler -TimerScheduler.name = "TimerScheduler" -function TimerScheduler.prototype.____constructor(self) - self.nextId = 1 - self.timers = {} - self.timeScale = 1 -end -function TimerScheduler.prototype.ScheduleOnce(self, delay, callback) - return self:AddTimer(delay, 1, callback) -end -function TimerScheduler.prototype.ScheduleRepeat(self, interval, callback, maxRepeats) - if maxRepeats == nil then - maxRepeats = 0 - end - return self:AddTimer(interval, maxRepeats, callback) -end -function TimerScheduler.prototype.AddTimer(self, interval, maxRepeats, callback) - local ____self_0, ____nextId_1 = self, "nextId" - local ____self_nextId_2 = ____self_0[____nextId_1] - ____self_0[____nextId_1] = ____self_nextId_2 + 1 - local id = ____self_nextId_2 - local safeInterval = math.max(0.0001, interval) - self.timers[#self.timers + 1] = { - id = id, - interval = safeInterval, - remaining = safeInterval, - maxRepeats = maxRepeats, - firedCount = 0, - paused = false, - cancelled = false, - callback = callback - } - return id -end -function TimerScheduler.prototype.Cancel(self, handleId) - do - local i = 0 - while i < #self.timers do - if self.timers[i + 1].id == handleId and not self.timers[i + 1].cancelled then - self.timers[i + 1].cancelled = true - return true - end - i = i + 1 - end - end - return false -end -function TimerScheduler.prototype.SetPaused(self, handleId, paused) - do - local i = 0 - while i < #self.timers do - if self.timers[i + 1].id == handleId then - self.timers[i + 1].paused = paused - return - end - i = i + 1 - end - end -end -function TimerScheduler.prototype.SetTimeScale(self, scale) - self.timeScale = math.max(0, scale) -end -function TimerScheduler.prototype.Tick(self, dt) - local scaledDt = dt * self.timeScale - if scaledDt <= 0 then - return - end - local snapshot = {} - do - local i = 0 - while i < #self.timers do - snapshot[i + 1] = self.timers[i + 1] - i = i + 1 - end - end - do - local i = 0 - while i < #snapshot do - do - local t = snapshot[i + 1] - if t.cancelled or t.paused then - goto __continue20 - end - t.remaining = t.remaining - scaledDt - while not t.cancelled and not t.paused and t.remaining <= 0 do - t.firedCount = t.firedCount + 1 - t.callback(t.id) - if t.maxRepeats > 0 and t.firedCount >= t.maxRepeats then - t.cancelled = true - break - end - t.remaining = t.remaining + t.interval - end - end - ::__continue20:: - i = i + 1 - end - end - do - local i = #self.timers - 1 - while i >= 0 do - if self.timers[i + 1].cancelled then - table.remove(self.timers, i + 1) - end - i = i - 1 - end - end -end -function TimerScheduler.prototype.GetActiveCount(self) - local count = 0 - do - local i = 0 - while i < #self.timers do - if not self.timers[i + 1].cancelled then - count = count + 1 - end - i = i + 1 - end - end - return count -end -____exports.CooldownTracker = __TS__DefineClass("CooldownTracker", __module) -local CooldownTracker = ____exports.CooldownTracker -CooldownTracker.name = "CooldownTracker" -function CooldownTracker.prototype.____constructor(self) - self.remainingMap = {} -end -function CooldownTracker.prototype.StartCooldown(self, skillId, duration) - if duration > 0 then - self.remainingMap[skillId] = duration - end -end -function CooldownTracker.prototype.IsReady(self, skillId) - local rem = self.remainingMap[skillId] - return rem == nil or rem <= 0 -end -function CooldownTracker.prototype.GetRemaining(self, skillId) - return self.remainingMap[skillId] or 0 -end -function CooldownTracker.prototype.ReduceCooldown(self, skillId, seconds) - local rem = self.remainingMap[skillId] - if rem ~= nil then - local next = rem - seconds - self.remainingMap[skillId] = next > 0 and next or nil - end -end -function CooldownTracker.prototype.Tick(self, dt) - for skillId, rem in pairs(self.remainingMap) do - if rem ~= nil then - local next = rem - dt - self.remainingMap[skillId] = next > 0 and next or nil - end - end -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Harness/MockUnLuaRuntime.lua b/Script/lua/Tests/Harness/MockUnLuaRuntime.lua deleted file mode 100644 index a976618..0000000 --- a/Script/lua/Tests/Harness/MockUnLuaRuntime.lua +++ /dev/null @@ -1,1082 +0,0 @@ -local ____exports = __module.env -local state -function ____exports.GetMockState() - return state -end -function ____exports.ResetMockState() - state = { - printedStrings = {}, - logs = {}, - timers = {}, - nextTimerId = 1, - latentDelays = {}, - inputBindings = {}, - manualRefs = {}, - spawnedActors = {}, - createdObjects = {}, - overriddenCalls = {} - } -end ---- 模拟推进定时器与 Latent Delay 协程 -function ____exports.AdvanceMockTime(deltaSeconds) - local timerSnapshot = {} - do - local i = 0 - while i < #state.timers do - timerSnapshot[i + 1] = state.timers[i + 1] - i = i + 1 - end - end - do - local i = 0 - while i < #timerSnapshot do - do - local t = timerSnapshot[i + 1] - if not t.active or t.paused then - goto __continue8 - end - t.remaining = t.remaining - deltaSeconds - while t.active and not t.paused and t.remaining <= 0 do - t.callback(t.target) - if t.looping and t.active then - t.remaining = t.remaining + t.interval - else - t.active = false - break - end - end - end - ::__continue8:: - i = i + 1 - end - end - local ready = {} - do - local i = #state.latentDelays - 1 - while i >= 0 do - local entry = state.latentDelays[i + 1] - entry.remaining = entry.remaining - deltaSeconds - if entry.remaining <= 0 then - table.remove(state.latentDelays, i + 1) - ready[#ready + 1] = entry - end - i = i - 1 - end - end - do - local i = 0 - while i < #ready do - local entry = ready[i + 1] - if coroutine.status(entry.co) == "suspended" then - local ok, err = coroutine.resume(entry.co) - if not ok then - error("Latent coroutine resume error: " .. tostring(err)) - end - end - i = i + 1 - end - end -end ---- 构造模拟的 MulticastDelegate -function ____exports.CreateMockMulticastDelegate() - local entries = {} - local delegate = { - Add = function(self, target, cb) - do - local i = 0 - while i < #entries do - if entries[i + 1].target == target and entries[i + 1].cb == cb then - return - end - i = i + 1 - end - end - entries[#entries + 1] = {target = target, cb = cb} - end, - Remove = function(self, target, cb) - do - local i = #entries - 1 - while i >= 0 do - if entries[i + 1].target == target and entries[i + 1].cb == cb then - table.remove(entries, i + 1) - end - i = i - 1 - end - end - end, - Clear = function(self) - do - local i = #entries - 1 - while i >= 0 do - table.remove(entries, i + 1) - i = i - 1 - end - end - end, - Broadcast = function(self, ...) - local snap = {} - do - local i = 0 - while i < #entries do - snap[i + 1] = entries[i + 1] - i = i + 1 - end - end - do - local i = 0 - while i < #snap do - snap[i + 1].cb(snap[i + 1].target, ...) - i = i + 1 - end - end - end, - IsBound = function(self) - return #entries > 0 - end - } - return delegate -end ---- 构造模拟的 FScriptDelegate -function ____exports.CreateMockScriptDelegate() - local boundTarget = nil - local boundCb = nil - local delegate = { - Bind = function(self, target, cb) - boundTarget = target - boundCb = cb - end, - Unbind = function(self) - boundTarget = nil - boundCb = nil - end, - Execute = function(self, ...) - if boundCb ~= nil then - return boundCb(boundTarget, ...) - end - return nil - end - } - return delegate -end ---- 构造模拟的 UObject/AActor/UUserWidget 实例并绑定 UnLua Lua 类表 -function ____exports.CreateBoundInstance(luaClass, nativeClassName, extraProps) - local uobj = { - __isMockUObject = true, - __valid = true, - __className = nativeClassName, - __name = nativeClassName .. "_Instance", - __location = UE.FVector(0, 0, 0), - __rotation = UE.FRotator(0, 0, 0), - __inViewport = false, - __released = false, - OnTakeAnyDamage = ____exports.CreateMockMulticastDelegate(), - OnActorBeginOverlap = ____exports.CreateMockMulticastDelegate(), - OnClicked = ____exports.CreateMockMulticastDelegate(), - Overridden = setmetatable( - {}, - {__index = function(_t, methodName) - return function(selfObj, ...) - state.overriddenCalls[#state.overriddenCalls + 1] = (tostring(selfObj.__className) .. ".") .. methodName - end - end} - ) - } - uobj.GetName = function(self) - return self.__name - end - uobj.IsValid = function(self) - return self.__valid == true - end - uobj.IsA = function(self, cls) - if not cls then - return false - end - local target = cls.__className - if self.__className == target then - return true - end - if target == "UObject" then - return true - end - if target == "AActor" and (self.__className == "AActor" or self.__className == "ALuaDemoActor" or self.__className == "APlayerController" or self.__className == "ACharacter") then - return true - end - if target == "UUserWidget" and self.__className == "UUserWidget" then - return true - end - return false - end - uobj.GetWorld = function() - return _G.__MockWorld - end - uobj.K2_GetActorLocation = function(self) - return UE.FVector(self.__location.X, self.__location.Y, self.__location.Z) - end - uobj.K2_SetActorLocation = function(self, loc, _bSweep, outHit, _bTeleport) - self.__location = UE.FVector(loc.X, loc.Y, loc.Z) - local hit = outHit or ({bBlockingHit = false, Distance = 0, Location = loc}) - return true, hit - end - uobj.K2_GetActorRotation = function(self) - return UE.FRotator(self.__rotation.Pitch, self.__rotation.Yaw, self.__rotation.Roll) - end - uobj.K2_SetActorRotation = function(self, rot) - self.__rotation = UE.FRotator(rot.Pitch, rot.Yaw, rot.Roll) - return true - end - uobj.K2_DestroyActor = function(self) - self.__valid = false - end - uobj.AddToViewport = function(self) - self.__inViewport = true - end - uobj.RemoveFromViewport = function(self) - self.__inViewport = false - end - uobj.RemoveFromParent = function(self) - self.__inViewport = false - end - uobj.Release = function(self) - self.__released = true - end - uobj.Destroy = function(self) - self.__valid = false - end - if extraProps ~= nil then - for k, v in pairs(extraProps) do - uobj[k] = v - end - end - setmetatable( - uobj, - {__index = function(t, k) - local cur = luaClass - while cur ~= nil do - local v = rawget(cur, k) - if v ~= nil then - return v - end - cur = rawget(cur, "Super") - end - return rawget(t, k) - end} - ) - return uobj -end -local function CreateMockTArray() - local data = {} - local arr = { - Length = function(self) - return #data - end, - Num = function(self) - return #data - end, - Add = function(self, item) - data[#data + 1] = item - return #data - end, - AddUnique = function(self, item) - do - local i = 0 - while i < #data do - if data[i + 1] == item then - return i + 1 - end - i = i + 1 - end - end - data[#data + 1] = item - return #data - end, - Find = function(self, item) - do - local i = 0 - while i < #data do - if data[i + 1] == item then - return i + 1 - end - i = i + 1 - end - end - return 0 - end, - Insert = function(self, item, index) - table.insert(data, index, item) - end, - Remove = function(self, index) - table.remove(data, index) - end, - RemoveItem = function(self, item) - local removed = 0 - do - local i = #data - 1 - while i >= 0 do - if data[i + 1] == item then - table.remove(data, i + 1) - removed = removed + 1 - end - i = i - 1 - end - end - return removed - end, - Clear = function(self) - do - local i = #data - 1 - while i >= 0 do - table.remove(data, i + 1) - i = i - 1 - end - end - end, - Reserve = function(self, _size) - return #data == 0 - end, - Resize = function(self, size) - while #data > size do - table.remove(data) - end - while #data < size do - data[#data + 1] = 0 - end - end, - GetData = function(self) - return data - end, - Get = function(self, index) - return data[index] - end, - GetRef = function(self, index) - return data[index] - end, - Set = function(self, index, item) - data[index] = item - end, - Swap = function(self, firstIndex, secondIndex) - local tmp = data[firstIndex] - data[firstIndex] = data[secondIndex] - data[secondIndex] = tmp - end, - Shuffle = function(self) - do - local i = #data - 1 - while i > 0 do - local j = math.random(0, i) - local tmp = data[i + 1] - data[i + 1] = data[j + 1] - data[j + 1] = tmp - i = i - 1 - end - end - end, - LastIndex = function(self) - return #data - end, - IsValidIndex = function(self, index) - return index >= 1 and index <= #data - end, - Contains = function(self, item) - do - local i = 0 - while i < #data do - if data[i + 1] == item then - return true - end - i = i + 1 - end - end - return false - end, - Append = function(self, other) - do - local i = 1 - while i <= other:Length() do - data[#data + 1] = other:Get(i) - i = i + 1 - end - end - end, - ToTable = function(self) - local copy = {} - do - local i = 0 - while i < #data do - copy[i + 1] = data[i + 1] - i = i + 1 - end - end - return copy - end - } - setmetatable( - arr, - {__pairs = function() - local idx = 0 - return function() - idx = idx + 1 - if idx <= #data then - return idx, data[idx] - end - return nil - end - end} - ) - return arr -end -local function CreateMockTMap() - local entries = {} - local m = { - Length = function(self) - local n = 0 - for _ in pairs(entries) do - n = n + 1 - end - return n - end, - Num = function(self) - return self:Length() - end, - Add = function(self, k, v) - entries[k] = v - end, - Remove = function(self, k) - if entries[k] ~= nil then - entries[k] = nil - return true - end - return false - end, - Find = function(self, k) - return entries[k] - end, - FindRef = function(self, k) - return entries[k] - end, - Clear = function(self) - for k in pairs(entries) do - entries[k] = nil - end - end, - Keys = function(self) - local arr = CreateMockTArray() - for k in pairs(entries) do - arr:Add(k) - end - return arr - end, - Values = function(self) - local arr = CreateMockTArray() - for _, v in pairs(entries) do - arr:Add(v) - end - return arr - end, - ToTable = function(self) - local copy = {} - for k, v in pairs(entries) do - copy[k] = v - end - return copy - end - } - setmetatable( - m, - {__pairs = function() - return next, entries, nil - end} - ) - return m -end -local function CreateMockTSet() - local entries = {} - local s = { - Length = function(self) - local n = 0 - for _ in pairs(entries) do - n = n + 1 - end - return n - end, - Num = function(self) - return self:Length() - end, - Add = function(self, item) - entries[item] = true - end, - Remove = function(self, item) - if entries[item] then - entries[item] = nil - return true - end - return false - end, - Contains = function(self, item) - return entries[item] == true - end, - Clear = function(self) - for k in pairs(entries) do - entries[k] = nil - end - end, - ToArray = function(self) - local arr = CreateMockTArray() - for k in pairs(entries) do - arr:Add(k) - end - return arr - end, - ToTable = function(self) - local arr = {} - for k in pairs(entries) do - arr[#arr + 1] = k - end - return arr - end - } - return s -end -local function CreateMockFVector(x, y, z) - local vx = 0 - local vy = 0 - local vz = 0 - if x ~= nil and y == nil and z == nil then - vx = x - vy = x - vz = x - else - vx = x or 0 - vy = y or 0 - vz = z or 0 - end - local vec = { - X = vx, - Y = vy, - Z = vz, - Set = function(self, nx, ny, nz) - if nx ~= nil then - self.X = nx - end - if ny ~= nil then - self.Y = ny - end - if nz ~= nil then - self.Z = nz - end - end, - Add = function(self, other) - if type(other) == "number" then - self.X = self.X + other - self.Y = self.Y + other - self.Z = self.Z + other - else - self.X = self.X + other.X - self.Y = self.Y + other.Y - self.Z = self.Z + other.Z - end - end, - Sub = function(self, other) - if type(other) == "number" then - self.X = self.X - other - self.Y = self.Y - other - self.Z = self.Z - other - else - self.X = self.X - other.X - self.Y = self.Y - other.Y - self.Z = self.Z - other.Z - end - end, - Mul = function(self, other) - if type(other) == "number" then - self.X = self.X * other - self.Y = self.Y * other - self.Z = self.Z * other - else - self.X = self.X * other.X - self.Y = self.Y * other.Y - self.Z = self.Z * other.Z - end - end, - Div = function(self, other) - if type(other) == "number" then - self.X = self.X / other - self.Y = self.Y / other - self.Z = self.Z / other - else - self.X = self.X / other.X - self.Y = self.Y / other.Y - self.Z = self.Z / other.Z - end - end, - Dot = function(self, other) - return self.X * other.X + self.Y * other.Y + self.Z * other.Z - end, - Cross = function(self, other) - return CreateMockFVector(self.Y * other.Z - self.Z * other.Y, self.Z * other.X - self.X * other.Z, self.X * other.Y - self.Y * other.X) - end, - Size = function(self) - return math.sqrt(self.X * self.X + self.Y * self.Y + self.Z * self.Z) - end, - Size2D = function(self) - return math.sqrt(self.X * self.X + self.Y * self.Y) - end, - SizeSquared = function(self) - return self.X * self.X + self.Y * self.Y + self.Z * self.Z - end, - SizeSquared2D = function(self) - return self.X * self.X + self.Y * self.Y - end, - Normalize = function(self, tol) - if tol == nil then - tol = 1e-8 - end - local sq = self:SizeSquared() - if sq > tol then - local inv = 1 / math.sqrt(sq) - self.X = self.X * inv - self.Y = self.Y * inv - self.Z = self.Z * inv - return true - end - return false - end, - IsNormalized = function(self) - return math.abs(1 - self:SizeSquared()) < 0.01 - end - } - return vec -end -local function CreateMockFRotator(pitch, yaw, roll) - if pitch == nil then - pitch = 0 - end - if yaw == nil then - yaw = 0 - end - if roll == nil then - roll = 0 - end - return { - Pitch = pitch, - Yaw = yaw, - Roll = roll, - ToQuat = function(self) - return {X = self.Pitch, Y = self.Yaw, Z = self.Roll, W = 1} - end - } -end -local function CreateMockFTransform(rot, trans, scale) - return { - Rotation = rot or ({X = 0, Y = 0, Z = 0, W = 1}), - Translation = trans or CreateMockFVector(), - Scale3D = scale or CreateMockFVector(1, 1, 1) - } -end -local function CreateMockFLinearColor(r, g, b, a) - if r == nil then - r = 0 - end - if g == nil then - g = 0 - end - if b == nil then - b = 0 - end - if a == nil then - a = 1 - end - return {R = r, G = g, B = b, A = a} -end -local function MakeMockClassObject(name) - return { - __className = name, - __valid = true, - GetName = function(self) - return name - end, - IsChildOf = function(self, other) - return other ~= nil and (self.__className == other.__className or other.__className == "UObject") - end - } -end -function ____exports.InstallIfNeeded() - ____exports.ResetMockState() - local g = _G - if g.UnLua ~= nil and g.UE ~= nil then - return - end - g.UnLua = { - PackagePath = "Script/lua/?.lua", - FTextEnabled = false, - Class = function(superName) - local ____temp_0 - if superName ~= nil then - ____temp_0 = require(superName) - else - ____temp_0 = nil - end - local superClass = ____temp_0 - local cls = {} - cls.Super = superClass - return cls - end, - Ref = function(obj) - local cur = state.manualRefs[obj] or 0 - state.manualRefs[obj] = cur + 1 - return {__refTarget = obj} - end, - Unref = function(obj) - state.manualRefs[obj] = nil - end, - HotReload = function() - state.logs[#state.logs + 1] = "UnLua.HotReload()" - end, - Log = function(...) - local args = {...} - local parts = {} - do - local i = 0 - while i < #args do - parts[i + 1] = tostring(args[i + 1]) - i = i + 1 - end - end - state.logs[#state.logs + 1] = table.concat(parts, "\t") - end, - LogWarn = function(...) - local args = {...} - local parts = {} - do - local i = 0 - while i < #args do - parts[i + 1] = tostring(args[i + 1]) - i = i + 1 - end - end - state.logs[#state.logs + 1] = "[WARN] " .. table.concat(parts, "\t") - end, - LogError = function(...) - local args = {...} - local parts = {} - do - local i = 0 - while i < #args do - parts[i + 1] = tostring(args[i + 1]) - i = i + 1 - end - end - state.logs[#state.logs + 1] = "[ERROR] " .. table.concat(parts, "\t") - end, - Input = { - BindKey = function(mod, keyName, keyEvent, handler, args) - state.inputBindings[#state.inputBindings + 1] = { - kind = "Key", - module = mod, - name = keyName, - event = keyEvent, - handler = handler, - args = args - } - end, - BindAction = function(mod, actionName, keyEvent, handler, args) - state.inputBindings[#state.inputBindings + 1] = { - kind = "Action", - module = mod, - name = actionName, - event = keyEvent, - handler = handler, - args = args - } - end, - BindAxis = function(mod, axisName, handler, args) - state.inputBindings[#state.inputBindings + 1] = { - kind = "Axis", - module = mod, - name = axisName, - event = "Axis", - handler = handler, - args = args - } - end - }, - EnhancedInput = {BindAction = function(mod, actionPath, triggerEvent, handler, args) - state.inputBindings[#state.inputBindings + 1] = { - kind = "EnhancedAction", - module = mod, - name = actionPath, - event = triggerEvent, - handler = handler, - args = args - } - end} - } - local FVectorTable = { - Dist = function(a, b) - local dx = a.X - b.X - local dy = a.Y - b.Y - local dz = a.Z - b.Z - return math.sqrt(dx * dx + dy * dy + dz * dz) - end, - Dist2D = function(a, b) - local dx = a.X - b.X - local dy = a.Y - b.Y - return math.sqrt(dx * dx + dy * dy) - end, - DistSquared = function(a, b) - local dx = a.X - b.X - local dy = a.Y - b.Y - local dz = a.Z - b.Z - return dx * dx + dy * dy + dz * dz - end - } - setmetatable( - FVectorTable, - {__call = function(self, x, y, z) - return CreateMockFVector(x, y, z) - end} - ) - local mockWorld = { - SpawnActor = function(self, actorClass, transform, _collision, owner, _instigator, moduleName, initializer) - local luaCls = moduleName ~= nil and require(moduleName) or ({}) - local ____exports_CreateBoundInstance_5 = ____exports.CreateBoundInstance - local ____tostring_4 = tostring - local ____temp_3 = actorClass and actorClass.__className - if ____temp_3 == nil then - ____temp_3 = "AActor" - end - local inst = ____exports_CreateBoundInstance_5( - luaCls, - ____tostring_4(____temp_3), - {Owner = owner} - ) - if transform ~= nil then - inst.__location = transform.Translation - end - if type(inst.Initialize) == "function" then - inst:Initialize(initializer) - end - if type(inst.ReceiveBeginPlay) == "function" then - inst:ReceiveBeginPlay() - end - state.spawnedActors[#state.spawnedActors + 1] = inst - return inst - end, - SpawnActorEx = function(self, actorClass, transform, initializer, moduleName, spawnParams) - return self:SpawnActor( - actorClass, - transform, - spawnParams and spawnParams.SpawnCollisionHandlingOverride, - spawnParams and spawnParams.Owner, - spawnParams and spawnParams.Instigator, - moduleName, - initializer - ) - end - } - g.__MockWorld = mockWorld - g.UE = { - int8 = "int8", - int16 = "int16", - int32 = "int32", - int64 = "int64", - uint8 = "uint8", - uint16 = "uint16", - uint32 = "uint32", - uint64 = "uint64", - float = "float", - double = "double", - bool = "bool", - FName = "FName", - FString = "FString", - FVector = FVectorTable, - FRotator = CreateMockFRotator, - FTransform = CreateMockFTransform, - FLinearColor = CreateMockFLinearColor, - FHitResult = function() return { - bBlockingHit = false, - Distance = 0, - Location = CreateMockFVector(), - ImpactPoint = CreateMockFVector(), - Normal = CreateMockFVector(0, 0, 1) - } end, - FActorSpawnParameters = function() return {Name = "", bNoFail = false, SpawnCollisionHandlingOverride = 0} end, - FWeakObjectPtr = function(initialObj) - local refObj = initialObj - return { - Set = function(self, o) - refObj = o - end, - Get = function(self) - return refObj ~= nil and refObj.__valid == true and refObj or nil - end, - IsValid = function(self) - return refObj ~= nil and refObj.__valid == true - end, - Reset = function(self) - refObj = nil - end - } - end, - TArray = function(_elemType) return CreateMockTArray() end, - TMap = function(_keyType, _valType) return CreateMockTMap() end, - TSet = function(_elemType) return CreateMockTSet() end, - ESpawnActorCollisionHandlingMethod = { - Undefined = 0, - AlwaysSpawn = 1, - AdjustIfPossibleButAlwaysSpawn = 2, - AdjustIfPossibleButDontSpawnIfColliding = 3, - DontSpawnIfColliding = 4 - }, - EDrawDebugTrace = {None = 0, ForOneFrame = 1, ForDuration = 2, Persistent = 3}, - ETraceTypeQuery = {TraceTypeQuery1 = 0, TraceTypeQuery2 = 1}, - EEndPlayReason = { - Destroyed = 0, - LevelTransition = 1, - EndPlayInEditor = 2, - RemovedFromWorld = 3, - Quit = 4 - }, - UObject = { - StaticClass = function() return MakeMockClassObject("UObject") end, - Load = function(assetPath) return { - __isMockUObject = true, - __valid = true, - __className = "UObject", - __assetPath = assetPath, - GetName = function(self) - return assetPath - end, - IsValid = function(self) - return true - end - } end - }, - UClass = { - StaticClass = function() return MakeMockClassObject("UClass") end, - Load = function(classPath) return MakeMockClassObject(classPath) end - }, - AActor = {StaticClass = function() return MakeMockClassObject("AActor") end}, - ALuaDemoActor = {StaticClass = function() return MakeMockClassObject("ALuaDemoActor") end}, - APlayerController = {StaticClass = function() return MakeMockClassObject("APlayerController") end}, - UUserWidget = {StaticClass = function() return MakeMockClassObject("UUserWidget") end}, - LoadClass = function(classPath) return MakeMockClassObject(classPath) end, - LoadObject = function(assetPath) return { - __isMockUObject = true, - __valid = true, - __className = "UObject", - __assetPath = assetPath, - GetName = function(self) - return assetPath - end, - IsValid = function(self) - return true - end - } end, - NewObject = function(cls, outer, name, moduleName, initializer) - local luaCls = moduleName ~= nil and require(moduleName) or ({}) - local ____exports_CreateBoundInstance_16 = ____exports.CreateBoundInstance - local ____tostring_15 = tostring - local ____temp_14 = cls and cls.__className - if ____temp_14 == nil then - ____temp_14 = "UObject" - end - local inst = ____exports_CreateBoundInstance_16( - luaCls, - ____tostring_15(____temp_14), - {__name = name or "NewObject", __outer = outer} - ) - if type(inst.Initialize) == "function" then - inst:Initialize(initializer) - end - state.createdObjects[#state.createdObjects + 1] = inst - return inst - end, - UKismetSystemLibrary = { - PrintString = function(_worldCtx, inString) - state.printedStrings[#state.printedStrings + 1] = inString or "" - end, - IsValid = function(obj) - return obj ~= nil and obj.__valid == true - end, - K2_SetTimerDelegate = function(delegatePair, time, bLooping) - local ____state_17, ____nextTimerId_18 = state, "nextTimerId" - local ____state_nextTimerId_19 = ____state_17[____nextTimerId_18] - ____state_17[____nextTimerId_18] = ____state_nextTimerId_19 + 1 - local handleId = ____state_nextTimerId_19 - state.timers[#state.timers + 1] = { - handleId = handleId, - target = delegatePair[1], - callback = delegatePair[2], - interval = time, - remaining = time, - looping = bLooping, - paused = false, - active = true - } - return {__handleId = handleId} - end, - K2_ClearAndInvalidateTimerHandle = function(_worldCtx, handle) - if handle and handle.__handleId ~= nil then - do - local i = 0 - while i < #state.timers do - if state.timers[i + 1].handleId == handle.__handleId then - state.timers[i + 1].active = false - end - i = i + 1 - end - end - handle.__handleId = nil - end - return handle or ({}) - end, - K2_IsTimerActiveHandle = function(_worldCtx, handle) - if not handle or handle.__handleId == nil then - return false - end - do - local i = 0 - while i < #state.timers do - if state.timers[i + 1].handleId == handle.__handleId then - return state.timers[i + 1].active and not state.timers[i + 1].paused - end - i = i + 1 - end - end - return false - end, - Delay = function(worldCtx, duration) - local co, isMain = coroutine.running() - assert(not isMain, "UKismetSystemLibrary.Delay must be called inside a coroutine!") - state.latentDelays[#state.latentDelays + 1] = {co = co, owner = worldCtx, remaining = duration} - coroutine.yield() - end, - RetriggerableDelay = function(worldCtx, duration) - local co, isMain = coroutine.running() - assert(not isMain, "RetriggerableDelay must be called inside a coroutine!") - state.latentDelays[#state.latentDelays + 1] = {co = co, owner = worldCtx, remaining = duration} - coroutine.yield() - end, - LineTraceSingle = function(_worldCtx, startVec, endVec, _channel, _bTraceComplex, _actorsToIgnore, _drawDebugType, outHit, _bIgnoreSelf) - local dist = UE.FVector.Dist(startVec, endVec) - local hit = outHit or ({ - bBlockingHit = false, - Distance = 0, - Location = CreateMockFVector(), - ImpactPoint = CreateMockFVector() - }) - local bHit = dist > 0 - hit.bBlockingHit = bHit - hit.Distance = dist * 0.5 - hit.Location = CreateMockFVector((startVec.X + endVec.X) * 0.5, (startVec.Y + endVec.Y) * 0.5, (startVec.Z + endVec.Z) * 0.5) - hit.ImpactPoint = hit.Location - if outHit ~= nil then - return bHit, nil - end - return bHit, hit - end - } - } -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/Harness/TestRunner.lua b/Script/lua/Tests/Harness/TestRunner.lua deleted file mode 100644 index 2a3b860..0000000 --- a/Script/lua/Tests/Harness/TestRunner.lua +++ /dev/null @@ -1,163 +0,0 @@ -local ____exports = __module.env -local currentSuite = "Default" -local results = {} -function ____exports.Reset() - currentSuite = "Default" - results = {} -end -function ____exports.Suite(name, body) - local prev = currentSuite - currentSuite = name - body() - currentSuite = prev -end -function ____exports.Test(name, fn) - local ok, err = pcall(fn) - if ok then - results[#results + 1] = {suite = currentSuite, name = name, passed = true} - else - results[#results + 1] = { - suite = currentSuite, - name = name, - passed = false, - errorMessage = tostring(err) - } - end -end -function ____exports.AssertTrue(cond, msg) - if not cond then - error(msg or "Expected condition to be truthy", 2) - end -end -function ____exports.AssertFalse(cond, msg) - if cond then - error(msg or "Expected condition to be falsy", 2) - end -end -function ____exports.AssertEqual(actual, expected, msg) - if actual ~= expected then - local prefix = msg and msg .. ": " or "" - error( - string.format( - "%sExpected %s, got %s", - prefix, - tostring(expected), - tostring(actual) - ), - 2 - ) - end -end -function ____exports.AssertNear(actual, expected, epsilon, msg) - if epsilon == nil then - epsilon = 0.0001 - end - if math.abs(actual - expected) > epsilon then - local prefix = msg and msg .. ": " or "" - error( - string.format( - "%sExpected %.6f (±%.6f), got %.6f", - prefix, - expected, - epsilon, - actual - ), - 2 - ) - end -end -function ____exports.AssertNil(value, msg) - if value ~= nil then - local prefix = msg and msg .. ": " or "" - error( - string.format( - "%sExpected nil, got %s", - prefix, - tostring(value) - ), - 2 - ) - end -end -function ____exports.AssertNotNil(value, msg) - if value == nil then - error(msg or "Expected non-nil value", 2) - end -end -function ____exports.AssertArrayEqual(actual, expected, msg) - local prefix = msg and msg .. ": " or "" - if #actual ~= #expected then - error( - string.format("%sArray length mismatch: expected %d, got %d", prefix, #expected, #actual), - 2 - ) - end - do - local i = 0 - while i < #expected do - if actual[i + 1] ~= expected[i + 1] then - error( - string.format( - "%sArray element [%d] mismatch: expected %s, got %s", - prefix, - i, - tostring(expected[i + 1]), - tostring(actual[i + 1]) - ), - 2 - ) - end - i = i + 1 - end - end -end -function ____exports.GetSummary() - local passed = 0 - local failed = 0 - do - local i = 0 - while i < #results do - if results[i + 1].passed then - passed = passed + 1 - else - failed = failed + 1 - end - i = i + 1 - end - end - return {total = #results, passed = passed, failed = failed, results = results} -end -function ____exports.FormatReport(summary) - local s = summary or ____exports.GetSummary() - local lines = {} - local lastSuite = "" - do - local i = 0 - while i < #s.results do - local r = s.results[i + 1] - if r.suite ~= lastSuite then - lastSuite = r.suite - lines[#lines + 1] = "" - lines[#lines + 1] = string.format("[%s]", r.suite) - end - if r.passed then - lines[#lines + 1] = string.format(" PASS %s", r.name) - else - lines[#lines + 1] = string.format(" FAIL %s\n -> %s", r.name, r.errorMessage or "unknown error") - end - i = i + 1 - end - end - lines[#lines + 1] = "" - lines[#lines + 1] = "========================================" - lines[#lines + 1] = string.format("Total: %d | Passed: %d | Failed: %d", s.total, s.passed, s.failed) - lines[#lines + 1] = "========================================" - return table.concat(lines, "\n") -end -function ____exports.PrintReport() - local summary = ____exports.GetSummary() - print(____exports.FormatReport(summary)) - return summary -end -function __module.UpdateImports() -end diff --git a/Script/lua/Tests/RunAllTests.lua b/Script/lua/Tests/RunAllTests.lua deleted file mode 100644 index 6e2b1e8..0000000 --- a/Script/lua/Tests/RunAllTests.lua +++ /dev/null @@ -1,59 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Reset = M__Tests_Harness_TestRunner.Reset -local PrintReport = M__Tests_Harness_TestRunner.PrintReport -local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) -local InstallIfNeeded = M__Tests_Harness_MockUnLuaRuntime.InstallIfNeeded -local M__Tests_Syntax_BasicTypesAndControlFlow = __MODULE__.Import("Tests.Syntax.BasicTypesAndControlFlow", __module) -local RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests -local M__Tests_Syntax_FunctionsClosuresAndTuples = __MODULE__.Import("Tests.Syntax.FunctionsClosuresAndTuples", __module) -local RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests -local M__Tests_Syntax_PureClassesAndGenerics = __MODULE__.Import("Tests.Syntax.PureClassesAndGenerics", __module) -local RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests -local M__Tests_Syntax_UnLuaSyntaxSuite = __MODULE__.Import("Tests.Syntax.UnLuaSyntaxSuite", __module) -local RunUnLuaSyntaxTests = M__Tests_Syntax_UnLuaSyntaxSuite.RunUnLuaSyntaxTests -local M__Tests_UnLuaExamples_UnLuaExamplesSuite = __MODULE__.Import("Tests.UnLuaExamples.UnLuaExamplesSuite", __module) -local RunUnLuaExamplesTests = M__Tests_UnLuaExamples_UnLuaExamplesSuite.RunUnLuaExamplesTests -local M__Tests_Gameplay_GameplaySuite = __MODULE__.Import("Tests.Gameplay.GameplaySuite", __module) -local RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests -local M__Tests_Extra_HotReloadAndFrameworkTest = __MODULE__.Import("Tests.Extra.HotReloadAndFrameworkTest", __module) -local RunHotReloadAndFrameworkTests = M__Tests_Extra_HotReloadAndFrameworkTest.RunHotReloadAndFrameworkTests -local M__Tests_Extra_Lua54PitfallsTest = __MODULE__.Import("Tests.Extra.Lua54PitfallsTest", __module) -local RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests -local M__Tests_Extra_LifecycleAndMemoryTest = __MODULE__.Import("Tests.Extra.LifecycleAndMemoryTest", __module) -local RunLifecycleAndMemoryTests = M__Tests_Extra_LifecycleAndMemoryTest.RunLifecycleAndMemoryTests -function ____exports.RunAll() - InstallIfNeeded() - Reset() - RunBasicTypesAndControlFlowTests() - RunFunctionsClosuresAndTuplesTests() - RunPureClassesAndGenericsTests() - RunUnLuaSyntaxTests() - RunUnLuaExamplesTests() - RunGameplayTests() - RunHotReloadAndFrameworkTests() - RunLua54PitfallsTests() - RunLifecycleAndMemoryTests() - return PrintReport() -end -local g = _G -if g.__TS2LUA_TEST_AUTO_RUN__ == true then - local summary = ____exports.RunAll() - if summary.failed > 0 then - os.exit(1) - end -end -function __module.UpdateImports() - Reset = M__Tests_Harness_TestRunner.Reset - PrintReport = M__Tests_Harness_TestRunner.PrintReport - InstallIfNeeded = M__Tests_Harness_MockUnLuaRuntime.InstallIfNeeded - RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests - RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests - RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests - RunUnLuaSyntaxTests = M__Tests_Syntax_UnLuaSyntaxSuite.RunUnLuaSyntaxTests - RunUnLuaExamplesTests = M__Tests_UnLuaExamples_UnLuaExamplesSuite.RunUnLuaExamplesTests - RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests - RunHotReloadAndFrameworkTests = M__Tests_Extra_HotReloadAndFrameworkTest.RunHotReloadAndFrameworkTests - RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests - RunLifecycleAndMemoryTests = M__Tests_Extra_LifecycleAndMemoryTest.RunLifecycleAndMemoryTests -end diff --git a/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua b/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua deleted file mode 100644 index 5c84076..0000000 --- a/Script/lua/Tests/Syntax/BasicTypesAndControlFlow.lua +++ /dev/null @@ -1,258 +0,0 @@ -local ____lualib = require("lualib_bundle") -local __TS__SparseArrayNew = ____lualib.__TS__SparseArrayNew -local __TS__SparseArrayPush = ____lualib.__TS__SparseArrayPush -local __TS__SparseArraySpread = ____lualib.__TS__SparseArraySpread -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertNear = M__Tests_Harness_TestRunner.AssertNear -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local function EvaluateCommand(action) - repeat - local ____switch3 = action.kind - local ____cond3 = ____switch3 == "move" - if ____cond3 then - return action.x + action.y - end - ____cond3 = ____cond3 or ____switch3 == "damage" - if ____cond3 then - return action.crit and action.amount * 2 or action.amount - end - ____cond3 = ____cond3 or ____switch3 == "noop" - if ____cond3 then - return 0 - end - until true -end -function ____exports.RunBasicTypesAndControlFlowTests() - Suite( - "Syntax.BasicTypesAndControlFlow", - function() - Test( - "primitives, template literals, nullish coalescing and optional chaining", - function() - local count = 42 - local ratio = 0.5 - local label = (("Count=" .. tostring(count)) .. ",Half=") .. tostring(math.floor(count * ratio)) - AssertEqual(label, "Count=42,Half=21") - AssertEqual( - tostring(count * ratio), - "21.0" - ) - local maybeNum = nil - local zeroNum = 0 - local falseFlag = false - AssertEqual(maybeNum or 99, 99) - AssertEqual(zeroNum or 99, 0) - local ____AssertEqual_1 = AssertEqual - local ____falseFlag_0 = falseFlag - if ____falseFlag_0 == nil then - ____falseFlag_0 = true - end - ____AssertEqual_1(____falseFlag_0, false) - local a = {} - local b = {inner = {value = 7}} - local ____AssertNil_4 = AssertNil - local ____opt_2 = a.inner - ____AssertNil_4(____opt_2 and ____opt_2.value) - local ____AssertEqual_7 = AssertEqual - local ____opt_5 = b.inner - ____AssertEqual_7(____opt_5 and ____opt_5.value or -1, 7) - end - ) - Test( - "Lua 5.4 native bitwise operators and const enum inlining", - function() - local flags = 0 - flags = flags | 1 | 4 - AssertTrue(flags & 1 ~= 0) - AssertFalse(flags & 2 ~= 0) - AssertTrue(flags & 4 ~= 0) - flags = flags & ~4 - flags = flags ~ 2 - AssertFalse(flags & 4 ~= 0) - AssertTrue(flags & 2 ~= 0) - AssertEqual(1 << 4, 16) - AssertEqual((64 & 4294967295) >> 2, 16) - local role = "Healer" - AssertEqual(role, "Healer") - end - ) - Test( - "control flow: switch/case fallthrough, loops, continue, break, labeled loop", - function() - local function Classify(n) - repeat - local ____switch10 = n - local ____cond10 = ____switch10 == 1 or ____switch10 == 2 - if ____cond10 then - return "small" - end - ____cond10 = ____cond10 or ____switch10 == 3 - if ____cond10 then - return "medium" - end - do - return "large" - end - until true - end - AssertEqual( - Classify(1), - "small" - ) - AssertEqual( - Classify(2), - "small" - ) - AssertEqual( - Classify(3), - "medium" - ) - AssertEqual( - Classify(9), - "large" - ) - local sum = 0 - local i = 0 - while i < 10 do - do - i = i + 1 - if i % 2 == 0 then - goto __continue11 - end - if i > 7 then - break - end - sum = sum + i - end - ::__continue11:: - end - AssertEqual(sum, 16) - local doCount = 0 - repeat - do - doCount = doCount + 1 - end - until not false - AssertEqual(doCount, 1) - local foundPair = "" - local found = false - do - local r = 0 - while r < 5 and not found do - do - local c = 0 - while c < 5 do - if r * 10 + c == 23 then - foundPair = (tostring(r) .. ",") .. tostring(c) - found = true - break - end - c = c + 1 - end - end - r = r + 1 - end - end - AssertEqual(foundPair, "2,3") - end - ) - Test( - "discriminated union narrowing and destructuring with defaults", - function() - AssertEqual( - EvaluateCommand({kind = "move", x = 3, y = 4}), - 7 - ) - AssertEqual( - EvaluateCommand({kind = "damage", amount = 25, crit = true}), - 50 - ) - AssertEqual( - EvaluateCommand({kind = "damage", amount = 25, crit = false}), - 25 - ) - AssertEqual( - EvaluateCommand({kind = "noop"}), - 0 - ) - local cfg = {host = "127.0.0.1"} - local host = cfg.host - local port = cfg.port - if port == nil then - port = 7777 - end - AssertEqual(host, "127.0.0.1") - AssertEqual(port, 7777) - local coords = {10, 20, 30} - local x, ____, z = table.unpack(coords, 1, 3) - AssertEqual(x, 10) - AssertEqual(z, 30) - AssertNear(0.1 + 0.2, 0.3, 0.000001) - end - ) - Test( - "rest parameters and spread into function calls", - function() - local function SumAll(...) - local nums = {...} - local total = 0 - do - local idx = 0 - while idx < #nums do - total = total + nums[idx + 1] - idx = idx + 1 - end - end - return total - end - local data = {2, 4, 6, 8} - AssertEqual( - SumAll(table.unpack(data)), - 20 - ) - local ____AssertEqual_9 = AssertEqual - local ____array_8 = __TS__SparseArrayNew( - 1, - table.unpack(data) - ) - __TS__SparseArrayPush(____array_8, 9) - ____AssertEqual_9( - SumAll(__TS__SparseArraySpread(____array_8)), - 30 - ) - local ____array_10 = __TS__SparseArrayNew( - 0, - table.unpack(data) - ) - __TS__SparseArrayPush(____array_10, 10) - local combined = {__TS__SparseArraySpread(____array_10)} - AssertArrayEqual(combined, { - 0, - 2, - 4, - 6, - 8, - 10 - }) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertNear = M__Tests_Harness_TestRunner.AssertNear - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -end diff --git a/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua b/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua deleted file mode 100644 index e3e092d..0000000 --- a/Script/lua/Tests/Syntax/FunctionsClosuresAndTuples.lua +++ /dev/null @@ -1,202 +0,0 @@ -local ____lualib = require("lualib_bundle") -local __TS__ArraySplice = ____lualib.__TS__ArraySplice -local __TS__ArraySort = ____lualib.__TS__ArraySort -local __TS__ArrayIndexOf = ____lualib.__TS__ArrayIndexOf -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local function DivideWithRemainder(a, b) - if b == 0 then - return false, 0, 0 - end - local q = math.floor(a / b) - local r = a % b - return true, q, r -end -local function FormatId(a, b) - if type(a) == "number" then - return string.format("ID_%04d", a) - end - return string.format("%s_%04d", a, b or 0) -end -function ____exports.RunFunctionsClosuresAndTuplesTests() - Suite( - "Syntax.FunctionsClosuresAndTuples", - function() - Test( - "LuaMultiReturn and $multi destructuring", - function() - local ok1, q1, r1 = DivideWithRemainder(17, 5) - AssertTrue(ok1) - AssertEqual(q1, 3) - AssertEqual(r1, 2) - local ok2, q2, r2 = DivideWithRemainder(10, 0) - AssertFalse(ok2) - AssertEqual(q2, 0) - AssertEqual(r2, 0) - end - ) - Test( - "function overloads, closures and upvalues", - function() - AssertEqual( - FormatId(7), - "ID_0007" - ) - AssertEqual( - FormatId("NPC", 42), - "NPC_0042" - ) - local function MakeAccumulator(start) - local acc = start - return function(delta) - acc = acc + delta - return acc - end - end - local acc = MakeAccumulator(10) - AssertEqual( - acc(5), - 15 - ) - AssertEqual( - acc(-3), - 12 - ) - AssertEqual( - acc(8), - 20 - ) - end - ) - Test( - "explicit self colon-call vs @noSelf dot-call", - function() - local counter = { - value = 10, - Add = function(self, delta) - self.value = self.value + delta - return self.value - end - } - AssertEqual( - counter:Add(5), - 15 - ) - AssertEqual( - counter:Add(7), - 22 - ) - end - ) - Test( - "TS arrays (0-based -> Lua 1-based) and table operations", - function() - local arr = {10, 20, 30, 40} - AssertEqual(#arr, 4) - AssertEqual(arr[1], 10) - AssertEqual(arr[4], 40) - arr[#arr + 1] = 50 - AssertEqual(#arr, 5) - AssertEqual( - table.remove(arr), - 50 - ) - local removed = __TS__ArraySplice(arr, 1, 2) - AssertArrayEqual(removed, {20, 30}) - AssertArrayEqual(arr, {10, 40}) - table.insert(arr, 2, 25) - AssertArrayEqual(arr, {10, 25, 40}) - table.remove(arr, 1) - AssertArrayEqual(arr, {25, 40}) - local unsorted = { - 5, - 1, - 4, - 2, - 3 - } - __TS__ArraySort( - unsorted, - function(____, a, b) return a - b end - ) - AssertArrayEqual(unsorted, { - 1, - 2, - 3, - 4, - 5 - }) - AssertEqual( - table.concat(unsorted, "-"), - "1-2-3-4-5" - ) - AssertEqual( - __TS__ArrayIndexOf(unsorted, 4), - 3 - ) - AssertEqual( - __TS__ArrayIndexOf(unsorted, 99), - -1 - ) - end - ) - Test( - "Record, LuaTable and pairs() iteration", - function() - local scores = {Alice = 100, Bob = 85, Carol = 92} - scores.Bob = nil - local count = 0 - local total = 0 - for k, v in pairs(scores) do - if v ~= nil then - count = count + 1 - total = total + v - end - AssertTrue(k ~= "Bob") - end - AssertEqual(count, 2) - AssertEqual(total, 192) - local luaTbl = {} - luaTbl[101] = "Sword" - luaTbl[202] = "Shield" - AssertEqual(luaTbl[101], "Sword") - AssertEqual(luaTbl[202], "Shield") - luaTbl[101] = nil - AssertNil(luaTbl[101]) - end - ) - Test( - "Lua patterns (replacing forbidden JS RegExp)", - function() - local tag, numStr = string.match("Item_Sword_042", "^(%a+)_%a+_(%d+)$") - AssertEqual(tag, "Item") - AssertEqual(numStr, "042") - local replaced, subCount = string.gsub("HP: 100, MP: 50", "%d+", "999") - AssertEqual(replaced, "HP: 999, MP: 999") - AssertEqual(subCount, 2) - local tokens = {} - for tok in string.gmatch("alpha,beta,gamma", "[^,]+") do - tokens[#tokens + 1] = tok - end - AssertArrayEqual(tokens, {"alpha", "beta", "gamma"}) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -end diff --git a/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua b/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua deleted file mode 100644 index e7f3289..0000000 --- a/Script/lua/Tests/Syntax/PureClassesAndGenerics.lua +++ /dev/null @@ -1,199 +0,0 @@ -local ____lualib = require("lualib_bundle") -local __TS__ClassExtends = ____lualib.__TS__ClassExtends -local __TS__New = ____lualib.__TS__New -local __TS__InstanceOf = ____lualib.__TS__InstanceOf -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local BaseEntity = __TS__DefineClass("BaseEntity", __module) -BaseEntity.name = "BaseEntity" -function BaseEntity.prototype.____constructor(self, id, name) - self.id = id - self.name = name -end -function BaseEntity.prototype.GetId(self) - return self.id -end -function BaseEntity.prototype.GetName(self) - return self.name -end -local PureMonster = __TS__DefineClass("PureMonster", __module) -PureMonster.name = "PureMonster" -__TS__ClassExtends(PureMonster, BaseEntity) -function PureMonster.prototype.____constructor(self, id, name, level) - if level == nil then - level = PureMonster.DefaultLevel - end - BaseEntity.prototype.____constructor(self, id, name) - self.level = level -end -function PureMonster.prototype.GetLevel(self) - return self.level -end -function PureMonster.prototype.Describe(self) - return ((((self.name .. "#") .. tostring(self.id)) .. "(Lv.") .. tostring(self.level)) .. ")" -end -function PureMonster.CompareLevel(a, b) - return a:GetLevel() - b:GetLevel() -end -PureMonster.DefaultLevel = 1 -local RingBuffer = __TS__DefineClass("RingBuffer", __module) -RingBuffer.name = "RingBuffer" -function RingBuffer.prototype.____constructor(self, capacity) - self.buffer = {} - self.head = 0 - self.count = 0 - self.capacity = capacity -end -function RingBuffer.prototype.Push(self, item) - if self.count < self.capacity then - local idx = (self.head + self.count) % self.capacity - self.buffer[idx + 1] = item - self.count = self.count + 1 - else - self.buffer[self.head + 1] = item - self.head = (self.head + 1) % self.capacity - end -end -function RingBuffer.prototype.Pop(self) - if self.count == 0 then - return nil - end - local item = self.buffer[self.head + 1] - self.buffer[self.head + 1] = nil - self.head = (self.head + 1) % self.capacity - self.count = self.count - 1 - return item -end -function RingBuffer.prototype.GetCount(self) - return self.count -end -local function FindById(list, targetId) - do - local i = 0 - while i < #list do - if list[i + 1]:GetId() == targetId then - return list[i + 1] - end - i = i + 1 - end - end - return nil -end -local function SafeFrameworkBoundary(shouldThrow) - do - local function ____catch(e) - return true, { - false, - tostring(e) - } - end - local ____try, ____hasReturned, ____returnValue = pcall(function() - if shouldThrow then - error("simulated_boundary_error", 0) - end - return true, {true, "ok"} - end) - if not ____try then - ____hasReturned, ____returnValue = ____catch(____hasReturned) - end - if ____hasReturned then - return table.unpack(____returnValue) - end - end -end -function ____exports.RunPureClassesAndGenericsTests() - Suite( - "Syntax.PureClassesAndGenerics", - function() - Test( - "pure TS class inheritance, abstract methods and static helpers", - function() - local m1 = __TS__New(PureMonster, 1, "Slime") - local m2 = __TS__New(PureMonster, 2, "Dragon", 50) - AssertEqual( - m1:GetId(), - 1 - ) - AssertEqual( - m1:GetLevel(), - 1 - ) - AssertEqual( - m1:Describe(), - "Slime#1(Lv.1)" - ) - AssertEqual( - m2:Describe(), - "Dragon#2(Lv.50)" - ) - AssertTrue(PureMonster.CompareLevel(m2, m1) > 0) - AssertTrue(__TS__InstanceOf(m1, PureMonster)) - AssertTrue(__TS__InstanceOf(m1, BaseEntity)) - end - ) - Test( - "generic class RingBuffer and constrained generic function", - function() - local rb = __TS__New(RingBuffer, 3) - rb:Push(10) - rb:Push(20) - rb:Push(30) - rb:Push(40) - AssertEqual( - rb:GetCount(), - 3 - ) - AssertEqual( - rb:Pop(), - 20 - ) - AssertEqual( - rb:Pop(), - 30 - ) - AssertEqual( - rb:Pop(), - 40 - ) - AssertNil(rb:Pop()) - local monsters = { - __TS__New(PureMonster, 10, "Orc", 5), - __TS__New(PureMonster, 20, "Goblin", 2) - } - local found = FindById(monsters, 20) - AssertTrue(found ~= nil) - AssertEqual( - found:GetName(), - "Goblin" - ) - AssertNil(FindById(monsters, 999)) - end - ) - Test( - "@unlua-allow-try framework boundary try/catch/throw", - function() - local ok1, msg1 = SafeFrameworkBoundary(false) - AssertTrue(ok1) - AssertEqual(msg1, "ok") - local ok2, msg2 = SafeFrameworkBoundary(true) - AssertFalse(ok2) - AssertTrue((string.find(msg2, "simulated_boundary_error", 1, true)) ~= nil) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNil = M__Tests_Harness_TestRunner.AssertNil -end diff --git a/Script/lua/Tests/Syntax/UnLuaBaseActor.lua b/Script/lua/Tests/Syntax/UnLuaBaseActor.lua deleted file mode 100644 index 19158f7..0000000 --- a/Script/lua/Tests/Syntax/UnLuaBaseActor.lua +++ /dev/null @@ -1,62 +0,0 @@ -local UnLuaBaseActor = UnLua.Class() -UnLuaBaseActor.DEFAULT_HP = 100 -function UnLuaBaseActor.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.hp = UnLuaBaseActor.DEFAULT_HP - self.callTrace = {"Base.ReceiveBeginPlay"} -end -function UnLuaBaseActor.ApplyConfig(self, ____param_0) - local name = ____param_0.name - local hp = ____param_0.hp - if hp == nil then - hp = UnLuaBaseActor.DEFAULT_HP - end - self.hp = hp - return (name .. ":") .. tostring(self.hp) -end -function UnLuaBaseActor.SumScores(self, ____param_1) - local first = ____param_1[1] - local second = ____param_1[2] - if second == nil then - second = 5 - end - local rest = {} - table.move( - ____param_1, - 3, - #____param_1, - 1, - rest - ) - local sum = first + second - do - local i = 0 - while i < #rest do - sum = sum + rest[i + 1] - i = i + 1 - end - end - return sum -end -function UnLuaBaseActor.GetTrace(self) - return self.callTrace -end -function UnLuaBaseActor.GetHp(self) - return self.hp -end -function UnLuaBaseActor.ComputeBonus(self, baseVal, multiplier) - if multiplier == nil then - multiplier = 2 - end - return baseVal * multiplier -end -function UnLuaBaseActor.StaticWithSelf(self, delta) - return self.DEFAULT_HP + delta -end -function UnLuaBaseActor.StaticNoSelf(a, b) - return a + b -end -function UnLuaBaseActor.StaticDocNoSelf(x) - return x * 3 -end -return UnLuaBaseActor diff --git a/Script/lua/Tests/Syntax/UnLuaExplicitWidget.lua b/Script/lua/Tests/Syntax/UnLuaExplicitWidget.lua deleted file mode 100644 index b25da42..0000000 --- a/Script/lua/Tests/Syntax/UnLuaExplicitWidget.lua +++ /dev/null @@ -1,8 +0,0 @@ -local UnLuaExplicitWidget = UnLua.Class("Tests.Syntax.UnLuaBaseActor") -function UnLuaExplicitWidget.Construct(self, model) - self.title = model.title -end -function UnLuaExplicitWidget.GetTitle(self) - return self.title -end -return UnLuaExplicitWidget diff --git a/Script/lua/Tests/Syntax/UnLuaGrandChildActor.lua b/Script/lua/Tests/Syntax/UnLuaGrandChildActor.lua deleted file mode 100644 index 54edd85..0000000 --- a/Script/lua/Tests/Syntax/UnLuaGrandChildActor.lua +++ /dev/null @@ -1,17 +0,0 @@ -local UnLuaSubActor = require("Tests.Syntax.UnLuaSubActor") -local UnLuaGrandChildActor = UnLua.Class("Tests.Syntax.UnLuaSubActor") -function UnLuaGrandChildActor.ReceiveBeginPlay(self) - UnLuaSubActor.ReceiveBeginPlay(self) - self.tier = 3 - self.callTrace[#self.callTrace + 1] = "GrandChild.ReceiveBeginPlay" -end -function UnLuaGrandChildActor.ComputeBonus(self, baseVal, multiplier) - if multiplier == nil then - multiplier = 2 - end - return UnLuaSubActor.ComputeBonus(self, baseVal, multiplier) + self.tier -end -function UnLuaGrandChildActor.GetTier(self) - return self.tier -end -return UnLuaGrandChildActor diff --git a/Script/lua/Tests/Syntax/UnLuaSubActor.lua b/Script/lua/Tests/Syntax/UnLuaSubActor.lua deleted file mode 100644 index 0a87d21..0000000 --- a/Script/lua/Tests/Syntax/UnLuaSubActor.lua +++ /dev/null @@ -1,21 +0,0 @@ -local UnLuaBaseActor = require("Tests.Syntax.UnLuaBaseActor") -local UnLuaSubActor = UnLua.Class("Tests.Syntax.UnLuaBaseActor") -function UnLuaSubActor.ReceiveBeginPlay(self) - UnLuaBaseActor.ReceiveBeginPlay(self) - self.faction = "Ally" - self.callTrace[#self.callTrace + 1] = "Sub.ReceiveBeginPlay" -end -function UnLuaSubActor.ComputeBonus(self, baseVal, multiplier) - if multiplier == nil then - multiplier = 2 - end - return UnLuaBaseActor.ComputeBonus(self, baseVal, multiplier) + 10 -end -function UnLuaSubActor.SetupWithFaction(self, cfg, faction) - self.faction = faction - return ((UnLuaBaseActor.ApplyConfig(self, cfg) .. "[") .. self.faction) .. "]" -end -function UnLuaSubActor.GetFaction(self) - return self.faction -end -return UnLuaSubActor diff --git a/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua b/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua deleted file mode 100644 index 63d4048..0000000 --- a/Script/lua/Tests/Syntax/UnLuaSyntaxSuite.lua +++ /dev/null @@ -1,132 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) -local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance -local GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState -local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -local UnLuaBaseActor = require("Tests.Syntax.UnLuaBaseActor") -local UnLuaGrandChildActor = require("Tests.Syntax.UnLuaGrandChildActor") -local UnLuaExplicitWidget = require("Tests.Syntax.UnLuaExplicitWidget") -function ____exports.RunUnLuaSyntaxTests() - Suite( - "Syntax.UnLuaClassFeatures", - function() - Test( - "@unlua base class: UnLua.Class(), self.Overridden, static methods and destructured params", - function() - ResetMockState() - local actor = CreateBoundInstance(UnLuaBaseActor, "AActor") - actor:ReceiveBeginPlay() - AssertEqual( - actor:GetHp(), - 100 - ) - AssertArrayEqual( - actor:GetTrace(), - {"Base.ReceiveBeginPlay"} - ) - AssertArrayEqual( - GetMockState().overriddenCalls, - {"AActor.ReceiveBeginPlay"} - ) - AssertEqual( - actor:ApplyConfig({name = "Hero"}), - "Hero:100" - ) - AssertEqual( - actor:ApplyConfig({name = "Boss", hp = 500}), - "Boss:500" - ) - AssertEqual( - actor:SumScores({10}), - 15 - ) - AssertEqual( - actor:SumScores({1, 2, 3, 4}), - 10 - ) - AssertEqual( - UnLuaBaseActor:StaticWithSelf(25), - 125 - ) - AssertEqual( - UnLuaBaseActor.StaticNoSelf(7, 8), - 15 - ) - AssertEqual( - UnLuaBaseActor.StaticDocNoSelf(9), - 27 - ) - AssertTrue(actor:IsA(UE.AActor.StaticClass())) - AssertTrue(UE.UKismetSystemLibrary.IsValid(actor)) - end - ) - Test( - "@unlua 3-level inheritance (GrandChild -> Sub -> Base) avoids self.Super infinite recursion", - function() - ResetMockState() - local grand = CreateBoundInstance(UnLuaGrandChildActor, "AActor") - grand:ReceiveBeginPlay() - AssertArrayEqual( - grand:GetTrace(), - {"Base.ReceiveBeginPlay", "Sub.ReceiveBeginPlay", "GrandChild.ReceiveBeginPlay"} - ) - AssertArrayEqual( - GetMockState().overriddenCalls, - {"AActor.ReceiveBeginPlay"} - ) - AssertEqual( - grand:GetFaction(), - "Ally" - ) - AssertEqual( - grand:GetTier(), - 3 - ) - AssertEqual( - grand:ComputeBonus(10), - 33 - ) - AssertEqual( - grand:ComputeBonus(10, 4), - 53 - ) - local summary = grand:SetupWithFaction({name = "Knight", hp = 250}, "Enemy") - AssertEqual(summary, "Knight:250[Enemy]") - AssertEqual( - grand:GetFaction(), - "Enemy" - ) - end - ) - Test( - "@unlua explicit base path class without extends", - function() - local widgetCls = UnLuaExplicitWidget - AssertEqual(widgetCls.Super, UnLuaBaseActor) - local widget = CreateBoundInstance(widgetCls, "UUserWidget") - widget:Construct({title = "MainHUD"}) - AssertEqual( - widget:GetTitle(), - "MainHUD" - ) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual - CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance - GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState - ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -end diff --git a/Script/lua/Tests/UE/UERuntimeSuite.lua b/Script/lua/Tests/UE/UERuntimeSuite.lua deleted file mode 100644 index 149cdeb..0000000 --- a/Script/lua/Tests/UE/UERuntimeSuite.lua +++ /dev/null @@ -1,550 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Reset = M__Tests_Harness_TestRunner.Reset -local PrintReport = M__Tests_Harness_TestRunner.PrintReport -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertNear = M__Tests_Harness_TestRunner.AssertNear -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local M__Tests_Syntax_BasicTypesAndControlFlow = __MODULE__.Import("Tests.Syntax.BasicTypesAndControlFlow", __module) -local RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests -local M__Tests_Syntax_FunctionsClosuresAndTuples = __MODULE__.Import("Tests.Syntax.FunctionsClosuresAndTuples", __module) -local RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests -local M__Tests_Syntax_PureClassesAndGenerics = __MODULE__.Import("Tests.Syntax.PureClassesAndGenerics", __module) -local RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests -local M__Tests_Gameplay_GameplaySuite = __MODULE__.Import("Tests.Gameplay.GameplaySuite", __module) -local RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests -local M__Tests_Extra_Lua54PitfallsTest = __MODULE__.Import("Tests.Extra.Lua54PitfallsTest", __module) -local RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests -local EventBus = __MODULE__.Import("Framework.EventBus", __module) -local HotReload = __MODULE__.Import("Framework.HotReload", __module) -local M__Tests_UnLuaExamples_Ex06_NativeContainers = __MODULE__.Import("Tests.UnLuaExamples.Ex06_NativeContainers", __module) -local VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations -local VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations -local VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations -local UnLuaBaseActorClass = require("Tests.Syntax.UnLuaBaseActor") -local function TickUEWorld(steps, deltaSeconds) - local tickFn = _G.__UE_TEST_TICK - if tickFn == nil then - return - end - do - local i = 0 - while i < steps do - tickFn(deltaSeconds) - i = i + 1 - end - end -end -function ____exports.RunUERuntimeSuite(world) - local canTickWorld = _G.__UE_TEST_TICK ~= nil - Suite( - "UE.RealEngineIntegration", - function() - Test( - "Real UE C++ TArray / TMap / TSet containers & native __pairs iteration", - function() - VerifyTArrayOperations() - VerifyTMapOperations() - VerifyTSetOperations() - end - ) - Test( - "Real UE SpawnActor + @unlua UnLuaBaseActor (Overridden, static methods, destructuring)", - function() - local actor = world:SpawnActor( - UE.ATargetPoint.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.Syntax.UnLuaBaseActor" - ) - AssertNotNil(actor) - AssertTrue(UE.UKismetSystemLibrary.IsValid(actor)) - AssertTrue(actor:IsA(UE.AActor.StaticClass())) - AssertEqual( - actor:GetHp(), - 100 - ) - AssertArrayEqual( - actor:GetTrace(), - {"Base.ReceiveBeginPlay"} - ) - AssertEqual( - actor:ApplyConfig({name = "UEHero"}), - "UEHero:100" - ) - AssertEqual( - actor:ApplyConfig({name = "UEBoss", hp = 888}), - "UEBoss:888" - ) - AssertEqual( - actor:SumScores({10}), - 15 - ) - AssertEqual( - actor:SumScores({1, 2, 3, 4}), - 10 - ) - AssertEqual( - UnLuaBaseActorClass:StaticWithSelf(25), - 125 - ) - AssertEqual( - UnLuaBaseActorClass.StaticNoSelf(7, 8), - 15 - ) - AssertEqual( - UnLuaBaseActorClass.StaticDocNoSelf(9), - 27 - ) - actor:K2_DestroyActor() - end - ) - Test( - "Real UE SpawnActor + 3-level @unlua inheritance (GrandChild -> Sub -> Base -> AActor)", - function() - local grand = world:SpawnActor( - UE.ATriggerBox.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.Syntax.UnLuaGrandChildActor" - ) - AssertNotNil(grand) - AssertArrayEqual( - grand:GetTrace(), - {"Base.ReceiveBeginPlay", "Sub.ReceiveBeginPlay", "GrandChild.ReceiveBeginPlay"} - ) - AssertEqual( - grand:GetFaction(), - "Ally" - ) - AssertEqual( - grand:GetTier(), - 3 - ) - AssertEqual( - grand:ComputeBonus(10), - 33 - ) - AssertEqual( - grand:SetupWithFaction({name = "Knight", hp = 250}, "Enemy"), - "Knight:250[Enemy]" - ) - grand:K2_DestroyActor() - end - ) - Test( - "Real UE Ex01_HelloWorld & Ex02_OverrideBlueprintEvents lifecycle", - function() - local hello = world:SpawnActor( - UE.ATriggerSphere.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.UnLuaExamples.Ex01_HelloWorld" - ) - AssertNotNil(hello) - AssertTrue((string.find( - hello:GetGreeting(), - "Hello UnLua from TypeScript", - 1, - true - )) ~= nil) - hello:K2_DestroyActor() - local eventsActor = world:SpawnActor( - UE.ATriggerCapsule.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents" - ) - AssertNotNil(eventsActor) - local events = eventsActor:GetEvents() - AssertTrue(#events >= 2) - AssertEqual(events[1], "Initialize") - eventsActor:K2_DestroyActor() - end - ) - Test( - "Real UE Ex04 DynamicBinding: SpawnActor, SpawnActorEx & UE.NewObject with Initializer", - function() - local spawned = world:SpawnActor( - UE.APlayerStart.StaticClass(), - UE.FTransform( - UE.FRotator(0, 90, 0):ToQuat(), - UE.FVector(100, 200, 300), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - {InitTag = "RealUESpawn", InitPower = 555} - ) - AssertNotNil(spawned) - AssertEqual( - spawned:GetInitTag(), - "RealUESpawn" - ) - AssertEqual( - spawned:GetInitPower(), - 555 - ) - AssertTrue(spawned:IsBeginPlayCalled()) - spawned:K2_DestroyActor() - local params = UE.FActorSpawnParameters() - params.bNoFail = true - params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - local spawnedEx = world:SpawnActorEx( - UE.APlayerStart.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(10, 20, 30), - UE.FVector(1, 1, 1) - ), - {InitTag = "RealUESpawnEx", InitPower = 777}, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - params - ) - AssertNotNil(spawnedEx) - AssertEqual( - spawnedEx:GetInitTag(), - "RealUESpawnEx" - ) - AssertEqual( - spawnedEx:GetInitPower(), - 777 - ) - spawnedEx:K2_DestroyActor() - local dynObj = UE.NewObject( - UE.ULuaBundleAsset.StaticClass(), - world, - "RealUEDynObj", - "Tests.UnLuaExamples.Ex04_DynamicObject", - {Seed = 10} - ) - AssertNotNil(dynObj) - AssertEqual( - dynObj:GetSeed(), - 10 - ) - AssertEqual( - dynObj:NextValue(), - 21 - ) - AssertEqual( - dynObj:NextValue(), - 43 - ) - end - ) - Test( - "Real UE Ex08 Struct math, K2_SetActorLocation & LineTraceSingle multi-return", - function() - local actor = world:SpawnActor( - UE.ATextRenderActor.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.UnLuaExamples.Ex08_StructAndTrace" - ) - AssertNotNil(actor) - local size, dot, dist = actor:ComputeVectorMath() - AssertNear(size, 13, 0.001) - AssertNear(dot, 0, 0.001) - AssertNear(dist, 13, 0.001) - local bHit, hitDist, impact = actor:TraceForward(500) - AssertEqual( - type(bHit), - "boolean" - ) - AssertEqual( - type(hitDist), - "number" - ) - AssertNotNil(impact) - local bHit2, outHit2 = actor:TraceForwardMultiReturn(500) - AssertEqual(bHit2, bHit) - AssertNotNil(outHit2) - if bHit then - AssertNear(hitDist, outHit2.Distance, 0.01) - end - actor:K2_DestroyActor() - end - ) - Test( - "Real UE UnLua.Ref / UnLua.Unref & FWeakObjectPtr validity", - function() - local obj = UE.NewObject( - UE.UObjectLibrary.StaticClass(), - world, - "WeakRefTarget" - ) - AssertTrue(UE.UKismetSystemLibrary.IsValid(obj)) - local refProxy = UnLua.Ref(obj) - AssertNotNil(refProxy) - local weak = UE.FWeakObjectPtr(obj) - AssertTrue(weak:IsValid()) - AssertNotNil(weak:Get()) - weak:Reset() - AssertFalse(weak:IsValid()) - AssertNil(weak:Get()) - UnLua.Unref(obj) - end - ) - Test( - "Real UE ALuaDemoActor (C++ callback -> pure TS Game.LuaDemoActor) + EventBus + Tick + EndPlay", - function() - local demoActor = world:SpawnActor( - UE.ALuaDemoActor.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 100), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - ) - AssertNotNil(demoActor) - AssertTrue(demoActor:IsA(UE.ALuaDemoActor.StaticClass())) - local initText = demoActor:GetStatusTextString() - AssertTrue((string.find(initText, "Pure-TS Actor", 1, true)) ~= nil, "initText: " .. initText) - AssertTrue((string.find(initText, "Pings: 0", 1, true)) ~= nil) - if canTickWorld then - TickUEWorld(5, 0.05) - end - EventBus.Emit("Demo.Ping", "UERealEngineTest") - local pingedText = demoActor:GetStatusTextString() - AssertTrue((string.find(pingedText, "Pings: 1", 1, true)) ~= nil) - AssertTrue((string.find(pingedText, "Color: Gold", 1, true)) ~= nil) - local bMoved = demoActor:K2_SetActorLocation( - UE.FVector(120, 240, 360), - false, - nil, - true - ) - AssertTrue(bMoved) - local loc = demoActor:K2_GetActorLocation() - AssertNear(loc.X, 120, 0.01) - AssertNear(loc.Y, 240, 0.01) - AssertNear(loc.Z, 360, 0.01) - demoActor:K2_DestroyActor() - end - ) - if canTickWorld then - Test( - "Real UE FTimerManager + K2_SetTimerDelegate(UnLua.Delegate) ticked by UWorld", - function() - local timerActor = world:SpawnActor( - UE.ACameraActor.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.UE.UETimerTestActor" - ) - AssertNotNil(timerActor) - AssertTrue(timerActor:IsTimerActive()) - AssertEqual( - timerActor:GetTimerCount(), - 0 - ) - TickUEWorld(10, 0.05) - AssertTrue(timerActor:GetTimerCount() >= 3) - local countBeforeStop = timerActor:GetTimerCount() - timerActor:StopTimer() - AssertFalse(timerActor:IsTimerActive()) - TickUEWorld(6, 0.05) - AssertEqual( - timerActor:GetTimerCount(), - countBeforeStop - ) - timerActor:K2_DestroyActor() - end - ) - Test( - "Real UE FLatentActionManager + UKismetSystemLibrary.Delay coroutine (Ex07)", - function() - local latentActor = world:SpawnActor( - UE.ADecalActor.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 0), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - nil, - nil, - "Tests.UnLuaExamples.Ex07_CallLatentFunction" - ) - AssertNotNil(latentActor) - AssertArrayEqual( - latentActor:GetSteps(), - {"Step1:Start"} - ) - AssertFalse(latentActor:IsCompleted()) - TickUEWorld(6, 0.1) - AssertArrayEqual( - latentActor:GetSteps(), - {"Step1:Start", "Step2:After0.5s"} - ) - AssertFalse(latentActor:IsCompleted()) - TickUEWorld(11, 0.1) - AssertArrayEqual( - latentActor:GetSteps(), - {"Step1:Start", "Step2:After0.5s", "Step3:Done"} - ) - AssertTrue(latentActor:IsCompleted()) - latentActor:K2_DestroyActor() - end - ) - end - Test( - "Real UE HotReload.ReloadModule validates arguments and emits events", - function() - local badOk = HotReload.ReloadModule("") - AssertFalse(badOk) - local ok = HotReload.ReloadModule("Framework.Log") - AssertTrue(ok) - end - ) - Test( - "Real UE single-file __MODULE__.Reimport hot-reloads Game.LuaDemoActor spin speed and color live", - function() - local demoActor = world:SpawnActor( - UE.ALuaDemoActor.StaticClass(), - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(0, 0, 200), - UE.FVector(1, 1, 1) - ), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - ) - AssertNotNil(demoActor) - local beforeText = demoActor:GetStatusTextString() - AssertTrue((string.find(beforeText, "v1", 1, true)) ~= nil) - AssertTrue((string.find(beforeText, "Speed: 60", 1, true)) ~= nil) - AssertTrue((string.find(beforeText, "Color: Cyan", 1, true)) ~= nil) - local actorMod = __MODULE__.Import("Game.LuaDemoActor") - local activeBefore = actorMod:GetActiveControllerCount() - AssertTrue(activeBefore >= 1) - local defaultDir = UE.ULuaHotUpdateSubsystem.GetDefaultScriptDir() - local overrideDir = UE.ULuaHotUpdateSubsystem.GetHotUpdateScriptDir() - local srcPath = defaultDir .. "/Game/LuaDemoActor.lua" - local dstGameDir = overrideDir .. "/Game" - local dstPath = dstGameDir .. "/LuaDemoActor.lua" - local srcFile = (io.open(srcPath, "rb")) - AssertNotNil(srcFile) - local origLua = srcFile:read("a") - srcFile:close() - local patchedLua = string.gsub(origLua, "\"v1\"", "\"v2-HOTFIX\"") - patchedLua = string.gsub(patchedLua, "ACTOR_SPIN_SPEED = 60", "ACTOR_SPIN_SPEED = 240") - patchedLua = string.gsub(patchedLua, "\"Cyan\"", "\"Crimson\"") - patchedLua = string.gsub(patchedLua, "R = 0%.08", "R = 0.95") - patchedLua = string.gsub(patchedLua, "G = 0%.78", "G = 0.12") - patchedLua = string.gsub(patchedLua, "B = 0%.95", "B = 0.18") - os.execute(string.format("mkdir -p \"%s\"", dstGameDir)) - local dstFile = (io.open(dstPath, "wb")) - AssertNotNil(dstFile) - dstFile:write(patchedLua) - dstFile:close() - local okReload, errReload = HotReload.ReloadModule("Game.LuaDemoActor") - os.remove(dstPath) - AssertTrue( - okReload, - tostring(errReload) - ) - AssertEqual(actorMod.DEMO_VERSION, "v2-HOTFIX") - AssertEqual(actorMod.ACTOR_SPIN_SPEED, 240) - AssertEqual( - actorMod:GetActiveControllerCount(), - activeBefore - ) - local newColor = demoActor:GetCubeColor() - AssertNear(newColor.R, 0.95, 0.01) - AssertNear(newColor.G, 0.12, 0.01) - local afterText = demoActor:GetStatusTextString() - AssertTrue((string.find(afterText, "v2-HOTFIX", 1, true)) ~= nil, "afterText: " .. afterText) - AssertTrue((string.find(afterText, "Speed: 240", 1, true)) ~= nil, "afterText: " .. afterText) - AssertTrue((string.find(afterText, "Color: Crimson", 1, true)) ~= nil, "afterText: " .. afterText) - local okRestore = HotReload.ReloadModule("Game.LuaDemoActor") - AssertTrue(okRestore) - AssertEqual(actorMod.DEMO_VERSION, "v1") - AssertEqual(actorMod.ACTOR_SPIN_SPEED, 60) - demoActor:K2_DestroyActor() - end - ) - end - ) -end ---- 在真实 UE 5.8 + UnLua 2.3.6 环境下运行的统一入口。 --- 可由 RunLuaTestsCommandlet 或编辑器控制台命令 `Lua.RunTests` 调用。 -function ____exports.RunAllInUE(world) - local targetWorld = world or _G.__UE_TEST_WORLD - Reset() - RunBasicTypesAndControlFlowTests() - RunFunctionsClosuresAndTuplesTests() - RunPureClassesAndGenericsTests() - RunGameplayTests() - RunLua54PitfallsTests() - if targetWorld ~= nil then - ____exports.RunUERuntimeSuite(targetWorld) - end - return PrintReport() -end -function __module.UpdateImports() - Reset = M__Tests_Harness_TestRunner.Reset - PrintReport = M__Tests_Harness_TestRunner.PrintReport - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertNear = M__Tests_Harness_TestRunner.AssertNear - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual - RunBasicTypesAndControlFlowTests = M__Tests_Syntax_BasicTypesAndControlFlow.RunBasicTypesAndControlFlowTests - RunFunctionsClosuresAndTuplesTests = M__Tests_Syntax_FunctionsClosuresAndTuples.RunFunctionsClosuresAndTuplesTests - RunPureClassesAndGenericsTests = M__Tests_Syntax_PureClassesAndGenerics.RunPureClassesAndGenericsTests - RunGameplayTests = M__Tests_Gameplay_GameplaySuite.RunGameplayTests - RunLua54PitfallsTests = M__Tests_Extra_Lua54PitfallsTest.RunLua54PitfallsTests - VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations - VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations - VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations -end diff --git a/Script/lua/Tests/UE/UETimerTestActor.lua b/Script/lua/Tests/UE/UETimerTestActor.lua deleted file mode 100644 index d3b03fe..0000000 --- a/Script/lua/Tests/UE/UETimerTestActor.lua +++ /dev/null @@ -1,26 +0,0 @@ -local UETimerTestActor = UnLua.Class() -function UETimerTestActor.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.timerCount = 0 - self.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate({self, self.OnTimerTick}, 0.1, true) -end -function UETimerTestActor.OnTimerTick(self) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.timerCount = self.timerCount + 1 -end -function UETimerTestActor.StopTimer(self) - UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(self, self.timerHandle) -end -function UETimerTestActor.GetTimerCount(self) - return self.timerCount -end -function UETimerTestActor.IsTimerActive(self) - return UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(self, self.timerHandle) -end -function UETimerTestActor.ReceiveEndPlay(self, EndPlayReason) - self:StopTimer() - self.Overridden.ReceiveEndPlay(self, EndPlayReason) -end -return UETimerTestActor diff --git a/Script/lua/Tests/UnLuaExamples/Ex01_HelloWorld.lua b/Script/lua/Tests/UnLuaExamples/Ex01_HelloWorld.lua deleted file mode 100644 index d8808a3..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex01_HelloWorld.lua +++ /dev/null @@ -1,17 +0,0 @@ -local Ex01_HelloWorld = UnLua.Class() -function Ex01_HelloWorld.ReceiveBeginPlay(self) - self.greeting = ("Hello UnLua from TypeScript (" .. _VERSION) .. ")!" - UnLua.Log(self.greeting) - UE.UKismetSystemLibrary.PrintString( - self, - self.greeting, - true, - true, - UE.FLinearColor(0.1, 0.9, 0.4, 1), - 5 - ) -end -function Ex01_HelloWorld.GetGreeting(self) - return self.greeting -end -return Ex01_HelloWorld diff --git a/Script/lua/Tests/UnLuaExamples/Ex02_OverrideBlueprintEvents.lua b/Script/lua/Tests/UnLuaExamples/Ex02_OverrideBlueprintEvents.lua deleted file mode 100644 index 91d1034..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex02_OverrideBlueprintEvents.lua +++ /dev/null @@ -1,54 +0,0 @@ -local Ex02_OverrideBlueprintEvents = UnLua.Class() -function Ex02_OverrideBlueprintEvents.Initialize(self, _Initializer) - self.events = {"Initialize"} - self.totalDamage = 0 - self.elapsed = 0 - self.overlapCount = 0 -end -function Ex02_OverrideBlueprintEvents.UserConstructionScript(self) - self.Overridden.UserConstructionScript(self) - self.events[#self.events + 1] = "UserConstructionScript" -end -function Ex02_OverrideBlueprintEvents.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.events[#self.events + 1] = "ReceiveBeginPlay" -end -function Ex02_OverrideBlueprintEvents.ReceiveTick(self, DeltaSeconds) - self.Overridden.ReceiveTick(self, DeltaSeconds) - self.elapsed = self.elapsed + DeltaSeconds -end -function Ex02_OverrideBlueprintEvents.ReceiveAnyDamage(self, Damage, _DamageType, _InstigatedBy, _DamageCauser) - self.Overridden.ReceiveAnyDamage( - self, - Damage, - _DamageType, - _InstigatedBy, - _DamageCauser - ) - self.totalDamage = self.totalDamage + Damage - self.events[#self.events + 1] = "Damage:" .. tostring(Damage) -end -function Ex02_OverrideBlueprintEvents.ReceiveActorBeginOverlap(self, OtherActor) - self.Overridden.ReceiveActorBeginOverlap(self, OtherActor) - if UE.UKismetSystemLibrary.IsValid(OtherActor) then - self.overlapCount = self.overlapCount + 1 - self.events[#self.events + 1] = "Overlap:" .. OtherActor:GetName() - end -end -function Ex02_OverrideBlueprintEvents.ReceiveEndPlay(self, EndPlayReason) - self.Overridden.ReceiveEndPlay(self, EndPlayReason) - self.events[#self.events + 1] = "EndPlay:" .. tostring(EndPlayReason) -end -function Ex02_OverrideBlueprintEvents.GetEvents(self) - return self.events -end -function Ex02_OverrideBlueprintEvents.GetTotalDamage(self) - return self.totalDamage -end -function Ex02_OverrideBlueprintEvents.GetElapsed(self) - return self.elapsed -end -function Ex02_OverrideBlueprintEvents.GetOverlapCount(self) - return self.overlapCount -end -return Ex02_OverrideBlueprintEvents diff --git a/Script/lua/Tests/UnLuaExamples/Ex03_BindDelegates.lua b/Script/lua/Tests/UnLuaExamples/Ex03_BindDelegates.lua deleted file mode 100644 index 68cdc9f..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex03_BindDelegates.lua +++ /dev/null @@ -1,43 +0,0 @@ -local Ex03_BindDelegates = UnLua.Class() -function Ex03_BindDelegates.Construct(self) - self.clickCount = 0 - self.timerTickCount = 0 - if self.ClickMeButton ~= nil then - self.ClickMeButton.OnClicked:Add(self, self.OnButtonClicked) - end - if self.CustomSingleDelegate ~= nil then - self.CustomSingleDelegate:Bind(self, self.OnCustomExecute) - end - self.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate({self, self.OnTimerTick}, 0.5, true) -end -function Ex03_BindDelegates.OnButtonClicked(self) - self.clickCount = self.clickCount + 1 -end -function Ex03_BindDelegates.OnCustomExecute(self, value) - return value * 10 + self.clickCount -end -function Ex03_BindDelegates.OnTimerTick(self) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.timerTickCount = self.timerTickCount + 1 -end -function Ex03_BindDelegates.Destruct(self) - if self.ClickMeButton ~= nil then - self.ClickMeButton.OnClicked:Remove(self, self.OnButtonClicked) - end - if self.CustomSingleDelegate ~= nil then - self.CustomSingleDelegate:Unbind() - end - UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(self, self.timerHandle) -end -function Ex03_BindDelegates.GetClickCount(self) - return self.clickCount -end -function Ex03_BindDelegates.GetTimerTickCount(self) - return self.timerTickCount -end -function Ex03_BindDelegates.GetTimerHandle(self) - return self.timerHandle -end -return Ex03_BindDelegates diff --git a/Script/lua/Tests/UnLuaExamples/Ex04_DynamicBinding.lua b/Script/lua/Tests/UnLuaExamples/Ex04_DynamicBinding.lua deleted file mode 100644 index a10f3e5..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex04_DynamicBinding.lua +++ /dev/null @@ -1,59 +0,0 @@ -local Ex04_DynamicBinding = UnLua.Class() -function Ex04_DynamicBinding.SpawnDynamicActor(self, tag, power) - local world = self:GetWorld() - local actorClass = UE.UClass.Load("/Game/Blueprints/BP_DynamicDemo.BP_DynamicDemo_C") - if not world or not actorClass then - return nil - end - local transform = UE.FTransform( - UE.FRotator(0, 90, 0):ToQuat(), - UE.FVector(100, 200, 300), - UE.FVector(1, 1, 1) - ) - return world:SpawnActor( - actorClass, - transform, - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - self, - nil, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - {InitTag = tag, InitPower = power} - ) -end -function Ex04_DynamicBinding.SpawnDynamicActorEx(self, tag) - local world = self:GetWorld() - local actorClass = UE.LoadClass("/Game/Blueprints/BP_DynamicDemoEx.BP_DynamicDemoEx_C") - if not world or not actorClass then - return nil - end - local params = UE.FActorSpawnParameters() - params.Name = "ExSpawnedActor" - params.bNoFail = true - params.Owner = self - params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - return world:SpawnActorEx( - actorClass, - UE.FTransform( - UE.FRotator(0, 0, 0):ToQuat(), - UE.FVector(10, 20, 30), - UE.FVector(1, 1, 1) - ), - {InitTag = tag, InitPower = 77}, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - params - ) -end -function Ex04_DynamicBinding.CreateDynamicObject(self, seed) - local objClass = UE.UClass.Load("/Script/CoreUObject.Object") - if not objClass then - return nil - end - return UE.NewObject( - objClass, - self, - "DynamicObjectInstance", - "Tests.UnLuaExamples.Ex04_DynamicObject", - {Seed = seed} - ) -end -return Ex04_DynamicBinding diff --git a/Script/lua/Tests/UnLuaExamples/Ex04_DynamicObject.lua b/Script/lua/Tests/UnLuaExamples/Ex04_DynamicObject.lua deleted file mode 100644 index 5be15e8..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex04_DynamicObject.lua +++ /dev/null @@ -1,12 +0,0 @@ -local Ex04_DynamicObject = UnLua.Class() -function Ex04_DynamicObject.Initialize(self, Initializer) - self.seed = Initializer and Initializer.Seed or 1 -end -function Ex04_DynamicObject.NextValue(self) - self.seed = self.seed * 2 + 1 - return self.seed -end -function Ex04_DynamicObject.GetSeed(self) - return self.seed -end -return Ex04_DynamicObject diff --git a/Script/lua/Tests/UnLuaExamples/Ex04_DynamicSpawnedActor.lua b/Script/lua/Tests/UnLuaExamples/Ex04_DynamicSpawnedActor.lua deleted file mode 100644 index b84d711..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex04_DynamicSpawnedActor.lua +++ /dev/null @@ -1,20 +0,0 @@ -local Ex04_DynamicSpawnedActor = UnLua.Class() -function Ex04_DynamicSpawnedActor.Initialize(self, Initializer) - self.initTag = Initializer and Initializer.InitTag or "Default" - self.initPower = Initializer and Initializer.InitPower or 0 - self.beginPlayCalled = false -end -function Ex04_DynamicSpawnedActor.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.beginPlayCalled = true -end -function Ex04_DynamicSpawnedActor.GetInitTag(self) - return self.initTag -end -function Ex04_DynamicSpawnedActor.GetInitPower(self) - return self.initPower -end -function Ex04_DynamicSpawnedActor.IsBeginPlayCalled(self) - return self.beginPlayCalled -end -return Ex04_DynamicSpawnedActor diff --git a/Script/lua/Tests/UnLuaExamples/Ex05_BindInputs.lua b/Script/lua/Tests/UnLuaExamples/Ex05_BindInputs.lua deleted file mode 100644 index c9aa15e..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex05_BindInputs.lua +++ /dev/null @@ -1,73 +0,0 @@ -local Ex05_BindInputs = UnLua.Class() -function Ex05_BindInputs.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.lastAction = "" - self.moveForwardValue = 0 - self.enhancedCount = 0 -end -function Ex05_BindInputs.HandleSpacePressed(self) - self.lastAction = "SpaceBar:Pressed" -end -function Ex05_BindInputs.HandleCtrlSave(self) - self.lastAction = "Ctrl+S" -end -function Ex05_BindInputs.HandleJumpAction(self) - self.lastAction = "Action:Jump" -end -function Ex05_BindInputs.HandleMoveForward(self, axisValue) - self.moveForwardValue = axisValue -end -function Ex05_BindInputs.HandleEnhancedMove(self, actionValue) - self.enhancedCount = self.enhancedCount + 1 - self.moveForwardValue = actionValue -end -function Ex05_BindInputs.GetLastAction(self) - return self.lastAction -end -function Ex05_BindInputs.GetMoveForwardValue(self) - return self.moveForwardValue -end -function Ex05_BindInputs.GetEnhancedCount(self) - return self.enhancedCount -end -UnLua.Input.BindKey( - Ex05_BindInputs, - "SpaceBar", - "Pressed", - function(self) - self:HandleSpacePressed() - end -) -UnLua.Input.BindKey( - Ex05_BindInputs, - "S", - "Pressed", - function(self) - self:HandleCtrlSave() - end, - {Ctrl = true} -) -UnLua.Input.BindAction( - Ex05_BindInputs, - "Jump", - "Pressed", - function(self) - self:HandleJumpAction() - end -) -UnLua.Input.BindAxis( - Ex05_BindInputs, - "MoveForward", - function(self, axisValue) - self:HandleMoveForward(axisValue) - end -) -UnLua.EnhancedInput.BindAction( - Ex05_BindInputs, - "/Game/Input/IA_Move.IA_Move", - "Triggered", - function(self, actionValue) - self:HandleEnhancedMove(actionValue) - end -) -return Ex05_BindInputs diff --git a/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua b/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua deleted file mode 100644 index 1e18f65..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex06_NativeContainers.lua +++ /dev/null @@ -1,207 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNil = M__Tests_Harness_TestRunner.AssertNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual ---- 参考 UnLua 官方示例 06_NativeContainers: --- 演示 UE.TArray / UE.TMap / UE.TSet 的构造(使用 UE.int32 / UE.FString Token)、 --- 1-based 索引访问、CRUD、ToTable 与原生 pairs() 遍历。 -function ____exports.VerifyTArrayOperations() - local arr = UE.TArray(UE.int32) - AssertTrue(arr:Reserve(8)) - AssertEqual( - arr:Length(), - 0 - ) - AssertEqual( - arr:Add(10), - 1 - ) - AssertEqual( - arr:Add(20), - 2 - ) - AssertEqual( - arr:Add(30), - 3 - ) - AssertEqual( - arr:Length(), - 3 - ) - AssertEqual( - arr:Num(), - 3 - ) - AssertEqual( - arr:Get(1), - 10 - ) - AssertEqual( - arr:Get(3), - 30 - ) - AssertEqual( - arr:LastIndex(), - 3 - ) - AssertTrue(arr:IsValidIndex(1)) - AssertFalse(arr:IsValidIndex(0)) - AssertFalse(arr:IsValidIndex(4)) - arr:Set(2, 25) - AssertEqual( - arr:Get(2), - 25 - ) - AssertEqual( - arr:Find(25), - 2 - ) - AssertTrue(arr:Contains(25)) - AssertFalse(arr:Contains(999)) - AssertEqual( - arr:AddUnique(25), - 2 - ) - AssertEqual( - arr:AddUnique(40), - 4 - ) - AssertEqual( - arr:Length(), - 4 - ) - arr:Insert(15, 2) - AssertEqual( - arr:Get(2), - 15 - ) - arr:Swap(1, 5) - AssertEqual( - arr:Get(1), - 40 - ) - AssertEqual( - arr:Get(5), - 10 - ) - arr:Add(15) - local removedCount = arr:RemoveItem(15) - AssertEqual(removedCount, 2) - AssertFalse(arr:Contains(15)) - local other = UE.TArray(UE.int32) - other:Add(100) - other:Add(200) - arr:Append(other) - local tbl = arr:ToTable() - AssertArrayEqual(tbl, { - 40, - 25, - 30, - 10, - 100, - 200 - }) - local sum = 0 - for idx, val in pairs(arr) do - AssertTrue(idx >= 1) - sum = sum + val - end - AssertEqual(sum, 405) - arr:Clear() - AssertEqual( - arr:Length(), - 0 - ) -end -function ____exports.VerifyTMapOperations() - local map = UE.TMap(UE.FString, UE.int32) - map:Add("HP", 100) - map:Add("MP", 50) - map:Add("ATK", 35) - AssertEqual( - map:Length(), - 3 - ) - AssertEqual( - map:Find("HP"), - 100 - ) - AssertEqual( - map:FindRef("MP"), - 50 - ) - AssertNil(map:Find("DEF")) - map:Add("HP", 120) - AssertEqual( - map:Find("HP"), - 120 - ) - AssertEqual( - map:Keys():Length(), - 3 - ) - AssertEqual( - map:Values():Length(), - 3 - ) - local tbl = map:ToTable() - AssertEqual(tbl.ATK, 35) - local sum = 0 - for _k, v in pairs(map) do - sum = sum + v - end - AssertEqual(sum, 205) - AssertTrue(map:Remove("MP")) - AssertFalse(map:Remove("NotExist")) - AssertEqual( - map:Length(), - 2 - ) - map:Clear() - AssertEqual( - map:Length(), - 0 - ) -end -function ____exports.VerifyTSetOperations() - local set = UE.TSet(UE.FString) - set:Add("Fire") - set:Add("Ice") - set:Add("Fire") - AssertEqual( - set:Length(), - 2 - ) - AssertTrue(set:Contains("Fire")) - AssertFalse(set:Contains("Poison")) - local asArr = set:ToArray() - AssertEqual( - asArr:Length(), - 2 - ) - AssertEqual( - #set:ToTable(), - 2 - ) - AssertTrue(set:Remove("Ice")) - AssertFalse(set:Remove("Ice")) - AssertEqual( - set:Length(), - 1 - ) - set:Clear() - AssertEqual( - set:Length(), - 0 - ) -end -function __module.UpdateImports() - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNil = M__Tests_Harness_TestRunner.AssertNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -end diff --git a/Script/lua/Tests/UnLuaExamples/Ex07_CallLatentFunction.lua b/Script/lua/Tests/UnLuaExamples/Ex07_CallLatentFunction.lua deleted file mode 100644 index 0ce8875..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex07_CallLatentFunction.lua +++ /dev/null @@ -1,37 +0,0 @@ -local Ex07_CallLatentFunction = UnLua.Class() -function Ex07_CallLatentFunction.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self.steps = {} - self.completed = false - local co = coroutine.create(function(actor) - actor:RunSequence() - end) - local ok, err = coroutine.resume(co, self) - if not ok then - UnLua.LogError( - "Ex07 coroutine failed:", - tostring(err) - ) - end -end -function Ex07_CallLatentFunction.RunSequence(self) - self.steps[#self.steps + 1] = "Step1:Start" - UE.UKismetSystemLibrary.Delay(self, 0.5) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.steps[#self.steps + 1] = "Step2:After0.5s" - UE.UKismetSystemLibrary.Delay(self, 1) - if not UE.UKismetSystemLibrary.IsValid(self) then - return - end - self.steps[#self.steps + 1] = "Step3:Done" - self.completed = true -end -function Ex07_CallLatentFunction.GetSteps(self) - return self.steps -end -function Ex07_CallLatentFunction.IsCompleted(self) - return self.completed -end -return Ex07_CallLatentFunction diff --git a/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua b/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua deleted file mode 100644 index 301c281..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex08_StructAndTrace.lua +++ /dev/null @@ -1,60 +0,0 @@ -local Ex08_StructAndTrace = UnLua.Class() -function Ex08_StructAndTrace.ReceiveBeginPlay(self) - self.Overridden.ReceiveBeginPlay(self) - self._tmpStart = UE.FVector(0, 0, 0) - self._tmpEnd = UE.FVector(0, 0, 0) - self._tmpHit = UE.FHitResult() - self._ignoreActors = UE.TArray(UE.AActor.StaticClass()) - self._ignoreActors:Add(self) -end -function Ex08_StructAndTrace.ComputeVectorMath(self) - local a = UE.FVector(3, 4, 0) - local b = UE.FVector(0, 0, 12) - local dot = a:Dot(b) - a:Add(b) - local dist = UE.FVector.Dist( - UE.FVector(0, 0, 0), - a - ) - return a:Size(), dot, dist -end -function Ex08_StructAndTrace.TraceForward(self, distance) - local origin = self:K2_GetActorLocation() - self._tmpStart:Set(origin.X, origin.Y, origin.Z) - self._tmpEnd:Set(origin.X + distance, origin.Y, origin.Z) - local bHit, returnedHit = UE.UKismetSystemLibrary.LineTraceSingle( - self, - self._tmpStart, - self._tmpEnd, - UE.ETraceTypeQuery.TraceTypeQuery1, - false, - self._ignoreActors, - UE.EDrawDebugTrace.None, - self._tmpHit, - true - ) - local hit = returnedHit or self._tmpHit - return bHit, hit.Distance, hit.ImpactPoint -end -function Ex08_StructAndTrace.TraceForwardMultiReturn(self, distance) - local origin = self:K2_GetActorLocation() - self._tmpStart:Set(origin.X, origin.Y, origin.Z) - self._tmpEnd:Set(origin.X + distance, origin.Y, origin.Z) - return UE.UKismetSystemLibrary.LineTraceSingle( - self, - self._tmpStart, - self._tmpEnd, - UE.ETraceTypeQuery.TraceTypeQuery1, - false, - self._ignoreActors, - UE.EDrawDebugTrace.None, - nil, - true - ) -end -function Ex08_StructAndTrace.TeleportTo(self, x, y, z) - local target = UE.FVector(x, y, z) - local bMoved = self:K2_SetActorLocation(target, false, self._tmpHit, true) - return bMoved -end -return Ex08_StructAndTrace diff --git a/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua b/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua deleted file mode 100644 index dc0ef78..0000000 --- a/Script/lua/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.lua +++ /dev/null @@ -1,47 +0,0 @@ -local Ex09_AssetRefAndUMG = UnLua.Class() -function Ex09_AssetRefAndUMG.Initialize(self, _Initializer) - self.isConstructed = false - self.isDestructed = false - self.weakRef = nil -end -function Ex09_AssetRefAndUMG.Construct(self) - self.isConstructed = true - self.loadedAsset = UE.UObject.Load("/Game/UI/Textures/T_Icon.T_Icon") - if self.loadedAsset ~= nil then - self.refProxy = UnLua.Ref(self.loadedAsset) - self.weakRef = UE.FWeakObjectPtr(self.loadedAsset) - end -end -function Ex09_AssetRefAndUMG.ShowOnScreen(self) - self:AddToViewport(10) -end -function Ex09_AssetRefAndUMG.CloseAndRelease(self) - self:RemoveFromParent() - self:Destruct() - self:Release() -end -function Ex09_AssetRefAndUMG.Destruct(self) - if self.isDestructed then - return - end - self.isDestructed = true - if self.loadedAsset ~= nil then - UnLua.Unref(self.loadedAsset) - self.refProxy = nil - self.loadedAsset = nil - end - if self.weakRef ~= nil then - self.weakRef:Reset() - self.weakRef = nil - end -end -function Ex09_AssetRefAndUMG.HasValidWeakAsset(self) - return self.weakRef ~= nil and self.weakRef:IsValid() -end -function Ex09_AssetRefAndUMG.IsConstructed(self) - return self.isConstructed -end -function Ex09_AssetRefAndUMG.IsDestructed(self) - return self.isDestructed -end -return Ex09_AssetRefAndUMG diff --git a/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua b/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua deleted file mode 100644 index 116c4a7..0000000 --- a/Script/lua/Tests/UnLuaExamples/UnLuaExamplesSuite.lua +++ /dev/null @@ -1,333 +0,0 @@ -local ____exports = __module.env -local M__Tests_Harness_TestRunner = __MODULE__.Import("Tests.Harness.TestRunner", __module) -local Suite = M__Tests_Harness_TestRunner.Suite -local Test = M__Tests_Harness_TestRunner.Test -local AssertEqual = M__Tests_Harness_TestRunner.AssertEqual -local AssertNear = M__Tests_Harness_TestRunner.AssertNear -local AssertTrue = M__Tests_Harness_TestRunner.AssertTrue -local AssertFalse = M__Tests_Harness_TestRunner.AssertFalse -local AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil -local AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual -local M__Tests_Harness_MockUnLuaRuntime = __MODULE__.Import("Tests.Harness.MockUnLuaRuntime", __module) -local AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime -local CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance -local CreateMockMulticastDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockMulticastDelegate -local CreateMockScriptDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockScriptDelegate -local GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState -local ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState -local M__Tests_UnLuaExamples_Ex06_NativeContainers = __MODULE__.Import("Tests.UnLuaExamples.Ex06_NativeContainers", __module) -local VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations -local VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations -local VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations -local Ex01_HelloWorld = require("Tests.UnLuaExamples.Ex01_HelloWorld") -local Ex02_OverrideBlueprintEvents = require("Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents") -local Ex03_BindDelegates = require("Tests.UnLuaExamples.Ex03_BindDelegates") -local Ex04_DynamicBinding = require("Tests.UnLuaExamples.Ex04_DynamicBinding") -local Ex05_BindInputs = require("Tests.UnLuaExamples.Ex05_BindInputs") -local Ex07_CallLatentFunction = require("Tests.UnLuaExamples.Ex07_CallLatentFunction") -local Ex08_StructAndTrace = require("Tests.UnLuaExamples.Ex08_StructAndTrace") -local Ex09_AssetRefAndUMG = require("Tests.UnLuaExamples.Ex09_AssetRefAndUMG") -function ____exports.RunUnLuaExamplesTests() - Suite( - "UnLuaExamples.OfficialPorts", - function() - Test( - "Ex01_HelloWorld: ReceiveBeginPlay prints and logs greeting", - function() - ResetMockState() - local actor = CreateBoundInstance(Ex01_HelloWorld, "AActor") - actor:ReceiveBeginPlay() - AssertTrue((string.find( - actor:GetGreeting(), - "Hello UnLua from TypeScript", - 1, - true - )) ~= nil) - AssertEqual( - #GetMockState().printedStrings, - 1 - ) - AssertEqual( - #GetMockState().logs, - 1 - ) - end - ) - Test( - "Ex02_OverrideBlueprintEvents: lifecycle events and self.Overridden chain", - function() - ResetMockState() - local actor = CreateBoundInstance(Ex02_OverrideBlueprintEvents, "AActor") - local other = CreateBoundInstance({}, "AActor", {__name = "OtherActor_1"}) - actor:Initialize() - actor:UserConstructionScript() - actor:ReceiveBeginPlay() - actor:ReceiveTick(0.016) - actor:ReceiveTick(0.034) - actor:ReceiveAnyDamage(35, nil, nil, other) - actor:ReceiveActorBeginOverlap(other) - actor:ReceiveEndPlay(UE.EEndPlayReason.Destroyed) - AssertNear( - actor:GetElapsed(), - 0.05 - ) - AssertEqual( - actor:GetTotalDamage(), - 35 - ) - AssertEqual( - actor:GetOverlapCount(), - 1 - ) - AssertArrayEqual( - actor:GetEvents(), - { - "Initialize", - "UserConstructionScript", - "ReceiveBeginPlay", - "Damage:35", - "Overlap:OtherActor_1", - "EndPlay:0" - } - ) - AssertEqual( - #GetMockState().overriddenCalls, - 7 - ) - end - ) - Test( - "Ex03_BindDelegates: Multicast, FScriptDelegate and K2_SetTimerDelegate via UnLua.Delegate", - function() - ResetMockState() - local mockBtn = {OnClicked = CreateMockMulticastDelegate()} - local singleDel = CreateMockScriptDelegate() - local widget = CreateBoundInstance(Ex03_BindDelegates, "UUserWidget", {ClickMeButton = mockBtn, CustomSingleDelegate = singleDel}) - widget:Construct() - AssertTrue(mockBtn.OnClicked:IsBound()) - mockBtn.OnClicked:Broadcast() - mockBtn.OnClicked:Broadcast() - AssertEqual( - widget:GetClickCount(), - 2 - ) - AssertEqual( - singleDel:Execute(5), - 52 - ) - AdvanceMockTime(1.6) - AssertEqual( - widget:GetTimerTickCount(), - 3 - ) - AssertTrue(UE.UKismetSystemLibrary.K2_IsTimerActiveHandle( - widget, - widget:GetTimerHandle() - )) - widget:Destruct() - AssertFalse(mockBtn.OnClicked:IsBound()) - mockBtn.OnClicked:Broadcast() - AssertEqual( - widget:GetClickCount(), - 2 - ) - AdvanceMockTime(2) - AssertEqual( - widget:GetTimerTickCount(), - 3 - ) - end - ) - Test( - "Ex04_DynamicBinding: World:SpawnActor, SpawnActorEx and UE.NewObject with Initializer", - function() - ResetMockState() - local spawner = CreateBoundInstance(Ex04_DynamicBinding, "AActor") - local spawned = spawner:SpawnDynamicActor("Fireball", 120) - AssertNotNil(spawned) - AssertEqual( - spawned:GetInitTag(), - "Fireball" - ) - AssertEqual( - spawned:GetInitPower(), - 120 - ) - AssertTrue(spawned:IsBeginPlayCalled()) - local spawnedEx = spawner:SpawnDynamicActorEx("IceShard") - AssertNotNil(spawnedEx) - AssertEqual( - spawnedEx:GetInitTag(), - "IceShard" - ) - AssertEqual( - spawnedEx:GetInitPower(), - 77 - ) - local dynObj = spawner:CreateDynamicObject(10) - AssertNotNil(dynObj) - AssertEqual( - dynObj:GetSeed(), - 10 - ) - AssertEqual( - dynObj:NextValue(), - 21 - ) - AssertEqual( - dynObj:NextValue(), - 43 - ) - end - ) - Test( - "Ex05_BindInputs: UnLua.Input and UnLua.EnhancedInput module registrations", - function() - local pc = CreateBoundInstance(Ex05_BindInputs, "APlayerController") - pc:ReceiveBeginPlay() - ResetMockState() - local pkg = _G.package - local modName = "Tests.UnLuaExamples.Ex05_BindInputs" - local prevMod = pkg.loaded[modName] - pkg.loaded[modName] = nil - require(modName) - pkg.loaded[modName] = prevMod - local bindings = GetMockState().inputBindings - AssertEqual(#bindings, 5) - AssertEqual(bindings[1].kind, "Key") - AssertEqual(bindings[1].name, "SpaceBar") - local ____AssertEqual_2 = AssertEqual - local ____opt_0 = bindings[2].args - ____AssertEqual_2(____opt_0 and ____opt_0.Ctrl, true) - AssertEqual(bindings[3].kind, "Action") - AssertEqual(bindings[4].kind, "Axis") - AssertEqual(bindings[5].kind, "EnhancedAction") - bindings[1].handler(pc) - AssertEqual( - pc:GetLastAction(), - "SpaceBar:Pressed" - ) - bindings[2].handler(pc) - AssertEqual( - pc:GetLastAction(), - "Ctrl+S" - ) - bindings[3].handler(pc) - AssertEqual( - pc:GetLastAction(), - "Action:Jump" - ) - bindings[4].handler(pc, 0.75) - AssertNear( - pc:GetMoveForwardValue(), - 0.75 - ) - bindings[5].handler(pc, -1) - AssertNear( - pc:GetMoveForwardValue(), - -1 - ) - AssertEqual( - pc:GetEnhancedCount(), - 1 - ) - end - ) - Test( - "Ex06_NativeContainers: TArray, TMap and TSet full API & pairs()", - function() - VerifyTArrayOperations() - VerifyTMapOperations() - VerifyTSetOperations() - end - ) - Test( - "Ex07_CallLatentFunction: coroutine Delay sequence & destroy abort guard", - function() - ResetMockState() - local actor = CreateBoundInstance(Ex07_CallLatentFunction, "AActor") - actor:ReceiveBeginPlay() - AssertArrayEqual( - actor:GetSteps(), - {"Step1:Start"} - ) - AssertFalse(actor:IsCompleted()) - AdvanceMockTime(0.5) - AssertArrayEqual( - actor:GetSteps(), - {"Step1:Start", "Step2:After0.5s"} - ) - AssertFalse(actor:IsCompleted()) - AdvanceMockTime(1) - AssertArrayEqual( - actor:GetSteps(), - {"Step1:Start", "Step2:After0.5s", "Step3:Done"} - ) - AssertTrue(actor:IsCompleted()) - local doomed = CreateBoundInstance(Ex07_CallLatentFunction, "AActor") - doomed:ReceiveBeginPlay() - doomed:K2_DestroyActor() - AdvanceMockTime(2) - AssertArrayEqual( - doomed:GetSteps(), - {"Step1:Start"} - ) - AssertFalse(doomed:IsCompleted()) - end - ) - Test( - "Ex08_StructAndTrace: FVector math, LineTraceSingle multi-return and K2_SetActorLocation", - function() - ResetMockState() - local actor = CreateBoundInstance(Ex08_StructAndTrace, "AActor") - actor:ReceiveBeginPlay() - local size, dot, dist = actor:ComputeVectorMath() - AssertNear(size, 13) - AssertNear(dot, 0) - AssertNear(dist, 13) - AssertTrue(actor:TeleportTo(100, 0, 50)) - local bHit, hitDist, impact = actor:TraceForward(200) - AssertTrue(bHit) - AssertNear(hitDist, 100) - AssertNear(impact.X, 200) - AssertNear(impact.Z, 50) - end - ) - Test( - "Ex09_AssetRefAndUMG: UObject.Load, UnLua.Ref/Unref, WeakPtr and UMG Release", - function() - ResetMockState() - local widget = CreateBoundInstance(Ex09_AssetRefAndUMG, "UUserWidget") - widget:Initialize() - widget:Construct() - widget:ShowOnScreen() - AssertTrue(widget:IsConstructed()) - AssertFalse(widget:IsDestructed()) - AssertTrue(widget:HasValidWeakAsset()) - widget:CloseAndRelease() - AssertTrue(widget:IsDestructed()) - AssertFalse(widget:HasValidWeakAsset()) - end - ) - end - ) -end -function __module.UpdateImports() - Suite = M__Tests_Harness_TestRunner.Suite - Test = M__Tests_Harness_TestRunner.Test - AssertEqual = M__Tests_Harness_TestRunner.AssertEqual - AssertNear = M__Tests_Harness_TestRunner.AssertNear - AssertTrue = M__Tests_Harness_TestRunner.AssertTrue - AssertFalse = M__Tests_Harness_TestRunner.AssertFalse - AssertNotNil = M__Tests_Harness_TestRunner.AssertNotNil - AssertArrayEqual = M__Tests_Harness_TestRunner.AssertArrayEqual - AdvanceMockTime = M__Tests_Harness_MockUnLuaRuntime.AdvanceMockTime - CreateBoundInstance = M__Tests_Harness_MockUnLuaRuntime.CreateBoundInstance - CreateMockMulticastDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockMulticastDelegate - CreateMockScriptDelegate = M__Tests_Harness_MockUnLuaRuntime.CreateMockScriptDelegate - GetMockState = M__Tests_Harness_MockUnLuaRuntime.GetMockState - ResetMockState = M__Tests_Harness_MockUnLuaRuntime.ResetMockState - VerifyTArrayOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTArrayOperations - VerifyTMapOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTMapOperations - VerifyTSetOperations = M__Tests_UnLuaExamples_Ex06_NativeContainers.VerifyTSetOperations -end diff --git a/Script/lua/framework/context/game_context.lua b/Script/lua/framework/context/game_context.lua new file mode 100644 index 0000000..b142607 --- /dev/null +++ b/Script/lua/framework/context/game_context.lua @@ -0,0 +1,266 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module) +local EventHub = M__share_event_event_hub.EventHub +local M__framework_core_scheduler = __MODULE__.Import("framework.core.scheduler", __module) +local FrameScheduler = M__framework_core_scheduler.FrameScheduler +local M__framework_module_mgr_registry = __MODULE__.Import("framework.module.mgr_registry", __module) +local MgrRegistry = M__framework_module_mgr_registry.MgrRegistry +local logger = Logger("GameContext") +____exports.WorldContext = __TS__DefineClass("WorldContext", __module) +local WorldContext = ____exports.WorldContext +WorldContext.name = "WorldContext" +__TS__ClassExtends(WorldContext, ScopedObject) +function WorldContext.prototype.____constructor(self, worldGen, world) + ScopedObject.prototype.____constructor(self) + self.worldGen = worldGen + self.world = world +end +____exports.LocalPlayerContext = __TS__DefineClass("LocalPlayerContext", __module) +local LocalPlayerContext = ____exports.LocalPlayerContext +LocalPlayerContext.name = "LocalPlayerContext" +__TS__ClassExtends(LocalPlayerContext, ScopedObject) +function LocalPlayerContext.prototype.____constructor(self, playerIndex, playerController) + ScopedObject.prototype.____constructor(self) + self.services = {} + self.playerIndex = playerIndex + self.playerController = playerController +end +function LocalPlayerContext.prototype.RegisterService(self, key, service) + local old = self.services[key] + if old ~= nil and old ~= service then + old:Dispose() + end + self.services[key] = service + self:AddScopedObject(service) + return service +end +function LocalPlayerContext.prototype.GetService(self, key) + return self.services[key] +end +--- +-- @module_data +local nextContextId = 0 +____exports.GameInstanceContext = __TS__DefineClass("GameInstanceContext", __module) +local GameInstanceContext = ____exports.GameInstanceContext +GameInstanceContext.name = "GameInstanceContext" +__TS__ClassExtends(GameInstanceContext, ScopedObject) +function GameInstanceContext.prototype.____constructor(self, gameInstance) + ScopedObject.prototype.____constructor(self) + self.shuttingDown = false + self.localPlayers = {} + self.services = {} + self.shutdownHooks = {} + nextContextId = nextContextId + 1 + self.contextId = nextContextId + self.gameInstance = gameInstance + self.scheduler = __TS__New(FrameScheduler) + self.mgrRegistry = __TS__New(MgrRegistry) + self.appEvents = __TS__New( + EventHub, + "AppLifecycle#" .. tostring(self.contextId) + ) + self.worldContext = __TS__New( + ____exports.WorldContext, + self.scheduler:GetCurrentWorldGen() + ) +end +function GameInstanceContext.prototype.IsShuttingDown(self) + return self.shuttingDown or self:IsDisposed() +end +function GameInstanceContext.prototype.GetWorldContext(self) + return self.worldContext +end +function GameInstanceContext.prototype.GetWorldGen(self) + return self.worldContext.worldGen +end +function GameInstanceContext.prototype.GetOrCreateLocalPlayer(self, playerIndex, pc) + local lp = self.localPlayers[playerIndex] + if lp == nil or lp:IsDisposed() then + lp = __TS__New(____exports.LocalPlayerContext, playerIndex, pc) + self.localPlayers[playerIndex] = lp + elseif pc ~= nil then + lp.playerController = pc + end + return lp +end +function GameInstanceContext.prototype.RemoveLocalPlayer(self, playerIndex) + local lp = self.localPlayers[playerIndex] + if lp ~= nil then + self.localPlayers[playerIndex] = nil + lp:Dispose() + end +end +function GameInstanceContext.prototype.RegisterService(self, key, service) + local old = self.services[key] + if old ~= nil and old ~= service then + old:Dispose() + end + self.services[key] = service + return service +end +function GameInstanceContext.prototype.GetService(self, key) + return self.services[key] +end +function GameInstanceContext.prototype.AddShutdownHook(self, hook) + if self.shuttingDown then + return + end + self.shutdownHooks[#self.shutdownHooks + 1] = hook +end +function GameInstanceContext.prototype.Tick(self, unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused) + if isWorldPaused == nil then + isWorldPaused = false + end + if self:IsShuttingDown() then + return + end + self.scheduler:Tick(unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused) +end +function GameInstanceContext.prototype.OnWorldCleanup(self, nextWorld) + if self:IsShuttingDown() then + return + end + local oldGen = self.worldContext.worldGen + self.appEvents.emit.OnWorldCleanup(oldGen) + self.worldContext:Dispose() + local newGen = self.scheduler:InvalidateWorld() + self.worldContext = __TS__New(____exports.WorldContext, newGen, nextWorld) +end +function GameInstanceContext.prototype.Dispose(self) + if self:IsDisposed() then + return + end + self.shuttingDown = true + self.appEvents.emit.OnBeforeShutdown() + local playerKeys = {} + for idx in pairs(self.localPlayers) do + playerKeys[#playerKeys + 1] = idx + end + do + local i = 0 + while i < #playerKeys do + local idx = playerKeys[i + 1] + local lp = self.localPlayers[idx] + self.localPlayers[idx] = nil + if lp ~= nil then + lp:Dispose() + end + i = i + 1 + end + end + self.worldContext:Dispose() + self.scheduler:InvalidateWorld() + do + local i = #self.shutdownHooks - 1 + while i >= 0 do + self.shutdownHooks[i + 1]() + i = i - 1 + end + end + self.shutdownHooks = {} + local serviceList = {} + for k, svc in pairs(self.services) do + if svc ~= nil then + self.services[k] = nil + serviceList[#serviceList + 1] = svc + end + end + do + local i = 0 + while i < #serviceList do + serviceList[i + 1]:Dispose() + i = i + 1 + end + end + self.mgrRegistry:Dispose() + self.scheduler:Dispose() + self.appEvents:Dispose() + ScopedObject.prototype.Dispose(self) + logger:Info("GameInstanceContext disposed", {contextId = self.contextId}) +end +--- +-- @module_data +local activeContextsByKey = {} +--- +-- @noSelf +function ____exports.GetGameInstanceKey(gameInstance) + if gameInstance.GetName ~= nil then + return gameInstance:GetName() + end + return tostring(gameInstance) +end +--- +-- @noSelf +function ____exports.CreateGameInstanceContext(gameInstance) + local key = ____exports.GetGameInstanceKey(gameInstance) + local old = activeContextsByKey[key] + if old ~= nil and not old:IsDisposed() then + old:Dispose() + end + local ctx = __TS__New(____exports.GameInstanceContext, gameInstance) + activeContextsByKey[key] = ctx + return ctx +end +--- +-- @noSelf +function ____exports.GetGameInstanceContext(gameInstance) + return activeContextsByKey[____exports.GetGameInstanceKey(gameInstance)] +end +--- +-- @noSelf +function ____exports.DestroyGameInstanceContext(gameInstance) + local key = ____exports.GetGameInstanceKey(gameInstance) + local ctx = activeContextsByKey[key] + if ctx ~= nil then + activeContextsByKey[key] = nil + ctx:Dispose() + end +end +--- +-- @noSelf +function ____exports.GetActiveGameInstanceContextCount() + local count = 0 + for _, ctx in pairs(activeContextsByKey) do + if ctx ~= nil and not ctx:IsDisposed() then + count = count + 1 + end + end + return count +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.nextContextId = nextContextId + ____has.nextContextId = true + to.activeContextsByKey = activeContextsByKey + ____has.activeContextsByKey = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.nextContextId then + nextContextId = from.nextContextId + end + if ____has.activeContextsByKey then + activeContextsByKey = from.activeContextsByKey + end +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + EventHub = M__share_event_event_hub.EventHub + FrameScheduler = M__framework_core_scheduler.FrameScheduler + MgrRegistry = M__framework_module_mgr_registry.MgrRegistry +end diff --git a/Script/lua/framework/core/json.lua b/Script/lua/framework/core/json.lua new file mode 100644 index 0000000..38493ea --- /dev/null +++ b/Script/lua/framework/core/json.lua @@ -0,0 +1,365 @@ +local ____exports = __module.env +local FALLBACK_NULL = {__json_null__ = true} +local FALLBACK_EMPTY_ARRAY = {__json_empty_array__ = true} +--- +-- @module_data +local cachedNative = nil +local function TryLoadNativeJson() + if cachedNative ~= nil then + local ____temp_0 + if cachedNative == false then + ____temp_0 = nil + else + ____temp_0 = cachedNative + end + return ____temp_0 + end + local ok, mod = pcall(require, "ue_json") + if ok and type(mod) == "table" and type(mod.encode) == "function" and type(mod.decode) == "function" then + cachedNative = mod + return cachedNative + end + cachedNative = false + return nil +end +local function EscapeJsonString(str) + local escaped = string.gsub( + str, + "[%z-\\\"]", + function(ch) + if ch == "\"" then + return "\\\"" + end + if ch == "\\" then + return "\\\\" + end + if ch == "\b" then + return "\\b" + end + if ch == "\f" then + return "\\f" + end + if ch == "\n" then + return "\\n" + end + if ch == "\r" then + return "\\r" + end + if ch == "\t" then + return "\\t" + end + return string.format( + "\\u%04x", + string.byte(ch) + ) + end + ) + return ("\"" .. escaped) .. "\"" +end +local function IsPureArray(tbl) + local count = 0 + local maxKey = 0 + for k in pairs(tbl) do + count = count + 1 + if type(k) ~= "number" or math.type(k) ~= "integer" or k <= 0 then + return false, 0 + end + if k > maxKey then + maxKey = k + end + end + return count > 0 and maxKey == count, maxKey +end +local function FallbackEncodeValue(val, depth) + if depth > 64 then + return nil, "JSON encode exceeded maximum depth (64)" + end + if val == nil or val == FALLBACK_NULL then + return "null", nil + end + if val == FALLBACK_EMPTY_ARRAY then + return "[]", nil + end + local t = type(val) + if t == "boolean" then + return val and "true" or "false", nil + end + if t == "number" then + local num = val + if num ~= num or num == math.huge or num == -math.huge then + return nil, "Cannot encode NaN or Infinity to JSON" + end + if math.type(num) == "integer" then + return string.format("%d", num), nil + end + return string.format("%.17g", num), nil + end + if t == "string" then + return EscapeJsonString(val), nil + end + if t == "table" then + local tbl = val + local isArr, len = IsPureArray(tbl) + if isArr then + local items = {} + do + local i = 1 + while i <= len do + local encoded, err = FallbackEncodeValue(tbl[i], depth + 1) + if err ~= nil then + return nil, err + end + items[#items + 1] = encoded + i = i + 1 + end + end + return ("[" .. table.concat(items, ",")) .. "]", nil + end + local pairsOut = {} + for k, v in pairs(tbl) do + local kt = type(k) + if kt ~= "string" and kt ~= "number" then + return nil, "Unsupported JSON object key type: " .. kt + end + local encodedVal, err = FallbackEncodeValue(v, depth + 1) + if err ~= nil then + return nil, err + end + pairsOut[#pairsOut + 1] = (EscapeJsonString(tostring(k)) .. ":") .. encodedVal + end + return ("{" .. table.concat(pairsOut, ",")) .. "}", nil + end + return nil, "Unsupported Lua type for JSON encode: " .. t +end +local function SkipWs(st) + while st.pos <= st.len do + local b = string.byte(st.src, st.pos) + if b == 32 or b == 9 or b == 10 or b == 13 then + st.pos = st.pos + 1 + else + break + end + end +end +local function ParseString(st) + st.pos = st.pos + 1 + local out = {} + while st.pos <= st.len do + local ch = string.sub(st.src, st.pos, st.pos) + if ch == "\"" then + st.pos = st.pos + 1 + return table.concat(out), nil + end + if ch == "\\" then + st.pos = st.pos + 1 + if st.pos > st.len then + return nil, "Unterminated escape in JSON string" + end + local esc = string.sub(st.src, st.pos, st.pos) + st.pos = st.pos + 1 + if esc == "\"" or esc == "\\" or esc == "/" then + out[#out + 1] = esc + elseif esc == "b" then + out[#out + 1] = "\b" + elseif esc == "f" then + out[#out + 1] = "\f" + elseif esc == "n" then + out[#out + 1] = "\n" + elseif esc == "r" then + out[#out + 1] = "\r" + elseif esc == "t" then + out[#out + 1] = "\t" + elseif esc == "u" then + local hex = string.sub(st.src, st.pos, st.pos + 3) + local code = tonumber(hex, 16) + if code == nil or #hex < 4 then + return nil, "Invalid \\u escape" + end + st.pos = st.pos + 4 + out[#out + 1] = utf8.char(code) + else + return nil, "Invalid escape char: \\" .. esc + end + else + out[#out + 1] = ch + st.pos = st.pos + 1 + end + end + return nil, "Unterminated JSON string" +end +local function ParseValue(st, depth) + if depth > 64 then + return nil, "JSON decode exceeded maximum depth (64)" + end + SkipWs(st) + if st.pos > st.len then + return nil, "Unexpected EOF" + end + local ch = string.sub(st.src, st.pos, st.pos) + if ch == "\"" then + return ParseString(st) + end + if ch == "{" then + st.pos = st.pos + 1 + local obj = {} + SkipWs(st) + if string.sub(st.src, st.pos, st.pos) == "}" then + st.pos = st.pos + 1 + return obj, nil + end + while true do + SkipWs(st) + if string.sub(st.src, st.pos, st.pos) ~= "\"" then + return nil, "Expected string key in JSON object" + end + local key, keyErr = ParseString(st) + if keyErr ~= nil then + return nil, keyErr + end + SkipWs(st) + if string.sub(st.src, st.pos, st.pos) ~= ":" then + return nil, "Expected ':' in JSON object" + end + st.pos = st.pos + 1 + local val, valErr = ParseValue(st, depth + 1) + if valErr ~= nil then + return nil, valErr + end + obj[key] = val + SkipWs(st) + local sep = string.sub(st.src, st.pos, st.pos) + if sep == "}" then + st.pos = st.pos + 1 + return obj, nil + end + if sep ~= "," then + return nil, "Expected ',' or '}' in JSON object" + end + st.pos = st.pos + 1 + end + end + if ch == "[" then + st.pos = st.pos + 1 + local arr = {} + SkipWs(st) + if string.sub(st.src, st.pos, st.pos) == "]" then + st.pos = st.pos + 1 + return arr, nil + end + local idx = 1 + while true do + local val, valErr = ParseValue(st, depth + 1) + if valErr ~= nil then + return nil, valErr + end + arr[idx] = val + idx = idx + 1 + SkipWs(st) + local sep = string.sub(st.src, st.pos, st.pos) + if sep == "]" then + st.pos = st.pos + 1 + return arr, nil + end + if sep ~= "," then + return nil, "Expected ',' or ']' in JSON array" + end + st.pos = st.pos + 1 + end + end + if string.sub(st.src, st.pos, st.pos + 3) == "true" then + st.pos = st.pos + 4 + return true, nil + end + if string.sub(st.src, st.pos, st.pos + 4) == "false" then + st.pos = st.pos + 5 + return false, nil + end + if string.sub(st.src, st.pos, st.pos + 3) == "null" then + st.pos = st.pos + 4 + return st.keepNull and FALLBACK_NULL or nil, nil + end + local numStr = string.match(st.src, "^%-?%d+%.?%d*[eE]?[%+%-]?%d*", st.pos) + if numStr ~= nil and numStr ~= "" then + local parsed = tonumber(numStr) + if parsed ~= nil then + st.pos = st.pos + #numStr + return parsed, nil + end + end + return nil, "Unexpected token at pos " .. tostring(st.pos) +end +local function FallbackDecode(raw, keepNull) + local st = {src = raw, len = #raw, pos = 1, keepNull = keepNull} + local val, err = ParseValue(st, 0) + if err ~= nil then + return nil, err + end + SkipWs(st) + if st.pos <= st.len then + return nil, "Trailing characters after JSON value" + end + return val, nil +end +function ____exports.IsNativeBackend() + return TryLoadNativeJson() ~= nil +end +function ____exports.GetNull() + local native = TryLoadNativeJson() + local ____temp_1 + if native ~= nil then + ____temp_1 = native.null + else + ____temp_1 = FALLBACK_NULL + end + return ____temp_1 +end +function ____exports.GetEmptyArray() + local native = TryLoadNativeJson() + local ____temp_2 + if native ~= nil then + ____temp_2 = native.empty_array + else + ____temp_2 = FALLBACK_EMPTY_ARRAY + end + return ____temp_2 +end +function ____exports.Encode(value) + local native = TryLoadNativeJson() + if native ~= nil then + return native.encode(value) + end + return FallbackEncodeValue(value, 0) +end +function ____exports.Decode(raw, keepNull) + if keepNull == nil then + keepNull = false + end + if type(raw) ~= "string" or raw == "" then + return nil, "Empty JSON input" + end + local native = TryLoadNativeJson() + if native ~= nil then + return native.decode(raw, keepNull) + end + return FallbackDecode(raw, keepNull) +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.cachedNative = cachedNative + ____has.cachedNative = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.cachedNative then + cachedNative = from.cachedNative + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/framework/core/scheduler.lua b/Script/lua/framework/core/scheduler.lua new file mode 100644 index 0000000..f4b40b6 --- /dev/null +++ b/Script/lua/framework/core/scheduler.lua @@ -0,0 +1,404 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local __TS__InstanceOf = ____lualib.__TS__InstanceOf +local __TS__ArraySetLength = ____lualib.__TS__ArraySetLength +local ____exports = __module.env +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local tbpcall = M__share_base_traceback.tbpcall +____exports.TimerHandle = __TS__DefineClass("TimerHandle", __module) +local TimerHandle = ____exports.TimerHandle +TimerHandle.name = "TimerHandle" +function TimerHandle.prototype.____constructor(self, scheduler, entryId) + self.disposed = false + self.scheduler = scheduler + self.entryId = entryId +end +function TimerHandle.prototype.GetId(self) + return self.entryId +end +function TimerHandle.prototype.IsDisposed(self) + return self.disposed +end +function TimerHandle.prototype.IsActive(self) + return not self.disposed and self.scheduler ~= nil and self.scheduler:IsEntryActive(self.entryId) +end +function TimerHandle.prototype.Cancel(self) + self:Dispose() +end +function TimerHandle.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + if self.scheduler ~= nil then + local s = self.scheduler + self.scheduler = nil + s:CancelById(self.entryId) + end +end +function TimerHandle.prototype.MarkCompletedInternal(self) + self.disposed = true + self.scheduler = nil +end +____exports.FrameScheduler = __TS__DefineClass("FrameScheduler", __module) +local FrameScheduler = ____exports.FrameScheduler +FrameScheduler.name = "FrameScheduler" +function FrameScheduler.prototype.____constructor(self) + self.nextId = 0 + self.monotonicTime = 0 + self.worldTime = 0 + self.currentWorldGen = 1 + self.frameCounter = 0 + self.disposed = false + self.entriesById = {} + self.frameIds = {} + self.worldIds = {} + self.monotonicIds = {} +end +function FrameScheduler.prototype.IsDisposed(self) + return self.disposed +end +function FrameScheduler.prototype.NowSeconds(self) + return self.monotonicTime +end +function FrameScheduler.prototype.GetWorldTimeSeconds(self) + return self.worldTime +end +function FrameScheduler.prototype.GetFrameCount(self) + return self.frameCounter +end +function FrameScheduler.prototype.GetCurrentWorldGen(self) + return self.currentWorldGen +end +function FrameScheduler.prototype.IsEntryActive(self, id) + local entry = self.entriesById[id] + return entry ~= nil and not entry.cancelled +end +function FrameScheduler.prototype.AddFrameTimer(self, frames, callback, owner) + local count = math.max( + 1, + math.floor(frames) + ) + return self:CreateEntry( + "frame", + count, + 0, + false, + callback, + owner + ) +end +function FrameScheduler.prototype.RunNextFrame(self, callback, owner) + return self:AddFrameTimer(1, callback, owner) +end +function FrameScheduler.prototype.AddWorldTimer(self, delaySeconds, callback, owner) + local delay = math.max(0, delaySeconds) + return self:CreateEntry( + "world", + 0, + delay, + false, + callback, + owner + ) +end +function FrameScheduler.prototype.AddWorldRepeatTimer(self, intervalSeconds, callback, owner) + if intervalSeconds <= 0 then + return self:CreateEntry( + "frame", + 1, + 0, + true, + callback, + owner + ) + end + return self:CreateEntry( + "world", + 0, + intervalSeconds, + true, + callback, + owner + ) +end +function FrameScheduler.prototype.AddTimer(self, delaySeconds, callback, owner) + return self:AddMonotonicTimer(delaySeconds, callback, owner) +end +function FrameScheduler.prototype.AddRepeatTimer(self, intervalSeconds, callback, owner) + return self:AddMonotonicRepeatTimer(intervalSeconds, callback, owner) +end +function FrameScheduler.prototype.AddMonotonicTimer(self, delaySeconds, callback, owner) + local delay = math.max(0, delaySeconds) + return self:CreateEntry( + "monotonic", + 0, + delay, + false, + callback, + owner + ) +end +function FrameScheduler.prototype.AddMonotonicRepeatTimer(self, intervalSeconds, callback, owner) + local interval = math.max(0.001, intervalSeconds) + return self:CreateEntry( + "monotonic", + 0, + interval, + true, + callback, + owner + ) +end +function FrameScheduler.prototype.CreateEntry(self, domain, remainingFrames, intervalSec, ____repeat, callback, owner) + self.nextId = self.nextId + 1 + local id = self.nextId + local handle = __TS__New(____exports.TimerHandle, self, id) + if self.disposed or owner ~= nil and owner:IsDisposed() then + handle:MarkCompletedInternal() + return handle + end + local baseTime = domain == "world" and self.worldTime or self.monotonicTime + local entry = { + id = id, + domain = domain, + callback = callback, + owner = owner, + ["repeat"] = ____repeat, + cancelled = false, + remainingFrames = remainingFrames, + intervalSec = intervalSec, + nextTriggerTime = baseTime + intervalSec, + worldGen = self.currentWorldGen, + handle = handle + } + self.entriesById[id] = entry + if domain == "frame" then + self.frameIds[#self.frameIds + 1] = id + elseif domain == "world" then + self.worldIds[#self.worldIds + 1] = id + else + self.monotonicIds[#self.monotonicIds + 1] = id + end + if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then + owner:AddScopedObject(handle) + end + return handle +end +function FrameScheduler.prototype.CancelById(self, id) + local entry = self.entriesById[id] + if entry == nil then + return + end + entry.cancelled = true + self.entriesById[id] = nil +end +function FrameScheduler.prototype.InvalidateWorld(self) + local prevGen = self.currentWorldGen + self.currentWorldGen = self.currentWorldGen + 1 + self.worldTime = 0 + self:CancelEntriesForWorldGen(self.worldIds, prevGen) + self:CancelEntriesForWorldGen(self.frameIds, prevGen) + return self.currentWorldGen +end +function FrameScheduler.prototype.CancelEntriesForWorldGen(self, idList, worldGen) + local kept = {} + do + local i = 0 + while i < #idList do + do + local id = idList[i + 1] + local entry = self.entriesById[id] + if entry == nil or entry.cancelled then + goto __continue38 + end + if entry.worldGen == worldGen then + entry.cancelled = true + self.entriesById[id] = nil + entry.handle:MarkCompletedInternal() + else + kept[#kept + 1] = id + end + end + ::__continue38:: + i = i + 1 + end + end + __TS__ArraySetLength(idList, 0) + do + local i = 0 + while i < #kept do + idList[i + 1] = kept[i + 1] + i = i + 1 + end + end +end +function FrameScheduler.prototype.Tick(self, unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused) + if isWorldPaused == nil then + isWorldPaused = false + end + if self.disposed then + return + end + local safeUnscaled = math.max(0, unscaledDeltaSeconds) + self.monotonicTime = self.monotonicTime + safeUnscaled + self.frameCounter = self.frameCounter + 1 + self:ProcessTimedQueue(self.monotonicIds, self.monotonicTime) + if not isWorldPaused then + local safeWorldDt = math.max(0, worldDeltaSeconds or safeUnscaled) + self.worldTime = self.worldTime + safeWorldDt + self:ProcessTimedQueue(self.worldIds, self.worldTime) + end + self:ProcessFrameQueue() +end +function FrameScheduler.prototype.ProcessFrameQueue(self) + local snapshotLen = #self.frameIds + local nextFrameIds = {} + do + local i = 0 + while i < snapshotLen do + do + local id = self.frameIds[i + 1] + local entry = self.entriesById[id] + if entry == nil or entry.cancelled then + goto __continue49 + end + if entry.owner ~= nil and entry.owner:IsDisposed() then + entry.cancelled = true + self.entriesById[id] = nil + entry.handle:MarkCompletedInternal() + goto __continue49 + end + entry.remainingFrames = entry.remainingFrames - 1 + if entry.remainingFrames <= 0 then + if not entry["repeat"] then + entry.cancelled = true + self.entriesById[id] = nil + entry.handle:MarkCompletedInternal() + else + entry.remainingFrames = 1 + nextFrameIds[#nextFrameIds + 1] = id + end + tbpcall(entry.callback) + else + nextFrameIds[#nextFrameIds + 1] = id + end + end + ::__continue49:: + i = i + 1 + end + end + do + local i = snapshotLen + while i < #self.frameIds do + local id = self.frameIds[i + 1] + local entry = self.entriesById[id] + if entry ~= nil and not entry.cancelled then + nextFrameIds[#nextFrameIds + 1] = id + end + i = i + 1 + end + end + self.frameIds = nextFrameIds +end +function FrameScheduler.prototype.ProcessTimedQueue(self, idList, currentTime) + local snapshotLen = #idList + local kept = {} + do + local i = 0 + while i < snapshotLen do + do + local id = idList[i + 1] + local entry = self.entriesById[id] + if entry == nil or entry.cancelled then + goto __continue61 + end + if entry.owner ~= nil and entry.owner:IsDisposed() then + entry.cancelled = true + self.entriesById[id] = nil + entry.handle:MarkCompletedInternal() + goto __continue61 + end + if currentTime + 1e-9 >= entry.nextTriggerTime then + if not entry["repeat"] then + entry.cancelled = true + self.entriesById[id] = nil + entry.handle:MarkCompletedInternal() + tbpcall(entry.callback) + else + entry.nextTriggerTime = currentTime + entry.intervalSec + tbpcall(entry.callback) + if not entry.cancelled and self.entriesById[id] ~= nil then + kept[#kept + 1] = id + end + end + else + kept[#kept + 1] = id + end + end + ::__continue61:: + i = i + 1 + end + end + do + local i = snapshotLen + while i < #idList do + local id = idList[i + 1] + local entry = self.entriesById[id] + if entry ~= nil and not entry.cancelled then + kept[#kept + 1] = id + end + i = i + 1 + end + end + __TS__ArraySetLength(idList, 0) + do + local i = 0 + while i < #kept do + idList[i + 1] = kept[i + 1] + i = i + 1 + end + end +end +function FrameScheduler.prototype.GetStats(self) + local frameTasks = self:CountActive(self.frameIds) + local worldTasks = self:CountActive(self.worldIds) + local monotonicTasks = self:CountActive(self.monotonicIds) + return {frameTasks = frameTasks, worldTasks = worldTasks, monotonicTasks = monotonicTasks, totalTasks = frameTasks + worldTasks + monotonicTasks} +end +function FrameScheduler.prototype.CountActive(self, idList) + local count = 0 + do + local i = 0 + while i < #idList do + local entry = self.entriesById[idList[i + 1]] + if entry ~= nil and not entry.cancelled then + count = count + 1 + end + i = i + 1 + end + end + return count +end +function FrameScheduler.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + for id, entry in pairs(self.entriesById) do + if entry ~= nil then + entry.cancelled = true + entry.handle:MarkCompletedInternal() + self.entriesById[id] = nil + end + end + self.frameIds = {} + self.worldIds = {} + self.monotonicIds = {} +end +function __module.UpdateImports() + ScopedObject = M__share_base_scoped_object.ScopedObject + tbpcall = M__share_base_traceback.tbpcall +end diff --git a/Script/lua/framework/module/mgr_base.lua b/Script/lua/framework/module/mgr_base.lua new file mode 100644 index 0000000..7a1ca09 --- /dev/null +++ b/Script/lua/framework/module/mgr_base.lua @@ -0,0 +1,130 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +____exports.MgrDataBase = __TS__DefineClass("MgrDataBase", __module) +local MgrDataBase = ____exports.MgrDataBase +MgrDataBase.name = "MgrDataBase" +function MgrDataBase.prototype.____constructor(self) +end +function MgrDataBase.prototype.OnEnterGame(self) +end +function MgrDataBase.prototype.OnExitGame(self) +end +____exports.ControllerBase = __TS__DefineClass("ControllerBase", __module) +local ControllerBase = ____exports.ControllerBase +ControllerBase.name = "ControllerBase" +__TS__ClassExtends(ControllerBase, ScopedObject) +function ControllerBase.prototype.____constructor(self, mgr) + ScopedObject.prototype.____constructor(self) + self.mgr = mgr +end +function ControllerBase.prototype.OnEnter(self) +end +function ControllerBase.prototype.OnBindEvents(self) +end +function ControllerBase.prototype.OnActive(self) +end +function ControllerBase.prototype.OnExit(self) +end +____exports.MgrBase = __TS__DefineClass("MgrBase", __module) +local MgrBase = ____exports.MgrBase +MgrBase.name = "MgrBase" +__TS__ClassExtends(MgrBase, ScopedObject) +function MgrBase.prototype.____constructor(self, ...) + ScopedObject.prototype.____constructor(self, ...) + self.controllers = {} + self.isActive = true +end +function MgrBase.prototype.Initialization(self) + self:OnCreate() + self:OnBindControllers() + self:OnBindEvents() +end +function MgrBase.prototype.OnBindControllers(self) +end +function MgrBase.prototype.OnBindEvents(self) +end +function MgrBase.prototype.OnEnterGame(self) +end +function MgrBase.prototype.OnExitGame(self) +end +function MgrBase.prototype.OnClean(self) +end +function MgrBase.prototype.SetActive(self, active) + self.isActive = active + if active then + self:EnableControllers() + self:EnableAllEventListeners() + else + self:DisableControllers() + self:DisableAllEventListeners() + end +end +function MgrBase.prototype.AddController(self, ctor) + local existing = self.controllers[ctor] + assert(existing == nil, "MgrBase.AddController: controller already added") + local ctrl = __TS__New(ctor, self) + self.controllers[ctor] = ctrl + ctrl:OnEnter() + ctrl:OnBindEvents() + ctrl:OnActive() + return ctrl +end +function MgrBase.prototype.GetController(self, ctor) + return self.controllers[ctor] +end +function MgrBase.prototype.DelController(self, ctor) + local ctrl = self.controllers[ctor] + if ctrl == nil then + return + end + self.controllers[ctor] = nil + ctrl:OnExit() + ctrl:Dispose() +end +function MgrBase.prototype.DelAllControllers(self) + local list = {} + for ctorKey, ctrl in pairs(self.controllers) do + if ctrl ~= nil then + self.controllers[ctorKey] = nil + list[#list + 1] = ctrl + end + end + do + local i = 0 + while i < #list do + list[i + 1]:OnExit() + list[i + 1]:Dispose() + i = i + 1 + end + end +end +function MgrBase.prototype.EnableControllers(self) + for _, ctrl in pairs(self.controllers) do + if ctrl ~= nil then + ctrl:EnableAllEventListeners() + ctrl:OnActive() + end + end +end +function MgrBase.prototype.DisableControllers(self) + for _, ctrl in pairs(self.controllers) do + if ctrl ~= nil then + ctrl:DisableAllEventListeners() + end + end +end +function MgrBase.prototype.Dispose(self) + if self:IsDisposed() then + return + end + self:DelAllControllers() + self:OnClean() + ScopedObject.prototype.Dispose(self) +end +function __module.UpdateImports() + ScopedObject = M__share_base_scoped_object.ScopedObject +end diff --git a/Script/lua/framework/module/mgr_registry.lua b/Script/lua/framework/module/mgr_registry.lua new file mode 100644 index 0000000..45b1140 --- /dev/null +++ b/Script/lua/framework/module/mgr_registry.lua @@ -0,0 +1,124 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +--- +-- @noSelf +local function ResolveClassName(ctor, explicitName) + if explicitName ~= nil and explicitName ~= "" then + return explicitName + end + local rawName = ctor.name + if rawName ~= nil and type(rawName) == "string" and rawName ~= "" then + return rawName + end + return tostring(ctor) +end +____exports.MgrRegistry = __TS__DefineClass("MgrRegistry", __module) +local MgrRegistry = ____exports.MgrRegistry +MgrRegistry.name = "MgrRegistry" +function MgrRegistry.prototype.____constructor(self) + self.mgrByCtor = {} + self.mgrNameByCtor = {} + self.mgrByName = {} + self.dataByCtor = {} + self.disposed = false +end +function MgrRegistry.prototype.CreateMgrData(self, ctor) + local existing = self.dataByCtor[ctor] + if existing ~= nil then + return existing + end + local data = __TS__New(ctor) + self.dataByCtor[ctor] = data + return data +end +function MgrRegistry.prototype.GetMgrData(self, ctor) + return self.dataByCtor[ctor] +end +function MgrRegistry.prototype.DelMgrData(self, ctor) + local data = self.dataByCtor[ctor] + if data == nil then + return + end + self.dataByCtor[ctor] = nil + data:Dispose() +end +function MgrRegistry.prototype.CreateMgr(self, ctor, explicitName) + local existing = self.mgrByCtor[ctor] + if existing ~= nil then + return existing + end + local mgr = __TS__New(ctor) + local name = ResolveClassName(ctor, explicitName) + self.mgrByCtor[ctor] = mgr + self.mgrNameByCtor[ctor] = name + self.mgrByName[name] = mgr + mgr:Initialization() + return mgr +end +function MgrRegistry.prototype.GetMgr(self, ctor) + return self.mgrByCtor[ctor] +end +function MgrRegistry.prototype.GetMgrByName(self, name) + return self.mgrByName[name] +end +function MgrRegistry.prototype.DelMgr(self, ctor) + local mgr = self.mgrByCtor[ctor] + if mgr == nil then + return + end + local name = self.mgrNameByCtor[ctor] + self.mgrByCtor[ctor] = nil + self.mgrNameByCtor[ctor] = nil + if name ~= nil and self.mgrByName[name] == mgr then + self.mgrByName[name] = nil + end + mgr:Dispose() +end +function MgrRegistry.prototype.GetMgrCount(self) + local count = 0 + for _, mgr in pairs(self.mgrByCtor) do + if mgr ~= nil then + count = count + 1 + end + end + return count +end +function MgrRegistry.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + local mgrList = {} + for key, mgr in pairs(self.mgrByCtor) do + if mgr ~= nil then + self.mgrByCtor[key] = nil + mgrList[#mgrList + 1] = mgr + end + end + self.mgrNameByCtor = {} + self.mgrByName = {} + do + local i = 0 + while i < #mgrList do + mgrList[i + 1]:Dispose() + i = i + 1 + end + end + local dataList = {} + for key, data in pairs(self.dataByCtor) do + if data ~= nil then + self.dataByCtor[key] = nil + dataList[#dataList + 1] = data + end + end + do + local i = 0 + while i < #dataList do + dataList[i + 1]:Dispose() + i = i + 1 + end + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/framework/resource/asset_catalog.lua b/Script/lua/framework/resource/asset_catalog.lua new file mode 100644 index 0000000..88a2e5e --- /dev/null +++ b/Script/lua/framework/resource/asset_catalog.lua @@ -0,0 +1,12 @@ +local ____exports = __module.env +--- +-- @noSelfInFile +____exports.ASSET_KEYS = {MINI_SETTINGS_ICON = "tex.mini_settings_icon", MINI_SETTINGS_WIDGET = "ui.mini_settings"} +____exports.BASE_ASSET_PATHS = {[____exports.ASSET_KEYS.MINI_SETTINGS_ICON] = "/Game/UI/Textures/T_MiniSettingsIcon.T_MiniSettingsIcon", [____exports.ASSET_KEYS.MINI_SETTINGS_WIDGET] = "/Game/UI/WBP_MiniSettings.WBP_MiniSettings_C"} +function ____exports.RegisterBaseAssetCatalog(subsystem) + for logicalKey, softPath in pairs(____exports.BASE_ASSET_PATHS) do + subsystem:RegisterBaseAssetKey(logicalKey, softPath) + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/framework/resource/resource_service.lua b/Script/lua/framework/resource/resource_service.lua new file mode 100644 index 0000000..fc27fb2 --- /dev/null +++ b/Script/lua/framework/resource/resource_service.lua @@ -0,0 +1,348 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local __TS__InstanceOf = ____lualib.__TS__InstanceOf +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local tbpcall = M__share_base_traceback.tbpcall +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local RegisterBaseAssetCatalog = M__framework_resource_asset_catalog.RegisterBaseAssetCatalog +local logger = Logger("ResourceService") +____exports.UEResourceBackend = __TS__DefineClass("UEResourceBackend", __module) +local UEResourceBackend = ____exports.UEResourceBackend +UEResourceBackend.name = "UEResourceBackend" +function UEResourceBackend.prototype.____constructor(self, subsystem) + self.subsystem = subsystem +end +function UEResourceBackend.prototype.ResolveAssetPath(self, keyOrPath) + return self.subsystem:ResolveAssetPath(keyOrPath) +end +function UEResourceBackend.prototype.DoesAssetExist(self, keyOrPath) + return self.subsystem:DoesAssetExist(keyOrPath) +end +function UEResourceBackend.prototype.IsPackagedMode(self) + return UE.ULuaResourceSubsystem.IsPackagedResourceMode() +end +function UEResourceBackend.prototype.RequestLoadObjectAsync(self, keyOrPath, worldGen) + return self.subsystem:RequestLoadObjectAsync(keyOrPath, worldGen) +end +function UEResourceBackend.prototype.RequestLoadClassAsync(self, keyOrPath, worldGen) + return self.subsystem:RequestLoadClassAsync(keyOrPath, worldGen) +end +function UEResourceBackend.prototype.CancelRequest(self, requestId) + return self.subsystem:CancelRequest(requestId) +end +function UEResourceBackend.prototype.CancelRequestsForWorld(self, worldGen) + return self.subsystem:CancelRequestsForWorld(worldGen) +end +function UEResourceBackend.prototype.ReleaseAsset(self, resolvedSoftPath) + self.subsystem:ReleaseAsset(resolvedSoftPath) +end +function UEResourceBackend.prototype.GetResourceStats(self) + return self.subsystem:GetResourceStats() +end +____exports.ResourceLease = __TS__DefineClass("ResourceLease", __module) +local ResourceLease = ____exports.ResourceLease +ResourceLease.name = "ResourceLease" +function ResourceLease.prototype.____constructor(self, resolvedPath, asset, backend) + self.disposed = false + self.resolvedPath = resolvedPath + self.asset = asset + self.backend = backend +end +function ResourceLease.prototype.GetAsset(self) + if self.disposed then + return nil + end + return self.asset +end +function ResourceLease.prototype.IsDisposed(self) + return self.disposed +end +function ResourceLease.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + self.asset = nil + if self.backend ~= nil then + local b = self.backend + self.backend = nil + b:ReleaseAsset(self.resolvedPath) + end +end +____exports.ResourceLoadHandle = __TS__DefineClass("ResourceLoadHandle", __module) +local ResourceLoadHandle = ____exports.ResourceLoadHandle +ResourceLoadHandle.name = "ResourceLoadHandle" +function ResourceLoadHandle.prototype.____constructor(self, service, requestId) + self.disposed = false + self.service = service + self.requestId = requestId +end +function ResourceLoadHandle.prototype.AttachLeaseInternal(self, lease) + if self.disposed then + lease:Dispose() + return + end + self.lease = lease + self.service = nil +end +function ResourceLoadHandle.prototype.MarkSettledWithoutLeaseInternal(self) + self.service = nil +end +function ResourceLoadHandle.prototype.GetLease(self) + return self.lease +end +function ResourceLoadHandle.prototype.IsDisposed(self) + return self.disposed +end +function ResourceLoadHandle.prototype.Cancel(self) + self:Dispose() +end +function ResourceLoadHandle.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + if self.service ~= nil then + local svc = self.service + self.service = nil + svc:CancelPendingByIdInternal(self.requestId) + end + if self.lease ~= nil then + local l = self.lease + self.lease = nil + l:Dispose() + end +end +--- +-- @module_data +local serviceByGameInstanceKey = {} +____exports.ResourceService = __TS__DefineClass("ResourceService", __module) +local ResourceService = ____exports.ResourceService +ResourceService.name = "ResourceService" +__TS__ClassExtends(ResourceService, ScopedObject) +function ResourceService.prototype.____constructor(self, ctx, backend) + ScopedObject.prototype.____constructor(self) + self.pendingById = {} + self.ctx = ctx + self.backend = backend + if ctx.gameInstance ~= nil then + self.giKey = GetGameInstanceKey(ctx.gameInstance) + serviceByGameInstanceKey[self.giKey] = self + end + ctx.appEvents.on.OnWorldCleanup( + function(oldWorldGen) + self:CancelForWorld(oldWorldGen) + end, + self + ) +end +function ResourceService.prototype.ResolveAssetPath(self, keyOrPath) + return self.backend:ResolveAssetPath(keyOrPath) +end +function ResourceService.prototype.DoesAssetExist(self, keyOrPath) + return self.backend:DoesAssetExist(keyOrPath) +end +function ResourceService.prototype.IsPackagedMode(self) + return self.backend:IsPackagedMode() +end +function ResourceService.prototype.LoadObjectAsync(self, keyOrPath, owner, callback) + return self:StartAsyncLoad(keyOrPath, owner, callback, false) +end +function ResourceService.prototype.LoadTextureAsync(self, keyOrPath, owner, callback) + return self:LoadObjectAsync(keyOrPath, owner, callback) +end +function ResourceService.prototype.LoadClassAsync(self, keyOrPath, owner, callback) + return self:StartAsyncLoad(keyOrPath, owner, callback, true) +end +function ResourceService.prototype.StartAsyncLoad(self, keyOrPath, owner, callback, isClassLoad) + if self:IsDisposed() or self.ctx:IsShuttingDown() or owner ~= nil and owner:IsDisposed() then + local dead = __TS__New(____exports.ResourceLoadHandle, self, 0) + dead:Dispose() + return dead + end + local worldGen = self.ctx:GetWorldGen() + local requestId = isClassLoad and self.backend:RequestLoadClassAsync(keyOrPath, worldGen) or self.backend:RequestLoadObjectAsync(keyOrPath, worldGen) + local handle = __TS__New(____exports.ResourceLoadHandle, self, requestId) + local record = { + requestId = requestId, + keyOrPath = keyOrPath, + worldGen = worldGen, + owner = owner, + callback = callback, + handle = handle, + cancelled = false + } + self.pendingById[requestId] = record + if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then + owner:AddScopedObject(handle) + end + return handle +end +function ResourceService.prototype.CancelPendingByIdInternal(self, requestId) + local record = self.pendingById[requestId] + if record == nil then + return + end + record.cancelled = true + self.pendingById[requestId] = nil + self.backend:CancelRequest(requestId) +end +function ResourceService.prototype.CancelForWorld(self, worldGen) + local toCancel = {} + for id, rec in pairs(self.pendingById) do + if rec ~= nil and rec.worldGen == worldGen then + toCancel[#toCancel + 1] = id + end + end + do + local i = 0 + while i < #toCancel do + local rec = self.pendingById[toCancel[i + 1]] + if rec ~= nil then + rec.cancelled = true + self.pendingById[toCancel[i + 1]] = nil + rec.handle:MarkSettledWithoutLeaseInternal() + end + i = i + 1 + end + end + self.backend:CancelRequestsForWorld(worldGen) + return #toCancel +end +function ResourceService.prototype.HandleNativeLoadComplete(self, requestId, ok, loadedObj, resolvedPath, errorMessage) + local record = self.pendingById[requestId] + if record == nil then + if ok and resolvedPath ~= "" then + self.backend:ReleaseAsset(resolvedPath) + end + return + end + self.pendingById[requestId] = nil + local isStale = record.cancelled or self:IsDisposed() or self.ctx:IsShuttingDown() or record.worldGen ~= self.ctx:GetWorldGen() or record.owner ~= nil and record.owner:IsDisposed() or record.handle:IsDisposed() + if isStale then + record.handle:MarkSettledWithoutLeaseInternal() + if ok and resolvedPath ~= "" then + self.backend:ReleaseAsset(resolvedPath) + end + return + end + if ok and loadedObj ~= nil then + local lease = __TS__New(____exports.ResourceLease, resolvedPath, loadedObj, self.backend) + record.handle:AttachLeaseInternal(lease) + tbpcall( + record.callback, + true, + loadedObj, + lease, + nil + ) + else + record.handle:MarkSettledWithoutLeaseInternal() + local err = errorMessage ~= "" and errorMessage or "Failed to load resource: " .. record.keyOrPath + logger:Warn("Resource load failed", {key = record.keyOrPath, path = resolvedPath, err = err}) + tbpcall( + record.callback, + false, + nil, + nil, + err + ) + end +end +function ResourceService.prototype.GetDiagnostics(self) + local pending = 0 + for _, rec in pairs(self.pendingById) do + if rec ~= nil and not rec.cancelled then + pending = pending + 1 + end + end + local nativeInFlight, nativeRetained, nativeRefs = self.backend:GetResourceStats() + return {tsPendingRequests = pending, nativeInFlight = nativeInFlight, nativeRetainedAssets = nativeRetained, nativeTotalRefCount = nativeRefs} +end +function ResourceService.prototype.Dispose(self) + if self:IsDisposed() then + return + end + local ids = {} + for id in pairs(self.pendingById) do + ids[#ids + 1] = id + end + do + local i = 0 + while i < #ids do + self:CancelPendingByIdInternal(ids[i + 1]) + i = i + 1 + end + end + if self.giKey ~= nil and serviceByGameInstanceKey[self.giKey] == self then + serviceByGameInstanceKey[self.giKey] = nil + end + ScopedObject.prototype.Dispose(self) +end +--- 供 C++ FLuaCallbackBridge 回调的纯函数入口(路由到对应 GameInstance 的 ResourceService)。 +-- +-- @noSelf +function ____exports.OnNativeLoadComplete(gameInstance, requestId, ok, loadedObj, resolvedPath, errorMessage) + local svc = serviceByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if svc ~= nil then + svc:HandleNativeLoadComplete( + requestId, + ok, + loadedObj, + resolvedPath, + errorMessage + ) + end +end +--- 为指定 GameInstanceContext 装配生产环境 ResourceService。 +-- +-- @noSelf +function ____exports.CreateUEResourceService(ctx) + if ctx.gameInstance == nil then + return nil + end + local subsystem = UE.ULuaResourceSubsystem.GetFromGameInstance(ctx.gameInstance) + if subsystem == nil then + logger:Error("ULuaResourceSubsystem unavailable on GameInstance") + return nil + end + RegisterBaseAssetCatalog(subsystem) + return __TS__New( + ____exports.ResourceService, + ctx, + __TS__New(____exports.UEResourceBackend, subsystem) + ) +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.serviceByGameInstanceKey = serviceByGameInstanceKey + ____has.serviceByGameInstanceKey = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.serviceByGameInstanceKey then + serviceByGameInstanceKey = from.serviceByGameInstanceKey + end +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + tbpcall = M__share_base_traceback.tbpcall + GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey + RegisterBaseAssetCatalog = M__framework_resource_asset_catalog.RegisterBaseAssetCatalog +end diff --git a/Script/lua/framework/storage/local_save.lua b/Script/lua/framework/storage/local_save.lua new file mode 100644 index 0000000..d56fb40 --- /dev/null +++ b/Script/lua/framework/storage/local_save.lua @@ -0,0 +1,222 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local Json = __MODULE__.Import("framework.core.json", __module) +local logger = Logger("LocalSave") +local SCOPE_PREFIX = {global = "gdata", role = "rdata", chat = "cdata", setting = "sdata"} +local SAVE_DEBOUNCE_SECONDS = 0.1 +--- +-- @noSelf +function ____exports.BuildSlotName(scope, identity) + local prefix = SCOPE_PREFIX[scope] + if identity == nil or identity == "" then + return prefix + end + return (prefix .. "_") .. identity +end +____exports.LocalSaveStore = __TS__DefineClass("LocalSaveStore", __module) +local LocalSaveStore = ____exports.LocalSaveStore +LocalSaveStore.name = "LocalSaveStore" +function LocalSaveStore.prototype.____constructor(self, slotName, backend, clock, schemaVersion, userIndex) + if schemaVersion == nil then + schemaVersion = 1 + end + if userIndex == nil then + userIndex = 0 + end + self.data = {} + self.loadedVersion = 0 + self.lastLoadStatus = "not_found" + self.lastWriteStatus = "ok" + self.recoveredFromBackup = false + self.dirty = false + self.disposed = false + self.slotName = slotName + self.backend = backend + self.clock = clock + self.schemaVersion = schemaVersion + self.userIndex = userIndex + self:Reload() +end +function LocalSaveStore.prototype.Reload(self) + local readResult = self.backend:LoadSlotUtf8(self.slotName, self.userIndex) + self.lastLoadStatus = readResult.status + self.recoveredFromBackup = readResult.recoveredFromBackup + if readResult.status == "not_found" then + self.data = {} + self.loadedVersion = self.schemaVersion + return "not_found" + end + if readResult.status ~= "ok" then + logger:Warn("Failed to load save slot", {slot = self.slotName, status = readResult.status, err = readResult.errorMessage}) + self.data = {} + self.loadedVersion = 0 + return readResult.status + end + local decoded, decodeErr = Json.Decode(readResult.payloadUtf8) + if decodeErr ~= nil or type(decoded) ~= "table" then + logger:Error("Corrupted JSON payload in save slot", {slot = self.slotName, err = decodeErr or "non-table root"}) + self.lastLoadStatus = "corrupted" + self.data = {} + self.loadedVersion = 0 + return "corrupted" + end + local env = decoded + if type(env.version) ~= "number" or type(env.data) ~= "table" then + logger:Error("Invalid LocalSaveEnvelope schema in save slot", {slot = self.slotName}) + self.lastLoadStatus = "corrupted" + self.data = {} + self.loadedVersion = 0 + return "corrupted" + end + self.loadedVersion = env.version + self.data = env.data + return "ok" +end +function LocalSaveStore.prototype.GetLastLoadStatus(self) + return self.lastLoadStatus +end +function LocalSaveStore.prototype.GetLastWriteStatus(self) + return self.lastWriteStatus +end +function LocalSaveStore.prototype.WasRecoveredFromBackup(self) + return self.recoveredFromBackup +end +function LocalSaveStore.prototype.GetLoadedSchemaVersion(self) + return self.loadedVersion +end +function LocalSaveStore.prototype.IsDirty(self) + return self.dirty +end +function LocalSaveStore.prototype.Has(self, key) + return self.data[key] ~= nil +end +function LocalSaveStore.prototype.Get(self, key) + return self.data[key] +end +function LocalSaveStore.prototype.GetDefault(self, key, defaultValue) + local val = self.data[key] + if val ~= nil then + return val + end + return defaultValue +end +function LocalSaveStore.prototype.Set(self, key, value) + if self.disposed then + return + end + self.data[key] = value + self.dirty = true + self:ScheduleSave() +end +function LocalSaveStore.prototype.DeleteKey(self, key) + if self.disposed then + return + end + self.data[key] = nil + self.dirty = true + self:ScheduleSave() +end +function LocalSaveStore.prototype.DeleteAll(self) + if self.disposed then + return + end + self.data = {} + self.dirty = true + self:ScheduleSave() +end +function LocalSaveStore.prototype.ScheduleSave(self) + if self.delayTimer ~= nil and self.delayTimer:IsActive() then + return + end + self.delayTimer = self.clock:AddTimer( + SAVE_DEBOUNCE_SECONDS, + function() + self.delayTimer = nil + self:Flush() + end + ) +end +function LocalSaveStore.prototype.Flush(self) + if self.delayTimer ~= nil then + self.delayTimer:Cancel() + self.delayTimer = nil + end + if not self.dirty then + return "ok" + end + local envelope = {version = self.schemaVersion, data = self.data} + local encoded, encodeErr = Json.Encode(envelope) + if encodeErr ~= nil or encoded == nil then + logger:Error("JSON encode failed for save slot", {slot = self.slotName, err = encodeErr}) + self.lastWriteStatus = "write_failed" + return "write_failed" + end + local status = self.backend:SaveSlotUtf8(self.slotName, encoded, self.userIndex) + self.lastWriteStatus = status + if status == "ok" then + self.dirty = false + self.loadedVersion = self.schemaVersion + else + logger:Error("Failed to save slot", {slot = self.slotName, status = status}) + end + return status +end +function LocalSaveStore.prototype.Dispose(self) + if self.disposed then + return + end + self:Flush() + self.disposed = true +end +____exports.LocalSaveManager = __TS__DefineClass("LocalSaveManager", __module) +local LocalSaveManager = ____exports.LocalSaveManager +LocalSaveManager.name = "LocalSaveManager" +function LocalSaveManager.prototype.____constructor(self, backend, clock) + self.storesBySlot = {} + self.disposed = false + self.backend = backend + self.clock = clock +end +function LocalSaveManager.prototype.GetOrOpenStore(self, scope, identity, schemaVersion) + if schemaVersion == nil then + schemaVersion = 1 + end + local slotName = ____exports.BuildSlotName(scope, identity) + local store = self.storesBySlot[slotName] + if store == nil then + store = __TS__New( + ____exports.LocalSaveStore, + slotName, + self.backend, + self.clock, + schemaVersion + ) + self.storesBySlot[slotName] = store + end + return store +end +function LocalSaveManager.prototype.FlushAll(self) + for _, store in pairs(self.storesBySlot) do + if store ~= nil then + store:Flush() + end + end +end +function LocalSaveManager.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + for slot, store in pairs(self.storesBySlot) do + if store ~= nil then + self.storesBySlot[slot] = nil + store:Dispose() + end + end +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger +end diff --git a/Script/lua/framework/storage/storage_backend.lua b/Script/lua/framework/storage/storage_backend.lua new file mode 100644 index 0000000..61032a6 --- /dev/null +++ b/Script/lua/framework/storage/storage_backend.lua @@ -0,0 +1,152 @@ +local ____exports = __module.env +--- +-- @noSelf +local function MapNativeStatus(nativeStatus) + if nativeStatus == UE.ELuaStorageStatus.Ok then + return "ok" + end + if nativeStatus == UE.ELuaStorageStatus.NotFound then + return "not_found" + end + if nativeStatus == UE.ELuaStorageStatus.Corrupted then + return "corrupted" + end + if nativeStatus == UE.ELuaStorageStatus.WriteFailed then + return "write_failed" + end + return "invalid_argument" +end +____exports.UEStorageBackend = __TS__DefineClass("UEStorageBackend", __module) +local UEStorageBackend = ____exports.UEStorageBackend +UEStorageBackend.name = "UEStorageBackend" +function UEStorageBackend.prototype.____constructor(self) +end +function UEStorageBackend.prototype.LoadSlotUtf8(self, slotName, userIndex) + if userIndex == nil then + userIndex = 0 + end + local res = UE.ULuaStorageLibrary.LoadSlotUtf8(slotName, userIndex) + return { + status = MapNativeStatus(res.Status), + payloadUtf8 = res.PayloadUtf8 or "", + containerVersion = res.ContainerVersion or 0, + recoveredFromBackup = res.bRecoveredFromBackup == true, + errorMessage = res.ErrorMessage or "" + } +end +function UEStorageBackend.prototype.SaveSlotUtf8(self, slotName, payloadUtf8, userIndex) + if userIndex == nil then + userIndex = 0 + end + return MapNativeStatus(UE.ULuaStorageLibrary.SaveSlotUtf8(slotName, payloadUtf8, userIndex)) +end +function UEStorageBackend.prototype.DeleteSlot(self, slotName, userIndex) + if userIndex == nil then + userIndex = 0 + end + return UE.ULuaStorageLibrary.DeleteSlot(slotName, userIndex, true) +end +function UEStorageBackend.prototype.DoesSlotExist(self, slotName, userIndex) + if userIndex == nil then + userIndex = 0 + end + return UE.ULuaStorageLibrary.DoesSlotExist(slotName, userIndex) +end +____exports.MemoryStorageBackend = __TS__DefineClass("MemoryStorageBackend", __module) +local MemoryStorageBackend = ____exports.MemoryStorageBackend +MemoryStorageBackend.name = "MemoryStorageBackend" +function MemoryStorageBackend.prototype.____constructor(self) + self.slots = {} + self.backups = {} + self.corruptCopies = {} + self.corruptedPrimaryFlags = {} + self.writeCount = 0 + self.failNextWrite = false +end +function MemoryStorageBackend.prototype.InjectCorruptPrimary(self, slotName, rawGarbage) + self.slots[slotName] = rawGarbage + self.corruptedPrimaryFlags[slotName] = true +end +function MemoryStorageBackend.prototype.GetCorruptCopy(self, slotName) + return self.corruptCopies[slotName] +end +function MemoryStorageBackend.prototype.LoadSlotUtf8(self, slotName, _userIndex) + if _userIndex == nil then + _userIndex = 0 + end + local primary = self.slots[slotName] + local backup = self.backups[slotName] + if primary == nil and backup == nil then + return { + status = "not_found", + payloadUtf8 = "", + containerVersion = 0, + recoveredFromBackup = false, + errorMessage = "" + } + end + if primary ~= nil and not self.corruptedPrimaryFlags[slotName] then + return { + status = "ok", + payloadUtf8 = primary, + containerVersion = 1, + recoveredFromBackup = false, + errorMessage = "" + } + end + if primary ~= nil and self.corruptedPrimaryFlags[slotName] then + self.corruptCopies[slotName] = primary + end + if backup ~= nil then + return { + status = "ok", + payloadUtf8 = backup, + containerVersion = 1, + recoveredFromBackup = true, + errorMessage = "Primary slot corrupted; recovered from backup" + } + end + return { + status = "corrupted", + payloadUtf8 = "", + containerVersion = 0, + recoveredFromBackup = false, + errorMessage = "Primary slot corrupted and no valid backup exists" + } +end +function MemoryStorageBackend.prototype.SaveSlotUtf8(self, slotName, payloadUtf8, _userIndex) + if _userIndex == nil then + _userIndex = 0 + end + self.writeCount = self.writeCount + 1 + if self.failNextWrite then + self.failNextWrite = false + return "write_failed" + end + local prev = self.slots[slotName] + if prev ~= nil and not self.corruptedPrimaryFlags[slotName] then + self.backups[slotName] = prev + end + self.slots[slotName] = payloadUtf8 + self.corruptedPrimaryFlags[slotName] = nil + return "ok" +end +function MemoryStorageBackend.prototype.DeleteSlot(self, slotName, _userIndex) + if _userIndex == nil then + _userIndex = 0 + end + local existed = self.slots[slotName] ~= nil or self.backups[slotName] ~= nil + self.slots[slotName] = nil + self.backups[slotName] = nil + self.corruptCopies[slotName] = nil + self.corruptedPrimaryFlags[slotName] = nil + return existed +end +function MemoryStorageBackend.prototype.DoesSlotExist(self, slotName, _userIndex) + if _userIndex == nil then + _userIndex = 0 + end + return self.slots[slotName] ~= nil +end +function __module.UpdateImports() +end diff --git a/Script/lua/framework/ui/ui_config.lua b/Script/lua/framework/ui/ui_config.lua new file mode 100644 index 0000000..2213329 --- /dev/null +++ b/Script/lua/framework/ui/ui_config.lua @@ -0,0 +1,76 @@ +local ____exports = __module.env +____exports.UI_LAYER_ZORDER = { + background = 0, + normal = 100, + popup = 200, + tips = 300, + system = 400 +} +--- +-- @module_data +local configByCtor = {} +--- +-- @module_data +local configByName = {} +--- 显式 UI 窗口注册表(替代源端 +-- +-- @UIConfig 装饰器,符合 ts2lua-unreal 编译期白名单规则)。 +function ____exports.RegisterUIConfig(ctor, input) + local ____input_name_2 = input.name + local ____input_assetKey_3 = input.assetKey + local ____input_singleton_0 = input.singleton + if ____input_singleton_0 == nil then + ____input_singleton_0 = true + end + local ____temp_4 = input.layer or "normal" + local ____temp_5 = input.type or "normal" + local ____temp_6 = input.cacheTag or "no_cache" + local ____input_blockWorldClick_1 = input.blockWorldClick + if ____input_blockWorldClick_1 == nil then + ____input_blockWorldClick_1 = true + end + local item = { + name = ____input_name_2, + assetKey = ____input_assetKey_3, + singleton = ____input_singleton_0, + layer = ____temp_4, + type = ____temp_5, + cacheTag = ____temp_6, + blockWorldClick = ____input_blockWorldClick_1, + ctor = ctor + } + configByCtor[ctor] = item + configByName[item.name] = item + return item +end +function ____exports.GetUIConfig(ctor) + return configByCtor[ctor] +end +function ____exports.GetUIConfigByName(name) + return configByName[name] +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.configByCtor = configByCtor + ____has.configByCtor = true + to.configByName = configByName + ____has.configByName = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.configByCtor then + configByCtor = from.configByCtor + end + if ____has.configByName then + configByName = from.configByName + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/framework/ui/ui_delegate_bridge.lua b/Script/lua/framework/ui/ui_delegate_bridge.lua new file mode 100644 index 0000000..abae0ff --- /dev/null +++ b/Script/lua/framework/ui/ui_delegate_bridge.lua @@ -0,0 +1,162 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local __TS__InstanceOf = ____lualib.__TS__InstanceOf +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local tbpcall = M__share_base_traceback.tbpcall +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey +local logger = Logger("UIDelegateBridge") +____exports.UEButtonDelegateBackend = __TS__DefineClass("UEButtonDelegateBackend", __module) +local UEButtonDelegateBackend = ____exports.UEButtonDelegateBackend +UEButtonDelegateBackend.name = "UEButtonDelegateBackend" +function UEButtonDelegateBackend.prototype.____constructor(self, subsystem) + self.subsystem = subsystem +end +function UEButtonDelegateBackend.prototype.BindButtonClicked(self, button) + return self.subsystem:BindButtonClicked(button) +end +function UEButtonDelegateBackend.prototype.UnbindButtonClicked(self, bindingId) + return self.subsystem:UnbindButtonClicked(bindingId) +end +function UEButtonDelegateBackend.prototype.GetActiveBindingCount(self) + return self.subsystem:GetActiveBindingCount() +end +local ButtonBindingHandle = __TS__DefineClass("ButtonBindingHandle", __module) +ButtonBindingHandle.name = "ButtonBindingHandle" +function ButtonBindingHandle.prototype.____constructor(self, bridge, bindingId) + self.bridge = bridge + self.bindingId = bindingId +end +function ButtonBindingHandle.prototype.Dispose(self) + if self.bridge ~= nil then + local b = self.bridge + self.bridge = nil + b:UnbindById(self.bindingId) + end +end +--- +-- @module_data +local bridgeByGameInstanceKey = {} +____exports.UIDelegateBridge = __TS__DefineClass("UIDelegateBridge", __module) +local UIDelegateBridge = ____exports.UIDelegateBridge +UIDelegateBridge.name = "UIDelegateBridge" +__TS__ClassExtends(UIDelegateBridge, ScopedObject) +function UIDelegateBridge.prototype.____constructor(self, ctx, backend) + ScopedObject.prototype.____constructor(self) + self.bindings = {} + self.backend = backend + if ctx.gameInstance ~= nil then + self.giKey = GetGameInstanceKey(ctx.gameInstance) + bridgeByGameInstanceKey[self.giKey] = self + end +end +function UIDelegateBridge.prototype.BindButtonClick(self, button, callback, owner) + local bindingId = self.backend:BindButtonClicked(button) + assert(bindingId > 0, "UIDelegateBridge.BindButtonClick: failed to bind button") + self.bindings[bindingId] = {bindingId = bindingId, callback = callback, owner = owner} + local handle = __TS__New(ButtonBindingHandle, self, bindingId) + if owner ~= nil and __TS__InstanceOf(owner, ScopedObject) then + owner:AddScopedObject(handle) + end + return handle +end +function UIDelegateBridge.prototype.UnbindById(self, bindingId) + if self.bindings[bindingId] == nil then + return + end + self.bindings[bindingId] = nil + self.backend:UnbindButtonClicked(bindingId) +end +function UIDelegateBridge.prototype.DispatchButtonClicked(self, bindingId) + if self:IsDisposed() then + return + end + local rec = self.bindings[bindingId] + if rec == nil then + return + end + if rec.owner ~= nil and rec.owner:IsDisposed() then + self:UnbindById(bindingId) + return + end + tbpcall(rec.callback) +end +function UIDelegateBridge.prototype.GetActiveBindingCount(self) + return self.backend:GetActiveBindingCount() +end +function UIDelegateBridge.prototype.Dispose(self) + if self:IsDisposed() then + return + end + local ids = {} + for id in pairs(self.bindings) do + ids[#ids + 1] = id + end + do + local i = 0 + while i < #ids do + self:UnbindById(ids[i + 1]) + i = i + 1 + end + end + if self.giKey ~= nil and bridgeByGameInstanceKey[self.giKey] == self then + bridgeByGameInstanceKey[self.giKey] = nil + end + ScopedObject.prototype.Dispose(self) +end +--- 供 C++ FLuaCallbackBridge::CallInt 回调的纯函数入口。 +-- +-- @noSelf +function ____exports.OnNativeButtonClicked(gameInstance, bindingId) + local bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)] + if bridge ~= nil then + bridge:DispatchButtonClicked(bindingId) + end +end +--- +-- @noSelf +function ____exports.CreateUEUIDelegateBridge(ctx) + if ctx.gameInstance == nil then + return nil + end + local subsystem = UE.ULuaUIEventSubsystem.GetFromGameInstance(ctx.gameInstance) + if subsystem == nil then + logger:Error("ULuaUIEventSubsystem unavailable on GameInstance") + return nil + end + return __TS__New( + ____exports.UIDelegateBridge, + ctx, + __TS__New(____exports.UEButtonDelegateBackend, subsystem) + ) +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.bridgeByGameInstanceKey = bridgeByGameInstanceKey + ____has.bridgeByGameInstanceKey = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.bridgeByGameInstanceKey then + bridgeByGameInstanceKey = from.bridgeByGameInstanceKey + end +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + tbpcall = M__share_base_traceback.tbpcall + GetGameInstanceKey = M__framework_context_game_context.GetGameInstanceKey +end diff --git a/Script/lua/framework/ui/ui_manager.lua b/Script/lua/framework/ui/ui_manager.lua new file mode 100644 index 0000000..d965405 --- /dev/null +++ b/Script/lua/framework/ui/ui_manager.lua @@ -0,0 +1,357 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module) +local EventHub = M__share_event_event_hub.EventHub +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local tbpcall = M__share_base_traceback.tbpcall +local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module) +local GetUIConfig = M__framework_ui_ui_config.GetUIConfig +local UI_LAYER_ZORDER = M__framework_ui_ui_config.UI_LAYER_ZORDER +local logger = Logger("UIManager") +____exports.UEWidgetAdapter = __TS__DefineClass("UEWidgetAdapter", __module) +local UEWidgetAdapter = ____exports.UEWidgetAdapter +UEWidgetAdapter.name = "UEWidgetAdapter" +function UEWidgetAdapter.prototype.____constructor(self) +end +function UEWidgetAdapter.prototype.FindChild(self, widget, name) + return UE.ULuaUIEventSubsystem.FindChildWidgetByName(widget, name) +end +function UEWidgetAdapter.prototype.AddToViewport(self, widget, zOrder) + if widget.IsInViewport ~= nil and widget:IsInViewport() then + return + end + local hasPlayer = widget.GetOwningPlayer ~= nil and widget:GetOwningPlayer() ~= nil + if hasPlayer and widget.AddToPlayerScreen ~= nil then + widget:AddToPlayerScreen(zOrder) + elseif widget.AddToViewport ~= nil then + widget:AddToViewport(zOrder) + end +end +function UEWidgetAdapter.prototype.RemoveFromParent(self, widget) + if widget.RemoveFromParent ~= nil then + widget:RemoveFromParent() + end +end +function UEWidgetAdapter.prototype.SetVisible(self, widget, visible) + if widget.SetVisibility ~= nil then + widget:SetVisibility(visible and UE.ESlateVisibility.Visible or UE.ESlateVisibility.Collapsed) + end +end +function UEWidgetAdapter.prototype.IsWidgetValid(self, widget) + return widget ~= nil and UE.UKismetSystemLibrary.IsValid(widget) +end +____exports.UEWidgetFactory = __TS__DefineClass("UEWidgetFactory", __module) +local UEWidgetFactory = ____exports.UEWidgetFactory +UEWidgetFactory.name = "UEWidgetFactory" +function UEWidgetFactory.prototype.____constructor(self) +end +function UEWidgetFactory.prototype.CreateWidget(self, widgetClass, worldContext, owningPlayer) + if worldContext == nil then + return nil + end + return UE.UWidgetBlueprintLibrary.Create(worldContext, widgetClass, owningPlayer) +end +____exports.UIManager = __TS__DefineClass("UIManager", __module) +local UIManager = ____exports.UIManager +UIManager.name = "UIManager" +__TS__ClassExtends(UIManager, ScopedObject) +function UIManager.prototype.____constructor(self, ctx, playerCtx, resourceService, widgetFactory, widgetAdapter) + ScopedObject.prototype.____constructor(self) + self.windowStack = {} + self.singletonByName = {} + self.cachedByName = {} + self.zOrderCounter = 0 + self.inputMode = "game" + self.ctx = ctx + self.playerCtx = playerCtx + self.resourceService = resourceService + self.widgetFactory = widgetFactory or __TS__New(____exports.UEWidgetFactory) + self.widgetAdapter = widgetAdapter or __TS__New(____exports.UEWidgetAdapter) + self.events = __TS__New( + EventHub, + string.format("UIManager#%d_P%d", ctx.contextId, playerCtx.playerIndex) + ) + ctx.appEvents.on.OnWorldCleanup( + function() + self:CloseAll(true) + end, + self + ) +end +function UIManager.prototype.ShowUI(self, ctor, args, onOpened) + if self:IsDisposed() or self.ctx:IsShuttingDown() then + if onOpened ~= nil then + tbpcall(onOpened, false, nil, "UIManager is shutting down") + end + return nil + end + local config = GetUIConfig(ctor) + if config == nil then + error("UIManager.ShowUI: window class is not registered via RegisterUIConfig") + return nil + end + if config.singleton then + local existing = self.singletonByName[config.name] + if existing ~= nil and not existing:IsDisposed() and not existing:IsClosing() then + if existing:IsLoaded() then + local zOrder = self:AllocateZOrder(config) + existing:ShowInternal(zOrder, args) + self:SyncFocusAndInputMode() + if onOpened ~= nil then + tbpcall(onOpened, true, existing, nil) + end + elseif onOpened ~= nil then + self.events.on.OnWindowOpened( + function(openedName, openedWin) + if openedName == config.name and openedWin == existing then + tbpcall(onOpened, true, openedWin, nil) + end + end, + existing + ) + end + return existing + end + end + local cached = self.cachedByName[config.name] + if cached ~= nil and not cached:IsDisposed() then + self.cachedByName[config.name] = nil + if config.singleton then + self.singletonByName[config.name] = cached + end + self.windowStack[#self.windowStack + 1] = cached + local zOrder = self:AllocateZOrder(config) + cached:ReuseInternal(zOrder, args) + self:SyncFocusAndInputMode() + self.events.emit.OnWindowOpened(config.name, cached) + if onOpened ~= nil then + tbpcall(onOpened, true, cached, nil) + end + return cached + end + local win = __TS__New(ctor) + win:InitContextInternal(self.ctx, self, config, self.widgetAdapter) + if config.singleton then + self.singletonByName[config.name] = win + end + self.windowStack[#self.windowStack + 1] = win + local loadHandle = self.resourceService:LoadClassAsync( + config.assetKey, + win, + function(ok, widgetClass, _lease, errMsg) + if win:IsDisposed() or win:IsClosing() or self:IsDisposed() then + return + end + if not ok or widgetClass == nil then + logger:Error("Failed to load widget class", {window = config.name, assetKey = config.assetKey, err = errMsg}) + self:RemoveFromStackAndSingleton(win) + win:SetLoadingStateInternal(false, nil) + win:Dispose() + if onOpened ~= nil then + tbpcall(onOpened, false, nil, errMsg or "Widget class load failed") + end + return + end + local worldContext = self.ctx:GetWorldContext().world or self.playerCtx.playerController or self.ctx.gameInstance + local widget = self.widgetFactory:CreateWidget(widgetClass, worldContext, self.playerCtx.playerController) + if widget == nil then + local createErr = string.format("[%s] Failed to instantiate UUserWidget", config.name) + logger:Error(createErr) + self:RemoveFromStackAndSingleton(win) + win:SetLoadingStateInternal(false, nil) + win:Dispose() + if onOpened ~= nil then + tbpcall(onOpened, false, nil, createErr) + end + return + end + win:AttachWidgetInternal(widget) + local zOrder = self:AllocateZOrder(config) + win:ShowInternal(zOrder, args) + self:SyncFocusAndInputMode() + self.events.emit.OnWindowOpened(config.name, win) + if onOpened ~= nil then + tbpcall(onOpened, true, win, nil) + end + end + ) + win:SetLoadingStateInternal(true, loadHandle) + return win +end +function UIManager.prototype.GetSingletonUI(self, ctor) + local config = GetUIConfig(ctor) + if config == nil then + return nil + end + return self.singletonByName[config.name] +end +function UIManager.prototype.CloseSingletonUI(self, ctor) + local win = self:GetSingletonUI(ctor) + if win ~= nil then + win:Close() + end +end +function UIManager.prototype.GetTopWindow(self) + do + local i = #self.windowStack - 1 + while i >= 0 do + local win = self.windowStack[i + 1] + if not win:IsDisposed() and not win:IsClosing() then + return win + end + i = i - 1 + end + end + return nil +end +function UIManager.prototype.HandleWindowCachedInternal(self, win) + self:RemoveFromStackAndSingleton(win) + local oldCached = self.cachedByName[win.config.name] + if oldCached ~= nil and oldCached ~= win then + oldCached:ForceDisposeFromCacheInternal() + end + self.cachedByName[win.config.name] = win + self:SyncFocusAndInputMode() + self.events.emit.OnWindowClosed(win.config.name, win) +end +function UIManager.prototype.HandleWindowClosedInternal(self, win) + self:RemoveFromStackAndSingleton(win) + self:SyncFocusAndInputMode() + self.events.emit.OnWindowClosed(win.config.name, win) +end +function UIManager.prototype.EvictCache(self) + local toEvict = {} + for name, win in pairs(self.cachedByName) do + if win ~= nil then + self.cachedByName[name] = nil + toEvict[#toEvict + 1] = win + end + end + do + local i = 0 + while i < #toEvict do + toEvict[i + 1]:ForceDisposeFromCacheInternal() + i = i + 1 + end + end +end +function UIManager.prototype.CloseAll(self, alsoEvictCache) + if alsoEvictCache == nil then + alsoEvictCache = true + end + local copy = {} + do + local i = #self.windowStack - 1 + while i >= 0 do + copy[#copy + 1] = self.windowStack[i + 1] + i = i - 1 + end + end + do + local i = 0 + while i < #copy do + copy[i + 1]:Close() + i = i + 1 + end + end + if alsoEvictCache then + self:EvictCache() + end + self:SyncFocusAndInputMode() +end +function UIManager.prototype.GetDiagnostics(self) + local openWindows = 0 + local loadingWindows = 0 + do + local i = 0 + while i < #self.windowStack do + local w = self.windowStack[i + 1] + if not w:IsDisposed() then + if w:IsLoading() then + loadingWindows = loadingWindows + 1 + else + openWindows = openWindows + 1 + end + end + i = i + 1 + end + end + local cachedWindows = 0 + for _, w in pairs(self.cachedByName) do + if w ~= nil and not w:IsDisposed() then + cachedWindows = cachedWindows + 1 + end + end + local top = self:GetTopWindow() + return { + openWindows = openWindows, + loadingWindows = loadingWindows, + cachedWindows = cachedWindows, + topWindowName = top ~= nil and top.config.name or nil, + inputMode = self.inputMode + } +end +function UIManager.prototype.AllocateZOrder(self, config) + self.zOrderCounter = self.zOrderCounter + 1 + return UI_LAYER_ZORDER[config.layer] + self.zOrderCounter % 90 +end +function UIManager.prototype.RemoveFromStackAndSingleton(self, win) + if self.singletonByName[win.config.name] == win then + self.singletonByName[win.config.name] = nil + end + do + local i = #self.windowStack - 1 + while i >= 0 do + if self.windowStack[i + 1] == win then + table.remove(self.windowStack, i + 1) + break + end + i = i - 1 + end + end +end +function UIManager.prototype.SyncFocusAndInputMode(self) + local top = self:GetTopWindow() + local nextMode = top ~= nil and top.config.blockWorldClick and "ui" or "game" + self.inputMode = nextMode + local pc = self.playerCtx.playerController + if pc ~= nil and UE ~= nil and UE.UKismetSystemLibrary.IsValid(pc) then + if nextMode == "ui" then + pc.bShowMouseCursor = true + local ____UE_UWidgetBlueprintLibrary_SetInputMode_UIOnlyEx_1 = UE.UWidgetBlueprintLibrary.SetInputMode_UIOnlyEx + local ____temp_0 + if top ~= nil then + ____temp_0 = top:GetWidget() + else + ____temp_0 = nil + end + ____UE_UWidgetBlueprintLibrary_SetInputMode_UIOnlyEx_1(pc, ____temp_0, UE.EMouseLockMode.DoNotLock, false) + else + pc.bShowMouseCursor = false + UE.UWidgetBlueprintLibrary.SetInputMode_GameOnly(pc, false) + end + end + self.events.emit.OnFocusRestored(top ~= nil and top.config.name or nil) +end +function UIManager.prototype.Dispose(self) + if self:IsDisposed() then + return + end + self:CloseAll(true) + self.events:Dispose() + ScopedObject.prototype.Dispose(self) +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + EventHub = M__share_event_event_hub.EventHub + tbpcall = M__share_base_traceback.tbpcall + GetUIConfig = M__framework_ui_ui_config.GetUIConfig + UI_LAYER_ZORDER = M__framework_ui_ui_config.UI_LAYER_ZORDER +end diff --git a/Script/lua/framework/ui/ui_window.lua b/Script/lua/framework/ui/ui_window.lua new file mode 100644 index 0000000..85fb083 --- /dev/null +++ b/Script/lua/framework/ui/ui_window.lua @@ -0,0 +1,202 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local tbpcall = M__share_base_traceback.tbpcall +local logger = Logger("UIWindow") +____exports.UIWindow = __TS__DefineClass("UIWindow", __module) +local UIWindow = ____exports.UIWindow +UIWindow.name = "UIWindow" +__TS__ClassExtends(UIWindow, ScopedObject) +function UIWindow.prototype.____constructor(self, ...) + ScopedObject.prototype.____constructor(self, ...) + self.widget = nil + self.isLoading = false + self.isLoaded = false + self.isVisible = false + self.isClosing = false + self.isCached = false + self.buttonBindings = {} +end +function UIWindow.prototype.InitContextInternal(self, ctx, uiManager, config, widgetAdapter) + self.ctx = ctx + self.uiManager = uiManager + self.config = config + self.widgetAdapter = widgetAdapter +end +function UIWindow.prototype.GetWidget(self) + return self.widget +end +function UIWindow.prototype.IsLoading(self) + return self.isLoading +end +function UIWindow.prototype.IsLoaded(self) + return self.isLoaded +end +function UIWindow.prototype.IsVisible(self) + return self.isVisible +end +function UIWindow.prototype.IsClosing(self) + return self.isClosing +end +function UIWindow.prototype.IsCached(self) + return self.isCached +end +function UIWindow.prototype.SetLoadingStateInternal(self, loading, handle) + self.isLoading = loading + self.classLoadHandle = handle +end +function UIWindow.prototype.AttachWidgetInternal(self, widget) + self.widget = widget + self.isLoading = false + self.isLoaded = true + self.isCached = false + self:OnBindWidgets() +end +function UIWindow.prototype.RequireWidget(self, widgetName) + assert( + self.widget ~= nil, + string.format("[%s] Widget root is not attached", self.config.name) + ) + local child = self.widgetAdapter:FindChild(self.widget, widgetName) + assert( + child ~= nil, + string.format("[%s] Required child widget '%s' not found in Widget Blueprint", self.config.name, widgetName) + ) + return child +end +function UIWindow.prototype.BindButtonClick(self, button, callback) + local bridge = self.ctx:GetService("uiDelegateBridge") + if bridge == nil then + logger:Warn("UIDelegateBridge not registered on context", {window = self.config.name}) + return nil + end + local handle = bridge:BindButtonClick(button, callback, self) + self.buttonBindings[#self.buttonBindings + 1] = handle + return handle +end +function UIWindow.prototype.UnbindAllButtons(self) + do + local i = 0 + while i < #self.buttonBindings do + self.buttonBindings[i + 1]:Dispose() + i = i + 1 + end + end + self.buttonBindings = {} +end +function UIWindow.prototype.ShowInternal(self, zOrder, args) + if self:IsDisposed() or self.isClosing then + return + end + tbpcall(function() + self:OnPreShow(args) + end) + if self.widget ~= nil then + self.widgetAdapter:AddToViewport(self.widget, zOrder) + self.widgetAdapter:SetVisible(self.widget, true) + end + self.isVisible = true + tbpcall(function() + self:OnShow() + end) +end +function UIWindow.prototype.ReuseInternal(self, zOrder, args) + if self:IsDisposed() then + return + end + self.isCached = false + self.isClosing = false + self:EnableAllEventListeners() + self:OnBindWidgets() + tbpcall(function() + self:OnReuseUI(args) + end) + self:ShowInternal(zOrder, args) +end +function UIWindow.prototype.Hide(self) + if not self.isVisible then + return + end + self.isVisible = false + if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then + self.widgetAdapter:SetVisible(self.widget, false) + end + tbpcall(function() + self:OnHide() + end) +end +function UIWindow.prototype.Close(self, onClosed) + if self:IsDisposed() or self.isCached or self.isClosing then + return + end + self.isClosing = true + if self.isLoading and self.classLoadHandle ~= nil then + self.classLoadHandle:Cancel() + self.classLoadHandle = nil + self.isLoading = false + end + local canCache = self.config.cacheTag == "cache" and self.isLoaded and self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) and not self.ctx:IsShuttingDown() + if canCache then + self.isVisible = false + self.isCached = true + self.isClosing = false + self:UnbindAllButtons() + self:DisableAllEventListeners() + self.widgetAdapter:RemoveFromParent(self.widget) + tbpcall(function() + self:OnClose() + end) + self.uiManager:HandleWindowCachedInternal(self) + if onClosed ~= nil then + tbpcall(onClosed) + end + return + end + if self.isLoaded then + tbpcall(function() + self:OnClose() + end) + end + self.isVisible = false + self:UnbindAllButtons() + if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then + self.widgetAdapter:RemoveFromParent(self.widget) + end + self.widget = nil + self.uiManager:HandleWindowClosedInternal(self) + self:Dispose() + if onClosed ~= nil then + tbpcall(onClosed) + end +end +function UIWindow.prototype.ForceDisposeFromCacheInternal(self) + self.isCached = false + self:UnbindAllButtons() + if self.widget ~= nil and self.widgetAdapter:IsWidgetValid(self.widget) then + self.widgetAdapter:RemoveFromParent(self.widget) + end + self.widget = nil + self:Dispose() +end +function UIWindow.prototype.OnBindWidgets(self) +end +function UIWindow.prototype.OnPreShow(self, _args) +end +function UIWindow.prototype.OnShow(self) +end +function UIWindow.prototype.OnReuseUI(self, _args) +end +function UIWindow.prototype.OnHide(self) +end +function UIWindow.prototype.OnClose(self) +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ScopedObject = M__share_base_scoped_object.ScopedObject + tbpcall = M__share_base_traceback.tbpcall +end diff --git a/Script/lua/game/bootstrap_player.lua b/Script/lua/game/bootstrap_player.lua new file mode 100644 index 0000000..1f38e0b --- /dev/null +++ b/Script/lua/game/bootstrap_player.lua @@ -0,0 +1,40 @@ +local ____exports = __module.env +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext +local M__game_startup = __MODULE__.Import("game.startup", __module) +local OpenMiniSettings = M__game_startup.OpenMiniSettings +--- PIE / 启动地图玩家入口:绑定 LocalPlayer(0) 的 PlayerController 并打开首期最小设置窗口。 +function ____exports.OnBeginPlay(pc) + local world = pc:GetWorld() + local gi = UE.UGameplayStatics.GetGameInstance(pc) + if gi == nil then + return + end + local ctx = GetGameInstanceContext(gi) + if ctx == nil then + return + end + if world ~= nil and ctx:GetWorldContext().world ~= world then + ctx:OnWorldCleanup(world) + end + ctx:GetOrCreateLocalPlayer(0, pc) + OpenMiniSettings(ctx) +end +function ____exports.OnEndPlay(pc, _endPlayReason) + local gi = UE.UGameplayStatics.GetGameInstance(pc) + if gi == nil then + return + end + local ctx = GetGameInstanceContext(gi) + if ctx == nil then + return + end + local lp = ctx:GetOrCreateLocalPlayer(0) + if lp.playerController == pc then + lp.playerController = nil + end +end +function __module.UpdateImports() + GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext + OpenMiniSettings = M__game_startup.OpenMiniSettings +end diff --git a/Script/lua/game/setting/mini_settings_window.lua b/Script/lua/game/setting/mini_settings_window.lua new file mode 100644 index 0000000..5f29c4c --- /dev/null +++ b/Script/lua/game/setting/mini_settings_window.lua @@ -0,0 +1,119 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS +local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module) +local RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig +local M__framework_ui_ui_window = __MODULE__.Import("framework.ui.ui_window", __module) +local UIWindow = M__framework_ui_ui_window.UIWindow +local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module) +local SETTING_KEYS = M__game_setting_setting_service.SETTING_KEYS +local logger = Logger("MiniSettingsWindow") +____exports.MiniSettingsWindow = __TS__DefineClass("MiniSettingsWindow", __module) +local MiniSettingsWindow = ____exports.MiniSettingsWindow +MiniSettingsWindow.name = "MiniSettingsWindow" +__TS__ClassExtends(MiniSettingsWindow, UIWindow) +function MiniSettingsWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.iconLoaded = false + self.toggleClickCount = 0 +end +function MiniSettingsWindow.prototype.OnBindWidgets(self) + self.imgIcon = self:RequireWidget("ImgIcon") + self.txtStatus = self:RequireWidget("TxtStatus") + self.btnToggle = self:RequireWidget("BtnToggle") + self.txtToggleLabel = self:RequireWidget("TxtToggleLabel") + self.btnClose = self:RequireWidget("BtnClose") + self:BindButtonClick( + self.btnToggle, + function() + self:HandleToggleClicked() + end + ) + self:BindButtonClick( + self.btnClose, + function() + self:Close() + end + ) +end +function MiniSettingsWindow.prototype.OnPreShow(self) + local settingSvc = self.ctx:GetService("setting") + if settingSvc ~= nil then + settingSvc.events.on.OnBoolSettingChanged( + function(key, _val) + if key == SETTING_KEYS.SOUND_ENABLED then + self:RefreshDisplay() + end + end, + self + ) + end + self:RefreshDisplay() + self:LoadIconTexture() +end +function MiniSettingsWindow.prototype.LoadIconTexture(self) + local resSvc = self.ctx:GetService("resource") + if resSvc == nil then + return + end + resSvc:LoadTextureAsync( + ASSET_KEYS.MINI_SETTINGS_ICON, + self, + function(ok, tex, _lease, err) + if not ok or tex == nil then + logger:Warn("Failed to load MiniSettings icon texture", {err = err}) + return + end + self.iconLoaded = true + if self.imgIcon ~= nil and self.imgIcon.SetBrushFromTexture ~= nil then + self.imgIcon:SetBrushFromTexture(tex, false) + end + end + ) +end +function MiniSettingsWindow.prototype.HandleToggleClicked(self) + self.toggleClickCount = self.toggleClickCount + 1 + local settingSvc = self.ctx:GetService("setting") + if settingSvc ~= nil then + local nextVal = settingSvc:ToggleSoundEnabled() + logger:Info("Sound setting toggled", {soundEnabled = nextVal}) + end +end +function MiniSettingsWindow.prototype.RefreshDisplay(self) + local settingSvc = self.ctx:GetService("setting") + local ____temp_0 + if settingSvc ~= nil then + ____temp_0 = settingSvc:GetSoundEnabled() + else + ____temp_0 = true + end + local soundEnabled = ____temp_0 + local statusText = soundEnabled and "Sound: ON" or "Sound: OFF" + local btnText = soundEnabled and "Disable Sound" or "Enable Sound" + if self.txtStatus ~= nil and self.txtStatus.SetText ~= nil then + self.txtStatus:SetText(statusText) + end + if self.txtToggleLabel ~= nil and self.txtToggleLabel.SetText ~= nil then + self.txtToggleLabel:SetText(btnText) + end +end +RegisterUIConfig(____exports.MiniSettingsWindow, { + name = "MiniSettingsWindow", + assetKey = ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton = true, + layer = "popup", + type = "popup", + cacheTag = "no_cache", + blockWorldClick = true +}) +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS + RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig + UIWindow = M__framework_ui_ui_window.UIWindow + SETTING_KEYS = M__game_setting_setting_service.SETTING_KEYS +end diff --git a/Script/lua/game/setting/setting_service.lua b/Script/lua/game/setting/setting_service.lua new file mode 100644 index 0000000..5ab5a54 --- /dev/null +++ b/Script/lua/game/setting/setting_service.lua @@ -0,0 +1,62 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module) +local EventHub = M__share_event_event_hub.EventHub +--- 阶段 0 冻结的首期全局布尔设置键 +____exports.SETTING_KEYS = {SOUND_ENABLED = "mini_settings.sound_enabled"} +____exports.SettingService = __TS__DefineClass("SettingService", __module) +local SettingService = ____exports.SettingService +SettingService.name = "SettingService" +__TS__ClassExtends(SettingService, ScopedObject) +function SettingService.prototype.____constructor(self, saveManager, slotIdentity) + ScopedObject.prototype.____constructor(self) + self.events = __TS__New(EventHub, "SettingEvents") + self.store = saveManager:GetOrOpenStore("setting", slotIdentity, 1) +end +function SettingService.prototype.GetStore(self) + return self.store +end +function SettingService.prototype.GetBool(self, key, defaultValue) + local val = self.store:Get(key) + if type(val) == "boolean" then + return val + end + return defaultValue +end +function SettingService.prototype.SetBool(self, key, value) + local prev = self:GetBool(key, not value) + self.store:Set(key, value) + if prev ~= value then + self.events.emit.OnBoolSettingChanged(key, value) + end +end +function SettingService.prototype.GetSoundEnabled(self) + return self:GetBool(____exports.SETTING_KEYS.SOUND_ENABLED, true) +end +function SettingService.prototype.SetSoundEnabled(self, enabled) + self:SetBool(____exports.SETTING_KEYS.SOUND_ENABLED, enabled) +end +function SettingService.prototype.ToggleSoundEnabled(self) + local nextVal = not self:GetSoundEnabled() + self:SetSoundEnabled(nextVal) + return nextVal +end +function SettingService.prototype.Flush(self) + return self.store:Flush() +end +function SettingService.prototype.Dispose(self) + if self:IsDisposed() then + return + end + self.store:Flush() + self.events:Dispose() + ScopedObject.prototype.Dispose(self) +end +function __module.UpdateImports() + ScopedObject = M__share_base_scoped_object.ScopedObject + EventHub = M__share_event_event_hub.EventHub +end diff --git a/Script/lua/game/startup.lua b/Script/lua/game/startup.lua new file mode 100644 index 0000000..5162bcb --- /dev/null +++ b/Script/lua/game/startup.lua @@ -0,0 +1,81 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__framework_resource_resource_service = __MODULE__.Import("framework.resource.resource_service", __module) +local CreateUEResourceService = M__framework_resource_resource_service.CreateUEResourceService +local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module) +local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager +local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module) +local UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend +local M__framework_ui_ui_delegate_bridge = __MODULE__.Import("framework.ui.ui_delegate_bridge", __module) +local CreateUEUIDelegateBridge = M__framework_ui_ui_delegate_bridge.CreateUEUIDelegateBridge +local M__framework_ui_ui_manager = __MODULE__.Import("framework.ui.ui_manager", __module) +local UIManager = M__framework_ui_ui_manager.UIManager +local M__game_setting_mini_settings_window = __MODULE__.Import("game.setting.mini_settings_window", __module) +local MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow +local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module) +local SettingService = M__game_setting_setting_service.SettingService +local logger = Logger("Startup") +--- 装配单个 GameInstanceContext 的全部首期框架服务(支持多 PIE 独立实例化): +-- - LocalSaveManager(UE ULuaSaveGame + 跨 World 单调时钟 0.1s 合并写 + 退出 FlushAll) +-- - SettingService(首期全局布尔设置键) +-- - ResourceService(C++ ULuaResourceSubsystem:PIE Content/ 直读 + 发布包热更挂载扩展) +-- - UIDelegateBridge(C++ ULuaUIEventSubsystem) +-- - 默认 LocalPlayer(0) 的 UIManager +function ____exports.AssembleGameInstanceServices(ctx) + local storageBackend = __TS__New(UEStorageBackend) + local saveManager = __TS__New(LocalSaveManager, storageBackend, ctx.scheduler) + ctx:RegisterService("saveManager", saveManager) + ctx:AddShutdownHook(function() + saveManager:FlushAll() + end) + local settingService = __TS__New(SettingService, saveManager) + ctx:RegisterService("setting", settingService) + local resourceService = CreateUEResourceService(ctx) + if resourceService ~= nil then + ctx:RegisterService("resource", resourceService) + end + local uiDelegateBridge = CreateUEUIDelegateBridge(ctx) + if uiDelegateBridge ~= nil then + ctx:RegisterService("uiDelegateBridge", uiDelegateBridge) + end + local lp0 = ctx:GetOrCreateLocalPlayer(0) + if resourceService ~= nil then + lp0:RegisterService( + "uiManager", + __TS__New(UIManager, ctx, lp0, resourceService) + ) + end + local ____logger_Info_2 = logger.Info + local ____ctx_contextId_1 = ctx.contextId + local ____temp_0 + if resourceService ~= nil then + ____temp_0 = resourceService:IsPackagedMode() + else + ____temp_0 = false + end + ____logger_Info_2(logger, "Framework services assembled", {contextId = ____ctx_contextId_1, packagedResourceMode = ____temp_0}) +end +function ____exports.GetPrimaryUIManager(ctx) + local lp0 = ctx:GetOrCreateLocalPlayer(0) + return lp0:GetService("uiManager") +end +function ____exports.OpenMiniSettings(ctx, onOpened) + local uiMgr = ____exports.GetPrimaryUIManager(ctx) + if uiMgr == nil then + return nil + end + return uiMgr:ShowUI(MiniSettingsWindow, nil, onOpened) +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + CreateUEResourceService = M__framework_resource_resource_service.CreateUEResourceService + LocalSaveManager = M__framework_storage_local_save.LocalSaveManager + UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend + CreateUEUIDelegateBridge = M__framework_ui_ui_delegate_bridge.CreateUEUIDelegateBridge + UIManager = M__framework_ui_ui_manager.UIManager + MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow + SettingService = M__game_setting_setting_service.SettingService +end diff --git a/Script/lua/Lib/Class.lua b/Script/lua/lib/class.lua similarity index 100% rename from Script/lua/Lib/Class.lua rename to Script/lua/lib/class.lua diff --git a/Script/lua/Lib/Module.lua b/Script/lua/lib/module.lua similarity index 100% rename from Script/lua/Lib/Module.lua rename to Script/lua/lib/module.lua diff --git a/Script/lua/lualib_bundle.lua b/Script/lua/lualib_bundle.lua index 1dc0075..0a184c8 100644 --- a/Script/lua/lualib_bundle.lua +++ b/Script/lua/lualib_bundle.lua @@ -4,142 +4,6 @@ local function __TS__New(target, ...) return instance end -local function __TS__CountVarargs(...) - return select("#", ...) -end - -local function __TS__SparseArrayNew(...) - local sparseArray = {...} - sparseArray.sparseLength = __TS__CountVarargs(...) - return sparseArray -end - -local function __TS__SparseArrayPush(sparseArray, ...) - local args = {...} - local argsLen = __TS__CountVarargs(...) - local listLen = sparseArray.sparseLength - for i = 1, argsLen do - sparseArray[listLen + i] = args[i] - end - sparseArray.sparseLength = listLen + argsLen -end - -local function __TS__SparseArraySpread(sparseArray) - local _unpack = unpack or table.unpack - return _unpack(sparseArray, 1, sparseArray.sparseLength) -end - -local function __TS__ArraySplice(self, ...) - local args = {...} - local len = #self - local actualArgumentCount = __TS__CountVarargs(...) - local start = args[1] - local deleteCount = args[2] - if start < 0 then - start = len + start - if start < 0 then - start = 0 - end - elseif start > len then - start = len - end - local itemCount = actualArgumentCount - 2 - if itemCount < 0 then - itemCount = 0 - end - local actualDeleteCount - if actualArgumentCount == 0 then - actualDeleteCount = 0 - elseif actualArgumentCount == 1 then - actualDeleteCount = len - start - else - actualDeleteCount = deleteCount or 0 - if actualDeleteCount < 0 then - actualDeleteCount = 0 - end - if actualDeleteCount > len - start then - actualDeleteCount = len - start - end - end - local out = {} - for k = 1, actualDeleteCount do - local from = start + k - if self[from] ~= nil then - out[k] = self[from] - end - end - if itemCount < actualDeleteCount then - for k = start + 1, len - actualDeleteCount do - local from = k + actualDeleteCount - local to = k + itemCount - if self[from] then - self[to] = self[from] - else - self[to] = nil - end - end - for k = len - actualDeleteCount + itemCount + 1, len do - self[k] = nil - end - elseif itemCount > actualDeleteCount then - for k = len - actualDeleteCount, start + 1, -1 do - local from = k + actualDeleteCount - local to = k + itemCount - if self[from] then - self[to] = self[from] - else - self[to] = nil - end - end - end - local j = start + 1 - for i = 3, actualArgumentCount do - self[j] = args[i] - j = j + 1 - end - for k = #self, len - actualDeleteCount + itemCount + 1, -1 do - self[k] = nil - end - return out -end - -local function __TS__ArraySort(self, compareFn) - if compareFn ~= nil then - table.sort( - self, - function(a, b) return compareFn(nil, a, b) < 0 end - ) - else - table.sort(self) - end - return self -end - -local function __TS__ArrayIndexOf(self, searchElement, fromIndex) - if fromIndex == nil then - fromIndex = 0 - end - local len = #self - if len == 0 then - return -1 - end - if fromIndex >= len then - return -1 - end - if fromIndex < 0 then - fromIndex = len + fromIndex - if fromIndex < 0 then - fromIndex = 0 - end - end - for i = fromIndex + 1, len do - if self[i] == searchElement then - return i - 1 - end - end - return -1 -end - local function __TS__ClassExtends(target, base) target.____super = base local staticMetatable = setmetatable({__index = base}, base) @@ -202,14 +66,22 @@ local function __TS__InstanceOf(obj, classTbl) return false end +local function __TS__ArraySetLength(self, length) + if length < 0 or length ~= length or length == math.huge or math.floor(length) ~= length then + error( + "invalid array length: " .. tostring(length), + 0 + ) + end + for i = length + 1, #self do + self[i] = nil + end + return length +end + return { __TS__New = __TS__New, - __TS__SparseArrayNew = __TS__SparseArrayNew, - __TS__SparseArrayPush = __TS__SparseArrayPush, - __TS__SparseArraySpread = __TS__SparseArraySpread, - __TS__ArraySplice = __TS__ArraySplice, - __TS__ArraySort = __TS__ArraySort, - __TS__ArrayIndexOf = __TS__ArrayIndexOf, __TS__ClassExtends = __TS__ClassExtends, - __TS__InstanceOf = __TS__InstanceOf + __TS__InstanceOf = __TS__InstanceOf, + __TS__ArraySetLength = __TS__ArraySetLength } diff --git a/Script/lua/main.lua b/Script/lua/main.lua new file mode 100644 index 0000000..c127d29 --- /dev/null +++ b/Script/lua/main.lua @@ -0,0 +1,39 @@ +local ____exports = __module.env +local M__share_base_logger = __MODULE__.Import("share.base.logger", __module) +local Logger = M__share_base_logger.Logger +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local CreateGameInstanceContext = M__framework_context_game_context.CreateGameInstanceContext +local DestroyGameInstanceContext = M__framework_context_game_context.DestroyGameInstanceContext +local GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext +local M__game_startup = __MODULE__.Import("game.startup", __module) +local AssembleGameInstanceServices = M__game_startup.AssembleGameInstanceServices +local logger = Logger("Main") +function ____exports.OnInit(gameInstance) + local ctx = CreateGameInstanceContext(gameInstance) + AssembleGameInstanceServices(ctx) + logger:Info("GameInstance initialized", {contextId = ctx.contextId, luaVersion = _VERSION}) + return ctx +end +function ____exports.OnTick(gameInstance, deltaSeconds) + local ctx = GetGameInstanceContext(gameInstance) + if ctx ~= nil then + ctx:Tick(deltaSeconds) + end +end +function ____exports.OnWorldCleanup(gameInstance) + local ctx = GetGameInstanceContext(gameInstance) + if ctx ~= nil then + ctx:OnWorldCleanup() + end +end +function ____exports.OnShutdown(gameInstance) + logger:Info("GameInstance shutting down") + DestroyGameInstanceContext(gameInstance) +end +function __module.UpdateImports() + Logger = M__share_base_logger.Logger + CreateGameInstanceContext = M__framework_context_game_context.CreateGameInstanceContext + DestroyGameInstanceContext = M__framework_context_game_context.DestroyGameInstanceContext + GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext + AssembleGameInstanceServices = M__game_startup.AssembleGameInstanceServices +end diff --git a/Script/lua/share/base/interface.lua b/Script/lua/share/base/interface.lua new file mode 100644 index 0000000..a873bac --- /dev/null +++ b/Script/lua/share/base/interface.lua @@ -0,0 +1,3 @@ +local ____exports = __module.env +function __module.UpdateImports() +end diff --git a/Script/lua/share/base/logger.lua b/Script/lua/share/base/logger.lua new file mode 100644 index 0000000..39cad22 --- /dev/null +++ b/Script/lua/share/base/logger.lua @@ -0,0 +1,228 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +____exports.LogLevel = { + TRACE = 0, + DEBUG = 1, + INFO = 2, + WARN = 3, + ERROR = 4 +} +--- +-- @noSelf +function ____exports.StringToLogLevel(lv) + if lv == "trace" then + return ____exports.LogLevel.TRACE + end + if lv == "debug" then + return ____exports.LogLevel.DEBUG + end + if lv == "warn" then + return ____exports.LogLevel.WARN + end + if lv == "error" then + return ____exports.LogLevel.ERROR + end + return ____exports.LogLevel.INFO +end +--- +-- @noSelf +local function LevelLabel(lv) + if lv == ____exports.LogLevel.TRACE then + return "TRACE" + end + if lv == ____exports.LogLevel.DEBUG then + return "DEBUG" + end + if lv == ____exports.LogLevel.INFO then + return "INFO" + end + if lv == ____exports.LogLevel.WARN then + return "WARN" + end + return "ERROR" +end +--- +-- @noSelf +function ____exports.SerializeLogValue(value, depth) + if depth == nil then + depth = 0 + end + local t = type(value) + if t == "nil" then + return "nil" + end + if t == "string" then + return string.format("%q", value) + end + if t == "number" or t == "boolean" then + return tostring(value) + end + if t ~= "table" then + return tostring(value) + end + if depth >= 3 then + return "{...}" + end + local parts = {} + for k, v in pairs(value) do + parts[#parts + 1] = string.format( + "%s=%s", + tostring(k), + ____exports.SerializeLogValue(v, depth + 1) + ) + end + table.sort(parts) + return ("{" .. table.concat(parts, ", ")) .. "}" +end +--- +-- @module_data +local defaultLogLevel = ____exports.LogLevel.INFO +--- +-- @module_data +local customSink = nil +--- +-- @module_data +local allLoggers = {} +--- +-- @noSelf +local function DefaultSink(level, moduleName, message) + local line = string.format( + "[%s][%s] %s", + LevelLabel(level), + moduleName, + message + ) + if UnLua ~= nil then + if level >= ____exports.LogLevel.ERROR and UnLua.LogError ~= nil then + UnLua.LogError(line) + return + end + if level == ____exports.LogLevel.WARN and UnLua.LogWarn ~= nil then + UnLua.LogWarn(line) + return + end + if UnLua.Log ~= nil then + UnLua.Log(line) + return + end + end + print(line) +end +____exports.LoggerObject = __TS__DefineClass("LoggerObject", __module) +local LoggerObject = ____exports.LoggerObject +LoggerObject.name = "LoggerObject" +function LoggerObject.prototype.____constructor(self, name) + self.debugEnabled = false + self.infoEnabled = false + self.warnEnabled = false + self.errorEnabled = false + self.name = name + self.level = defaultLogLevel + self:UpdateLevelFlags() +end +function LoggerObject.prototype.UpdateLevelFlags(self) + self.debugEnabled = self.level <= ____exports.LogLevel.DEBUG + self.infoEnabled = self.level <= ____exports.LogLevel.INFO + self.warnEnabled = self.level <= ____exports.LogLevel.WARN + self.errorEnabled = self.level <= ____exports.LogLevel.ERROR +end +function LoggerObject.prototype.EmitLog(self, level, msg, data) + if self.level > level then + return + end + local payload = data ~= nil and (msg .. ", ") .. ____exports.SerializeLogValue(data, 0) or msg + local sink = customSink or DefaultSink + sink(level, self.name, payload) +end +function LoggerObject.prototype.Debug(self, msg, data) + self:EmitLog(____exports.LogLevel.DEBUG, msg, data) +end +function LoggerObject.prototype.Info(self, msg, data) + self:EmitLog(____exports.LogLevel.INFO, msg, data) +end +function LoggerObject.prototype.Warn(self, msg, data) + self:EmitLog(____exports.LogLevel.WARN, msg, data) +end +function LoggerObject.prototype.Error(self, msg, data) + self:EmitLog(____exports.LogLevel.ERROR, msg, data) +end +function LoggerObject.prototype.d(self, msg, data) + self:Debug(msg, data) +end +function LoggerObject.prototype.i(self, msg, data) + self:Info(msg, data) +end +function LoggerObject.prototype.w(self, msg, data) + self:Warn(msg, data) +end +function LoggerObject.prototype.e(self, msg, data) + self:Error(msg, data) +end +function LoggerObject.prototype.GetLevel(self) + return self.level +end +function LoggerObject.prototype.SetLevel(self, lv) + self.level = type(lv) == "string" and ____exports.StringToLogLevel(lv) or lv + self:UpdateLevelFlags() + return self +end +--- +-- @noSelf +function ____exports.SetLogSink(sink) + customSink = sink +end +--- +-- @noSelf +function ____exports.SetDefaultLogLevel(lv) + defaultLogLevel = lv +end +--- +-- @noSelf +function ____exports.SetAllLoggersLevel(lv) + for _, logger in pairs(allLoggers) do + if logger ~= nil then + logger:SetLevel(lv) + end + end +end +--- +-- @noSelf +function ____exports.Logger(name) + local logger = allLoggers[name] + if logger == nil then + logger = __TS__New(____exports.LoggerObject, name) + allLoggers[name] = logger + end + return logger +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.defaultLogLevel = defaultLogLevel + ____has.defaultLogLevel = true + to.customSink = customSink + ____has.customSink = true + to.allLoggers = allLoggers + ____has.allLoggers = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.defaultLogLevel then + defaultLogLevel = from.defaultLogLevel + end + if ____has.customSink then + customSink = from.customSink + end + if ____has.allLoggers then + allLoggers = from.allLoggers + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/share/base/scoped_object.lua b/Script/lua/share/base/scoped_object.lua new file mode 100644 index 0000000..bd388a8 --- /dev/null +++ b/Script/lua/share/base/scoped_object.lua @@ -0,0 +1,63 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local ____exports = __module.env +local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module) +local EventListenerContainer = M__share_event_event_hub.EventListenerContainer +____exports.ScopedObject = __TS__DefineClass("ScopedObject", __module) +local ScopedObject = ____exports.ScopedObject +ScopedObject.name = "ScopedObject" +__TS__ClassExtends(ScopedObject, EventListenerContainer) +function ScopedObject.prototype.____constructor(self, ...) + EventListenerContainer.prototype.____constructor(self, ...) + self.scopedObjects = {} + self.disposed = false +end +function ScopedObject.prototype.IsDisposed(self) + return self.disposed +end +function ScopedObject.prototype.AddScopedObject(self, obj) + if self.disposed then + obj:Dispose() + return + end + self.scopedObjects[obj] = true +end +function ScopedObject.prototype.RemoveScopedObject(self, obj) + self.scopedObjects[obj] = nil +end +function ScopedObject.prototype.GetScopedObjectCount(self) + local count = 0 + for _, active in pairs(self.scopedObjects) do + if active == true then + count = count + 1 + end + end + return count +end +function ScopedObject.prototype.DisposeAllScopedObjects(self) + local list = {} + for obj, active in pairs(self.scopedObjects) do + if active == true then + list[#list + 1] = obj + end + end + self.scopedObjects = {} + do + local i = 0 + while i < #list do + list[i + 1]:Dispose() + i = i + 1 + end + end +end +function ScopedObject.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + self:DisposeAllScopedObjects() + EventListenerContainer.prototype.Dispose(self) +end +function __module.UpdateImports() + EventListenerContainer = M__share_event_event_hub.EventListenerContainer +end diff --git a/Script/lua/share/base/traceback.lua b/Script/lua/share/base/traceback.lua new file mode 100644 index 0000000..fe0076e --- /dev/null +++ b/Script/lua/share/base/traceback.lua @@ -0,0 +1,62 @@ +local ____exports = __module.env +--- +-- @module_data +local activeHandler = nil +function ____exports.SetupTracebackHandler(handler) + activeHandler = handler +end +local function DefaultDump(msg) + if UnLua ~= nil and UnLua.LogError ~= nil then + UnLua.LogError(msg) + else + print("[ERROR] " .. msg) + end +end +local function OnError(err) + local errText = tostring(err) + local fullStack = debug.traceback(errText, 2) + if activeHandler ~= nil then + if activeHandler.LogTraceback ~= nil then + pcall(activeHandler.LogTraceback, errText, fullStack) + end + if activeHandler.DumpTraceback ~= nil then + pcall(activeHandler.DumpTraceback, fullStack) + else + DefaultDump(fullStack) + end + else + DefaultDump(fullStack) + end + return fullStack +end +--- 带完整堆栈上报的安全调用(对应 gamelogic 的 tbpcall),保留全部多返回值。 +function ____exports.tbpcall(fn, ...) + return xpcall(fn, OnError, ...) +end +--- 调用带 self 的对象方法并捕获异常上报堆栈。 +function ____exports.tbpcallMethod(fn, selfObj, ...) + return xpcall(fn, OnError, selfObj, ...) +end +function ____exports.ReportError(message) + OnError(message) +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.activeHandler = activeHandler + ____has.activeHandler = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.activeHandler then + activeHandler = from.activeHandler + end +end +function __module.UpdateImports() +end diff --git a/Script/lua/share/event/event_hub.lua b/Script/lua/share/event/event_hub.lua new file mode 100644 index 0000000..b8d1d16 --- /dev/null +++ b/Script/lua/share/event/event_hub.lua @@ -0,0 +1,166 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_event_events = __MODULE__.Import("share.event.events", __module) +local EvEmitter = M__share_event_events.EvEmitter +____exports.EventListenerContainer = __TS__DefineClass("EventListenerContainer", __module) +local EventListenerContainer = ____exports.EventListenerContainer +EventListenerContainer.name = "EventListenerContainer" +function EventListenerContainer.prototype.____constructor(self) +end +function EventListenerContainer.prototype.GetAllEventListenerTable(self) + return rawget(self, "__events__") +end +function EventListenerContainer.prototype.EnableAllEventListeners(self) + local tbl = self:GetAllEventListenerTable() + if tbl ~= nil then + for _, listener in pairs(tbl) do + if listener ~= nil then + listener:Enable() + end + end + end +end +function EventListenerContainer.prototype.DisableAllEventListeners(self) + local tbl = self:GetAllEventListenerTable() + if tbl ~= nil then + for _, listener in pairs(tbl) do + if listener ~= nil then + listener:Disable() + end + end + end +end +function EventListenerContainer.prototype.OffAllEventListeners(self) + local tbl = self:GetAllEventListenerTable() + if tbl ~= nil then + local keys = {} + for ekey in pairs(tbl) do + keys[#keys + 1] = ekey + end + do + local i = 0 + while i < #keys do + local key = keys[i + 1] + local listener = tbl[key] + if listener ~= nil then + listener:Off() + tbl[key] = nil + end + i = i + 1 + end + end + end +end +function EventListenerContainer.prototype.GetActiveEventListenerCount(self) + local tbl = self:GetAllEventListenerTable() + if tbl == nil then + return 0 + end + local count = 0 + for _, listener in pairs(tbl) do + if listener ~= nil and listener:IsActive() then + count = count + 1 + end + end + return count +end +function EventListenerContainer.prototype.Dispose(self) + self:OffAllEventListeners() +end +____exports.EventHub = __TS__DefineClass("EventHub", __module) +local EventHub = ____exports.EventHub +EventHub.name = "EventHub" +function EventHub.prototype.____constructor(self, name, options) + self.emit = {} + self.on = {} + self.disposed = false + self.ev = __TS__New(EvEmitter, name) + if options ~= nil then + self.preEmit = options.preEmit + self.asyncEmit = options.asyncEmit + end + self:SetupEmit() + self:SetupOn() +end +function EventHub.prototype.Dispose(self) + if self.disposed then + return + end + self.disposed = true + self.ev:Dispose() +end +function EventHub.prototype.IsDisposed(self) + return self.disposed +end +function EventHub.prototype.HasOnEvent(self, name) + return self.ev:HasOnEvent(name) +end +function EventHub.prototype.GetListenerCount(self, name) + return self.ev:GetListenerCount(name) +end +function EventHub.prototype.Emit(self, name, ...) + if self.disposed then + return + end + if self.preEmit ~= nil then + self.preEmit(name) + end + self.ev:Emit(name, ...) +end +function EventHub.prototype.EmitWithArgs(self, name, packed) + if self.disposed then + return + end + if self.preEmit ~= nil then + self.preEmit(name) + end + self.ev:Emit( + name, + table.unpack(packed, 1, packed.n) + ) +end +function EventHub.prototype.SetupEmit(self) + local hub = self + local mt = { + __name = "EventHubEmit", + __index = function(tbl, name) + local function dispatch(...) + if hub.disposed then + return + end + if hub.asyncEmit ~= nil then + local packed = table.pack(...) + hub.asyncEmit( + name, + function() + hub:EmitWithArgs(name, packed) + end + ) + else + hub:Emit(name, ...) + end + end + rawset(tbl, name, dispatch) + return dispatch + end + } + setmetatable(self.emit, mt) +end +function EventHub.prototype.SetupOn(self) + local ev = self.ev + local mt = { + __name = "EventHubOn", + __index = function(tbl, name) + local function subscribe(handle, ctx) + return ev:On(name, handle, ctx) + end + rawset(tbl, name, subscribe) + return subscribe + end + } + setmetatable(self.on, mt) +end +function __module.UpdateImports() + EvEmitter = M__share_event_events.EvEmitter +end diff --git a/Script/lua/share/event/events.lua b/Script/lua/share/event/events.lua new file mode 100644 index 0000000..dcfad49 --- /dev/null +++ b/Script/lua/share/event/events.lua @@ -0,0 +1,282 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local tbpcall = M__share_base_traceback.tbpcall +local EMPTY_SLOT = -999999 +--- +-- @module_data +local nextEmitterId = 0 +--- +-- @module_data +local globalOwnerFilter = nil +--- +-- @noSelf +local function AllocateEmitterId() + nextEmitterId = nextEmitterId + 1 + return nextEmitterId +end +--- +-- @noSelf +local function IsOwnerDisposed(owner) + if owner == nil then + return false + end + if globalOwnerFilter ~= nil and globalOwnerFilter(owner) then + return true + end + local checkFn = owner.IsDisposed + if checkFn ~= nil and type(checkFn) == "function" then + return checkFn(owner) == true + end + return false +end +--- +-- @noSelf +function ____exports.SetGlobalEventFilter(filter) + globalOwnerFilter = filter +end +____exports.EvListener = __TS__DefineClass("EvListener", __module) +local EvListener = ____exports.EvListener +EvListener.name = "EvListener" +function EvListener.prototype.____constructor(self, channel, callable, target, ekey) + self.enabled = true + self.channel = channel + self.callable = callable + self.target = target + self.ekey = ekey + self.enabled = true +end +function EvListener.prototype.Off(self) + if self.channel == nil then + return + end + local ch = self.channel + self.channel = nil + ch:Off(self) + local owner = self.target + local key = self.ekey + if owner ~= nil and key ~= nil then + local ownerEvents = rawget(owner, "__events__") + if ownerEvents ~= nil and ownerEvents[key] == self then + ownerEvents[key] = nil + end + end + self.callable = nil + self.target = nil + self.ekey = nil + self.enabled = false +end +function EvListener.prototype.Enable(self) + self.enabled = true +end +function EvListener.prototype.Disable(self) + self.enabled = false +end +function EvListener.prototype.IsActive(self) + return self.channel ~= nil and self.enabled +end +function EvListener.prototype.Dispose(self) + self:Off() +end +____exports.EvChannel = __TS__DefineClass("EvChannel", __module) +local EvChannel = ____exports.EvChannel +EvChannel.name = "EvChannel" +function EvChannel.prototype.____constructor(self, emitter, event) + self.listeners = {} + self.liveCount = 0 + self.indexes = {} + self.dispatchDepth = 0 + self.emitter = emitter + self.event = event +end +function EvChannel.prototype.On(self, callable, target, ekey) + assert( + type(callable) == "function", + "EvChannel.On: callable must be a function" + ) + local listener = __TS__New( + ____exports.EvListener, + self, + callable, + target, + ekey + ) + local idx = #self.listeners + self.listeners[idx + 1] = listener + self.liveCount = self.liveCount + 1 + self.indexes[listener] = idx + return listener +end +function EvChannel.prototype.Off(self, listener) + local idx = self.indexes[listener] + if idx == nil then + return + end + self.listeners[idx + 1] = EMPTY_SLOT + self.liveCount = self.liveCount - 1 + self.indexes[listener] = nil + if self.dispatchDepth == 0 then + self:TryPurge() + end +end +function EvChannel.prototype.TryPurge(self) + if #self.listeners - self.liveCount <= 4 then + return + end + local compacted = {} + local newIndexes = {} + do + local i = 0 + while i < #self.listeners do + local item = self.listeners[i + 1] + if item ~= EMPTY_SLOT then + local newIdx = #compacted + compacted[newIdx + 1] = item + newIndexes[item] = newIdx + end + i = i + 1 + end + end + self.listeners = compacted + self.liveCount = #compacted + self.indexes = newIndexes +end +function EvChannel.prototype.Emit(self, unsafeCall, ...) + self.dispatchDepth = self.dispatchDepth + 1 + local list = self.listeners + do + local i = 0 + while i < #list do + local listener = list[i + 1] + if listener ~= EMPTY_SLOT and listener.enabled then + local owner = listener.target + if not IsOwnerDisposed(owner) then + local callable = listener.callable + if callable ~= nil then + if unsafeCall then + callable(...) + else + tbpcall(callable, ...) + end + end + end + end + i = i + 1 + end + end + self.dispatchDepth = self.dispatchDepth - 1 + if self.dispatchDepth == 0 then + self:TryPurge() + end +end +____exports.EvEmitter = __TS__DefineClass("EvEmitter", __module) +local EvEmitter = ____exports.EvEmitter +EvEmitter.name = "EvEmitter" +function EvEmitter.prototype.____constructor(self, name) + self.channels = {} + self.enableUnsafeCall = false + self.name = name + self.id = AllocateEmitterId() + self.key = (name .. ":") .. tostring(self.id) +end +function EvEmitter.prototype.On(self, event, callable, target) + assert( + type(target) == "table", + "EvEmitter.On: owner(target) must be a table/object" + ) + assert( + type(callable) == "function", + "EvEmitter.On: callable must be a function" + ) + local ekey = (self.key .. ":") .. event + local targetEvents = rawget(target, "__events__") + if targetEvents == nil then + targetEvents = {} + setmetatable(targetEvents, {__mode = "v"}) + rawset(target, "__events__", targetEvents) + end + local existing = targetEvents[ekey] + if existing ~= nil then + existing:Off() + end + local channel = self.channels[event] + if channel == nil then + channel = __TS__New(____exports.EvChannel, self, event) + self.channels[event] = channel + end + local listener = channel:On(callable, target, ekey) + targetEvents[ekey] = listener + return listener +end +function EvEmitter.prototype.Emit(self, event, ...) + local channel = self.channels[event] + if channel == nil then + return + end + channel:Emit(self.enableUnsafeCall, ...) +end +function EvEmitter.prototype.HasOnEvent(self, event) + local channel = self.channels[event] + return channel ~= nil and channel.liveCount > 0 +end +function EvEmitter.prototype.GetListenerCount(self, event) + if event ~= nil then + local ch = self.channels[event] + return ch ~= nil and ch.liveCount or 0 + end + local total = 0 + for _, ch in pairs(self.channels) do + if ch ~= nil then + total = total + ch.liveCount + end + end + return total +end +function EvEmitter.prototype.ClearAll(self) + for evName, ch in pairs(self.channels) do + if ch ~= nil then + local list = ch.listeners + do + local i = 0 + while i < #list do + local listener = list[i + 1] + if listener ~= EMPTY_SLOT then + listener:Off() + end + i = i + 1 + end + end + self.channels[evName] = nil + end + end +end +function EvEmitter.prototype.Dispose(self) + self:ClearAll() +end +function __module.StashData(env, to) + local ____has = to.__has__ + if not ____has then + ____has = {} + to.__has__ = ____has + end + to.nextEmitterId = nextEmitterId + ____has.nextEmitterId = true + to.globalOwnerFilter = globalOwnerFilter + ____has.globalOwnerFilter = true +end +function __module.RestoreData(env, from) + local ____has = from.__has__ + if not ____has then + return + end + if ____has.nextEmitterId then + nextEmitterId = from.nextEmitterId + end + if ____has.globalOwnerFilter then + globalOwnerFilter = from.globalOwnerFilter + end +end +function __module.UpdateImports() + tbpcall = M__share_base_traceback.tbpcall +end diff --git a/Script/lua/tests/harness/test_runner.lua b/Script/lua/tests/harness/test_runner.lua new file mode 100644 index 0000000..e23cf33 --- /dev/null +++ b/Script/lua/tests/harness/test_runner.lua @@ -0,0 +1,120 @@ +local ____exports = __module.env +function ____exports.Assert(condition, message) + if not condition then + error(message or "Assertion failed", 2) + end +end +function ____exports.AssertEqual(actual, expected, label) + if actual ~= expected then + local prefix = label ~= nil and label .. ": " or "" + error( + string.format( + "%sexpected %s, got %s", + prefix, + tostring(expected), + tostring(actual) + ), + 2 + ) + end +end +function ____exports.AssertNotEqual(actual, unexpected, label) + if actual == unexpected then + local prefix = label ~= nil and label .. ": " or "" + error( + string.format( + "%sexpected value different from %s", + prefix, + tostring(unexpected) + ), + 2 + ) + end +end +function ____exports.AssertNear(actual, expected, epsilon, label) + if math.abs(actual - expected) > epsilon then + local prefix = label ~= nil and label .. ": " or "" + error( + string.format( + "%sexpected %s (+/- %s), got %s", + prefix, + tostring(expected), + tostring(epsilon), + tostring(actual) + ), + 2 + ) + end +end +function ____exports.AssertArrayEqual(actual, expected, label) + local prefix = label ~= nil and label .. ": " or "" + if #actual ~= #expected then + error( + string.format("%sarray length mismatch: expected %d, got %d", prefix, #expected, #actual), + 2 + ) + end + do + local i = 0 + while i < #expected do + if actual[i + 1] ~= expected[i + 1] then + error( + string.format( + "%sarray[%d] mismatch: expected %s, got %s", + prefix, + i, + tostring(expected[i + 1]), + tostring(actual[i + 1]) + ), + 2 + ) + end + i = i + 1 + end + end +end +function ____exports.RunSuites(suites) + local summary = {total = 0, passed = 0, failed = 0, failures = {}} + do + local s = 0 + while s < #suites do + local suite = suites[s + 1] + do + local c = 0 + while c < #suite.cases do + local testCase = suite.cases[c + 1] + summary.total = summary.total + 1 + local ok, err = xpcall(testCase.fn, debug.traceback) + if ok then + summary.passed = summary.passed + 1 + else + summary.failed = summary.failed + 1 + summary.failures[#summary.failures + 1] = { + suite = suite.name, + name = testCase.name, + error = tostring(err) + } + end + c = c + 1 + end + end + s = s + 1 + end + end + return summary +end +function ____exports.FormatReport(summary) + local lines = {} + lines[#lines + 1] = string.format("=== Test Summary: %d/%d passed (%d failed) ===", summary.passed, summary.total, summary.failed) + do + local i = 0 + while i < #summary.failures do + local f = summary.failures[i + 1] + lines[#lines + 1] = string.format("[FAIL] %s :: %s\n%s", f.suite, f.name, f.error) + i = i + 1 + end + end + return table.concat(lines, "\n") +end +function __module.UpdateImports() +end diff --git a/Script/lua/tests/run_unit_tests.lua b/Script/lua/tests/run_unit_tests.lua new file mode 100644 index 0000000..99b4184 --- /dev/null +++ b/Script/lua/tests/run_unit_tests.lua @@ -0,0 +1,39 @@ +local ____exports = __module.env +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local FormatReport = M__tests_harness_test_runner.FormatReport +local RunSuites = M__tests_harness_test_runner.RunSuites +local M__tests_unit_context_and_mgr_test = __MODULE__.Import("tests.unit.context_and_mgr_test", __module) +local CreateContextAndMgrSuite = M__tests_unit_context_and_mgr_test.CreateContextAndMgrSuite +local M__tests_unit_event_hub_test = __MODULE__.Import("tests.unit.event_hub_test", __module) +local CreateEventHubSuite = M__tests_unit_event_hub_test.CreateEventHubSuite +local M__tests_unit_scheduler_test = __MODULE__.Import("tests.unit.scheduler_test", __module) +local CreateSchedulerSuite = M__tests_unit_scheduler_test.CreateSchedulerSuite +local M__tests_unit_smoke_test = __MODULE__.Import("tests.unit.smoke_test", __module) +local CreateSmokeSuite = M__tests_unit_smoke_test.CreateSmokeSuite +local M__tests_unit_storage_and_setting_test = __MODULE__.Import("tests.unit.storage_and_setting_test", __module) +local CreateStorageAndSettingSuite = M__tests_unit_storage_and_setting_test.CreateStorageAndSettingSuite +local M__tests_unit_ui_and_resource_test = __MODULE__.Import("tests.unit.ui_and_resource_test", __module) +local CreateUIAndResourceSuite = M__tests_unit_ui_and_resource_test.CreateUIAndResourceSuite +function ____exports.RunAllUnitTests() + local suites = { + CreateSmokeSuite(), + CreateEventHubSuite(), + CreateSchedulerSuite(), + CreateContextAndMgrSuite(), + CreateStorageAndSettingSuite(), + CreateUIAndResourceSuite() + } + local summary = RunSuites(suites) + print(FormatReport(summary)) + return summary +end +function __module.UpdateImports() + FormatReport = M__tests_harness_test_runner.FormatReport + RunSuites = M__tests_harness_test_runner.RunSuites + CreateContextAndMgrSuite = M__tests_unit_context_and_mgr_test.CreateContextAndMgrSuite + CreateEventHubSuite = M__tests_unit_event_hub_test.CreateEventHubSuite + CreateSchedulerSuite = M__tests_unit_scheduler_test.CreateSchedulerSuite + CreateSmokeSuite = M__tests_unit_smoke_test.CreateSmokeSuite + CreateStorageAndSettingSuite = M__tests_unit_storage_and_setting_test.CreateStorageAndSettingSuite + CreateUIAndResourceSuite = M__tests_unit_ui_and_resource_test.CreateUIAndResourceSuite +end diff --git a/Script/lua/tests/ue/run_ue_tests.lua b/Script/lua/tests/ue/run_ue_tests.lua new file mode 100644 index 0000000..2957ed1 --- /dev/null +++ b/Script/lua/tests/ue/run_ue_tests.lua @@ -0,0 +1,410 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext +local Json = __MODULE__.Import("framework.core.json", __module) +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS +local BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS +local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module) +local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager +local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module) +local UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend +local M__game_setting_mini_settings_window = __MODULE__.Import("game.setting.mini_settings_window", __module) +local MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow +local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module) +local SettingService = M__game_setting_setting_service.SettingService +local M__game_startup = __MODULE__.Import("game.startup", __module) +local GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local Assert = M__tests_harness_test_runner.Assert +local AssertEqual = M__tests_harness_test_runner.AssertEqual +local FormatReport = M__tests_harness_test_runner.FormatReport +local RunSuites = M__tests_harness_test_runner.RunSuites +local function PumpUEFrames(frames, dt) + if dt == nil then + dt = 0.02 + end + if __UE_TEST_TICK == nil then + return + end + do + local i = 0 + while i < frames do + __UE_TEST_TICK(dt) + i = i + 1 + end + end +end +function ____exports.RunAllUETests(gameInstance, world) + local suites = { + { + name = "UE.NativeJson", + cases = {{ + name = "ue_json native C++ module is active and preserves 64-bit integers and UTF-8", + fn = function() + Assert( + Json.IsNativeBackend(), + "expected native ue_json backend inside UE" + ) + local bigInt = tonumber("9007199254740993") + AssertEqual( + math.type(bigInt), + "integer", + "bigInt is Lua 5.4 integer" + ) + local input = { + version = 2, + roleId = bigInt, + title = "UE5.8中文测试", + enabled = true, + list = {10, 20, 30}, + empty = Json.GetEmptyArray() + } + local encoded, encErr = Json.Encode(input) + AssertEqual(encErr, nil, "encode error") + Assert( + type(encoded) == "string", + "encoded string" + ) + local decoded, decErr = Json.Decode(encoded) + AssertEqual(decErr, nil, "decode error") + local obj = decoded + AssertEqual(obj.version, 2) + AssertEqual(obj.roleId, bigInt, "int64 lossless round-trip") + AssertEqual(obj.title, "UE5.8中文测试") + AssertEqual(obj.enabled, true) + local list = obj.list + AssertEqual(list[1], 10) + AssertEqual(list[3], 30) + local badVal, badErr = Json.Decode("{broken") + AssertEqual(badVal, nil) + Assert(badErr ~= nil and badErr ~= "", "malformed JSON returns error") + end + }} + }, + { + name = "UE.LocalStorage", + cases = {{ + name = "ULuaStorageLibrary + ULuaSaveGame: debounce save, cold-start readback, and corruption recovery", + fn = function() + Assert(gameInstance ~= nil, "gameInstance required") + local ctx = GetGameInstanceContext(gameInstance) + Assert(ctx ~= nil, "GameInstanceContext must be initialized") + local slotId = "ue_test_slot" + local fullSlotName = "sdata_" .. slotId + UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true) + local backend = __TS__New(UEStorageBackend) + local saveMgr = __TS__New(LocalSaveManager, backend, ctx.scheduler) + local settings = __TS__New(SettingService, saveMgr, slotId) + AssertEqual( + settings:GetStore():GetLastLoadStatus(), + "not_found" + ) + AssertEqual( + settings:GetSoundEnabled(), + true, + "missing slot returns default" + ) + settings:SetSoundEnabled(false) + PumpUEFrames(8, 0.02) + AssertEqual( + settings:GetStore():IsDirty(), + false, + "debounced save flushed to UE SaveGame" + ) + Assert( + UE.ULuaStorageLibrary.DoesSlotExist(fullSlotName, 0), + "SaveGame file created on disk" + ) + settings:SetSoundEnabled(true) + AssertEqual( + settings:Flush(), + "ok" + ) + settings:Dispose() + saveMgr:Dispose() + local saveMgr2 = __TS__New(LocalSaveManager, backend, ctx.scheduler) + local settings2 = __TS__New(SettingService, saveMgr2, slotId) + AssertEqual( + settings2:GetStore():GetLastLoadStatus(), + "ok" + ) + AssertEqual( + settings2:GetSoundEnabled(), + true, + "cold-start reads latest value" + ) + settings2:Dispose() + saveMgr2:Dispose() + Assert( + UE.ULuaStorageLibrary.WriteCorruptRawSlotForTest(fullSlotName, "CORRUPTED_SAV_DATA", 0), + "corrupt injection succeeded" + ) + local saveMgr3 = __TS__New(LocalSaveManager, backend, ctx.scheduler) + local settings3 = __TS__New(SettingService, saveMgr3, slotId) + AssertEqual( + settings3:GetStore():GetLastLoadStatus(), + "ok" + ) + Assert( + settings3:GetStore():WasRecoveredFromBackup(), + "recovered from .bak" + ) + AssertEqual( + settings3:GetSoundEnabled(), + false, + "recovered previous valid value" + ) + Assert( + UE.ULuaStorageLibrary.DoesCorruptBackupExist(fullSlotName, 0), + ".corrupt evidence preserved" + ) + settings3:Dispose() + saveMgr3:Dispose() + UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true) + end + }} + }, + { + name = "UE.ResourceManager", + cases = {{ + name = "ULuaResourceSubsystem: PIE Content load, PatchManifest override, coalesced cancel, and GC ref-count", + fn = function() + Assert(gameInstance ~= nil, "gameInstance required") + local ctx = GetGameInstanceContext(gameInstance) + local resSvc = ctx:GetService("resource") + local sub = UE.ULuaResourceSubsystem.GetFromGameInstance(gameInstance) + Assert(resSvc ~= nil and sub ~= nil, "ResourceService & Subsystem ready") + Assert( + resSvc:DoesAssetExist(ASSET_KEYS.MINI_SETTINGS_ICON), + "T_MiniSettingsIcon exists" + ) + Assert( + resSvc:DoesAssetExist(ASSET_KEYS.MINI_SETTINGS_WIDGET), + "WBP_MiniSettings exists" + ) + Assert( + not resSvc:DoesAssetExist("/Game/DoesNotExist/MissingAsset"), + "missing asset returns false" + ) + local aliasKey = "tex.patch_alias_icon" + Assert( + sub:ApplyPatchManifest(string.format("{\"%s\":\"%s\"}", aliasKey, BASE_ASSET_PATHS[ASSET_KEYS.MINI_SETTINGS_ICON])), + "ApplyPatchManifest succeeded" + ) + AssertEqual( + resSvc:ResolveAssetPath(aliasKey), + BASE_ASSET_PATHS[ASSET_KEYS.MINI_SETTINGS_ICON], + "PatchOverlay resolves alias key" + ) + local owner1 = __TS__New(ScopedObject) + local owner2 = __TS__New(ScopedObject) + local owner3 = __TS__New(ScopedObject) + local tex1 + local tex2 + local cancelledFired = false + local widgetCls + local missingCalls = 0 + local missingOk = true + resSvc:LoadTextureAsync( + ASSET_KEYS.MINI_SETTINGS_ICON, + owner1, + function(ok, asset) + if ok then + tex1 = asset + end + end + ) + local hCancel = resSvc:LoadTextureAsync( + aliasKey, + owner3, + function() + cancelledFired = true + end + ) + resSvc:LoadTextureAsync( + aliasKey, + owner2, + function(ok, asset) + if ok then + tex2 = asset + end + end + ) + resSvc:LoadClassAsync( + ASSET_KEYS.MINI_SETTINGS_WIDGET, + owner1, + function(ok, cls) + if ok then + widgetCls = cls + end + end + ) + resSvc:LoadObjectAsync( + "/Game/DoesNotExist/MissingAsset", + owner1, + function(ok) + missingCalls = missingCalls + 1 + missingOk = ok + end + ) + hCancel:Cancel() + PumpUEFrames(15, 0.02) + Assert(not cancelledFired, "cancelled caller must not receive callback") + Assert( + tex1 ~= nil and UE.UKismetSystemLibrary.IsValid(tex1), + "tex1 loaded & valid" + ) + Assert( + tex2 ~= nil and UE.UKismetSystemLibrary.IsValid(tex2), + "tex2 loaded & valid" + ) + Assert( + widgetCls ~= nil and UE.UKismetSystemLibrary.IsValid(widgetCls), + "WBP_MiniSettings class loaded" + ) + AssertEqual(missingCalls, 1, "missing asset delivers exactly once") + AssertEqual(missingOk, false, "missing asset reports ok=false") + owner1:Dispose() + if __UE_TEST_GC ~= nil then + __UE_TEST_GC() + end + Assert( + UE.UKismetSystemLibrary.IsValid(tex2), + "tex2 survives GC while owner2 holds ref" + ) + AssertEqual( + sub:GetAssetRefCount(ASSET_KEYS.MINI_SETTINGS_ICON), + 1, + "refcount decremented to 1" + ) + owner2:Dispose() + owner3:Dispose() + sub:ClearPatchManifest() + if __UE_TEST_GC ~= nil then + __UE_TEST_GC() + end + local diag = resSvc:GetDiagnostics() + AssertEqual(diag.tsPendingRequests, 0, "tsPending back to 0") + AssertEqual(diag.nativeInFlight, 0, "nativeInFlight back to 0") + AssertEqual(diag.nativeRetainedAssets, 0, "nativeRetained back to 0") + AssertEqual(diag.nativeTotalRefCount, 0, "nativeTotalRefCount back to 0") + end + }} + }, + { + name = "UE.MiniSettingsUMG", + cases = {{ + name = "Real WBP_MiniSettings open, async icon, button click delegate, SaveGame persist, and clean baseline teardown", + fn = function() + Assert(gameInstance ~= nil and world ~= nil, "GI & World required") + local ctx = GetGameInstanceContext(gameInstance) + local uiMgr = GetPrimaryUIManager(ctx) + local settingSvc = ctx:GetService("setting") + local resSvc = ctx:GetService("resource") + local uiBridge = ctx:GetService("uiDelegateBridge") + UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true) + settingSvc:GetStore():Reload() + AssertEqual( + settingSvc:GetSoundEnabled(), + true, + "initial sound ON" + ) + ctx:OnWorldCleanup(world) + local openedOk = false + local win = uiMgr:ShowUI( + MiniSettingsWindow, + nil, + function(ok) + openedOk = ok + end + ) + Assert(win ~= nil, "MiniSettingsWindow controller created") + PumpUEFrames(20, 0.02) + Assert(openedOk, "MiniSettingsWindow opened callback fired") + Assert( + win:IsLoaded(), + "widget loaded" + ) + Assert(win.iconLoaded, "T_MiniSettingsIcon loaded and applied to ImgIcon") + Assert(win.btnToggle ~= nil and win.btnClose ~= nil, "named UMG buttons bound") + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonClick(win.btnToggle), + "SimulateButtonClick BtnToggle" + ) + AssertEqual(win.toggleClickCount, 1, "toggle click handled exactly once") + AssertEqual( + settingSvc:GetSoundEnabled(), + false, + "sound toggled OFF" + ) + PumpUEFrames(8, 0.02) + AssertEqual( + settingSvc:GetStore():IsDirty(), + false, + "setting persisted to UE SaveGame" + ) + Assert( + UE.ULuaUIEventSubsystem.SimulateButtonClick(win.btnClose), + "SimulateButtonClick BtnClose" + ) + Assert( + win:IsDisposed(), + "MiniSettingsWindow disposed after close" + ) + AssertEqual( + uiMgr:GetDiagnostics().openWindows, + 0, + "openWindows back to 0" + ) + AssertEqual( + uiBridge:GetActiveBindingCount(), + 0, + "button delegate bindings back to 0" + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0, + "resource refcount back to 0" + ) + local freshStore = __TS__New( + LocalSaveManager, + __TS__New(UEStorageBackend), + ctx.scheduler + ) + local freshSettings = __TS__New(SettingService, freshStore) + AssertEqual( + freshSettings:GetSoundEnabled(), + false, + "cold readback reads OFF" + ) + freshSettings:Dispose() + freshStore:Dispose() + UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true) + end + }} + } + } + local summary = RunSuites(suites) + print(FormatReport(summary)) + return summary +end +function __module.UpdateImports() + GetGameInstanceContext = M__framework_context_game_context.GetGameInstanceContext + ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS + BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS + LocalSaveManager = M__framework_storage_local_save.LocalSaveManager + UEStorageBackend = M__framework_storage_storage_backend.UEStorageBackend + MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow + SettingService = M__game_setting_setting_service.SettingService + GetPrimaryUIManager = M__game_startup.GetPrimaryUIManager + ScopedObject = M__share_base_scoped_object.ScopedObject + Assert = M__tests_harness_test_runner.Assert + AssertEqual = M__tests_harness_test_runner.AssertEqual + FormatReport = M__tests_harness_test_runner.FormatReport + RunSuites = M__tests_harness_test_runner.RunSuites +end diff --git a/Script/lua/tests/unit/context_and_mgr_test.lua b/Script/lua/tests/unit/context_and_mgr_test.lua new file mode 100644 index 0000000..d5f6e0b --- /dev/null +++ b/Script/lua/tests/unit/context_and_mgr_test.lua @@ -0,0 +1,188 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local GameInstanceContext = M__framework_context_game_context.GameInstanceContext +local M__framework_module_mgr_base = __MODULE__.Import("framework.module.mgr_base", __module) +local ControllerBase = M__framework_module_mgr_base.ControllerBase +local MgrBase = M__framework_module_mgr_base.MgrBase +local MgrDataBase = M__framework_module_mgr_base.MgrDataBase +local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module) +local EventHub = M__share_event_event_hub.EventHub +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local Assert = M__tests_harness_test_runner.Assert +local AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual +local AssertEqual = M__tests_harness_test_runner.AssertEqual +local SampleData = __TS__DefineClass("SampleData", __module) +SampleData.name = "SampleData" +__TS__ClassExtends(SampleData, MgrDataBase) +function SampleData.prototype.____constructor(self, ...) + MgrDataBase.prototype.____constructor(self, ...) + self.value = 0 + self.disposed = false +end +function SampleData.prototype.Dispose(self) + self.disposed = true +end +local SampleSubController = __TS__DefineClass("SampleSubController", __module) +SampleSubController.name = "SampleSubController" +__TS__ClassExtends(SampleSubController, ControllerBase) +function SampleSubController.prototype.____constructor(self, ...) + ControllerBase.prototype.____constructor(self, ...) + self.events = {} +end +function SampleSubController.prototype.OnEnter(self) + self.events[#self.events + 1] = "enter" +end +function SampleSubController.prototype.OnActive(self) + self.events[#self.events + 1] = "active" +end +function SampleSubController.prototype.OnExit(self) + self.events[#self.events + 1] = "exit" +end +local SampleMgr = __TS__DefineClass("SampleMgr", __module) +SampleMgr.name = "SampleMgr" +__TS__ClassExtends(SampleMgr, MgrBase) +function SampleMgr.prototype.____constructor(self, ...) + MgrBase.prototype.____constructor(self, ...) + self.lifecycle = {} +end +function SampleMgr.prototype.OnCreate(self) + self.lifecycle[#self.lifecycle + 1] = "create" +end +function SampleMgr.prototype.OnBindControllers(self) + self.subCtrl = self:AddController(SampleSubController) +end +function SampleMgr.prototype.OnBindEvents(self) + self.lifecycle[#self.lifecycle + 1] = "bind" +end +function SampleMgr.prototype.OnClean(self) + self.lifecycle[#self.lifecycle + 1] = "clean" +end +function ____exports.CreateContextAndMgrSuite() + return { + name = "Step1.ContextAndMgr", + cases = { + { + name = "MgrRegistry creates, looks up by ctor and name, and cleans both indexes on DelMgr", + fn = function() + local ctx = __TS__New(GameInstanceContext) + local mgr = ctx.mgrRegistry:CreateMgr(SampleMgr, "SampleMgr") + local data = ctx.mgrRegistry:CreateMgrData(SampleData) + data.value = 123 + AssertEqual( + ctx.mgrRegistry:GetMgr(SampleMgr), + mgr + ) + AssertEqual( + ctx.mgrRegistry:GetMgrByName("SampleMgr"), + mgr + ) + AssertEqual( + ctx.mgrRegistry:GetMgrData(SampleData), + data + ) + AssertArrayEqual(mgr.lifecycle, {"create", "bind"}) + Assert(mgr.subCtrl ~= nil, "sub controller attached") + AssertArrayEqual(mgr.subCtrl.events, {"enter", "active"}) + ctx.mgrRegistry:DelMgr(SampleMgr) + AssertEqual( + ctx.mgrRegistry:GetMgr(SampleMgr), + nil + ) + AssertEqual( + ctx.mgrRegistry:GetMgrByName("SampleMgr"), + nil, + "name index must be cleared" + ) + Assert( + mgr:IsDisposed(), + "mgr disposed" + ) + AssertArrayEqual(mgr.lifecycle, {"create", "bind", "clean"}) + AssertArrayEqual(mgr.subCtrl.events, {"enter", "active", "exit"}) + ctx:Dispose() + Assert(data.disposed, "data disposed with context") + end + }, + { + name = "Two GameInstanceContexts coexist in one Lua VM; disposing #1 keeps #2 intact", + fn = function() + local ctx1 = __TS__New(GameInstanceContext) + local ctx2 = __TS__New(GameInstanceContext) + local hub1 = __TS__New(EventHub, "Hub1") + local hub2 = __TS__New(EventHub, "Hub2") + ctx1:RegisterService("bizHub", hub1) + ctx2:RegisterService("bizHub", hub2) + local mgr1 = ctx1.mgrRegistry:CreateMgr(SampleMgr, "SampleMgr") + local mgr2 = ctx2.mgrRegistry:CreateMgr(SampleMgr, "SampleMgr") + local log1 = {} + local log2 = {} + hub1.on.Notify( + function(msg) + log1[#log1 + 1] = msg + end, + mgr1 + ) + hub2.on.Notify( + function(msg) + log2[#log2 + 1] = msg + end, + mgr2 + ) + ctx1.scheduler:AddMonotonicRepeatTimer( + 0.05, + function() + log1[#log1 + 1] = "tick1" + end, + mgr1 + ) + ctx2.scheduler:AddMonotonicRepeatTimer( + 0.05, + function() + log2[#log2 + 1] = "tick2" + end, + mgr2 + ) + local shutdownOrder = {} + ctx1:AddShutdownHook(function() + shutdownOrder[#shutdownOrder + 1] = "hook1" + end) + ctx1:AddShutdownHook(function() + shutdownOrder[#shutdownOrder + 1] = "hook2" + end) + ctx1:Dispose() + AssertArrayEqual(shutdownOrder, {"hook2", "hook1"}, "shutdown hooks run in reverse order") + Assert( + mgr1:IsDisposed(), + "mgr1 disposed" + ) + Assert( + not mgr2:IsDisposed(), + "mgr2 still alive" + ) + hub2.emit.Notify("alive") + ctx2:Tick(0.06) + AssertArrayEqual(log1, {}) + AssertArrayEqual(log2, {"alive", "tick2"}) + ctx2:Dispose() + Assert( + mgr2:IsDisposed(), + "mgr2 disposed cleanly" + ) + end + } + } + } +end +function __module.UpdateImports() + GameInstanceContext = M__framework_context_game_context.GameInstanceContext + ControllerBase = M__framework_module_mgr_base.ControllerBase + MgrBase = M__framework_module_mgr_base.MgrBase + MgrDataBase = M__framework_module_mgr_base.MgrDataBase + EventHub = M__share_event_event_hub.EventHub + Assert = M__tests_harness_test_runner.Assert + AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual + AssertEqual = M__tests_harness_test_runner.AssertEqual +end diff --git a/Script/lua/tests/unit/event_hub_test.lua b/Script/lua/tests/unit/event_hub_test.lua new file mode 100644 index 0000000..7f2b7da --- /dev/null +++ b/Script/lua/tests/unit/event_hub_test.lua @@ -0,0 +1,216 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__share_base_traceback = __MODULE__.Import("share.base.traceback", __module) +local SetupTracebackHandler = M__share_base_traceback.SetupTracebackHandler +local M__share_event_event_hub = __MODULE__.Import("share.event.event_hub", __module) +local EventHub = M__share_event_event_hub.EventHub +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local Assert = M__tests_harness_test_runner.Assert +local AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual +local AssertEqual = M__tests_harness_test_runner.AssertEqual +function ____exports.CreateEventHubSuite() + return { + name = "Step1.EventHub", + cases = { + { + name = "Duplicate (emitter, event, owner) subscription replaces previous listener", + fn = function() + local hub = __TS__New(EventHub, "DupTest") + local owner = __TS__New(ScopedObject) + local log = {} + hub.on.Ping( + function(a) + log[#log + 1] = "old:" .. tostring(a) + end, + owner + ) + hub.on.Ping( + function(a) + log[#log + 1] = "new:" .. tostring(a) + end, + owner + ) + AssertEqual( + hub:GetListenerCount("Ping"), + 1, + "listener count" + ) + hub.emit.Ping(42) + AssertArrayEqual(log, {"new:42"}) + owner:Dispose() + AssertEqual( + hub:GetListenerCount("Ping"), + 0, + "after dispose" + ) + hub:Dispose() + end + }, + { + name = "Callback receives exact event args (no owner prepended) and respects Enable/Disable/OffAll", + fn = function() + local hub = __TS__New(EventHub, "ArgsTest") + local owner = __TS__New(ScopedObject) + local received = {} + hub.on.Ping( + function(a, b, c) + received[#received + 1] = string.format( + "%s|%s|%s", + tostring(a), + tostring(b), + tostring(c) + ) + end, + owner + ) + hub.emit.Ping(7, "hello", 9) + owner:DisableAllEventListeners() + hub.emit.Ping(8, "skip", 10) + owner:EnableAllEventListeners() + hub.emit.Ping(11, nil, 13) + owner:OffAllEventListeners() + hub.emit.Ping(99, "gone") + AssertArrayEqual(received, {"7|hello|9", "11|nil|13"}) + hub:Dispose() + end + }, + { + name = "Cancelling next listener or disposing next owner during dispatch skips it immediately", + fn = function() + local subB + local hub = __TS__New(EventHub, "MutationTest") + local ownerA = __TS__New(ScopedObject) + local ownerB = __TS__New(ScopedObject) + local ownerC = __TS__New(ScopedObject) + local order = {} + local listenerB = hub.on.Ping( + function() + order[#order + 1] = "B" + end, + ownerB + ) + listenerB:Off() + hub.on.Ping( + function() + order[#order + 1] = "A" + subB:Off() + ownerC:Dispose() + end, + ownerA + ) + subB = hub.on.Ping( + function() + order[#order + 1] = "B" + end, + ownerB + ) + hub.on.Ping( + function() + order[#order + 1] = "C" + end, + ownerC + ) + hub.emit.Ping(1) + AssertArrayEqual(order, {"A"}) + ownerA:Dispose() + ownerB:Dispose() + hub:Dispose() + end + }, + { + name = "Nested Emit and listener error isolation", + fn = function() + local capturedErrors = {} + SetupTracebackHandler({DumpTraceback = function(msg) + capturedErrors[#capturedErrors + 1] = msg + end}) + local hub = __TS__New(EventHub, "NestedTest") + local ownerA = __TS__New(ScopedObject) + local ownerB = __TS__New(ScopedObject) + local order = {} + hub.on.Chain( + function(step) + order[#order + 1] = "A:" .. tostring(step) + if step == 1 then + hub.emit.Chain(2) + end + if step == 2 then + error("boom-in-listener") + end + end, + ownerA + ) + hub.on.Chain( + function(step) + order[#order + 1] = "B:" .. tostring(step) + end, + ownerB + ) + hub.emit.Chain(1) + SetupTracebackHandler(nil) + AssertArrayEqual(order, {"A:1", "A:2", "B:2", "B:1"}) + Assert(#capturedErrors == 1, "expected 1 isolated error") + ownerA:Dispose() + ownerB:Dispose() + hub:Dispose() + end + }, + { + name = "preEmit and asyncEmit preserve trailing nil via table.pack.n", + fn = function() + local pending = {} + local preCalls = {} + local hub = __TS__New( + EventHub, + "AsyncTest", + { + preEmit = function(evName) + preCalls[#preCalls + 1] = evName + end, + asyncEmit = function(_evName, emit) + pending[#pending + 1] = emit + end + } + ) + local owner = __TS__New(ScopedObject) + local argCount = -1 + local capturedA + local capturedB + local capturedC + hub.on.Trailing( + function(...) + local args = {...} + argCount = select("#", ...) + capturedA = args[1] + capturedB = args[2] + capturedC = args[3] + end, + owner + ) + hub.emit.Trailing("first", nil, nil) + AssertEqual(#preCalls, 0, "preEmit should not run before async flush") + AssertEqual(#pending, 1, "one queued async emit") + pending[1]() + AssertArrayEqual(preCalls, {"Trailing"}) + AssertEqual(argCount, 3, "trailing nils must be preserved") + AssertEqual(capturedA, "first") + AssertEqual(capturedB, nil) + AssertEqual(capturedC, nil) + owner:Dispose() + hub:Dispose() + end + } + } + } +end +function __module.UpdateImports() + ScopedObject = M__share_base_scoped_object.ScopedObject + SetupTracebackHandler = M__share_base_traceback.SetupTracebackHandler + EventHub = M__share_event_event_hub.EventHub + Assert = M__tests_harness_test_runner.Assert + AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual + AssertEqual = M__tests_harness_test_runner.AssertEqual +end diff --git a/Script/lua/tests/unit/scheduler_test.lua b/Script/lua/tests/unit/scheduler_test.lua new file mode 100644 index 0000000..f2259a0 --- /dev/null +++ b/Script/lua/tests/unit/scheduler_test.lua @@ -0,0 +1,168 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__share_base_scoped_object = __MODULE__.Import("share.base.scoped_object", __module) +local ScopedObject = M__share_base_scoped_object.ScopedObject +local M__framework_core_scheduler = __MODULE__.Import("framework.core.scheduler", __module) +local FrameScheduler = M__framework_core_scheduler.FrameScheduler +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual +local AssertEqual = M__tests_harness_test_runner.AssertEqual +function ____exports.CreateSchedulerSuite() + return { + name = "Step1.Scheduler", + cases = { + { + name = "Frame timers: 0 and 1 fire next frame, N fires on N-th frame", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local fired = {} + scheduler:AddFrameTimer( + 0, + function() + fired[#fired + 1] = "f0@" .. tostring(scheduler:GetFrameCount()) + end + ) + scheduler:AddFrameTimer( + 1, + function() + fired[#fired + 1] = "f1@" .. tostring(scheduler:GetFrameCount()) + end + ) + scheduler:AddFrameTimer( + 3, + function() + fired[#fired + 1] = "f3@" .. tostring(scheduler:GetFrameCount()) + end + ) + scheduler:Tick(0.016) + AssertArrayEqual(fired, {"f0@1", "f1@1"}) + scheduler:Tick(0.016) + AssertArrayEqual(fired, {"f0@1", "f1@1"}) + scheduler:Tick(0.016) + AssertArrayEqual(fired, {"f0@1", "f1@1", "f3@3"}) + AssertEqual( + scheduler:GetStats().totalTasks, + 0, + "all frame tasks completed" + ) + scheduler:Dispose() + end + }, + { + name = "World pause freezes world timers while monotonic timers continue", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local log = {} + scheduler:AddWorldTimer( + 0.1, + function() + log[#log + 1] = "world" + end + ) + scheduler:AddMonotonicTimer( + 0.1, + function() + log[#log + 1] = "mono" + end + ) + scheduler:Tick(0.06, 0.06, true) + scheduler:Tick(0.06, 0.06, true) + AssertArrayEqual(log, {"mono"}) + scheduler:Tick(0.05, 0.05, false) + AssertArrayEqual(log, {"mono"}) + scheduler:Tick(0.06, 0.06, false) + AssertArrayEqual(log, {"mono", "world"}) + AssertEqual( + scheduler:GetStats().totalTasks, + 0 + ) + scheduler:Dispose() + end + }, + { + name = "World invalidation cancels world & frame tasks but preserves monotonic tasks", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local log = {} + scheduler:AddFrameTimer( + 2, + function() + log[#log + 1] = "frame" + end + ) + scheduler:AddWorldTimer( + 0.05, + function() + log[#log + 1] = "world" + end + ) + scheduler:AddMonotonicTimer( + 0.05, + function() + log[#log + 1] = "mono" + end + ) + local nextGen = scheduler:InvalidateWorld() + AssertEqual(nextGen, 2, "worldGen incremented") + AssertEqual( + scheduler:GetStats().worldTasks, + 0, + "world tasks cleared" + ) + AssertEqual( + scheduler:GetStats().frameTasks, + 0, + "frame tasks cleared" + ) + AssertEqual( + scheduler:GetStats().monotonicTasks, + 1, + "monotonic task survives" + ) + scheduler:Tick(0.06) + scheduler:Tick(0.06) + AssertArrayEqual(log, {"mono"}) + AssertEqual( + scheduler:GetStats().totalTasks, + 0 + ) + scheduler:Dispose() + end + }, + { + name = "Disposing ScopedObject owner automatically cancels owned timers", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local owner = __TS__New(ScopedObject) + local count = 0 + scheduler:AddMonotonicRepeatTimer( + 0.05, + function() + count = count + 1 + end, + owner + ) + scheduler:Tick(0.06) + AssertEqual(count, 1) + owner:Dispose() + scheduler:Tick(0.06) + scheduler:Tick(0.06) + AssertEqual(count, 1, "disposed owner timer must not fire") + AssertEqual( + scheduler:GetStats().totalTasks, + 0, + "timer cleaned up" + ) + scheduler:Dispose() + end + } + } + } +end +function __module.UpdateImports() + ScopedObject = M__share_base_scoped_object.ScopedObject + FrameScheduler = M__framework_core_scheduler.FrameScheduler + AssertArrayEqual = M__tests_harness_test_runner.AssertArrayEqual + AssertEqual = M__tests_harness_test_runner.AssertEqual +end diff --git a/Script/lua/tests/unit/smoke_test.lua b/Script/lua/tests/unit/smoke_test.lua new file mode 100644 index 0000000..44ed69a --- /dev/null +++ b/Script/lua/tests/unit/smoke_test.lua @@ -0,0 +1,42 @@ +local ____exports = __module.env +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local Assert = M__tests_harness_test_runner.Assert +local AssertEqual = M__tests_harness_test_runner.AssertEqual +function ____exports.CreateSmokeSuite() + return { + name = "Baseline.Smoke", + cases = { + { + name = "Lua 5.4 and __MODULE__ runtime are loaded", + fn = function() + Assert((string.match(_VERSION, "Lua 5%.4")) ~= nil, "Expected Lua 5.4 runtime") + Assert(__MODULE__ ~= nil, "Expected __MODULE__ global") + Assert( + type(__MODULE__.Import) == "function", + "Expected __MODULE__.Import function" + ) + Assert( + type(__MODULE__.ReimportSafely) == "function", + "Expected __MODULE__.ReimportSafely" + ) + end + }, + { + name = "table.pack preserves trailing nil count n", + fn = function() + local packed = table.pack("a", nil, "c", nil) + AssertEqual(packed.n, 4, "packed.n") + local a, b, c, d = table.unpack(packed, 1, packed.n) + AssertEqual(a, "a") + AssertEqual(b, nil) + AssertEqual(c, "c") + AssertEqual(d, nil) + end + } + } + } +end +function __module.UpdateImports() + Assert = M__tests_harness_test_runner.Assert + AssertEqual = M__tests_harness_test_runner.AssertEqual +end diff --git a/Script/lua/tests/unit/storage_and_setting_test.lua b/Script/lua/tests/unit/storage_and_setting_test.lua new file mode 100644 index 0000000..f93d9b9 --- /dev/null +++ b/Script/lua/tests/unit/storage_and_setting_test.lua @@ -0,0 +1,250 @@ +local ____lualib = require("lualib_bundle") +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__framework_core_scheduler = __MODULE__.Import("framework.core.scheduler", __module) +local FrameScheduler = M__framework_core_scheduler.FrameScheduler +local Json = __MODULE__.Import("framework.core.json", __module) +local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module) +local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager +local LocalSaveStore = M__framework_storage_local_save.LocalSaveStore +local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module) +local MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend +local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module) +local SettingService = M__game_setting_setting_service.SettingService +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local Assert = M__tests_harness_test_runner.Assert +local AssertEqual = M__tests_harness_test_runner.AssertEqual +function ____exports.CreateStorageAndSettingSuite() + return { + name = "Step2A.StorageAndSetting", + cases = { + { + name = "JSON encodes/decodes nested objects, arrays, escapes, and 64-bit integers", + fn = function() + local bigId = tonumber("9007199254740993") + AssertEqual( + math.type(bigId), + "integer", + "bigId is Lua 5.4 integer" + ) + local payload = { + version = 1, + roleId = bigId, + enabled = true, + label = "hello \"ue\"\nline2", + tags = {"a", "b", "c"}, + emptyArr = Json.GetEmptyArray() + } + local encoded, encErr = Json.Encode(payload) + AssertEqual(encErr, nil, "encode error") + Assert( + type(encoded) == "string", + "encoded is string" + ) + local decoded, decErr = Json.Decode(encoded) + AssertEqual(decErr, nil, "decode error") + local obj = decoded + AssertEqual(obj.version, 1) + AssertEqual(obj.roleId, bigId, "int64 round-trip") + AssertEqual(obj.enabled, true) + AssertEqual(obj.label, "hello \"ue\"\nline2") + local tags = obj.tags + AssertEqual(tags[1], "a") + AssertEqual(tags[3], "c") + end + }, + { + name = "Missing slot returns defaults and coalesces rapid Set calls via 0.1s monotonic clock", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local backend = __TS__New(MemoryStorageBackend) + local saveMgr = __TS__New(LocalSaveManager, backend, scheduler) + local settings = __TS__New(SettingService, saveMgr, "unit_coalesce") + AssertEqual( + settings:GetStore():GetLastLoadStatus(), + "not_found" + ) + AssertEqual( + settings:GetSoundEnabled(), + true, + "default true" + ) + settings:SetSoundEnabled(false) + settings:SetSoundEnabled(true) + settings:SetSoundEnabled(false) + AssertEqual(backend.writeCount, 0, "debounced before 0.1s") + scheduler:Tick(0.05, 0.05, true) + AssertEqual(backend.writeCount, 0) + scheduler:Tick(0.06, 0.06, true) + AssertEqual(backend.writeCount, 1, "coalesced into single write") + AssertEqual( + settings:GetStore():IsDirty(), + false + ) + settings:Dispose() + saveMgr:Dispose() + local saveMgr2 = __TS__New(LocalSaveManager, backend, scheduler) + local settings2 = __TS__New(SettingService, saveMgr2, "unit_coalesce") + AssertEqual( + settings2:GetStore():GetLastLoadStatus(), + "ok" + ) + AssertEqual( + settings2:GetStore():GetLoadedSchemaVersion(), + 1 + ) + AssertEqual( + settings2:GetSoundEnabled(), + false, + "cold restart reads saved value" + ) + settings2:Dispose() + saveMgr2:Dispose() + scheduler:Dispose() + end + }, + { + name = "Write failure preserves previous valid data, retains dirty state, and succeeds on retry", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local backend = __TS__New(MemoryStorageBackend) + local store = __TS__New( + LocalSaveStore, + "sdata_retry", + backend, + scheduler, + 1 + ) + store:Set("k", "v1") + AssertEqual( + store:Flush(), + "ok" + ) + backend.failNextWrite = true + store:Set("k", "v2") + AssertEqual( + store:Flush(), + "write_failed" + ) + AssertEqual( + store:IsDirty(), + true, + "dirty remains true after failed write" + ) + local reader = __TS__New( + LocalSaveStore, + "sdata_retry", + backend, + scheduler, + 1 + ) + AssertEqual( + reader:Get("k"), + "v1", + "previous valid value preserved" + ) + reader:Dispose() + AssertEqual( + store:Flush(), + "ok" + ) + AssertEqual( + store:IsDirty(), + false + ) + local reader2 = __TS__New( + LocalSaveStore, + "sdata_retry", + backend, + scheduler, + 1 + ) + AssertEqual( + reader2:Get("k"), + "v2", + "retry wrote v2" + ) + reader2:Dispose() + store:Dispose() + scheduler:Dispose() + end + }, + { + name = "Corrupted primary slot preserves .corrupt evidence and recovers from .bak when available", + fn = function() + local scheduler = __TS__New(FrameScheduler) + local backend = __TS__New(MemoryStorageBackend) + backend:InjectCorruptPrimary("sdata_corrupt_only", "{not-valid-json") + local store1 = __TS__New( + LocalSaveStore, + "sdata_corrupt_only", + backend, + scheduler, + 1 + ) + AssertEqual( + store1:GetLastLoadStatus(), + "corrupted" + ) + AssertEqual( + backend:GetCorruptCopy("sdata_corrupt_only"), + "{not-valid-json" + ) + AssertEqual( + store1:GetDefault("x", 42), + 42 + ) + store1:Dispose() + local store2 = __TS__New( + LocalSaveStore, + "sdata_bak_recover", + backend, + scheduler, + 1 + ) + store2:Set("val", "v1") + store2:Flush() + store2:Set("val", "v2") + store2:Flush() + store2:Dispose() + backend:InjectCorruptPrimary("sdata_bak_recover", "CORRUPTED_BYTES") + local store3 = __TS__New( + LocalSaveStore, + "sdata_bak_recover", + backend, + scheduler, + 1 + ) + AssertEqual( + store3:GetLastLoadStatus(), + "ok" + ) + AssertEqual( + store3:WasRecoveredFromBackup(), + true + ) + AssertEqual( + store3:Get("val"), + "v1", + "recovered from backup" + ) + AssertEqual( + backend:GetCorruptCopy("sdata_bak_recover"), + "CORRUPTED_BYTES" + ) + store3:Dispose() + scheduler:Dispose() + end + } + } + } +end +function __module.UpdateImports() + FrameScheduler = M__framework_core_scheduler.FrameScheduler + LocalSaveManager = M__framework_storage_local_save.LocalSaveManager + LocalSaveStore = M__framework_storage_local_save.LocalSaveStore + MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend + SettingService = M__game_setting_setting_service.SettingService + Assert = M__tests_harness_test_runner.Assert + AssertEqual = M__tests_harness_test_runner.AssertEqual +end diff --git a/Script/lua/tests/unit/ui_and_resource_test.lua b/Script/lua/tests/unit/ui_and_resource_test.lua new file mode 100644 index 0000000..98949d5 --- /dev/null +++ b/Script/lua/tests/unit/ui_and_resource_test.lua @@ -0,0 +1,489 @@ +local ____lualib = require("lualib_bundle") +local __TS__ClassExtends = ____lualib.__TS__ClassExtends +local __TS__New = ____lualib.__TS__New +local ____exports = __module.env +local M__framework_context_game_context = __MODULE__.Import("framework.context.game_context", __module) +local GameInstanceContext = M__framework_context_game_context.GameInstanceContext +local M__framework_resource_asset_catalog = __MODULE__.Import("framework.resource.asset_catalog", __module) +local ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS +local BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS +local M__framework_resource_resource_service = __MODULE__.Import("framework.resource.resource_service", __module) +local ResourceService = M__framework_resource_resource_service.ResourceService +local M__framework_storage_local_save = __MODULE__.Import("framework.storage.local_save", __module) +local LocalSaveManager = M__framework_storage_local_save.LocalSaveManager +local M__framework_storage_storage_backend = __MODULE__.Import("framework.storage.storage_backend", __module) +local MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend +local M__framework_ui_ui_config = __MODULE__.Import("framework.ui.ui_config", __module) +local RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig +local M__framework_ui_ui_delegate_bridge = __MODULE__.Import("framework.ui.ui_delegate_bridge", __module) +local UIDelegateBridge = M__framework_ui_ui_delegate_bridge.UIDelegateBridge +local M__framework_ui_ui_manager = __MODULE__.Import("framework.ui.ui_manager", __module) +local UIManager = M__framework_ui_ui_manager.UIManager +local M__framework_ui_ui_window = __MODULE__.Import("framework.ui.ui_window", __module) +local UIWindow = M__framework_ui_ui_window.UIWindow +local M__game_setting_mini_settings_window = __MODULE__.Import("game.setting.mini_settings_window", __module) +local MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow +local M__game_setting_setting_service = __MODULE__.Import("game.setting.setting_service", __module) +local SettingService = M__game_setting_setting_service.SettingService +local M__tests_harness_test_runner = __MODULE__.Import("tests.harness.test_runner", __module) +local Assert = M__tests_harness_test_runner.Assert +local AssertEqual = M__tests_harness_test_runner.AssertEqual +local MockResourceBackend = __TS__DefineClass("MockResourceBackend", __module) +MockResourceBackend.name = "MockResourceBackend" +function MockResourceBackend.prototype.____constructor(self) + self.nextReqId = 0 + self.pending = {} + self.refCounts = {} + self.loadRequestsCount = 0 +end +function MockResourceBackend.prototype.ResolveAssetPath(self, keyOrPath) + return BASE_ASSET_PATHS[keyOrPath] or keyOrPath +end +function MockResourceBackend.prototype.DoesAssetExist(self, keyOrPath) + local resolved = self:ResolveAssetPath(keyOrPath) + return resolved ~= "/Game/Missing/BadAsset" +end +function MockResourceBackend.prototype.IsPackagedMode(self) + return false +end +function MockResourceBackend.prototype.RequestLoadObjectAsync(self, keyOrPath, worldGen) + self.nextReqId = self.nextReqId + 1 + self.loadRequestsCount = self.loadRequestsCount + 1 + self.pending[self.nextReqId] = {keyOrPath = keyOrPath, worldGen = worldGen, isClass = false} + return self.nextReqId +end +function MockResourceBackend.prototype.RequestLoadClassAsync(self, keyOrPath, worldGen) + self.nextReqId = self.nextReqId + 1 + self.loadRequestsCount = self.loadRequestsCount + 1 + self.pending[self.nextReqId] = {keyOrPath = keyOrPath, worldGen = worldGen, isClass = true} + return self.nextReqId +end +function MockResourceBackend.prototype.FlushAll(self) + local ids = {} + for id in pairs(self.pending) do + ids[#ids + 1] = id + end + table.sort(ids) + do + local i = 0 + while i < #ids do + local id = ids[i + 1] + local req = self.pending[id] + if req ~= nil then + self.pending[id] = nil + local resolved = self:ResolveAssetPath(req.keyOrPath) + local exists = self:DoesAssetExist(req.keyOrPath) + if exists then + self.refCounts[resolved] = (self.refCounts[resolved] or 0) + 1 + local ____opt_0 = self.service + if ____opt_0 ~= nil then + ____opt_0:HandleNativeLoadComplete( + id, + true, + {mockAsset = resolved}, + resolved, + "" + ) + end + else + local ____opt_2 = self.service + if ____opt_2 ~= nil then + ____opt_2:HandleNativeLoadComplete( + id, + false, + nil, + resolved, + "Asset not found" + ) + end + end + end + i = i + 1 + end + end +end +function MockResourceBackend.prototype.CancelRequest(self, requestId) + if self.pending[requestId] == nil then + return false + end + self.pending[requestId] = nil + return true +end +function MockResourceBackend.prototype.CancelRequestsForWorld(self, worldGen) + local count = 0 + for id, req in pairs(self.pending) do + if req ~= nil and req.worldGen == worldGen then + self.pending[id] = nil + count = count + 1 + end + end + return count +end +function MockResourceBackend.prototype.ReleaseAsset(self, resolvedSoftPath) + local cur = self.refCounts[resolvedSoftPath] or 0 + if cur <= 1 then + self.refCounts[resolvedSoftPath] = nil + else + self.refCounts[resolvedSoftPath] = cur - 1 + end +end +function MockResourceBackend.prototype.GetResourceStats(self) + local inFlight = 0 + for _, v in pairs(self.pending) do + if v ~= nil then + inFlight = inFlight + 1 + end + end + local retained = 0 + local totalRefs = 0 + for _, refs in pairs(self.refCounts) do + if refs ~= nil and refs > 0 then + retained = retained + 1 + totalRefs = totalRefs + refs + end + end + return inFlight, retained, totalRefs +end +local MockButtonBackend = __TS__DefineClass("MockButtonBackend", __module) +MockButtonBackend.name = "MockButtonBackend" +function MockButtonBackend.prototype.____constructor(self) + self.nextId = 0 + self.buttonToIds = {} + self.idToButton = {} +end +function MockButtonBackend.prototype.BindButtonClicked(self, button) + self.nextId = self.nextId + 1 + local id = self.nextId + self.idToButton[id] = button + local list = self.buttonToIds[button] + if list == nil then + list = {} + self.buttonToIds[button] = list + end + list[#list + 1] = id + return id +end +function MockButtonBackend.prototype.UnbindButtonClicked(self, bindingId) + local btn = self.idToButton[bindingId] + if btn == nil then + return false + end + self.idToButton[bindingId] = nil + local list = self.buttonToIds[btn] + if list ~= nil then + do + local i = #list - 1 + while i >= 0 do + if list[i + 1] == bindingId then + table.remove(list, i + 1) + end + i = i - 1 + end + end + end + return true +end +function MockButtonBackend.prototype.Click(self, button) + local list = self.buttonToIds[button] + if list == nil then + return + end + local snapshot = {} + do + local i = 0 + while i < #list do + snapshot[i + 1] = list[i + 1] + i = i + 1 + end + end + do + local i = 0 + while i < #snapshot do + local ____opt_4 = self.bridge + if ____opt_4 ~= nil then + ____opt_4:DispatchButtonClicked(snapshot[i + 1]) + end + i = i + 1 + end + end +end +function MockButtonBackend.prototype.GetActiveBindingCount(self) + local count = 0 + for _, btn in pairs(self.idToButton) do + if btn ~= nil then + count = count + 1 + end + end + return count +end +local MockWidgetFactory = __TS__DefineClass("MockWidgetFactory", __module) +MockWidgetFactory.name = "MockWidgetFactory" +function MockWidgetFactory.prototype.____constructor(self) + self.createdCount = 0 +end +function MockWidgetFactory.prototype.CreateWidget(self) + self.createdCount = self.createdCount + 1 + local txtStatus = { + text = "", + SetText = function(self, t) + self.text = t + end + } + local txtToggleLabel = { + text = "", + SetText = function(self, t) + self.text = t + end + } + local imgIcon = { + texture = nil, + SetBrushFromTexture = function(self, tex) + self.texture = tex + end + } + return { + valid = true, + inViewport = false, + visible = false, + zOrder = 0, + children = { + ImgIcon = imgIcon, + TxtStatus = txtStatus, + BtnToggle = {name = "BtnToggle"}, + TxtToggleLabel = txtToggleLabel, + BtnClose = {name = "BtnClose"} + } + } +end +local MockWidgetAdapter = __TS__DefineClass("MockWidgetAdapter", __module) +MockWidgetAdapter.name = "MockWidgetAdapter" +function MockWidgetAdapter.prototype.____constructor(self) +end +function MockWidgetAdapter.prototype.FindChild(self, widget, name) + return widget.children[name] +end +function MockWidgetAdapter.prototype.AddToViewport(self, widget, zOrder) + widget.inViewport = true + widget.zOrder = zOrder +end +function MockWidgetAdapter.prototype.RemoveFromParent(self, widget) + widget.inViewport = false +end +function MockWidgetAdapter.prototype.SetVisible(self, widget, visible) + widget.visible = visible +end +function MockWidgetAdapter.prototype.IsWidgetValid(self, widget) + return widget ~= nil and widget.valid +end +local CachedTestWindow = __TS__DefineClass("CachedTestWindow", __module) +CachedTestWindow.name = "CachedTestWindow" +__TS__ClassExtends(CachedTestWindow, UIWindow) +function CachedTestWindow.prototype.____constructor(self, ...) + UIWindow.prototype.____constructor(self, ...) + self.reuseCount = 0 + self.clickCount = 0 +end +function CachedTestWindow.prototype.OnBindWidgets(self) + self.btn = self:RequireWidget("BtnToggle") + self:BindButtonClick( + self.btn, + function() + self.clickCount = self.clickCount + 1 + end + ) +end +function CachedTestWindow.prototype.OnReuseUI(self) + self.reuseCount = self.reuseCount + 1 +end +RegisterUIConfig(CachedTestWindow, { + name = "CachedTestWindow", + assetKey = ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton = true, + layer = "normal", + cacheTag = "cache" +}) +function ____exports.CreateUIAndResourceSuite() + return { + name = "Step2B_3.UIAndResource", + cases = { + { + name = "MiniSettingsWindow full lifecycle: open, load icon, click once, persist, close, reopen, zero leaks", + fn = function() + local ctx = __TS__New(GameInstanceContext) + local storageBackend = __TS__New(MemoryStorageBackend) + local saveMgr = __TS__New(LocalSaveManager, storageBackend, ctx.scheduler) + local settingSvc = __TS__New(SettingService, saveMgr, "ui_test") + local resBackend = __TS__New(MockResourceBackend) + local resSvc = __TS__New(ResourceService, ctx, resBackend) + resBackend.service = resSvc + local btnBackend = __TS__New(MockButtonBackend) + local btnBridge = __TS__New(UIDelegateBridge, ctx, btnBackend) + btnBackend.bridge = btnBridge + ctx:RegisterService("saveManager", saveMgr) + ctx:RegisterService("setting", settingSvc) + ctx:RegisterService("resource", resSvc) + ctx:RegisterService("uiDelegateBridge", btnBridge) + local widgetFactory = __TS__New(MockWidgetFactory) + local lp = ctx:GetOrCreateLocalPlayer(0) + local uiMgr = lp:RegisterService( + "uiManager", + __TS__New( + UIManager, + ctx, + lp, + resSvc, + widgetFactory, + __TS__New(MockWidgetAdapter) + ) + ) + local w1 = uiMgr:ShowUI(MiniSettingsWindow) + local w2 = uiMgr:ShowUI(MiniSettingsWindow) + AssertEqual(w1, w2, "concurrent singleton returns same controller") + resBackend:FlushAll() + resBackend:FlushAll() + AssertEqual(widgetFactory.createdCount, 1, "only 1 widget created") + Assert(w1 ~= nil and w1.iconLoaded, "icon loaded") + AssertEqual(w1.txtStatus.text, "Sound: ON") + AssertEqual( + uiMgr:GetDiagnostics().inputMode, + "ui" + ) + btnBackend:Click(w1.btnToggle) + AssertEqual(w1.toggleClickCount, 1, "toggle click fired once") + AssertEqual( + settingSvc:GetSoundEnabled(), + false + ) + AssertEqual(w1.txtStatus.text, "Sound: OFF") + ctx:Tick(0.12) + AssertEqual(storageBackend.writeCount, 1) + btnBackend:Click(w1.btnClose) + w1:Close() + Assert( + w1:IsDisposed(), + "window disposed" + ) + AssertEqual( + btnBackend:GetActiveBindingCount(), + 0, + "button bindings back to 0" + ) + AssertEqual( + uiMgr:GetDiagnostics().openWindows, + 0 + ) + AssertEqual( + uiMgr:GetDiagnostics().inputMode, + "game", + "focus restored to game" + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0, + "resource refs back to 0" + ) + local w3 = uiMgr:ShowUI(MiniSettingsWindow) + resBackend:FlushAll() + resBackend:FlushAll() + AssertEqual(w3.txtStatus.text, "Sound: OFF", "reopened window reflects persisted setting") + ctx:Dispose() + AssertEqual( + btnBackend:GetActiveBindingCount(), + 0 + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0 + ) + end + }, + { + name = "Close while loading cancels request and cached window reuse does not duplicate clicks", + fn = function() + local ctx = __TS__New(GameInstanceContext) + local resBackend = __TS__New(MockResourceBackend) + local resSvc = __TS__New(ResourceService, ctx, resBackend) + resBackend.service = resSvc + local btnBackend = __TS__New(MockButtonBackend) + local btnBridge = __TS__New(UIDelegateBridge, ctx, btnBackend) + btnBackend.bridge = btnBridge + ctx:RegisterService("resource", resSvc) + ctx:RegisterService("uiDelegateBridge", btnBridge) + local widgetFactory = __TS__New(MockWidgetFactory) + local lp = ctx:GetOrCreateLocalPlayer(0) + local uiMgr = lp:RegisterService( + "uiManager", + __TS__New( + UIManager, + ctx, + lp, + resSvc, + widgetFactory, + __TS__New(MockWidgetAdapter) + ) + ) + local loadingWin = uiMgr:ShowUI(CachedTestWindow) + loadingWin:Close() + resBackend:FlushAll() + AssertEqual(widgetFactory.createdCount, 0, "cancelled load never creates widget") + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0 + ) + local win = uiMgr:ShowUI(CachedTestWindow) + resBackend:FlushAll() + AssertEqual(widgetFactory.createdCount, 1) + btnBackend:Click(win.btn) + AssertEqual(win.clickCount, 1) + win:Close() + AssertEqual( + uiMgr:GetDiagnostics().cachedWindows, + 1, + "window moved to cache" + ) + AssertEqual( + btnBackend:GetActiveBindingCount(), + 0, + "cached window unbound buttons" + ) + local reused = uiMgr:ShowUI(CachedTestWindow) + AssertEqual(reused, win, "reused cached controller") + AssertEqual(widgetFactory.createdCount, 1, "no second widget instantiated") + AssertEqual(reused.reuseCount, 1) + btnBackend:Click(reused.btn) + AssertEqual(reused.clickCount, 2, "single click after reuse increments by exactly 1") + uiMgr:CloseAll(true) + AssertEqual( + uiMgr:GetDiagnostics().cachedWindows, + 0 + ) + AssertEqual( + btnBackend:GetActiveBindingCount(), + 0 + ) + AssertEqual( + resSvc:GetDiagnostics().nativeTotalRefCount, + 0 + ) + ctx:Dispose() + end + } + } + } +end +function __module.UpdateImports() + GameInstanceContext = M__framework_context_game_context.GameInstanceContext + ASSET_KEYS = M__framework_resource_asset_catalog.ASSET_KEYS + BASE_ASSET_PATHS = M__framework_resource_asset_catalog.BASE_ASSET_PATHS + ResourceService = M__framework_resource_resource_service.ResourceService + LocalSaveManager = M__framework_storage_local_save.LocalSaveManager + MemoryStorageBackend = M__framework_storage_storage_backend.MemoryStorageBackend + RegisterUIConfig = M__framework_ui_ui_config.RegisterUIConfig + UIDelegateBridge = M__framework_ui_ui_delegate_bridge.UIDelegateBridge + UIManager = M__framework_ui_ui_manager.UIManager + UIWindow = M__framework_ui_ui_window.UIWindow + MiniSettingsWindow = M__game_setting_mini_settings_window.MiniSettingsWindow + SettingService = M__game_setting_setting_service.SettingService + Assert = M__tests_harness_test_runner.Assert + AssertEqual = M__tests_harness_test_runner.AssertEqual +end diff --git a/Script/ts/package-lock.json b/Script/ts/package-lock.json index bb53aa8..ae64c0f 100644 --- a/Script/ts/package-lock.json +++ b/Script/ts/package-lock.json @@ -8,7 +8,7 @@ "name": "unreal-lua-demo-ts", "version": "1.0.0", "devDependencies": { - "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.3.0" + "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.3.1" } }, "node_modules/@typescript-to-lua/language-extensions": { @@ -175,8 +175,8 @@ } }, "node_modules/ts2lua-unreal": { - "version": "0.3.0", - "resolved": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#b1a53d8660061dc51dabe5fc5ea0038d8d25a343", + "version": "0.3.1", + "resolved": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#1e2a0b7546aa8e429bd44ce5b174bdf75a57bc52", "dev": true, "dependencies": { "lua-types": "^2.14.1", diff --git a/Script/ts/package.json b/Script/ts/package.json index fb1a185..8baf27b 100644 --- a/Script/ts/package.json +++ b/Script/ts/package.json @@ -6,11 +6,11 @@ "scripts": { "build": "ts2lua-unreal build", "watch": "ts2lua-unreal watch", - "test": "npm run build && node scripts/run-tests.mjs", - "test:ue": "npm run build && /Applications/Unreal5/UE_5.8/Engine/Binaries/Mac/UnrealEditor-Cmd \"$(pwd)/../../UnrealLuaDemo.uproject\" -run=RunLuaTests -unattended -nop4 -nosplash -NullRHI", + "test": "npm run build && node scripts/run-unit-tests.mjs", + "test:ue": "npm run build && /Applications/Unreal5/UE_5.8/Engine/Binaries/Mac/UnrealEditor-Cmd \"$(pwd)/../../UnrealLuaDemo.uproject\" -run=RunLuaFrameworkTests -unattended -nop4 -nosplash -NullRHI", "info": "ts2lua-unreal info" }, "devDependencies": { - "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.3.0" + "ts2lua-unreal": "git+ssh://git@106.55.3.105:20022/szy73711/ts2lua-unreal.git#v0.3.1" } } diff --git a/Script/ts/scripts/run-tests.mjs b/Script/ts/scripts/run-unit-tests.mjs similarity index 71% rename from Script/ts/scripts/run-tests.mjs rename to Script/ts/scripts/run-unit-tests.mjs index bf1bfba..d70067b 100644 --- a/Script/ts/scripts/run-tests.mjs +++ b/Script/ts/scripts/run-unit-tests.mjs @@ -11,7 +11,7 @@ const luaBin = ["lua5.4", "lua"].find((cmd) => { }); if (!luaBin) { - console.error("[run-tests] Lua 5.4 interpreter (lua5.4 / lua) not found in PATH."); + console.error("[run-unit-tests] Lua 5.4 interpreter (lua5.4 / lua) not found in PATH."); process.exit(1); } @@ -25,11 +25,13 @@ const luaPath = [ const code = ` package.path = ${JSON.stringify(luaPath)} .. ";" .. package.path -require("Lib.Module") -require("Lib.Class") -__MODULE__.Import("Tests.Harness.MockUnLuaRuntime").InstallIfNeeded() -_G.__TS2LUA_TEST_AUTO_RUN__ = true -__MODULE__.Import("Tests.RunAllTests") +require("lib.module") +require("lib.class") +local runner = __MODULE__.Import("tests.run_unit_tests") +local summary = runner.RunAllUnitTests() +if not summary or (summary.total or 0) <= 0 or (summary.failed or 0) > 0 then + os.exit(1) +end `; const result = spawnSync(luaBin, ["-e", code], { diff --git a/Script/ts/src/Framework/Bootstrap.ts b/Script/ts/src/Framework/Bootstrap.ts deleted file mode 100644 index 22a614d..0000000 --- a/Script/ts/src/Framework/Bootstrap.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** @noSelfInFile */ - -import * as Log from "./Log"; -import * as EventBus from "./EventBus"; -import * as HotReload from "./HotReload"; - -export const Version = "0.2.0"; - -/** @module_data */ -export let IsInitialized = false; - -/** @module_data */ -export let GameInstance: UE.ULuaGameInstance | undefined = undefined; - -export function Init(gameInstance: UE.ULuaGameInstance): void { - GameInstance = gameInstance; - IsInitialized = true; - - _G.GameFramework = { - Log, - EventBus, - HotReload, - Bootstrap: { - Version, - Init, - Shutdown, - }, - GameInstance: gameInstance, - }; - - Log.Info("Lua GameFramework initialized (version=%s, Lua=%s)", Version, _VERSION); -} - -export function Shutdown(): void { - Log.Info("Lua GameFramework shutting down..."); - EventBus.Clear(); - GameInstance = undefined; - IsInitialized = false; - _G.GameFramework = undefined; -} diff --git a/Script/ts/src/Framework/EventBus.ts b/Script/ts/src/Framework/EventBus.ts deleted file mode 100644 index b9a33b5..0000000 --- a/Script/ts/src/Framework/EventBus.ts +++ /dev/null @@ -1,121 +0,0 @@ -/** @noSelfInFile */ - -type RawEventCallback = (this: any, ...args: any[]) => void; - -interface EventEntry { - callback: RawEventCallback; - owner?: unknown; -} - -/** @module_data */ -let Listeners: Record = {}; - -export function On( - eventName: string, - callback: (this: TOwner, ...args: any[]) => void, - owner: TOwner -): void; -export function On( - eventName: string, - callback: (this: void, ...args: any[]) => void -): void; -export function On( - eventName: string, - callback: RawEventCallback, - owner?: unknown -): void { - assert(type(eventName) === "string", "EventBus.On: eventName must be a string"); - assert(type(callback) === "function", "EventBus.On: callback must be a function"); - - let list = Listeners[eventName]; - if (!list) { - list = []; - Listeners[eventName] = list; - } - - for (let i = 0; i < list.length; i++) { - const entry = list[i]; - if (entry.callback === callback && entry.owner === owner) { - return; - } - } - - list[list.length] = { - callback, - owner, - }; -} - -export function Off( - eventName: string, - callback: (this: TOwner, ...args: any[]) => void, - owner: TOwner -): void; -export function Off( - eventName: string, - callback: (this: void, ...args: any[]) => void -): void; -export function Off( - eventName: string, - callback: RawEventCallback, - owner?: unknown -): void { - const list = Listeners[eventName]; - if (!list) { - return; - } - - for (let i = list.length - 1; i >= 0; i--) { - const entry = list[i]; - if (entry.callback === callback && (owner === undefined || entry.owner === owner)) { - table.remove(list, i + 1); - } - } -} - -export function OffAllForOwner(owner: unknown): void { - if (owner === undefined) { - return; - } - - for (const [_, list] of pairs(Listeners)) { - if (list !== undefined) { - for (let i = list.length - 1; i >= 0; i--) { - if (list[i].owner === owner) { - table.remove(list, i + 1); - } - } - } - } -} - -export function Emit(eventName: string, ...args: unknown[]): void { - const list = Listeners[eventName]; - if (!list) { - return; - } - - // Snapshot to allow listeners to unsubscribe during dispatch - const snapshot: EventEntry[] = []; - for (let i = 0; i < list.length; i++) { - snapshot[i] = list[i]; - } - - for (let i = 0; i < snapshot.length; i++) { - const entry = snapshot[i]; - let ok: boolean; - let err: unknown; - if (entry.owner !== undefined) { - [ok, err] = pcall(entry.callback as unknown as (this: any, ...args: any[]) => void, entry.owner, ...args); - } else { - [ok, err] = pcall(entry.callback as unknown as (this: void, ...args: any[]) => void, ...args); - } - if (!ok) { - print(string.format("[UnrealLuaDemo][ERROR] EventBus(%s): %s", eventName, tostring(err))); - } - } -} - -export function Clear(): void { - Listeners = {}; -} diff --git a/Script/ts/src/Framework/HotReload.ts b/Script/ts/src/Framework/HotReload.ts deleted file mode 100644 index 12d1632..0000000 --- a/Script/ts/src/Framework/HotReload.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** @noSelfInFile */ - -import * as Log from "./Log"; -import * as EventBus from "./EventBus"; - -export const EVENT_BEFORE_RELOAD = "Framework.BeforeHotReload"; -export const EVENT_AFTER_RELOAD = "Framework.AfterHotReload"; - -function CollectLoadedHotReloadModules(): string[] { - const modules: string[] = []; - if (__MODULE__ === undefined) { - return modules; - } - for (const [name] of pairs(__MODULE__.AllLoadedModules())) { - if ( - type(name) === "string" && - name !== "Framework.HotReload" && - (string.match(name as string, "^Game%.")[0] !== undefined || - string.match(name as string, "^Framework%.")[0] !== undefined) - ) { - modules[modules.length] = name as string; - } - } - table.sort(modules); - return modules; -} - -/** - * 单文件热更指定模块(完全基于 Lib/Module.lua 的 __MODULE__.ReimportSafely,零入侵 UnLua)。 - */ -export function ReloadModule(moduleName: string): LuaMultiReturn<[boolean, unknown?]> { - if (type(moduleName) !== "string" || moduleName === "") { - return $multi(false, "Invalid module name"); - } - - if (__MODULE__ === undefined) { - return $multi(false, "__MODULE__ runtime is not initialized"); - } - - if (__MODULE__.GetModuleByName(moduleName) === undefined) { - Log.Warn("Module '%s' is not loaded yet, skipping hot-reload.", moduleName); - return $multi(false, "Module not loaded: " + moduleName); - } - - Log.Info("Hot-reloading module via __MODULE__: %s", moduleName); - EventBus.Emit(EVENT_BEFORE_RELOAD, moduleName); - - const [ok, err] = __MODULE__.ReimportSafely(moduleName); - if (!ok) { - Log.Error("__MODULE__.ReimportSafely('%s') failed: %s", moduleName, tostring(err)); - return $multi(false, err); - } - - EventBus.Emit(EVENT_AFTER_RELOAD, moduleName); - Log.Info("Successfully hot-reloaded module: %s", moduleName); - return $multi(true); -} - -/** - * 批量热更所有已加载的业务/框架模块(Game.* / Framework.*)。 - */ -export function ReloadAll(): boolean { - const managedModules = CollectLoadedHotReloadModules(); - Log.Info("Triggering HotReload via __MODULE__ (modules=%d)...", managedModules.length); - EventBus.Emit(EVENT_BEFORE_RELOAD, "*"); - - let allOk = true; - for (let i = 0; i < managedModules.length; i++) { - const modName = managedModules[i]; - const [ok, err] = __MODULE__.ReimportSafely(modName); - if (!ok) { - Log.Error("__MODULE__.ReimportSafely('%s') failed: %s", modName, tostring(err)); - allOk = false; - } - } - - EventBus.Emit(EVENT_AFTER_RELOAD, "*"); - Log.Info("HotReload completed (ok=%s).", tostring(allOk)); - return allOk; -} diff --git a/Script/ts/src/Framework/Log.ts b/Script/ts/src/Framework/Log.ts deleted file mode 100644 index c0a4315..0000000 --- a/Script/ts/src/Framework/Log.ts +++ /dev/null @@ -1,27 +0,0 @@ -/** @noSelfInFile */ - -const TAG = "[UnrealLuaDemo]"; - -function FormatMessage(level: string, fmt: unknown, ...args: unknown[]): string { - const fmtStr = tostring(fmt); - let msg: string; - if (args.length > 0) { - const [ok, formatted] = pcall(string.format, fmtStr, ...args); - msg = ok ? (formatted as string) : fmtStr; - } else { - msg = fmtStr; - } - return string.format("%s[%s] %s", TAG, level, msg); -} - -export function Info(fmt: unknown, ...args: unknown[]): void { - print(FormatMessage("INFO", fmt, ...args)); -} - -export function Warn(fmt: unknown, ...args: unknown[]): void { - print(FormatMessage("WARN", fmt, ...args)); -} - -export function Error(fmt: unknown, ...args: unknown[]): void { - print(FormatMessage("ERROR", fmt, ...args)); -} diff --git a/Script/ts/src/Game/LuaCharacter.ts b/Script/ts/src/Game/LuaCharacter.ts deleted file mode 100644 index 33fbedf..0000000 --- a/Script/ts/src/Game/LuaCharacter.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** @noSelfInFile */ - -import * as Log from "../Framework/Log"; - -export function OnBeginPlay(_character: UE.ALuaCharacter): void { - Log.Info("LuaCharacter.OnBeginPlay()"); -} - -export function OnEndPlay(_character: UE.ALuaCharacter, endPlayReason: number): void { - Log.Info("LuaCharacter.OnEndPlay(reason=%s)", tostring(endPlayReason)); -} diff --git a/Script/ts/src/Game/LuaDemoActor.ts b/Script/ts/src/Game/LuaDemoActor.ts deleted file mode 100644 index dae558b..0000000 --- a/Script/ts/src/Game/LuaDemoActor.ts +++ /dev/null @@ -1,298 +0,0 @@ -import * as Log from "../Framework/Log"; -import * as EventBus from "../Framework/EventBus"; -import * as HotReload from "../Framework/HotReload"; - -export interface DemoColorEntry { - Name: string; - R: number; - G: number; - B: number; - A: number; -} - -// ============================================================ -// PIE 单文件热更测试参数区(修改此处 -> npm run build -> 触发热更,即时生效) -// ============================================================ -export const DEMO_VERSION = "v1"; -/** 目标旋转速度(度/秒,直接驱动方块自转速度,热更后下一帧立即生效) */ -export const ACTOR_SPIN_SPEED = 60.0; -/** 当前展示配色(热更修改颜色值与名称后,__module.OnReimport 立即刷新方块材质与 3D 文本) */ -export const DEMO_COLORS: DemoColorEntry[] = [ - { Name: "Cyan", R: 0.08, G: 0.78, B: 0.95, A: 1.0 }, - { Name: "Gold", R: 0.98, G: 0.72, B: 0.12, A: 1.0 }, - { Name: "Magenta", R: 0.92, G: 0.22, B: 0.65, A: 1.0 }, - { Name: "Lime", R: 0.25, G: 0.9, B: 0.35, A: 1.0 }, - { Name: "Orange", R: 0.98, G: 0.42, B: 0.14, A: 1.0 }, -]; - -/** @noSelf */ -function MakeLinearColor(c: DemoColorEntry): UE.FLinearColor { - return UE.FLinearColor(c.R, c.G, c.B, c.A); -} - -/** @noSelf */ -function IsActorAlive(actor: UE.ALuaDemoActor | undefined): boolean { - if (actor === undefined) { - return false; - } - if (UE !== undefined && UE.UKismetSystemLibrary !== undefined && UE.UKismetSystemLibrary.IsValid !== undefined) { - return UE.UKismetSystemLibrary.IsValid(actor); - } - return true; -} - -/** - * 纯 TS 组合控制器(不继承 UE 对象、不使用 @unlua): - * 组合持有 `UE.ALuaDemoActor` 引用,由 `Lib/Class.lua` 的 `__TS__DefineClass` 托管原型表, - * 支持单文件热更 `Game.LuaDemoActor` 时在运行中实例上原地更新旋转速度、颜色与全部方法逻辑。 - */ -export class DemoActorController { - private actor: UE.ALuaDemoActor; - private elapsedTime = 0.0; - private textRefreshTimer = 0.0; - private tickCount = 0; - private pingCount = 0; - private reloadCount = 0; - private colorIndex = 0; - private hasLoggedTick = false; - private _tmpDeltaRot: UE.FRotator; - - constructor(actor: UE.ALuaDemoActor) { - this.actor = actor; - this._tmpDeltaRot = UE.FRotator(0.0, 0.0, 0.0); - } - - IsValid(): boolean { - return IsActorAlive(this.actor); - } - - GetSpinSpeed(): number { - return ACTOR_SPIN_SPEED; - } - - GetCurrentColor(): DemoColorEntry { - return DEMO_COLORS[this.colorIndex] ?? DEMO_COLORS[0]; - } - - OnBeginPlay(): void { - EventBus.On("Demo.Ping", this.OnDemoPing, this); - EventBus.On(HotReload.EVENT_AFTER_RELOAD, this.OnAfterHotReload, this); - - this.ApplyCurrentColor(); - this.RefreshStatusText(); - - Log.Info( - "LuaDemoActor.OnBeginPlay() ready! version=%s speed=%.1f color=%s Lua=%s", - DEMO_VERSION, - this.GetSpinSpeed(), - this.GetCurrentColor().Name, - _VERSION - ); - - const msg = string.format( - "[UnLua Demo] Pure-TS Actor active (%s | Speed=%.0f | Color=%s) - [Space] Ping, [R] HotReload", - DEMO_VERSION, - this.GetSpinSpeed(), - this.GetCurrentColor().Name - ); - UE.UKismetSystemLibrary.PrintString( - this.actor, - msg, - true, - true, - UE.FLinearColor(0.2, 1.0, 0.4, 1.0), - 8.0 - ); - } - - OnTick(deltaSeconds: number): void { - this.elapsedTime = this.elapsedTime + deltaSeconds; - this.tickCount = this.tickCount + 1; - - if (!this.hasLoggedTick) { - this.hasLoggedTick = true; - Log.Info("LuaDemoActor.OnTick() first tick verified (dt=%.4f, speed=%.1f)", deltaSeconds, this.GetSpinSpeed()); - } - - const yawDelta = this.GetSpinSpeed() * deltaSeconds; - const pitchDelta = yawDelta * 0.35; - this._tmpDeltaRot.Pitch = pitchDelta; - this._tmpDeltaRot.Yaw = yawDelta; - this._tmpDeltaRot.Roll = 0.0; - this.actor.AddCubeLocalRotation(this._tmpDeltaRot); - - const zOffset = math.sin(this.elapsedTime * (this.actor.BobFrequency ?? 2.0)) * (this.actor.BobAmplitude ?? 25.0); - this.actor.SetCubeVerticalOffset(zOffset); - - this.textRefreshTimer = this.textRefreshTimer + deltaSeconds; - if (this.textRefreshTimer >= 0.2) { - this.textRefreshTimer = 0.0; - this.RefreshStatusText(); - } - } - - OnDemoPing(sourceName: unknown): void { - this.pingCount = this.pingCount + 1; - globalPingCount = globalPingCount + 1; - this.colorIndex = (this.colorIndex + 1) % DEMO_COLORS.length; - const colorEntry = this.ApplyCurrentColor(); - this.RefreshStatusText(); - - const msg = string.format( - "[UnLua Demo] Ping #%d from %s -> Cube color: %s (Speed=%.0f)", - this.pingCount, - tostring(sourceName), - colorEntry.Name, - this.GetSpinSpeed() - ); - Log.Info(msg); - UE.UKismetSystemLibrary.PrintString(this.actor, msg, true, true, MakeLinearColor(colorEntry), 3.0); - } - - OnAfterHotReload(moduleName: unknown): void { - this.reloadCount = this.reloadCount + 1; - globalReloadCount = globalReloadCount + 1; - this.ApplyCurrentColor(); - this.RefreshStatusText(); - - const msg = string.format( - "[UnLua Demo] HotReload #%d applied! target=%s | version=%s | Speed=%.0f | Color=%s", - this.reloadCount, - tostring(moduleName), - DEMO_VERSION, - this.GetSpinSpeed(), - this.GetCurrentColor().Name - ); - Log.Info(msg); - UE.UKismetSystemLibrary.PrintString( - this.actor, - msg, - true, - true, - UE.FLinearColor(1.0, 0.85, 0.2, 1.0), - 4.0 - ); - } - - ResetToPrimaryColor(): void { - this.colorIndex = 0; - } - - ApplyCurrentColor(): DemoColorEntry { - const colorEntry = this.GetCurrentColor(); - this.actor.SetCubeColor(MakeLinearColor(colorEntry)); - return colorEntry; - } - - RefreshStatusText(): void { - const colorEntry = this.GetCurrentColor(); - const text = string.format( - "Pure-TS Actor (%s | %s)\nSpeed: %.0f deg/s | Color: %s\nTime: %.1fs | Pings: %d | Reloads: %d\n[Space] Ping | [R] HotReload", - _VERSION, - DEMO_VERSION, - this.GetSpinSpeed(), - colorEntry.Name, - this.elapsedTime, - this.pingCount, - this.reloadCount - ); - this.actor.SetStatusText(text); - } - - OnEndPlay(_endPlayReason: number): void { - EventBus.OffAllForOwner(this); - Log.Info("LuaDemoActor.OnEndPlay(ticks=%d, pings=%d)", this.tickCount, this.pingCount); - } -} - -/** 跨热更保留的运行中控制器映射表(key = actor:GetName()) */ -/** @module_data */ -const activeControllers: Record = {}; - -/** @module_data */ -let globalPingCount = 0; - -/** @module_data */ -let globalReloadCount = 0; - -/** @noSelf */ -function GetActorKey(actor: UE.ALuaDemoActor): string { - if (actor.GetName !== undefined) { - return actor.GetName(); - } - return tostring(actor); -} - -/** @noSelf */ -export function OnBeginPlay(actor: UE.ALuaDemoActor): void { - const key = GetActorKey(actor); - const old = activeControllers[key]; - if (old !== undefined) { - old.OnEndPlay(0); - } - const ctrl = new DemoActorController(actor); - activeControllers[key] = ctrl; - ctrl.OnBeginPlay(); -} - -/** @noSelf */ -export function OnTick(actor: UE.ALuaDemoActor, deltaSeconds: number): void { - const ctrl = activeControllers[GetActorKey(actor)]; - if (ctrl !== undefined) { - ctrl.OnTick(deltaSeconds); - } -} - -/** @noSelf */ -export function OnEndPlay(actor: UE.ALuaDemoActor, endPlayReason: number): void { - const key = GetActorKey(actor); - const ctrl = activeControllers[key]; - if (ctrl !== undefined) { - ctrl.OnEndPlay(endPlayReason); - activeControllers[key] = undefined; - } -} - -/** @noSelf */ -export function GetGlobalStats(): { pings: number; reloads: number; version: string; spinSpeed: number; primaryColor: string } { - return { - pings: globalPingCount, - reloads: globalReloadCount, - version: DEMO_VERSION, - spinSpeed: ACTOR_SPIN_SPEED, - primaryColor: DEMO_COLORS[0].Name, - }; -} - -/** @noSelf */ -export function GetActiveControllerCount(): number { - let count = 0; - for (const [_, ctrl] of pairs(activeControllers)) { - if (ctrl !== undefined) { - count = count + 1; - } - } - return count; -} - -// 模块单文件热更完成后立即将新的颜色、旋转速度与 3D 文本应用到 PIE 中所有活跃 Actor -__module.OnReimport = () => { - for (const [key, ctrl] of pairs(activeControllers)) { - if (ctrl !== undefined) { - if (ctrl.IsValid()) { - ctrl.ResetToPrimaryColor(); - ctrl.ApplyCurrentColor(); - ctrl.RefreshStatusText(); - } else { - activeControllers[key] = undefined; - } - } - } - Log.Info( - "Game.LuaDemoActor OnReimport applied! version=%s speed=%.1f color=%s activeActors=%d", - DEMO_VERSION, - ACTOR_SPIN_SPEED, - DEMO_COLORS[0].Name, - GetActiveControllerCount() - ); -}; diff --git a/Script/ts/src/Game/LuaGameInstance.ts b/Script/ts/src/Game/LuaGameInstance.ts deleted file mode 100644 index 8bf59e6..0000000 --- a/Script/ts/src/Game/LuaGameInstance.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** @noSelfInFile */ - -import * as Bootstrap from "../Framework/Bootstrap"; -import * as Log from "../Framework/Log"; - -export function OnInit(gameInstance: UE.ULuaGameInstance): void { - Bootstrap.Init(gameInstance); - Log.Info("LuaGameInstance.OnInit()"); -} - -export function OnShutdown(_gameInstance: UE.ULuaGameInstance): void { - Log.Info("LuaGameInstance.OnShutdown()"); - Bootstrap.Shutdown(); -} diff --git a/Script/ts/src/Game/LuaGameMode.ts b/Script/ts/src/Game/LuaGameMode.ts deleted file mode 100644 index 11c8400..0000000 --- a/Script/ts/src/Game/LuaGameMode.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** @noSelfInFile */ - -import * as Log from "../Framework/Log"; - -export function OnBeginPlay(gameMode: UE.ALuaGameModeBase): void { - Log.Info("LuaGameMode.OnBeginPlay() - Demo scene started"); - UE.UKismetSystemLibrary.PrintString( - gameMode, - "[UnLua Demo] LuaGameMode initialized (Pure TS Callback Mode)!", - true, - true, - UE.FLinearColor(0.3, 0.85, 1.0, 1.0), - 5.0 - ); -} - -export function OnEndPlay(_gameMode: UE.ALuaGameModeBase, endPlayReason: number): void { - Log.Info("LuaGameMode.OnEndPlay(reason=%s)", tostring(endPlayReason)); -} diff --git a/Script/ts/src/Game/LuaPlayerController.ts b/Script/ts/src/Game/LuaPlayerController.ts deleted file mode 100644 index 02cf8f8..0000000 --- a/Script/ts/src/Game/LuaPlayerController.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** @noSelfInFile */ - -import * as Log from "../Framework/Log"; -import * as EventBus from "../Framework/EventBus"; -import * as HotReload from "../Framework/HotReload"; - -export function OnBeginPlay(_pc: UE.ALuaPlayerController): void { - Log.Info("LuaPlayerController.OnBeginPlay() - Ready for [Space]=Ping, [R]=HotReload"); -} - -export function OnDemoPingPressed(_pc: UE.ALuaPlayerController): void { - Log.Info("LuaPlayerController.OnDemoPingPressed() -> Emitting Demo.Ping"); - EventBus.Emit("Demo.Ping", "LuaPlayerController"); -} - -export function OnDemoHotReloadPressed(_pc: UE.ALuaPlayerController): void { - Log.Info("LuaPlayerController.OnDemoHotReloadPressed() -> Triggering HotReload.ReloadAll()"); - HotReload.ReloadAll(); -} - -export function OnEndPlay(_pc: UE.ALuaPlayerController, endPlayReason: number): void { - Log.Info("LuaPlayerController.OnEndPlay(reason=%s)", tostring(endPlayReason)); -} diff --git a/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts b/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts deleted file mode 100644 index a6df83d..0000000 --- a/Script/ts/src/Tests/Extra/HotReloadAndFrameworkTest.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertTrue, - AssertFalse, - AssertNotNil, - AssertNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; -import { CreateBoundInstance, ResetMockState } from "../Harness/MockUnLuaRuntime"; -import * as Bootstrap from "../../Framework/Bootstrap"; -import * as EventBus from "../../Framework/EventBus"; -import * as HotReload from "../../Framework/HotReload"; -import * as LuaDemoActor from "../../Game/LuaDemoActor"; - -export function RunHotReloadAndFrameworkTests(): void { - Suite("Extra.FrameworkAndHotReload", () => { - Test("EventBus: dedup, owner dispatch, mid-emit unsubscribe, OffAllForOwner and error isolation", () => { - EventBus.Clear(); - const received: string[] = []; - - interface OwnerObj { - tag: string; - OnEvent(this: OwnerObj, msg: string): void; - } - const ownerA: OwnerObj = { - tag: "A", - OnEvent(this: OwnerObj, msg: string) { - received[received.length] = `${this.tag}:${msg}`; - }, - }; - const ownerB: OwnerObj = { - tag: "B", - OnEvent(this: OwnerObj, msg: string) { - received[received.length] = `${this.tag}:${msg}`; - // 在回调执行期间取消自己 - EventBus.Off("Test.Ping", this.OnEvent, this); - }, - }; - - // 重复注册应自动去重 - EventBus.On("Test.Ping", ownerA.OnEvent, ownerA); - EventBus.On("Test.Ping", ownerA.OnEvent, ownerA); - EventBus.On("Test.Ping", ownerB.OnEvent, ownerB); - - // 注册一个会抛错的监听者,验证 EventBus 内 pcall 隔离不影响其他监听者 - EventBus.On("Test.Ping", () => { - error("intentional listener error"); - }); - - let afterErrorCalled = false; - EventBus.On("Test.Ping", () => { - afterErrorCalled = true; - }); - - EventBus.Emit("Test.Ping", "hello"); - AssertArrayEqual(received, ["A:hello", "B:hello"]); - AssertTrue(afterErrorCalled); - - // 第二次 Emit:ownerB 已自退订 - EventBus.Emit("Test.Ping", "world"); - AssertArrayEqual(received, ["A:hello", "B:hello", "A:world"]); - - // OffAllForOwner 清理 ownerA - EventBus.OffAllForOwner(ownerA); - EventBus.Emit("Test.Ping", "ignored"); - AssertArrayEqual(received, ["A:hello", "B:hello", "A:world"]); - - EventBus.Clear(); - }); - - Test("Bootstrap Init/Shutdown lifecycle and _G.GameFramework registration", () => { - const fakeGI = CreateBoundInstance({}, "ULuaGameInstance"); - Bootstrap.Init(fakeGI); - AssertTrue(Bootstrap.IsInitialized); - AssertEqual(Bootstrap.GameInstance, fakeGI); - AssertNotNil(_G.GameFramework); - - Bootstrap.Shutdown(); - AssertFalse(Bootstrap.IsInitialized); - AssertNil(Bootstrap.GameInstance); - AssertNil(_G.GameFramework); - }); - - Test("HotReload.ReloadModule validates arguments and emits Before/After events", () => { - EventBus.Clear(); - const [badOk, badErr] = HotReload.ReloadModule(""); - AssertFalse(badOk); - AssertEqual(badErr, "Invalid module name"); - - const order: string[] = []; - EventBus.On(HotReload.EVENT_BEFORE_RELOAD, (modName: string) => { - order[order.length] = "before:" + modName; - }); - EventBus.On(HotReload.EVENT_AFTER_RELOAD, (modName: string) => { - order[order.length] = "after:" + modName; - }); - - const [ok] = HotReload.ReloadModule("Framework.Log"); - AssertTrue(ok); - AssertArrayEqual(order, ["before:Framework.Log", "after:Framework.Log"]); - EventBus.Clear(); - }); - - Test("LuaDemoActor full integration: pure TS callback BeginPlay, Tick, Ping color cycle, HotReload & EndPlay cleanup", () => { - ResetMockState(); - EventBus.Clear(); - - let lastStatusText = ""; - let colorApplyCount = 0; - let rotationAddCount = 0; - let lastVerticalOffset = 0; - - const fakeActor = CreateBoundInstance( - {}, - "ALuaDemoActor", - { - SpinSpeed: 90, - BobAmplitude: 20, - BobFrequency: 2, - SetStatusText(this: unknown, text: string) { - lastStatusText = text; - }, - SetCubeColor(this: unknown, _color: UE.FLinearColor) { - colorApplyCount++; - }, - AddCubeLocalRotation(this: unknown, _delta: UE.FRotator) { - rotationAddCount++; - }, - SetCubeVerticalOffset(this: unknown, zOffset: number) { - lastVerticalOffset = zOffset; - }, - } - ); - - LuaDemoActor.OnBeginPlay(fakeActor); - AssertEqual(colorApplyCount, 1); - AssertTrue(string.find(lastStatusText, "Pings: 0", 1, true)[0] !== undefined); - AssertTrue(string.find(lastStatusText, "Speed: 60", 1, true)[0] !== undefined); - - LuaDemoActor.OnTick(fakeActor, 0.25); - AssertEqual(rotationAddCount, 1); - AssertTrue(lastVerticalOffset !== 0); - - EventBus.Emit("Demo.Ping", "TestSuite"); - AssertEqual(colorApplyCount, 2); - AssertTrue(string.find(lastStatusText, "Pings: 1", 1, true)[0] !== undefined); - - EventBus.Emit(HotReload.EVENT_AFTER_RELOAD, "Game.LuaDemoActor"); - AssertEqual(colorApplyCount, 3); - AssertTrue(string.find(lastStatusText, "Reloads: 1", 1, true)[0] !== undefined); - - // EndPlay 后不再响应 EventBus - LuaDemoActor.OnEndPlay(fakeActor, UE.EEndPlayReason.Destroyed); - EventBus.Emit("Demo.Ping", "AfterEndPlay"); - AssertEqual(colorApplyCount, 3); - EventBus.Clear(); - }); - }); -} diff --git a/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts b/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts deleted file mode 100644 index 06c132f..0000000 --- a/Script/ts/src/Tests/Extra/LifecycleAndMemoryTest.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertTrue, - AssertFalse, - AssertNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; -import { - AdvanceMockTime, - CreateBoundInstance, - GetMockState, - ResetMockState, -} from "../Harness/MockUnLuaRuntime"; -import * as EventBus from "../../Framework/EventBus"; -import LifecycleSafetyActor from "./LifecycleSafetyActor"; - -export function RunLifecycleAndMemoryTests(): void { - Suite("Extra.LifecycleAndMemorySafety", () => { - Test("multiple @unlua instances maintain isolated state (no shared class-table arrays)", () => { - ResetMockState(); - EventBus.Clear(); - - const cls = LifecycleSafetyActor as unknown as Record; - const a = CreateBoundInstance(cls, "AActor"); - const b = CreateBoundInstance(cls, "AActor"); - - a.ReceiveBeginPlay(); - b.ReceiveBeginPlay(); - - a.PushItem("only_in_a"); - b.PushItem("only_in_b"); - - AssertArrayEqual(a.GetItems(), ["only_in_a"]); - AssertArrayEqual(b.GetItems(), ["only_in_b"]); - - a.ReceiveEndPlay(UE.EEndPlayReason.Destroyed); - b.ReceiveEndPlay(UE.EEndPlayReason.Destroyed); - EventBus.Clear(); - }); - - Test("paired cleanup on ReceiveEndPlay prevents leaked EventBus, Delegate, Timer & manual Ref", () => { - ResetMockState(); - EventBus.Clear(); - - const actor = CreateBoundInstance( - LifecycleSafetyActor as unknown as Record, - "AActor" - ); - const asset = UE.UObject.Load("/Game/Data/DA_Config.DA_Config")!; - const weak = UE.FWeakObjectPtr(actor); - - actor.ReceiveBeginPlay(); - actor.HoldManualRef(asset); - AssertEqual(GetMockState().manualRefs.get(asset as unknown as object), 1); - - EventBus.Emit("Lifecycle.Broadcast", "msg1"); - actor.OnTakeAnyDamage.Broadcast(actor, 25, undefined, undefined, undefined); - AdvanceMockTime(1.0); - AssertEqual(actor.GetReceivedEvents(), 3); - AssertTrue(weak.IsValid()); - - // 触发 EndPlay 与销毁 - actor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed); - actor.K2_DestroyActor(); - - AssertFalse(actor.OnTakeAnyDamage.IsBound()); - AssertFalse(weak.IsValid()); - AssertNil(weak.Get()); - AssertNil(GetMockState().manualRefs.get(asset as unknown as object)); - - // 销毁后再次广播事件/推进时间,计数不应再增长 - EventBus.Emit("Lifecycle.Broadcast", "msg2"); - AdvanceMockTime(3.0); - AssertEqual(actor.GetReceivedEvents(), 3); - EventBus.Clear(); - }); - }); -} diff --git a/Script/ts/src/Tests/Extra/LifecycleSafetyActor.ts b/Script/ts/src/Tests/Extra/LifecycleSafetyActor.ts deleted file mode 100644 index 92b2033..0000000 --- a/Script/ts/src/Tests/Extra/LifecycleSafetyActor.ts +++ /dev/null @@ -1,78 +0,0 @@ -import * as EventBus from "../../Framework/EventBus"; - -/** - * 演示多实例隔离、配对清理(EventBus + Delegate + Timer + UnLua.Ref)与销毁后安全防护的 @unlua Actor。 - */ -@unlua -export default class LifecycleSafetyActor extends UE.AActor { - private items!: string[]; - private receivedEvents!: number; - private timerHandle!: UE.FTimerHandle; - private keptRef!: UE.UObject | undefined; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - // 每个实例独立初始化,严禁类字段初始化导致多实例共享表 - this.items = []; - this.receivedEvents = 0; - - EventBus.On("Lifecycle.Broadcast", this.OnBroadcast, this); - this.OnTakeAnyDamage.Add(this, this.OnDamaged); - this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate( - UnLua.Delegate(this, this.OnHeartbeat), - 1.0, - true - ); - } - - PushItem(item: string): void { - this.items[this.items.length] = item; - } - - GetItems(): string[] { - return this.items; - } - - HoldManualRef(asset: UE.UObject): void { - this.keptRef = asset; - UnLua.Ref(asset); - } - - OnBroadcast(tag: string): void { - if (!UE.UKismetSystemLibrary.IsValid(this)) return; - this.receivedEvents++; - this.items[this.items.length] = tag; - } - - OnDamaged( - _DamagedActor: UE.AActor | undefined, - Damage: number, - _DamageType: UE.UDamageType | undefined, - _InstigatedBy: UE.AController | undefined, - _DamageCauser: UE.AActor | undefined - ): void { - if (!UE.UKismetSystemLibrary.IsValid(this)) return; - this.receivedEvents++; - this.items[this.items.length] = `dmg:${Damage}`; - } - - OnHeartbeat(): void { - if (!UE.UKismetSystemLibrary.IsValid(this)) return; - this.receivedEvents++; - } - - GetReceivedEvents(): number { - return this.receivedEvents; - } - - ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void { - EventBus.OffAllForOwner(this); - this.OnTakeAnyDamage.Remove(this, this.OnDamaged); - UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle); - if (this.keptRef !== undefined) { - UnLua.Unref(this.keptRef); - this.keptRef = undefined; - } - super.ReceiveEndPlay(EndPlayReason); - } -} diff --git a/Script/ts/src/Tests/Extra/Lua54PitfallsTest.ts b/Script/ts/src/Tests/Extra/Lua54PitfallsTest.ts deleted file mode 100644 index 89667cc..0000000 --- a/Script/ts/src/Tests/Extra/Lua54PitfallsTest.ts +++ /dev/null @@ -1,142 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertTrue, - AssertFalse, - AssertNear, - AssertArrayEqual, -} from "../Harness/TestRunner"; - -function EscapeLuaPattern(literal: string): string { - const [escaped] = string.gsub(literal, "([%(%)%.%%%+%-%*%?%[%]%^%$])", "%%%1"); - return escaped; -} - -function DeepCloneTable(src: T, seen?: LuaTable): T { - if (type(src) !== "table") { - return src; - } - const visited = seen ?? new LuaTable(); - const existing = visited.get(src as unknown as object); - if (existing !== undefined) { - return existing as T; - } - const copy: Record = {}; - visited.set(src as unknown as object, copy); - for (const [k, v] of pairs(src as unknown as Record)) { - copy[DeepCloneTable(k, visited)] = DeepCloneTable(v, visited); - } - return copy as T; -} - -export function RunLua54PitfallsTests(): void { - Suite("Extra.Lua54PitfallsAndEdgeCases", () => { - Test("Lua truthiness vs JS: explicit checks for 0 and empty string, ?? vs ||", () => { - const zero = 0; - const empty = ""; - - // 在 Lua 中 0 和 "" 均为 truthy!业务代码必须使用显式比较 - AssertTrue(zero === 0); - AssertTrue(empty === ""); - AssertTrue((zero as unknown as boolean) ? true : false); - AssertTrue((empty as unknown as boolean) ? true : false); - - // ?? 在 TSTL 中安全地仅判断 == nil,不会误替换 0 / "" / false - const optZero: number | undefined = 0; - const optEmpty: string | undefined = ""; - const optFalse: boolean | undefined = false; - const optNil: number | undefined = undefined; - - AssertEqual(optZero ?? 100, 0); - AssertEqual(optEmpty ?? "fallback", ""); - AssertEqual(optFalse ?? true, false); - AssertEqual(optNil ?? 100, 100); - }); - - Test("Lua 5.4 UTF-8 character counting for CJK game text vs byte length", () => { - const cnText = "你好UE5世界"; - // UTF-8 字节数: 4 个汉字 * 3 + 3 ASCII = 15 - AssertEqual(cnText.length, 15); - // utf8.len 返回 Unicode 码点数 = 7 - const charCount = utf8.len(cnText); - AssertEqual(charCount, 7); - - // utf8.codepoint 提取全部码点 - const codes = [...utf8.codepoint(cnText, 1, -1)]; - AssertEqual(codes.length, 7); - AssertEqual(codes[0], 0x4f60); // '你' - AssertEqual(codes[2], 85); // 'U' - }); - - Test("Lua pattern magic character escaping for literal search & replace", () => { - const raw = "Item[Epic]+10 (50.5%)"; - const escaped = EscapeLuaPattern("[Epic]+10 (50.5%)"); - const [startIdx] = string.find(raw, escaped); - AssertTrue(startIdx !== undefined); - - // 注意:string.gsub 的 replacement 字符串中字面量 % 同样需要转义为 %% - const [replaced] = string.gsub(raw, EscapeLuaPattern("(50.5%)"), "(100%%)"); - AssertEqual(replaced, "Item[Epic]+10 (100%)"); - }); - - Test("0-based TS array vs 1-based UE.TArray interop without sparse holes", () => { - const tsArr: string[] = ["first", "second", "third"]; - const ueArr = UE.TArray(UE.FString); - - for (let i = 0; i < tsArr.length; i++) { - ueArr.Add(tsArr[i]); - } - AssertEqual(ueArr.Length(), tsArr.length); - AssertEqual(ueArr.Get(1), tsArr[0]); - AssertEqual(ueArr.Get(3), tsArr[2]); - - // Swap-remove O(1) 删除保持紧凑数组无空洞 - const dense = [10, 20, 30, 40]; - const removeIdx = 1; // 移除 20 - dense[removeIdx] = dense[dense.length - 1]; - table.remove(dense); - AssertEqual(dense.length, 3); - AssertArrayEqual(dense, [10, 40, 30]); - }); - - Test("deep clone plain tables safely including circular references", () => { - interface Node { - name: string; - tags: string[]; - selfRef?: Node; - } - const original: Node = { name: "Root", tags: ["a", "b"] }; - original.selfRef = original; - - const cloned = DeepCloneTable(original); - AssertEqual(cloned.name, "Root"); - AssertArrayEqual(cloned.tags, ["a", "b"]); - AssertTrue(cloned !== original); - AssertTrue(cloned.tags !== original.tags); - AssertEqual(cloned.selfRef, cloned); - - cloned.tags.push("c"); - AssertEqual(original.tags.length, 2); - AssertEqual(cloned.tags.length, 3); - }); - - Test("zero-GC hot-path Tick simulation with cached FVector/FRotator (10,000 frames)", () => { - const pos = UE.FVector(0, 0, 0); - const vel = UE.FVector(10, 20, -5); - const dt = 0.016; - - for (let frame = 0; frame < 10000; frame++) { - pos.X += vel.X * dt; - pos.Y += vel.Y * dt; - pos.Z += vel.Z * dt; - } - - AssertNear(pos.X, 1600, 0.1); - AssertNear(pos.Y, 3200, 0.1); - AssertNear(pos.Z, -800, 0.1); - }); - }); -} diff --git a/Script/ts/src/Tests/Gameplay/BehaviorTree.ts b/Script/ts/src/Tests/Gameplay/BehaviorTree.ts deleted file mode 100644 index 5e29d27..0000000 --- a/Script/ts/src/Tests/Gameplay/BehaviorTree.ts +++ /dev/null @@ -1,160 +0,0 @@ -/** - * 轻量级 AI 行为树(Behavior Tree):支持 Sequence / Selector / Inverter / Cooldown / Condition / Action 与黑板。 - */ -export const enum EBTStatus { - Success = 0, - Failure = 1, - Running = 2, -} - -export interface BTBlackboard { - [key: string]: unknown; -} - -export interface BTContext { - dt: number; - time: number; - bb: BTBlackboard; -} - -export interface IBTNode { - Tick(ctx: BTContext): EBTStatus; - Reset(): void; -} - -export class BTCondition implements IBTNode { - private check: (this: void, ctx: BTContext) => boolean; - - constructor(check: (this: void, ctx: BTContext) => boolean) { - this.check = check; - } - - Tick(ctx: BTContext): EBTStatus { - return this.check(ctx) ? EBTStatus.Success : EBTStatus.Failure; - } - - Reset(): void {} -} - -export class BTAction implements IBTNode { - private action: (this: void, ctx: BTContext) => EBTStatus; - - constructor(action: (this: void, ctx: BTContext) => EBTStatus) { - this.action = action; - } - - Tick(ctx: BTContext): EBTStatus { - return this.action(ctx); - } - - Reset(): void {} -} - -export class BTSequence implements IBTNode { - private children: IBTNode[]; - private runningIndex = 0; - - constructor(children: IBTNode[]) { - this.children = children; - } - - Tick(ctx: BTContext): EBTStatus { - while (this.runningIndex < this.children.length) { - const status = this.children[this.runningIndex].Tick(ctx); - if (status === EBTStatus.Running) { - return EBTStatus.Running; - } - if (status === EBTStatus.Failure) { - this.Reset(); - return EBTStatus.Failure; - } - this.runningIndex++; - } - this.Reset(); - return EBTStatus.Success; - } - - Reset(): void { - this.runningIndex = 0; - for (let i = 0; i < this.children.length; i++) { - this.children[i].Reset(); - } - } -} - -export class BTSelector implements IBTNode { - private children: IBTNode[]; - private runningIndex = 0; - - constructor(children: IBTNode[]) { - this.children = children; - } - - Tick(ctx: BTContext): EBTStatus { - while (this.runningIndex < this.children.length) { - const status = this.children[this.runningIndex].Tick(ctx); - if (status === EBTStatus.Running) { - return EBTStatus.Running; - } - if (status === EBTStatus.Success) { - this.Reset(); - return EBTStatus.Success; - } - this.runningIndex++; - } - this.Reset(); - return EBTStatus.Failure; - } - - Reset(): void { - this.runningIndex = 0; - for (let i = 0; i < this.children.length; i++) { - this.children[i].Reset(); - } - } -} - -export class BTInverter implements IBTNode { - private child: IBTNode; - - constructor(child: IBTNode) { - this.child = child; - } - - Tick(ctx: BTContext): EBTStatus { - const st = this.child.Tick(ctx); - if (st === EBTStatus.Success) return EBTStatus.Failure; - if (st === EBTStatus.Failure) return EBTStatus.Success; - return EBTStatus.Running; - } - - Reset(): void { - this.child.Reset(); - } -} - -export class BTCooldown implements IBTNode { - private child: IBTNode; - private cooldownSeconds: number; - private lastSuccessTime = -9999; - - constructor(child: IBTNode, cooldownSeconds: number) { - this.child = child; - this.cooldownSeconds = cooldownSeconds; - } - - Tick(ctx: BTContext): EBTStatus { - if (ctx.time - this.lastSuccessTime < this.cooldownSeconds) { - return EBTStatus.Failure; - } - const st = this.child.Tick(ctx); - if (st === EBTStatus.Success) { - this.lastSuccessTime = ctx.time; - } - return st; - } - - Reset(): void { - this.child.Reset(); - } -} diff --git a/Script/ts/src/Tests/Gameplay/BuffAndAttributeSystem.ts b/Script/ts/src/Tests/Gameplay/BuffAndAttributeSystem.ts deleted file mode 100644 index 217aa2b..0000000 --- a/Script/ts/src/Tests/Gameplay/BuffAndAttributeSystem.ts +++ /dev/null @@ -1,196 +0,0 @@ -/** - * RPG 属性修改器、Buff 叠加/周期结算(DoT/HoT)与伤害计算管线。 - */ -export const enum EAttributeId { - MaxHP = "MaxHP", - HP = "HP", - Attack = "Attack", - Defense = "Defense", - MoveSpeed = "MoveSpeed", -} - -export const enum EModifierOp { - FlatAdd = 0, - PercentMul = 1, // 例如 0.2 表示 +20% -} - -export const enum EBuffStackPolicy { - RefreshDuration = 0, - AddStack = 1, - IgnoreIfExists = 2, -} - -export interface AttributeModifier { - attr: EAttributeId; - op: EModifierOp; - value: number; -} - -export interface BuffSpec { - id: string; - duration: number; - maxStacks?: number; - stackPolicy?: EBuffStackPolicy; - modifiers?: AttributeModifier[]; - tickInterval?: number; - hpPerTick?: number; // 正数 HoT,负数 DoT -} - -interface ActiveBuff { - spec: BuffSpec; - stacks: number; - remaining: number; - tickAccumulator: number; -} - -export interface DamageResult { - rawDamage: number; - mitigatedDamage: number; - isCrit: boolean; - targetHpAfter: number; - targetKilled: boolean; -} - -export class AttributeAndBuffComponent { - private baseStats: Record = {}; - private buffs: ActiveBuff[] = []; - private listeners: ((this: void, attr: EAttributeId, newVal: number) => void)[] = []; - - constructor(initialStats: Record) { - for (const [k, v] of pairs(initialStats)) { - this.baseStats[k] = v; - } - } - - OnAttributeChanged(cb: (this: void, attr: EAttributeId, newVal: number) => void): void { - this.listeners[this.listeners.length] = cb; - } - - GetBase(attr: EAttributeId): number { - return this.baseStats[attr] ?? 0; - } - - SetBase(attr: EAttributeId, val: number): void { - let clamped = val; - if (attr === EAttributeId.HP) { - clamped = math.max(0, math.min(val, this.GetFinal(EAttributeId.MaxHP))); - } - this.baseStats[attr] = clamped; - this.Notify(attr, this.GetFinal(attr)); - } - - /** 最终值 = (Base + Sum(FlatAdd)) * (1 + Sum(PercentMul)) */ - GetFinal(attr: EAttributeId): number { - const baseVal = this.baseStats[attr] ?? 0; - let flat = 0; - let pct = 0; - for (let i = 0; i < this.buffs.length; i++) { - const b = this.buffs[i]; - const mods = b.spec.modifiers; - if (mods === undefined) continue; - for (let j = 0; j < mods.length; j++) { - const m = mods[j]; - if (m.attr !== attr) continue; - if (m.op === EModifierOp.FlatAdd) { - flat += m.value * b.stacks; - } else { - pct += m.value * b.stacks; - } - } - } - return (baseVal + flat) * (1 + pct); - } - - ApplyBuff(spec: BuffSpec): void { - const policy = spec.stackPolicy ?? EBuffStackPolicy.RefreshDuration; - const maxStacks = spec.maxStacks ?? 1; - - for (let i = 0; i < this.buffs.length; i++) { - const existing = this.buffs[i]; - if (existing.spec.id === spec.id) { - if (policy === EBuffStackPolicy.IgnoreIfExists) { - return; - } - existing.remaining = spec.duration; - if (policy === EBuffStackPolicy.AddStack && existing.stacks < maxStacks) { - existing.stacks++; - } - return; - } - } - - this.buffs[this.buffs.length] = { - spec, - stacks: 1, - remaining: spec.duration, - tickAccumulator: 0, - }; - } - - RemoveBuff(buffId: string): boolean { - for (let i = this.buffs.length - 1; i >= 0; i--) { - if (this.buffs[i].spec.id === buffId) { - table.remove(this.buffs, i + 1); - return true; - } - } - return false; - } - - GetBuffStacks(buffId: string): number { - for (let i = 0; i < this.buffs.length; i++) { - if (this.buffs[i].spec.id === buffId) { - return this.buffs[i].stacks; - } - } - return 0; - } - - Tick(dt: number): void { - for (let i = this.buffs.length - 1; i >= 0; i--) { - const b = this.buffs[i]; - b.remaining -= dt; - - if (b.spec.tickInterval !== undefined && b.spec.tickInterval > 0 && b.spec.hpPerTick !== undefined) { - b.tickAccumulator += dt; - while (b.tickAccumulator >= b.spec.tickInterval) { - b.tickAccumulator -= b.spec.tickInterval; - const delta = b.spec.hpPerTick * b.stacks; - this.SetBase(EAttributeId.HP, this.GetBase(EAttributeId.HP) + delta); - } - } - - if (b.remaining <= 0) { - table.remove(this.buffs, i + 1); - } - } - } - - /** 伤害管线:护甲减伤公式 mitigation = 100 / (100 + max(0, def)) */ - ApplyDamageFrom( - attacker: AttributeAndBuffComponent, - skillMultiplier: number, - isCrit: boolean, - critMultiplier = 1.5 - ): DamageResult { - const atk = attacker.GetFinal(EAttributeId.Attack); - const def = math.max(0, this.GetFinal(EAttributeId.Defense)); - const raw = atk * skillMultiplier * (isCrit ? critMultiplier : 1.0); - const mitigated = math.floor(raw * (100 / (100 + def)) + 0.5); - const nextHp = math.max(0, this.GetBase(EAttributeId.HP) - mitigated); - this.SetBase(EAttributeId.HP, nextHp); - return { - rawDamage: raw, - mitigatedDamage: mitigated, - isCrit, - targetHpAfter: nextHp, - targetKilled: nextHp <= 0, - }; - } - - private Notify(attr: EAttributeId, val: number): void { - for (let i = 0; i < this.listeners.length; i++) { - this.listeners[i](attr, val); - } - } -} diff --git a/Script/ts/src/Tests/Gameplay/CoroutineTaskRunner.ts b/Script/ts/src/Tests/Gameplay/CoroutineTaskRunner.ts deleted file mode 100644 index d95d1c9..0000000 --- a/Script/ts/src/Tests/Gameplay/CoroutineTaskRunner.ts +++ /dev/null @@ -1,128 +0,0 @@ -/** - * 基于 Lua 原生 coroutine 的异步任务编排器(替代禁用的 async/await 与 Promise)。 - * 支持 WaitSeconds、WaitUntil、任务取消,以及可选的 UObject 存活自动取消保护。 - */ -type YieldCommand = - | { kind: "wait_seconds"; remaining: number } - | { kind: "wait_until"; predicate: (this: void) => boolean }; - -interface RunningTask { - id: number; - co: LuaThread; - owner?: UE.UObject; - pending?: YieldCommand; - cancelled: boolean; -} - -export class CoroutineTaskRunner { - private nextId = 1; - private tasks: RunningTask[] = []; - - Start(body: (this: void) => void, owner?: UE.UObject): number { - const id = this.nextId++; - const co = coroutine.create(body); - const task: RunningTask = { - id, - co, - owner, - cancelled: false, - }; - this.tasks[this.tasks.length] = task; - this.StepTask(task); - return id; - } - - Cancel(taskId: number): boolean { - for (let i = 0; i < this.tasks.length; i++) { - if (this.tasks[i].id === taskId && !this.tasks[i].cancelled) { - this.tasks[i].cancelled = true; - return true; - } - } - return false; - } - - Tick(dt: number): void { - const snapshot: RunningTask[] = []; - for (let i = 0; i < this.tasks.length; i++) { - snapshot[i] = this.tasks[i]; - } - - for (let i = 0; i < snapshot.length; i++) { - const task = snapshot[i]; - if (task.cancelled || coroutine.status(task.co) === "dead") { - task.cancelled = true; - continue; - } - - // 若绑定了 UObject,自动检测是否已被销毁 - if (task.owner !== undefined && !UE.UKismetSystemLibrary.IsValid(task.owner)) { - task.cancelled = true; - continue; - } - - const cmd = task.pending; - if (cmd === undefined) { - this.StepTask(task); - } else if (cmd.kind === "wait_seconds") { - cmd.remaining -= dt; - if (cmd.remaining <= 0) { - task.pending = undefined; - this.StepTask(task); - } - } else if (cmd.kind === "wait_until") { - if (cmd.predicate()) { - task.pending = undefined; - this.StepTask(task); - } - } - } - - for (let i = this.tasks.length - 1; i >= 0; i--) { - const t = this.tasks[i]; - if (t.cancelled || coroutine.status(t.co) === "dead") { - table.remove(this.tasks, i + 1); - } - } - } - - GetActiveTaskCount(): number { - let count = 0; - for (let i = 0; i < this.tasks.length; i++) { - const t = this.tasks[i]; - if (!t.cancelled && coroutine.status(t.co) !== "dead") { - count++; - } - } - return count; - } - - private StepTask(task: RunningTask): void { - if (task.cancelled || coroutine.status(task.co) === "dead") { - return; - } - const [ok, yielded] = coroutine.resume(task.co); - if (!ok) { - task.cancelled = true; - error("CoroutineTaskRunner error: " + tostring(yielded)); - } - if (coroutine.status(task.co) === "dead") { - task.cancelled = true; - } else if (yielded !== undefined) { - task.pending = yielded as YieldCommand; - } - } - - /** 在协程内挂起指定秒数 */ - static WaitSeconds(this: void, seconds: number): void { - const cmd: YieldCommand = { kind: "wait_seconds", remaining: seconds }; - coroutine.yield(cmd); - } - - /** 在协程内挂起直到条件成立 */ - static WaitUntil(this: void, predicate: (this: void) => boolean): void { - if (predicate()) return; - const cmd: YieldCommand = { kind: "wait_until", predicate }; - coroutine.yield(cmd); - } -} diff --git a/Script/ts/src/Tests/Gameplay/FSM.ts b/Script/ts/src/Tests/Gameplay/FSM.ts deleted file mode 100644 index ef934e8..0000000 --- a/Script/ts/src/Tests/Gameplay/FSM.ts +++ /dev/null @@ -1,116 +0,0 @@ -/** - * 通用有限状态机(Finite State Machine),适用于角色状态、AI 状态、UI 流程等。 - */ -export interface IStateHandler { - OnEnter?: (this: void, ctx: TContext, fromState?: string) => void; - OnUpdate?: (this: void, ctx: TContext, dt: number) => void; - OnExit?: (this: void, ctx: TContext, toState: string) => void; -} - -export interface IStateTransition { - from: TStateId | "*"; - to: TStateId; - condition: (this: void, ctx: TContext) => boolean; -} - -export class StateMachine { - private ctx: TContext; - private states: Record | undefined> = {}; - private transitions: IStateTransition[] = []; - private currentState: TStateId | undefined = undefined; - private stateElapsed = 0; - private paused = false; - private history: TStateId[] = []; - - constructor(ctx: TContext) { - this.ctx = ctx; - } - - RegisterState(id: TStateId, handler: IStateHandler): void { - this.states[id] = handler; - } - - AddTransition( - from: TStateId | "*", - to: TStateId, - condition: (this: void, ctx: TContext) => boolean - ): void { - this.transitions[this.transitions.length] = { from, to, condition }; - } - - Start(initialState: TStateId): boolean { - if (this.states[initialState] === undefined) { - return false; - } - this.currentState = initialState; - this.stateElapsed = 0; - this.history[this.history.length] = initialState; - const handler = this.states[initialState]; - if (handler && handler.OnEnter) { - handler.OnEnter(this.ctx, undefined); - } - return true; - } - - ChangeState(nextState: TStateId): boolean { - if (this.currentState === nextState || this.states[nextState] === undefined) { - return false; - } - const prev = this.currentState; - if (prev !== undefined) { - const prevHandler = this.states[prev]; - if (prevHandler && prevHandler.OnExit) { - prevHandler.OnExit(this.ctx, nextState); - } - } - this.currentState = nextState; - this.stateElapsed = 0; - this.history[this.history.length] = nextState; - const nextHandler = this.states[nextState]; - if (nextHandler && nextHandler.OnEnter) { - nextHandler.OnEnter(this.ctx, prev); - } - return true; - } - - Update(dt: number): void { - if (this.paused || this.currentState === undefined) { - return; - } - this.stateElapsed += dt; - - // 先检查条件转换 - for (let i = 0; i < this.transitions.length; i++) { - const tr = this.transitions[i]; - if ( - (tr.from === "*" || tr.from === this.currentState) && - tr.to !== this.currentState && - tr.condition(this.ctx) - ) { - this.ChangeState(tr.to); - break; - } - } - - const handler = this.states[this.currentState]; - if (handler && handler.OnUpdate) { - handler.OnUpdate(this.ctx, dt); - } - } - - SetPaused(paused: boolean): void { - this.paused = paused; - } - - GetCurrentState(): TStateId | undefined { - return this.currentState; - } - - GetStateElapsed(): number { - return this.stateElapsed; - } - - GetHistory(): TStateId[] { - return this.history; - } -} diff --git a/Script/ts/src/Tests/Gameplay/GameplaySuite.ts b/Script/ts/src/Tests/Gameplay/GameplaySuite.ts deleted file mode 100644 index ab4c369..0000000 --- a/Script/ts/src/Tests/Gameplay/GameplaySuite.ts +++ /dev/null @@ -1,368 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertNear, - AssertTrue, - AssertFalse, - AssertNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; -import { CreateBoundInstance } from "../Harness/MockUnLuaRuntime"; -import { StateMachine } from "./FSM"; -import { ObjectPool } from "./ObjectPool"; -import { TimerScheduler, CooldownTracker } from "./TimerScheduler"; -import { - AttributeAndBuffComponent, - EAttributeId, - EBuffStackPolicy, - EModifierOp, -} from "./BuffAndAttributeSystem"; -import { InventorySystem, EItemRarity } from "./InventorySystem"; -import { CoroutineTaskRunner } from "./CoroutineTaskRunner"; -import { - BTAction, - BTCondition, - BTCooldown, - BTInverter, - BTSelector, - BTSequence, - BTContext, - EBTStatus, -} from "./BehaviorTree"; - -export function RunGameplayTests(): void { - Suite("Gameplay.Systems", () => { - Test("FSM: state lifecycle, conditional transitions, pause and history", () => { - interface HeroCtx { - speed: number; - hp: number; - log: string[]; - } - type HeroState = "Idle" | "Run" | "Dead"; - - const ctx: HeroCtx = { speed: 0, hp: 100, log: [] }; - const fsm = new StateMachine(ctx); - - fsm.RegisterState("Idle", { - OnEnter: (c) => { c.log[c.log.length] = "Enter:Idle"; }, - OnExit: (c) => { c.log[c.log.length] = "Exit:Idle"; }, - }); - fsm.RegisterState("Run", { - OnEnter: (c) => { c.log[c.log.length] = "Enter:Run"; }, - OnUpdate: (c, dt) => { c.log[c.log.length] = `Run:${math.floor(dt * 100)}`; }, - }); - fsm.RegisterState("Dead", { - OnEnter: (c) => { c.log[c.log.length] = "Enter:Dead"; }, - }); - - fsm.AddTransition("Idle", "Run", (c) => c.speed > 0); - fsm.AddTransition("Run", "Idle", (c) => c.speed === 0); - fsm.AddTransition("*", "Dead", (c) => c.hp <= 0); - - AssertTrue(fsm.Start("Idle")); - AssertEqual(fsm.GetCurrentState(), "Idle"); - - ctx.speed = 300; - fsm.Update(0.1); - AssertEqual(fsm.GetCurrentState(), "Run"); - - fsm.SetPaused(true); - ctx.hp = 0; - fsm.Update(0.1); - AssertEqual(fsm.GetCurrentState(), "Run"); // paused - - fsm.SetPaused(false); - fsm.Update(0.1); - AssertEqual(fsm.GetCurrentState(), "Dead"); - AssertArrayEqual(fsm.GetHistory(), ["Idle", "Run", "Dead"]); - }); - - Test("ObjectPool: prewarm, acquire/reuse, maxCapacity cap and reset hooks", () => { - interface Bullet { - active: boolean; - damage: number; - } - const pool = new ObjectPool({ - factory: () => ({ active: false, damage: 0 }), - onAcquire: (b) => { b.active = true; b.damage = 10; }, - onRelease: (b) => { b.active = false; b.damage = 0; }, - maxCapacity: 2, - }); - - pool.Prewarm(2); - AssertEqual(pool.GetIdleCount(), 2); - AssertEqual(pool.GetTotalCreated(), 2); - - const b1 = pool.Acquire(); - const b2 = pool.Acquire(); - const b3 = pool.Acquire(); // exceeds prewarm -> creates 3rd - AssertTrue(b1.active); - AssertEqual(b1.damage, 10); - AssertEqual(pool.GetActiveCount(), 3); - AssertEqual(pool.GetTotalCreated(), 3); - - pool.Release(b1); - pool.Release(b2); - pool.Release(b3); // capped at maxCapacity=2 - AssertFalse(b1.active); - AssertEqual(pool.GetActiveCount(), 0); - AssertEqual(pool.GetIdleCount(), 2); - - const reused = pool.Acquire(); - AssertEqual(pool.GetTotalCreated(), 3); // no new allocation - AssertTrue(reused.active); - }); - - Test("TimerScheduler & CooldownTracker: one-shot, repeat, self-cancel, timeScale and cooldowns", () => { - const scheduler = new TimerScheduler(); - const events: string[] = []; - - scheduler.ScheduleOnce(0.5, () => { - events[events.length] = "once"; - }); - const repId = scheduler.ScheduleRepeat(0.25, (id) => { - events[events.length] = `rep#${id}`; - }, 3); - - let selfCancelCount = 0; - scheduler.ScheduleRepeat(0.2, (id) => { - selfCancelCount++; - if (selfCancelCount === 2) { - scheduler.Cancel(id); - } - }); - - scheduler.Tick(0.5); - AssertEqual(selfCancelCount, 2); - AssertEqual(events.length, 3); // once + 2 reps (rep at 0.25, 0.5) - - scheduler.SetPaused(repId, true); - scheduler.Tick(1.0); - AssertEqual(events.length, 3); // paused - - scheduler.SetPaused(repId, false); - scheduler.SetTimeScale(0.5); - scheduler.Tick(0.5); // effective dt = 0.25 -> 3rd rep fires & finishes - AssertEqual(events.length, 4); - AssertEqual(scheduler.GetActiveCount(), 0); - - // CooldownTracker - const cd = new CooldownTracker(); - AssertTrue(cd.IsReady("Fireball")); - cd.StartCooldown("Fireball", 5.0); - AssertFalse(cd.IsReady("Fireball")); - cd.Tick(2.0); - AssertNear(cd.GetRemaining("Fireball"), 3.0); - cd.ReduceCooldown("Fireball", 3.5); - AssertTrue(cd.IsReady("Fireball")); - AssertEqual(cd.GetRemaining("Fireball"), 0); - }); - - Test("BuffAndAttributeSystem: flat/percent modifiers, stacking, DoT tick and damage mitigation", () => { - const hero = new AttributeAndBuffComponent({ - [EAttributeId.MaxHP]: 200, - [EAttributeId.HP]: 200, - [EAttributeId.Attack]: 50, - [EAttributeId.Defense]: 0, - }); - const boss = new AttributeAndBuffComponent({ - [EAttributeId.MaxHP]: 500, - [EAttributeId.HP]: 500, - [EAttributeId.Attack]: 40, - [EAttributeId.Defense]: 100, // 50% damage reduction - }); - - // 攻击力 Buff: +10 Flat, +20% Mul,叠加 2 层 -> (50 + 20) * 1.4 = 98 - const furyBuff = { - id: "Fury", - duration: 5.0, - maxStacks: 3, - stackPolicy: EBuffStackPolicy.AddStack, - modifiers: [ - { attr: EAttributeId.Attack, op: EModifierOp.FlatAdd, value: 10 }, - { attr: EAttributeId.Attack, op: EModifierOp.PercentMul, value: 0.2 }, - ], - }; - hero.ApplyBuff(furyBuff); - hero.ApplyBuff(furyBuff); - AssertEqual(hero.GetBuffStacks("Fury"), 2); - AssertNear(hero.GetFinal(EAttributeId.Attack), 98); - - // 暴击打击 Boss: raw = 98 * 1.0 * 1.5 = 147, mitigated = round(147 * 100/200) = 74 - const dmg = boss.ApplyDamageFrom(hero, 1.0, true, 1.5); - AssertEqual(dmg.mitigatedDamage, 74); - AssertEqual(dmg.targetHpAfter, 426); - AssertFalse(dmg.targetKilled); - - // 中毒 DoT: 每 1 秒 -15 HP,持续 3.1 秒 - boss.ApplyBuff({ - id: "Poison", - duration: 3.1, - tickInterval: 1.0, - hpPerTick: -15, - }); - boss.Tick(2.5); // 触发 2 次 -> -30 HP -> 396 - AssertEqual(boss.GetBase(EAttributeId.HP), 396); - boss.Tick(1.0); // 触发第 3 次并过期 -> 381 - AssertEqual(boss.GetBase(EAttributeId.HP), 381); - AssertEqual(boss.GetBuffStacks("Poison"), 0); - }); - - Test("InventorySystem: stack merge, split, swap, consume, filter and serialize/deserialize", () => { - const inv = new InventorySystem(4); - inv.RegisterItemDef({ - itemId: "potion_hp", - name: "Health Potion", - category: "Consumable", - rarity: EItemRarity.Common, - maxStack: 10, - }); - inv.RegisterItemDef({ - itemId: "sword_excalibur", - name: "Excalibur", - category: "Weapon", - rarity: EItemRarity.Legendary, - maxStack: 1, - }); - - // 添加 25 瓶药水 -> 占 3 格 (10, 10, 5) - AssertEqual(inv.AddItem("potion_hp", 25), 0); - AssertEqual(inv.GetItemCount("potion_hp"), 25); - AssertEqual(inv.GetUsedSlotCount(), 3); - - // 添加 2 把不可堆叠武器 -> 第 1 把占第 4 格,第 2 把放不下返回 overflow=1 - AssertEqual(inv.AddItem("sword_excalibur", 2), 1); - AssertEqual(inv.GetItemCount("sword_excalibur"), 1); - - // 消耗 12 瓶药水 -> 剩 13 瓶 (10, 3),释放 1 个空格 - AssertTrue(inv.ConsumeItem("potion_hp", 12)); - AssertEqual(inv.GetItemCount("potion_hp"), 13); - AssertNil(inv.GetSlot(2)); - - // 拆分第 0 格 (10 -> 6 + 4 放入第 2 格) - AssertTrue(inv.SplitSlot(0, 2, 4)); - AssertEqual(inv.GetSlot(0)!.count, 6); - AssertEqual(inv.GetSlot(2)!.count, 4); - - // 交换格子 & 按类别筛选(此时 slot 0=武器,slot 1/2/3=药水共 3 格) - AssertTrue(inv.SwapSlots(0, 3)); - AssertEqual(inv.GetSlot(0)!.itemId, "sword_excalibur"); - AssertEqual(inv.FilterByCategory("Weapon").length, 1); - AssertEqual(inv.FilterByCategory("Consumable").length, 3); - - // 序列化与反序列化 - const saved = inv.Serialize(); - const restored = new InventorySystem(1); - restored.Deserialize(saved); - AssertEqual(restored.GetItemCount("potion_hp"), 13); - AssertEqual(restored.GetSlot(0)!.itemId, "sword_excalibur"); - }); - - Test("CoroutineTaskRunner: WaitSeconds, WaitUntil and UObject destroy auto-cancellation", () => { - const runner = new CoroutineTaskRunner(); - const trace: string[] = []; - let doorOpened = false; - - runner.Start(() => { - trace[trace.length] = "start"; - CoroutineTaskRunner.WaitSeconds(0.5); - trace[trace.length] = "after_delay"; - CoroutineTaskRunner.WaitUntil(() => doorOpened); - trace[trace.length] = "entered_room"; - }); - - AssertArrayEqual(trace, ["start"]); - runner.Tick(0.3); - AssertArrayEqual(trace, ["start"]); - runner.Tick(0.3); - AssertArrayEqual(trace, ["start", "after_delay"]); - runner.Tick(1.0); - AssertArrayEqual(trace, ["start", "after_delay"]); // still waiting for door - - doorOpened = true; - runner.Tick(0.016); - AssertArrayEqual(trace, ["start", "after_delay", "entered_room"]); - AssertEqual(runner.GetActiveTaskCount(), 0); - - // 绑定 UObject 存活自动取消测试(兼容独立 Mock 环境与真实 UE 环境) - const world = _G.__UE_TEST_WORLD; - const ownerActor = - world !== undefined - ? world.SpawnActor( - UE.AActor.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - )! - : CreateBoundInstance({}, "AActor"); - let postDestroyExecuted = false; - runner.Start(() => { - CoroutineTaskRunner.WaitSeconds(1.0); - postDestroyExecuted = true; - }, ownerActor); - - ownerActor.K2_DestroyActor(); - runner.Tick(2.0); - AssertFalse(postDestroyExecuted); - AssertEqual(runner.GetActiveTaskCount(), 0); - }); - - Test("BehaviorTree: Selector/Sequence/Cooldown/Inverter with Running resumption", () => { - const log: string[] = []; - let castProgress = 0; - - const castUltimate = new BTCooldown( - new BTSequence([ - new BTCondition((ctx) => (ctx.bb["mana"] as number) >= 50), - new BTAction((ctx) => { - castProgress += ctx.dt; - if (castProgress < 1.0) { - log[log.length] = "casting"; - return EBTStatus.Running; - } - castProgress = 0; - ctx.bb["mana"] = (ctx.bb["mana"] as number) - 50; - log[log.length] = "ult_fired"; - return EBTStatus.Success; - }), - ]), - 5.0 - ); - - const basicAttack = new BTSequence([ - new BTInverter(new BTCondition((ctx) => ctx.bb["stunned"] === true)), - new BTAction(() => { - log[log.length] = "basic_attack"; - return EBTStatus.Success; - }), - ]); - - const root = new BTSelector([castUltimate, basicAttack]); - const ctx: BTContext = { - dt: 0.5, - time: 0, - bb: { mana: 60, stunned: false }, - }; - - // t=0: 开始施放终极技能 -> Running - AssertEqual(root.Tick(ctx), EBTStatus.Running); - // t=0.5: 继续施放并完成 -> Success, 进入 5 秒冷却 - ctx.time = 0.5; - AssertEqual(root.Tick(ctx), EBTStatus.Success); - AssertEqual(ctx.bb["mana"], 10); - - // t=1.0: 终极技能冷却中 -> 回退到普通攻击 - ctx.time = 1.0; - AssertEqual(root.Tick(ctx), EBTStatus.Success); - - // t=1.5: 被眩晕 -> 全部失败 - ctx.time = 1.5; - ctx.bb["stunned"] = true; - AssertEqual(root.Tick(ctx), EBTStatus.Failure); - - AssertArrayEqual(log, ["casting", "ult_fired", "basic_attack"]); - }); - }); -} diff --git a/Script/ts/src/Tests/Gameplay/InventorySystem.ts b/Script/ts/src/Tests/Gameplay/InventorySystem.ts deleted file mode 100644 index 7712978..0000000 --- a/Script/ts/src/Tests/Gameplay/InventorySystem.ts +++ /dev/null @@ -1,182 +0,0 @@ -/** - * 格子背包系统:支持堆叠合并、拆分、交换、消耗、标签过滤与纯 Lua 表序列化/反序列化。 - */ -export const enum EItemRarity { - Common = 0, - Rare = 1, - Epic = 2, - Legendary = 3, -} - -export interface ItemDef { - itemId: string; - name: string; - category: "Weapon" | "Consumable" | "Material"; - rarity: EItemRarity; - maxStack: number; -} - -export interface InventorySlot { - itemId: string; - count: number; -} - -export interface SerializedInventory { - capacity: number; - slots: Record; -} - -export class InventorySystem { - private capacity: number; - private defs: Record = {}; - private slots: Record = {}; - - constructor(capacity: number) { - this.capacity = capacity; - } - - RegisterItemDef(def: ItemDef): void { - this.defs[def.itemId] = def; - } - - /** 添加物品,返回未放下的剩余数量(0 表示全部成功放入) */ - AddItem(itemId: string, amount: number): number { - const def = this.defs[itemId]; - if (def === undefined || amount <= 0) { - return amount; - } - let remaining = amount; - - // 1. 先合并到已有未满堆叠格 - for (let i = 0; i < this.capacity && remaining > 0; i++) { - const slot = this.slots[i]; - if (slot !== undefined && slot.itemId === itemId && slot.count < def.maxStack) { - const space = def.maxStack - slot.count; - const add = math.min(space, remaining); - slot.count += add; - remaining -= add; - } - } - - // 2. 放入空格子 - for (let i = 0; i < this.capacity && remaining > 0; i++) { - if (this.slots[i] === undefined) { - const add = math.min(def.maxStack, remaining); - this.slots[i] = { itemId, count: add }; - remaining -= add; - } - } - - return remaining; - } - - ConsumeItem(itemId: string, amount: number): boolean { - if (amount <= 0 || this.GetItemCount(itemId) < amount) { - return false; - } - let remaining = amount; - for (let i = this.capacity - 1; i >= 0 && remaining > 0; i--) { - const slot = this.slots[i]; - if (slot !== undefined && slot.itemId === itemId) { - const take = math.min(slot.count, remaining); - slot.count -= take; - remaining -= take; - if (slot.count <= 0) { - this.slots[i] = undefined; - } - } - } - return true; - } - - SwapSlots(slotA: number, slotB: number): boolean { - if (slotA < 0 || slotA >= this.capacity || slotB < 0 || slotB >= this.capacity) { - return false; - } - const tmp = this.slots[slotA]; - this.slots[slotA] = this.slots[slotB]; - this.slots[slotB] = tmp; - return true; - } - - SplitSlot(fromSlot: number, toSlot: number, splitCount: number): boolean { - if ( - fromSlot < 0 || - fromSlot >= this.capacity || - toSlot < 0 || - toSlot >= this.capacity || - fromSlot === toSlot - ) { - return false; - } - const src = this.slots[fromSlot]; - if (src === undefined || this.slots[toSlot] !== undefined) { - return false; - } - if (splitCount <= 0 || splitCount >= src.count) { - return false; - } - src.count -= splitCount; - this.slots[toSlot] = { itemId: src.itemId, count: splitCount }; - return true; - } - - GetItemCount(itemId: string): number { - let total = 0; - for (let i = 0; i < this.capacity; i++) { - const slot = this.slots[i]; - if (slot !== undefined && slot.itemId === itemId) { - total += slot.count; - } - } - return total; - } - - GetSlot(index: number): InventorySlot | undefined { - return this.slots[index]; - } - - GetUsedSlotCount(): number { - let used = 0; - for (let i = 0; i < this.capacity; i++) { - if (this.slots[i] !== undefined) used++; - } - return used; - } - - FilterByCategory(category: ItemDef["category"]): InventorySlot[] { - const out: InventorySlot[] = []; - for (let i = 0; i < this.capacity; i++) { - const slot = this.slots[i]; - if (slot !== undefined) { - const def = this.defs[slot.itemId]; - if (def !== undefined && def.category === category) { - out[out.length] = slot; - } - } - } - return out; - } - - Serialize(): SerializedInventory { - const copiedSlots: Record = {}; - for (let i = 0; i < this.capacity; i++) { - const s = this.slots[i]; - if (s !== undefined) { - copiedSlots[i] = { itemId: s.itemId, count: s.count }; - } - } - return { - capacity: this.capacity, - slots: copiedSlots, - }; - } - - Deserialize(data: SerializedInventory): void { - this.capacity = data.capacity; - this.slots = {}; - for (const [idx, s] of pairs(data.slots)) { - this.slots[idx] = { itemId: s.itemId, count: s.count }; - } - } -} diff --git a/Script/ts/src/Tests/Gameplay/ObjectPool.ts b/Script/ts/src/Tests/Gameplay/ObjectPool.ts deleted file mode 100644 index eb449db..0000000 --- a/Script/ts/src/Tests/Gameplay/ObjectPool.ts +++ /dev/null @@ -1,78 +0,0 @@ -/** - * 通用对象池(Object Pool),减少高频创建/销毁(子弹、特效、伤害飘字等)的 GC 压力。 - */ -export interface IObjectPoolOptions { - factory: (this: void) => T; - onAcquire?: (this: void, obj: T) => void; - onRelease?: (this: void, obj: T) => void; - maxCapacity?: number; -} - -export class ObjectPool { - private factory: (this: void) => T; - private onAcquire?: (this: void, obj: T) => void; - private onRelease?: (this: void, obj: T) => void; - private maxCapacity: number; - private idle: T[] = []; - private activeCount = 0; - private totalCreated = 0; - - constructor(options: IObjectPoolOptions) { - this.factory = options.factory; - this.onAcquire = options.onAcquire; - this.onRelease = options.onRelease; - this.maxCapacity = options.maxCapacity ?? 64; - } - - Prewarm(count: number): void { - const target = math.min(count, this.maxCapacity); - while (this.idle.length < target) { - this.totalCreated++; - this.idle[this.idle.length] = this.factory(); - } - } - - Acquire(): T { - let obj: T; - if (this.idle.length > 0) { - obj = table.remove(this.idle) as T; - } else { - this.totalCreated++; - obj = this.factory(); - } - this.activeCount++; - if (this.onAcquire) { - this.onAcquire(obj); - } - return obj; - } - - Release(obj: T): void { - if (this.activeCount > 0) { - this.activeCount--; - } - if (this.onRelease) { - this.onRelease(obj); - } - if (this.idle.length < this.maxCapacity) { - this.idle[this.idle.length] = obj; - } - } - - Clear(): void { - this.idle = []; - this.activeCount = 0; - } - - GetIdleCount(): number { - return this.idle.length; - } - - GetActiveCount(): number { - return this.activeCount; - } - - GetTotalCreated(): number { - return this.totalCreated; - } -} diff --git a/Script/ts/src/Tests/Gameplay/TimerScheduler.ts b/Script/ts/src/Tests/Gameplay/TimerScheduler.ts deleted file mode 100644 index 97de520..0000000 --- a/Script/ts/src/Tests/Gameplay/TimerScheduler.ts +++ /dev/null @@ -1,151 +0,0 @@ -/** - * 帧驱动定时器调度器与技能冷却追踪器(零 JS polyfill,回调中支持安全取消/新增)。 - */ -interface ScheduledTimer { - id: number; - interval: number; - remaining: number; - maxRepeats: number; // 0 = infinite - firedCount: number; - paused: boolean; - cancelled: boolean; - callback: (this: void, handleId: number) => void; -} - -export class TimerScheduler { - private nextId = 1; - private timers: ScheduledTimer[] = []; - private timeScale = 1.0; - - ScheduleOnce(delay: number, callback: (this: void, handleId: number) => void): number { - return this.AddTimer(delay, 1, callback); - } - - ScheduleRepeat( - interval: number, - callback: (this: void, handleId: number) => void, - maxRepeats = 0 - ): number { - return this.AddTimer(interval, maxRepeats, callback); - } - - private AddTimer( - interval: number, - maxRepeats: number, - callback: (this: void, handleId: number) => void - ): number { - const id = this.nextId++; - const safeInterval = math.max(0.0001, interval); - this.timers[this.timers.length] = { - id, - interval: safeInterval, - remaining: safeInterval, - maxRepeats, - firedCount: 0, - paused: false, - cancelled: false, - callback, - }; - return id; - } - - Cancel(handleId: number): boolean { - for (let i = 0; i < this.timers.length; i++) { - if (this.timers[i].id === handleId && !this.timers[i].cancelled) { - this.timers[i].cancelled = true; - return true; - } - } - return false; - } - - SetPaused(handleId: number, paused: boolean): void { - for (let i = 0; i < this.timers.length; i++) { - if (this.timers[i].id === handleId) { - this.timers[i].paused = paused; - return; - } - } - } - - SetTimeScale(scale: number): void { - this.timeScale = math.max(0, scale); - } - - Tick(dt: number): void { - const scaledDt = dt * this.timeScale; - if (scaledDt <= 0) return; - - // 快照遍历,避免回调内增删影响当前帧 - const snapshot: ScheduledTimer[] = []; - for (let i = 0; i < this.timers.length; i++) { - snapshot[i] = this.timers[i]; - } - - for (let i = 0; i < snapshot.length; i++) { - const t = snapshot[i]; - if (t.cancelled || t.paused) continue; - t.remaining -= scaledDt; - while (!t.cancelled && !t.paused && t.remaining <= 0) { - t.firedCount++; - t.callback(t.id); - if (t.maxRepeats > 0 && t.firedCount >= t.maxRepeats) { - t.cancelled = true; - break; - } - t.remaining += t.interval; - } - } - - // 统一清理已完成或已取消的定时器 - for (let i = this.timers.length - 1; i >= 0; i--) { - if (this.timers[i].cancelled) { - table.remove(this.timers, i + 1); - } - } - } - - GetActiveCount(): number { - let count = 0; - for (let i = 0; i < this.timers.length; i++) { - if (!this.timers[i].cancelled) count++; - } - return count; - } -} - -export class CooldownTracker { - private remainingMap: Record = {}; - - StartCooldown(skillId: string, duration: number): void { - if (duration > 0) { - this.remainingMap[skillId] = duration; - } - } - - IsReady(skillId: string): boolean { - const rem = this.remainingMap[skillId]; - return rem === undefined || rem <= 0; - } - - GetRemaining(skillId: string): number { - return this.remainingMap[skillId] ?? 0; - } - - ReduceCooldown(skillId: string, seconds: number): void { - const rem = this.remainingMap[skillId]; - if (rem !== undefined) { - const next = rem - seconds; - this.remainingMap[skillId] = next > 0 ? next : undefined; - } - } - - Tick(dt: number): void { - for (const [skillId, rem] of pairs(this.remainingMap)) { - if (rem !== undefined) { - const next = rem - dt; - this.remainingMap[skillId] = next > 0 ? next : undefined; - } - } - } -} diff --git a/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts b/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts deleted file mode 100644 index 1a27ab2..0000000 --- a/Script/ts/src/Tests/Harness/MockUnLuaRuntime.ts +++ /dev/null @@ -1,1077 +0,0 @@ -/** @noSelfInFile */ - -/** - * 独立 Lua 5.4 环境下的 UnLua + UE 轻量级 Mock 运行时。 - * 用于在未启动 UE 编辑器时直接用 `lua5.4` 执行编译后的 TS -> UnLua 产物并校验运行时行为。 - * 在真实 UE 进程中(已存在 `_G.UnLua` 与 `_G.UE`),InstallIfNeeded() 会自动跳过安装。 - */ - -export interface MockTimerEntry { - handleId: number; - target: unknown; - callback: (this: any) => void; - interval: number; - remaining: number; - looping: boolean; - paused: boolean; - active: boolean; -} - -export interface MockLatentDelayEntry { - co: LuaThread; - owner: unknown; - remaining: number; -} - -export interface MockInputBindingRecord { - kind: "Key" | "Action" | "Axis" | "EnhancedAction"; - module: Record; - name: string; - event: string; - handler: (this: any, ...args: any[]) => void; - args?: Record; -} - -export interface MockRuntimeState { - printedStrings: string[]; - logs: string[]; - timers: MockTimerEntry[]; - nextTimerId: number; - latentDelays: MockLatentDelayEntry[]; - inputBindings: MockInputBindingRecord[]; - manualRefs: LuaTable; - spawnedActors: Record[]; - createdObjects: Record[]; - overriddenCalls: string[]; -} - -let state: MockRuntimeState; - -export function GetMockState(): MockRuntimeState { - return state; -} - -export function ResetMockState(): void { - state = { - printedStrings: [], - logs: [], - timers: [], - nextTimerId: 1, - latentDelays: [], - inputBindings: [], - manualRefs: new LuaTable(), - spawnedActors: [], - createdObjects: [], - overriddenCalls: [], - }; -} - -/** 模拟推进定时器与 Latent Delay 协程 */ -export function AdvanceMockTime(deltaSeconds: number): void { - // 1. 推进 Timers(快照避免回调中取消/新增破坏遍历) - const timerSnapshot: MockTimerEntry[] = []; - for (let i = 0; i < state.timers.length; i++) { - timerSnapshot[i] = state.timers[i]; - } - for (let i = 0; i < timerSnapshot.length; i++) { - const t = timerSnapshot[i]; - if (!t.active || t.paused) continue; - t.remaining -= deltaSeconds; - while (t.active && !t.paused && t.remaining <= 0) { - t.callback.call(t.target); - if (t.looping && t.active) { - t.remaining += t.interval; - } else { - t.active = false; - break; - } - } - } - - // 2. 推进 Latent Delay 协程 - const ready: MockLatentDelayEntry[] = []; - for (let i = state.latentDelays.length - 1; i >= 0; i--) { - const entry = state.latentDelays[i]; - entry.remaining -= deltaSeconds; - if (entry.remaining <= 0) { - table.remove(state.latentDelays, i + 1); - ready[ready.length] = entry; - } - } - for (let i = 0; i < ready.length; i++) { - const entry = ready[i]; - if (coroutine.status(entry.co) === "suspended") { - const [ok, err] = coroutine.resume(entry.co); - if (!ok) { - error("Latent coroutine resume error: " + tostring(err)); - } - } - } -} - -/** 构造模拟的 MulticastDelegate */ -export function CreateMockMulticastDelegate(): UE.FMulticastScriptDelegate { - const entries: { target: unknown; cb: (this: any, ...args: any[]) => void }[] = []; - const delegate = { - Add(this: unknown, target: unknown, cb: (this: any, ...args: any[]) => void): void { - for (let i = 0; i < entries.length; i++) { - if (entries[i].target === target && entries[i].cb === cb) return; - } - entries[entries.length] = { target, cb }; - }, - Remove(this: unknown, target: unknown, cb: (this: any, ...args: any[]) => void): void { - for (let i = entries.length - 1; i >= 0; i--) { - if (entries[i].target === target && entries[i].cb === cb) { - table.remove(entries, i + 1); - } - } - }, - Clear(this: unknown): void { - for (let i = entries.length - 1; i >= 0; i--) { - table.remove(entries, i + 1); - } - }, - Broadcast(this: unknown, ...args: any[]): void { - const snap: { target: unknown; cb: (this: any, ...args: any[]) => void }[] = []; - for (let i = 0; i < entries.length; i++) snap[i] = entries[i]; - for (let i = 0; i < snap.length; i++) { - snap[i].cb.call(snap[i].target, ...args); - } - }, - IsBound(this: unknown): boolean { - return entries.length > 0; - }, - }; - return delegate as unknown as UE.FMulticastScriptDelegate; -} - -/** 构造模拟的 FScriptDelegate */ -export function CreateMockScriptDelegate(): UE.FScriptDelegate { - let boundTarget: unknown = undefined; - let boundCb: ((this: any, ...args: any[]) => any) | undefined = undefined; - const delegate = { - Bind(this: unknown, target: unknown, cb: (this: any, ...args: any[]) => any): void { - boundTarget = target; - boundCb = cb; - }, - Unbind(this: unknown): void { - boundTarget = undefined; - boundCb = undefined; - }, - Execute(this: unknown, ...args: any[]): any { - if (boundCb !== undefined) { - return boundCb.call(boundTarget, ...args); - } - return undefined; - }, - }; - return delegate as unknown as UE.FScriptDelegate; -} - -/** 构造模拟的 UObject/AActor/UUserWidget 实例并绑定 UnLua Lua 类表 */ -export function CreateBoundInstance( - luaClass: Record, - nativeClassName: string, - extraProps?: Record -): T { - const uobj: Record = { - __isMockUObject: true, - __valid: true, - __className: nativeClassName, - __name: nativeClassName + "_Instance", - __location: UE.FVector(0, 0, 0), - __rotation: UE.FRotator(0, 0, 0), - __inViewport: false, - __released: false, - OnTakeAnyDamage: CreateMockMulticastDelegate(), - OnActorBeginOverlap: CreateMockMulticastDelegate(), - OnClicked: CreateMockMulticastDelegate(), - Overridden: setmetatable( - {}, - { - __index: (_t: unknown, methodName: string) => { - return (selfObj: Record, ..._args: unknown[]) => { - state.overriddenCalls[state.overriddenCalls.length] = - tostring(selfObj.__className) + "." + methodName; - }; - }, - } - ), - }; - - // 常用 UObject / AActor / UUserWidget 基础方法 - uobj.GetName = function (this: Record) { - return this.__name; - }; - uobj.IsValid = function (this: Record) { - return this.__valid === true; - }; - uobj.IsA = function (this: Record, cls: Record) { - if (!cls) return false; - const target = cls.__className as string; - if (this.__className === target) return true; - if (target === "UObject") return true; - if (target === "AActor" && (this.__className === "AActor" || this.__className === "ALuaDemoActor" || this.__className === "APlayerController" || this.__className === "ACharacter")) { - return true; - } - if (target === "UUserWidget" && this.__className === "UUserWidget") { - return true; - } - return false; - }; - uobj.GetWorld = function () { - return (_G as unknown as Record).__MockWorld; - }; - uobj.K2_GetActorLocation = function (this: Record) { - return UE.FVector(this.__location.X, this.__location.Y, this.__location.Z); - }; - uobj.K2_SetActorLocation = function ( - this: Record, - loc: UE.FVector, - _bSweep?: boolean, - outHit?: Record, - _bTeleport?: boolean - ) { - this.__location = UE.FVector(loc.X, loc.Y, loc.Z); - const hit = outHit ?? { bBlockingHit: false, Distance: 0, Location: loc }; - return $multi(true, hit); - }; - uobj.K2_GetActorRotation = function (this: Record) { - return UE.FRotator(this.__rotation.Pitch, this.__rotation.Yaw, this.__rotation.Roll); - }; - uobj.K2_SetActorRotation = function (this: Record, rot: UE.FRotator) { - this.__rotation = UE.FRotator(rot.Pitch, rot.Yaw, rot.Roll); - return true; - }; - uobj.K2_DestroyActor = function (this: Record) { - this.__valid = false; - }; - uobj.AddToViewport = function (this: Record) { - this.__inViewport = true; - }; - uobj.RemoveFromViewport = function (this: Record) { - this.__inViewport = false; - }; - uobj.RemoveFromParent = function (this: Record) { - this.__inViewport = false; - }; - uobj.Release = function (this: Record) { - this.__released = true; - }; - uobj.Destroy = function (this: Record) { - this.__valid = false; - }; - - if (extraProps !== undefined) { - for (const [k, v] of pairs(extraProps)) { - uobj[k] = v; - } - } - - // 模拟 UnLua 元表继承链(实例 -> luaClass -> Super -> ...) - setmetatable(uobj, { - __index: (t: Record, k: string) => { - let cur: Record | undefined = luaClass; - while (cur !== undefined) { - const v = rawget(cur, k); - if (v !== undefined) { - return v; - } - cur = rawget(cur, "Super") as Record | undefined; - } - return rawget(t, k); - }, - }); - - return uobj as unknown as T; -} - -function CreateMockTArray(): UE.TArray { - const data: any[] = []; - const arr: Record = { - Length(this: unknown) { - return data.length; - }, - Num(this: unknown) { - return data.length; - }, - Add(this: unknown, item: any) { - data[data.length] = item; - return data.length; // 1-based index - }, - AddUnique(this: unknown, item: any) { - for (let i = 0; i < data.length; i++) { - if (data[i] === item) return i + 1; // UnLua C++ 返回已有元素的 1-based 索引 - } - data[data.length] = item; - return data.length; - }, - Find(this: unknown, item: any) { - for (let i = 0; i < data.length; i++) { - if (data[i] === item) return i + 1; - } - return 0; - }, - Insert(this: unknown, item: any, index: number) { - table.insert(data, index, item); - }, - Remove(this: unknown, index: number) { - table.remove(data, index); - }, - RemoveItem(this: unknown, item: any) { - let removed = 0; - for (let i = data.length - 1; i >= 0; i--) { - if (data[i] === item) { - table.remove(data, i + 1); - removed++; - } - } - return removed; - }, - Clear(this: unknown) { - for (let i = data.length - 1; i >= 0; i--) { - table.remove(data, i + 1); - } - }, - Reserve(this: unknown, _size: number) { - return data.length === 0; - }, - Resize(this: unknown, size: number) { - while (data.length > size) table.remove(data); - while (data.length < size) data[data.length] = 0; - }, - GetData(this: unknown) { - return data; - }, - Get(this: unknown, index: number) { - return data[index - 1]; - }, - GetRef(this: unknown, index: number) { - return data[index - 1]; - }, - Set(this: unknown, index: number, item: any) { - data[index - 1] = item; - }, - Swap(this: unknown, firstIndex: number, secondIndex: number) { - const tmp = data[firstIndex - 1]; - data[firstIndex - 1] = data[secondIndex - 1]; - data[secondIndex - 1] = tmp; - }, - Shuffle(this: unknown) { - for (let i = data.length - 1; i > 0; i--) { - const j = math.random(0, i); - const tmp = data[i]; - data[i] = data[j]; - data[j] = tmp; - } - }, - LastIndex(this: unknown) { - return data.length; - }, - IsValidIndex(this: unknown, index: number) { - return index >= 1 && index <= data.length; - }, - Contains(this: unknown, item: any) { - for (let i = 0; i < data.length; i++) { - if (data[i] === item) return true; - } - return false; - }, - Append(this: unknown, other: UE.TArray) { - for (let i = 1; i <= other.Length(); i++) { - data[data.length] = other.Get(i); - } - }, - ToTable(this: unknown) { - const copy: any[] = []; - for (let i = 0; i < data.length; i++) copy[i] = data[i]; - return copy; - }, - }; - setmetatable(arr, { - __pairs: () => { - let idx = 0; - return () => { - idx++; - if (idx <= data.length) { - return $multi(idx, data[idx - 1]); - } - return undefined; - }; - }, - } as any); - return arr as unknown as UE.TArray; -} - -function CreateMockTMap(): UE.TMap { - const entries: Record = {}; - const m: Record = { - Length(this: unknown) { - let n = 0; - for (const [_] of pairs(entries)) n++; - return n; - }, - Num(this: unknown) { - return (this as Record).Length(); - }, - Add(this: unknown, k: any, v: any) { - entries[k] = v; - }, - Remove(this: unknown, k: any) { - if (entries[k] !== undefined) { - entries[k] = undefined; - return true; - } - return false; - }, - Find(this: unknown, k: any) { - return entries[k]; - }, - FindRef(this: unknown, k: any) { - return entries[k]; - }, - Clear(this: unknown) { - for (const [k] of pairs(entries)) { - entries[k] = undefined; - } - }, - Keys(this: unknown) { - const arr = CreateMockTArray(); - for (const [k] of pairs(entries)) arr.Add(k); - return arr; - }, - Values(this: unknown) { - const arr = CreateMockTArray(); - for (const [_, v] of pairs(entries)) arr.Add(v); - return arr; - }, - ToTable(this: unknown) { - const copy: Record = {}; - for (const [k, v] of pairs(entries)) copy[k] = v; - return copy; - }, - }; - setmetatable(m, { - __pairs: () => { - return $multi(next, entries, undefined); - }, - } as any); - return m as unknown as UE.TMap; -} - -function CreateMockTSet(): UE.TSet { - const entries: Record = {}; - const s: Record = { - Length(this: unknown) { - let n = 0; - for (const [_] of pairs(entries)) n++; - return n; - }, - Num(this: unknown) { - return (this as Record).Length(); - }, - Add(this: unknown, item: any) { - entries[item] = true; - }, - Remove(this: unknown, item: any) { - if (entries[item]) { - entries[item] = undefined; - return true; - } - return false; - }, - Contains(this: unknown, item: any) { - return entries[item] === true; - }, - Clear(this: unknown) { - for (const [k] of pairs(entries)) entries[k] = undefined; - }, - ToArray(this: unknown) { - const arr = CreateMockTArray(); - for (const [k] of pairs(entries)) arr.Add(k); - return arr; - }, - ToTable(this: unknown) { - const arr: any[] = []; - for (const [k] of pairs(entries)) arr[arr.length] = k; - return arr; - }, - }; - return s as unknown as UE.TSet; -} - -function CreateMockFVector(x?: number, y?: number, z?: number): UE.FVector { - let vx = 0; - let vy = 0; - let vz = 0; - if (x !== undefined && y === undefined && z === undefined) { - vx = x; - vy = x; - vz = x; - } else { - vx = x ?? 0; - vy = y ?? 0; - vz = z ?? 0; - } - const vec: Record = { - X: vx, - Y: vy, - Z: vz, - Set(this: Record, nx?: number, ny?: number, nz?: number) { - if (nx !== undefined) this.X = nx; - if (ny !== undefined) this.Y = ny; - if (nz !== undefined) this.Z = nz; - }, - Add(this: Record, other: any) { - if (type(other) === "number") { - this.X += other; - this.Y += other; - this.Z += other; - } else { - this.X += other.X; - this.Y += other.Y; - this.Z += other.Z; - } - }, - Sub(this: Record, other: any) { - if (type(other) === "number") { - this.X -= other; - this.Y -= other; - this.Z -= other; - } else { - this.X -= other.X; - this.Y -= other.Y; - this.Z -= other.Z; - } - }, - Mul(this: Record, other: any) { - if (type(other) === "number") { - this.X *= other; - this.Y *= other; - this.Z *= other; - } else { - this.X *= other.X; - this.Y *= other.Y; - this.Z *= other.Z; - } - }, - Div(this: Record, other: any) { - if (type(other) === "number") { - this.X /= other; - this.Y /= other; - this.Z /= other; - } else { - this.X /= other.X; - this.Y /= other.Y; - this.Z /= other.Z; - } - }, - Dot(this: Record, other: any) { - return this.X * other.X + this.Y * other.Y + this.Z * other.Z; - }, - Cross(this: Record, other: any) { - return CreateMockFVector( - this.Y * other.Z - this.Z * other.Y, - this.Z * other.X - this.X * other.Z, - this.X * other.Y - this.Y * other.X - ); - }, - Size(this: Record) { - return math.sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z); - }, - Size2D(this: Record) { - return math.sqrt(this.X * this.X + this.Y * this.Y); - }, - SizeSquared(this: Record) { - return this.X * this.X + this.Y * this.Y + this.Z * this.Z; - }, - SizeSquared2D(this: Record) { - return this.X * this.X + this.Y * this.Y; - }, - Normalize(this: Record, tol = 1e-8) { - const sq = this.SizeSquared(); - if (sq > tol) { - const inv = 1 / math.sqrt(sq); - this.X *= inv; - this.Y *= inv; - this.Z *= inv; - return true; - } - return false; - }, - IsNormalized(this: Record) { - return math.abs(1 - this.SizeSquared()) < 0.01; - }, - }; - return vec as unknown as UE.FVector; -} - -function CreateMockFRotator(pitch = 0, yaw = 0, roll = 0): UE.FRotator { - return { - Pitch: pitch, - Yaw: yaw, - Roll: roll, - ToQuat(this: Record) { - return { X: this.Pitch, Y: this.Yaw, Z: this.Roll, W: 1 }; - }, - } as unknown as UE.FRotator; -} - -function CreateMockFTransform( - rot?: UE.FQuat, - trans?: UE.FVector, - scale?: UE.FVector -): UE.FTransform { - return { - Rotation: rot ?? { X: 0, Y: 0, Z: 0, W: 1 }, - Translation: trans ?? CreateMockFVector(), - Scale3D: scale ?? CreateMockFVector(1, 1, 1), - } as unknown as UE.FTransform; -} - -function CreateMockFLinearColor(r = 0, g = 0, b = 0, a = 1): UE.FLinearColor { - return { R: r, G: g, B: b, A: a } as unknown as UE.FLinearColor; -} - -function MakeMockClassObject(name: string): Record { - return { - __className: name, - __valid: true, - GetName() { - return name; - }, - IsChildOf(this: Record, other: Record) { - return other !== undefined && (this.__className === other.__className || other.__className === "UObject"); - }, - }; -} - -export function InstallIfNeeded(): void { - ResetMockState(); - const g = _G as unknown as Record; - if (g.UnLua !== undefined && g.UE !== undefined) { - return; - } - - // ---- UnLua 全局表 ---- - g.UnLua = { - PackagePath: "Script/lua/?.lua", - FTextEnabled: false, - Class: (superName?: string) => { - const superClass = superName !== undefined ? require(superName) : undefined; - const cls: Record = {}; - cls.Super = superClass; - return cls; - }, - Ref: (obj: object) => { - const cur = state.manualRefs.get(obj) ?? 0; - state.manualRefs.set(obj, cur + 1); - return { __refTarget: obj }; - }, - Unref: (obj: object) => { - state.manualRefs.set(obj, undefined as unknown as number); - }, - HotReload: () => { - state.logs[state.logs.length] = "UnLua.HotReload()"; - }, - Log: (...args: unknown[]) => { - const parts: string[] = []; - for (let i = 0; i < args.length; i++) parts[i] = tostring(args[i]); - state.logs[state.logs.length] = table.concat(parts, "\t"); - }, - LogWarn: (...args: unknown[]) => { - const parts: string[] = []; - for (let i = 0; i < args.length; i++) parts[i] = tostring(args[i]); - state.logs[state.logs.length] = "[WARN] " + table.concat(parts, "\t"); - }, - LogError: (...args: unknown[]) => { - const parts: string[] = []; - for (let i = 0; i < args.length; i++) parts[i] = tostring(args[i]); - state.logs[state.logs.length] = "[ERROR] " + table.concat(parts, "\t"); - }, - Input: { - BindKey: ( - mod: Record, - keyName: string, - keyEvent: string, - handler: (this: any, ...args: any[]) => void, - args?: Record - ) => { - state.inputBindings[state.inputBindings.length] = { - kind: "Key", - module: mod, - name: keyName, - event: keyEvent, - handler, - args, - }; - }, - BindAction: ( - mod: Record, - actionName: string, - keyEvent: string, - handler: (this: any, ...args: any[]) => void, - args?: Record - ) => { - state.inputBindings[state.inputBindings.length] = { - kind: "Action", - module: mod, - name: actionName, - event: keyEvent, - handler, - args, - }; - }, - BindAxis: ( - mod: Record, - axisName: string, - handler: (this: any, ...args: any[]) => void, - args?: Record - ) => { - state.inputBindings[state.inputBindings.length] = { - kind: "Axis", - module: mod, - name: axisName, - event: "Axis", - handler, - args, - }; - }, - }, - EnhancedInput: { - BindAction: ( - mod: Record, - actionPath: string, - triggerEvent: string, - handler: (this: any, ...args: any[]) => void, - args?: Record - ) => { - state.inputBindings[state.inputBindings.length] = { - kind: "EnhancedAction", - module: mod, - name: actionPath, - event: triggerEvent, - handler, - args, - }; - }, - }, - }; - - // ---- UE 向量函数表(支持既可调用 UE.FVector(...) 又有静态方法 UE.FVector.Dist(...)) ---- - const FVectorTable: Record = { - Dist: (a: UE.FVector, b: UE.FVector) => { - const dx = a.X - b.X; - const dy = a.Y - b.Y; - const dz = a.Z - b.Z; - return math.sqrt(dx * dx + dy * dy + dz * dz); - }, - Dist2D: (a: UE.FVector, b: UE.FVector) => { - const dx = a.X - b.X; - const dy = a.Y - b.Y; - return math.sqrt(dx * dx + dy * dy); - }, - DistSquared: (a: UE.FVector, b: UE.FVector) => { - const dx = a.X - b.X; - const dy = a.Y - b.Y; - const dz = a.Z - b.Z; - return dx * dx + dy * dy + dz * dz; - }, - }; - setmetatable(FVectorTable, { - __call(this: unknown, x?: number, y?: number, z?: number) { - return CreateMockFVector(x, y, z); - }, - }); - - const mockWorld: Record = { - SpawnActor( - this: unknown, - actorClass: Record, - transform?: UE.FTransform, - _collision?: number, - owner?: unknown, - _instigator?: unknown, - moduleName?: string, - initializer?: Record - ) { - const luaCls = moduleName !== undefined ? (require(moduleName) as Record) : {}; - const inst = CreateBoundInstance>( - luaCls, - tostring(actorClass?.__className ?? "AActor"), - { Owner: owner } - ); - if (transform !== undefined) { - inst.__location = transform.Translation; - } - if (type(inst.Initialize) === "function") { - inst.Initialize(initializer); - } - if (type(inst.ReceiveBeginPlay) === "function") { - inst.ReceiveBeginPlay(); - } - state.spawnedActors[state.spawnedActors.length] = inst; - return inst; - }, - SpawnActorEx( - this: unknown, - actorClass: Record, - transform?: UE.FTransform, - initializer?: Record, - moduleName?: string, - spawnParams?: Record - ) { - return (this as Record).SpawnActor( - actorClass, - transform, - spawnParams?.SpawnCollisionHandlingOverride, - spawnParams?.Owner, - spawnParams?.Instigator, - moduleName, - initializer - ); - }, - }; - g.__MockWorld = mockWorld; - - // ---- UE 全局命名空间 ---- - g.UE = { - int8: "int8", - int16: "int16", - int32: "int32", - int64: "int64", - uint8: "uint8", - uint16: "uint16", - uint32: "uint32", - uint64: "uint64", - float: "float", - double: "double", - bool: "bool", - FName: "FName", - FString: "FString", - - FVector: FVectorTable, - FRotator: CreateMockFRotator, - FTransform: CreateMockFTransform, - FLinearColor: CreateMockFLinearColor, - FHitResult: () => ({ - bBlockingHit: false, - Distance: 0, - Location: CreateMockFVector(), - ImpactPoint: CreateMockFVector(), - Normal: CreateMockFVector(0, 0, 1), - }), - FActorSpawnParameters: () => ({ - Name: "", - bNoFail: false, - SpawnCollisionHandlingOverride: 0, - }), - FWeakObjectPtr: (initialObj?: Record) => { - let refObj: Record | undefined = initialObj; - return { - Set(this: unknown, o: Record | undefined) { - refObj = o; - }, - Get(this: unknown) { - return refObj !== undefined && refObj.__valid === true ? refObj : undefined; - }, - IsValid(this: unknown) { - return refObj !== undefined && refObj.__valid === true; - }, - Reset(this: unknown) { - refObj = undefined; - }, - }; - }, - - TArray: (_elemType: unknown) => CreateMockTArray(), - TMap: (_keyType: unknown, _valType: unknown) => CreateMockTMap(), - TSet: (_elemType: unknown) => CreateMockTSet(), - - ESpawnActorCollisionHandlingMethod: { - Undefined: 0, - AlwaysSpawn: 1, - AdjustIfPossibleButAlwaysSpawn: 2, - AdjustIfPossibleButDontSpawnIfColliding: 3, - DontSpawnIfColliding: 4, - }, - EDrawDebugTrace: { - None: 0, - ForOneFrame: 1, - ForDuration: 2, - Persistent: 3, - }, - ETraceTypeQuery: { - TraceTypeQuery1: 0, - TraceTypeQuery2: 1, - }, - EEndPlayReason: { - Destroyed: 0, - LevelTransition: 1, - EndPlayInEditor: 2, - RemovedFromWorld: 3, - Quit: 4, - }, - - UObject: { - StaticClass: () => MakeMockClassObject("UObject"), - Load: (assetPath: string) => ({ - __isMockUObject: true, - __valid: true, - __className: "UObject", - __assetPath: assetPath, - GetName() { - return assetPath; - }, - IsValid() { - return true; - }, - }), - }, - UClass: { - StaticClass: () => MakeMockClassObject("UClass"), - Load: (classPath: string) => MakeMockClassObject(classPath), - }, - AActor: { - StaticClass: () => MakeMockClassObject("AActor"), - }, - ALuaDemoActor: { - StaticClass: () => MakeMockClassObject("ALuaDemoActor"), - }, - APlayerController: { - StaticClass: () => MakeMockClassObject("APlayerController"), - }, - UUserWidget: { - StaticClass: () => MakeMockClassObject("UUserWidget"), - }, - - LoadClass: (classPath: string) => MakeMockClassObject(classPath), - LoadObject: (assetPath: string) => ({ - __isMockUObject: true, - __valid: true, - __className: "UObject", - __assetPath: assetPath, - GetName() { - return assetPath; - }, - IsValid() { - return true; - }, - }), - NewObject: ( - cls: Record, - outer?: unknown, - name?: string, - moduleName?: string, - initializer?: Record - ) => { - const luaCls = moduleName !== undefined ? (require(moduleName) as Record) : {}; - const inst = CreateBoundInstance>( - luaCls, - tostring(cls?.__className ?? "UObject"), - { __name: name ?? "NewObject", __outer: outer } - ); - if (type(inst.Initialize) === "function") { - inst.Initialize(initializer); - } - state.createdObjects[state.createdObjects.length] = inst; - return inst; - }, - - UKismetSystemLibrary: { - PrintString: (_worldCtx: unknown, inString?: string) => { - state.printedStrings[state.printedStrings.length] = inString ?? ""; - }, - IsValid: (obj: Record | undefined) => { - return obj !== undefined && obj.__valid === true; - }, - K2_SetTimerDelegate: (delegatePair: [unknown, (this: any) => void], time: number, bLooping: boolean) => { - const handleId = state.nextTimerId++; - state.timers[state.timers.length] = { - handleId, - target: delegatePair[0], - callback: delegatePair[1], - interval: time, - remaining: time, - looping: bLooping, - paused: false, - active: true, - }; - return { __handleId: handleId }; - }, - K2_ClearAndInvalidateTimerHandle: (_worldCtx: unknown, handle?: { __handleId?: number }) => { - if (handle && handle.__handleId !== undefined) { - for (let i = 0; i < state.timers.length; i++) { - if (state.timers[i].handleId === handle.__handleId) { - state.timers[i].active = false; - } - } - handle.__handleId = undefined; - } - return handle ?? {}; - }, - K2_IsTimerActiveHandle: (_worldCtx: unknown, handle?: { __handleId?: number }) => { - if (!handle || handle.__handleId === undefined) return false; - for (let i = 0; i < state.timers.length; i++) { - if (state.timers[i].handleId === handle.__handleId) { - return state.timers[i].active && !state.timers[i].paused; - } - } - return false; - }, - Delay: (worldCtx: unknown, duration: number) => { - const [co, isMain] = coroutine.running(); - assert(!isMain, "UKismetSystemLibrary.Delay must be called inside a coroutine!"); - state.latentDelays[state.latentDelays.length] = { - co, - owner: worldCtx, - remaining: duration, - }; - coroutine.yield(); - }, - RetriggerableDelay: (worldCtx: unknown, duration: number) => { - const [co, isMain] = coroutine.running(); - assert(!isMain, "RetriggerableDelay must be called inside a coroutine!"); - state.latentDelays[state.latentDelays.length] = { - co, - owner: worldCtx, - remaining: duration, - }; - coroutine.yield(); - }, - LineTraceSingle: ( - _worldCtx: unknown, - startVec: UE.FVector, - endVec: UE.FVector, - _channel: number, - _bTraceComplex: boolean, - _actorsToIgnore: UE.TArray, - _drawDebugType: number, - outHit: Record | undefined, - _bIgnoreSelf: boolean - ) => { - const dist = UE.FVector.Dist(startVec, endVec); - const hit = outHit ?? { - bBlockingHit: false, - Distance: 0, - Location: CreateMockFVector(), - ImpactPoint: CreateMockFVector(), - }; - const bHit = dist > 0; - hit.bBlockingHit = bHit; - hit.Distance = dist * 0.5; - hit.Location = CreateMockFVector( - (startVec.X + endVec.X) * 0.5, - (startVec.Y + endVec.Y) * 0.5, - (startVec.Z + endVec.Z) * 0.5 - ); - hit.ImpactPoint = hit.Location; - // 还原 UnLua 真实语义:传入复用 Out 参数时原地修改并返回单值;传入 nil 时返回多值 (bHit, newHit) - if (outHit !== undefined) { - return $multi(bHit, undefined as unknown as Record); - } - return $multi(bHit, hit); - }, - }, - }; -} diff --git a/Script/ts/src/Tests/Harness/TestRunner.ts b/Script/ts/src/Tests/Harness/TestRunner.ts deleted file mode 100644 index 3a078ca..0000000 --- a/Script/ts/src/Tests/Harness/TestRunner.ts +++ /dev/null @@ -1,185 +0,0 @@ -/** @noSelfInFile */ - -export interface TestCaseResult { - suite: string; - name: string; - passed: boolean; - errorMessage?: string; -} - -export interface SuiteSummary { - total: number; - passed: number; - failed: number; - results: TestCaseResult[]; -} - -let currentSuite = "Default"; -let results: TestCaseResult[] = []; - -export function Reset(): void { - currentSuite = "Default"; - results = []; -} - -export function Suite(name: string, body: (this: void) => void): void { - const prev = currentSuite; - currentSuite = name; - body(); - currentSuite = prev; -} - -export function Test(name: string, fn: (this: void) => void): void { - const [ok, err] = pcall(fn); - if (ok) { - results[results.length] = { - suite: currentSuite, - name, - passed: true, - }; - } else { - results[results.length] = { - suite: currentSuite, - name, - passed: false, - errorMessage: tostring(err), - }; - } -} - -export function AssertTrue(cond: unknown, msg?: string): void { - if (!cond) { - error(msg ?? "Expected condition to be truthy", 2); - } -} - -export function AssertFalse(cond: unknown, msg?: string): void { - if (cond) { - error(msg ?? "Expected condition to be falsy", 2); - } -} - -export function AssertEqual(actual: T, expected: T, msg?: string): void { - if (actual !== expected) { - const prefix = msg ? `${msg}: ` : ""; - error( - string.format("%sExpected %s, got %s", prefix, tostring(expected), tostring(actual)), - 2 - ); - } -} - -export function AssertNear(actual: number, expected: number, epsilon = 1e-4, msg?: string): void { - if (math.abs(actual - expected) > epsilon) { - const prefix = msg ? `${msg}: ` : ""; - error( - string.format( - "%sExpected %.6f (±%.6f), got %.6f", - prefix, - expected, - epsilon, - actual - ), - 2 - ); - } -} - -export function AssertNil(value: unknown, msg?: string): void { - if (value !== undefined) { - const prefix = msg ? `${msg}: ` : ""; - error(string.format("%sExpected nil, got %s", prefix, tostring(value)), 2); - } -} - -export function AssertNotNil(value: unknown, msg?: string): void { - if (value === undefined) { - error(msg ?? "Expected non-nil value", 2); - } -} - -export function AssertArrayEqual(actual: T[], expected: T[], msg?: string): void { - const prefix = msg ? `${msg}: ` : ""; - if (actual.length !== expected.length) { - error( - string.format( - "%sArray length mismatch: expected %d, got %d", - prefix, - expected.length, - actual.length - ), - 2 - ); - } - for (let i = 0; i < expected.length; i++) { - if (actual[i] !== expected[i]) { - error( - string.format( - "%sArray element [%d] mismatch: expected %s, got %s", - prefix, - i, - tostring(expected[i]), - tostring(actual[i]) - ), - 2 - ); - } - } -} - -export function GetSummary(): SuiteSummary { - let passed = 0; - let failed = 0; - for (let i = 0; i < results.length; i++) { - if (results[i].passed) { - passed++; - } else { - failed++; - } - } - return { - total: results.length, - passed, - failed, - results, - }; -} - -export function FormatReport(summary?: SuiteSummary): string { - const s = summary ?? GetSummary(); - const lines: string[] = []; - let lastSuite = ""; - for (let i = 0; i < s.results.length; i++) { - const r = s.results[i]; - if (r.suite !== lastSuite) { - lastSuite = r.suite; - lines[lines.length] = ""; - lines[lines.length] = string.format("[%s]", r.suite); - } - if (r.passed) { - lines[lines.length] = string.format(" PASS %s", r.name); - } else { - lines[lines.length] = string.format( - " FAIL %s\n -> %s", - r.name, - r.errorMessage ?? "unknown error" - ); - } - } - lines[lines.length] = ""; - lines[lines.length] = "========================================"; - lines[lines.length] = string.format( - "Total: %d | Passed: %d | Failed: %d", - s.total, - s.passed, - s.failed - ); - lines[lines.length] = "========================================"; - return table.concat(lines, "\n"); -} - -export function PrintReport(): SuiteSummary { - const summary = GetSummary(); - print(FormatReport(summary)); - return summary; -} diff --git a/Script/ts/src/Tests/RunAllTests.ts b/Script/ts/src/Tests/RunAllTests.ts deleted file mode 100644 index 1aa9ac6..0000000 --- a/Script/ts/src/Tests/RunAllTests.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** @noSelfInFile */ - -import { Reset, PrintReport, SuiteSummary } from "./Harness/TestRunner"; -import { InstallIfNeeded } from "./Harness/MockUnLuaRuntime"; -import { RunBasicTypesAndControlFlowTests } from "./Syntax/BasicTypesAndControlFlow"; -import { RunFunctionsClosuresAndTuplesTests } from "./Syntax/FunctionsClosuresAndTuples"; -import { RunPureClassesAndGenericsTests } from "./Syntax/PureClassesAndGenerics"; -import { RunUnLuaSyntaxTests } from "./Syntax/UnLuaSyntaxSuite"; -import { RunUnLuaExamplesTests } from "./UnLuaExamples/UnLuaExamplesSuite"; -import { RunGameplayTests } from "./Gameplay/GameplaySuite"; -import { RunHotReloadAndFrameworkTests } from "./Extra/HotReloadAndFrameworkTest"; -import { RunLua54PitfallsTests } from "./Extra/Lua54PitfallsTest"; -import { RunLifecycleAndMemoryTests } from "./Extra/LifecycleAndMemoryTest"; - -export function RunAll(): SuiteSummary { - InstallIfNeeded(); - Reset(); - - // 1. ts2lua 语法与 @unlua 特性测试 - RunBasicTypesAndControlFlowTests(); - RunFunctionsClosuresAndTuplesTests(); - RunPureClassesAndGenericsTests(); - RunUnLuaSyntaxTests(); - - // 2. UnLua 官方示例 TS 实现测试(Ex01 ~ Ex09) - RunUnLuaExamplesTests(); - - // 3. 常用游戏开发功能 TS 实现测试 - RunGameplayTests(); - - // 4. 补充测试:框架集成、热重载、Lua 5.4 陷阱与生命周期安全 - RunHotReloadAndFrameworkTests(); - RunLua54PitfallsTests(); - RunLifecycleAndMemoryTests(); - - return PrintReport(); -} - -// 当作为脚本由 `lua5.4` 直接执行时自动运行并返回标准退出码 -const g = _G as unknown as Record; -if (g.__TS2LUA_TEST_AUTO_RUN__ === true) { - const summary = RunAll(); - if (summary.failed > 0) { - os.exit(1); - } -} diff --git a/Script/ts/src/Tests/Syntax/BasicTypesAndControlFlow.ts b/Script/ts/src/Tests/Syntax/BasicTypesAndControlFlow.ts deleted file mode 100644 index ad7f100..0000000 --- a/Script/ts/src/Tests/Syntax/BasicTypesAndControlFlow.ts +++ /dev/null @@ -1,180 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertNear, - AssertTrue, - AssertFalse, - AssertNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; - -const enum EBitFlag { - None = 0, - Move = 1 << 0, - Jump = 1 << 1, - Attack = 1 << 2, - Stunned = 1 << 3, -} - -const enum ERoleName { - Tank = "Tank", - Healer = "Healer", - DPS = "DPS", -} - -type CommandAction = - | { kind: "move"; x: number; y: number } - | { kind: "damage"; amount: number; crit: boolean } - | { kind: "noop" }; - -function EvaluateCommand(action: CommandAction): number { - switch (action.kind) { - case "move": - return action.x + action.y; - case "damage": - return action.crit ? action.amount * 2 : action.amount; - case "noop": - return 0; - } -} - -export function RunBasicTypesAndControlFlowTests(): void { - Suite("Syntax.BasicTypesAndControlFlow", () => { - Test("primitives, template literals, nullish coalescing and optional chaining", () => { - const count = 42; - const ratio = 0.5; - // Lua 5.4 中浮点运算结果转为字符串带 ".0",需要整数格式时用 math.floor 或 string.format("%d") - const label = `Count=${count},Half=${math.floor(count * ratio)}`; - AssertEqual(label, "Count=42,Half=21"); - AssertEqual(`${count * ratio}`, "21.0"); - - const maybeNum: number | undefined = undefined; - const zeroNum: number | undefined = 0; - const falseFlag: boolean | undefined = false; - - // ?? 只在 nil/undefined 时回退,不吞 0 和 false - AssertEqual(maybeNum ?? 99, 99); - AssertEqual(zeroNum ?? 99, 0); - AssertEqual(falseFlag ?? true, false); - - interface NestedCfg { - inner?: { value?: number }; - } - const a: NestedCfg = {}; - const b: NestedCfg = { inner: { value: 7 } }; - AssertNil(a.inner?.value); - AssertEqual(b.inner?.value ?? -1, 7); - }); - - Test("Lua 5.4 native bitwise operators and const enum inlining", () => { - let flags: number = EBitFlag.None; - flags = flags | EBitFlag.Move | EBitFlag.Attack; - AssertTrue((flags & EBitFlag.Move) !== 0); - AssertFalse((flags & EBitFlag.Jump) !== 0); - AssertTrue((flags & EBitFlag.Attack) !== 0); - - // 清除 Attack,切换 Jump - flags = flags & ~EBitFlag.Attack; - flags = flags ^ EBitFlag.Jump; - AssertFalse((flags & EBitFlag.Attack) !== 0); - AssertTrue((flags & EBitFlag.Jump) !== 0); - - // 位移运算(Lua 5.4 原生右移为逻辑右移,TSTL 要求使用 >>>) - AssertEqual(1 << 4, 16); - AssertEqual(64 >>> 2, 16); - - // 字符串 const enum 内联 - const role: string = ERoleName.Healer; - AssertEqual(role, "Healer"); - }); - - Test("control flow: switch/case fallthrough, loops, continue, break, labeled loop", () => { - const Classify = (n: number): string => { - switch (n) { - case 1: - case 2: - return "small"; - case 3: - return "medium"; - default: - return "large"; - } - }; - AssertEqual(Classify(1), "small"); - AssertEqual(Classify(2), "small"); - AssertEqual(Classify(3), "medium"); - AssertEqual(Classify(9), "large"); - - // while + continue + break - let sum = 0; - let i = 0; - while (i < 10) { - i++; - if (i % 2 === 0) continue; - if (i > 7) break; - sum += i; // 1 + 3 + 5 + 7 = 16 - } - AssertEqual(sum, 16); - - // do-while 至少执行一次 - let doCount = 0; - do { - doCount++; - } while (false); - AssertEqual(doCount, 1); - - // 嵌套循环提前退出(TSTL 不支持 LabeledStatement,使用标志位退出) - let foundPair = ""; - let found = false; - for (let r = 0; r < 5 && !found; r++) { - for (let c = 0; c < 5; c++) { - if (r * 10 + c === 23) { - foundPair = `${r},${c}`; - found = true; - break; - } - } - } - AssertEqual(foundPair, "2,3"); - }); - - Test("discriminated union narrowing and destructuring with defaults", () => { - AssertEqual(EvaluateCommand({ kind: "move", x: 3, y: 4 }), 7); - AssertEqual(EvaluateCommand({ kind: "damage", amount: 25, crit: true }), 50); - AssertEqual(EvaluateCommand({ kind: "damage", amount: 25, crit: false }), 25); - AssertEqual(EvaluateCommand({ kind: "noop" }), 0); - - const cfg: { host: string; port?: number } = { host: "127.0.0.1" }; - const { host, port = 7777 } = cfg; - AssertEqual(host, "127.0.0.1"); - AssertEqual(port, 7777); - - const coords: [number, number, number] = [10, 20, 30]; - const [x, , z] = coords; - AssertEqual(x, 10); - AssertEqual(z, 30); - - // 数值精度 - AssertNear(0.1 + 0.2, 0.3, 1e-6); - }); - - Test("rest parameters and spread into function calls", () => { - const SumAll = (...nums: number[]): number => { - let total = 0; - for (let idx = 0; idx < nums.length; idx++) { - total += nums[idx]; - } - return total; - }; - const data = [2, 4, 6, 8]; - AssertEqual(SumAll(...data), 20); - AssertEqual(SumAll(1, ...data, 9), 30); - - const combined = [0, ...data, 10]; - AssertArrayEqual(combined, [0, 2, 4, 6, 8, 10]); - }); - }); -} diff --git a/Script/ts/src/Tests/Syntax/FunctionsClosuresAndTuples.ts b/Script/ts/src/Tests/Syntax/FunctionsClosuresAndTuples.ts deleted file mode 100644 index c13935f..0000000 --- a/Script/ts/src/Tests/Syntax/FunctionsClosuresAndTuples.ts +++ /dev/null @@ -1,155 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertTrue, - AssertFalse, - AssertNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; - -function DivideWithRemainder(a: number, b: number): LuaMultiReturn<[boolean, number, number]> { - if (b === 0) { - return $multi(false, 0, 0); - } - const q = math.floor(a / b); - const r = a % b; - return $multi(true, q, r); -} - -// 函数重载 -function FormatId(id: number): string; -function FormatId(prefix: string, id: number): string; -function FormatId(a: number | string, b?: number): string { - if (type(a) === "number") { - return string.format("ID_%04d", a as number); - } - return string.format("%s_%04d", a as string, b ?? 0); -} - -interface CounterObj { - value: number; - Add(this: CounterObj, delta: number): number; -} - -export function RunFunctionsClosuresAndTuplesTests(): void { - Suite("Syntax.FunctionsClosuresAndTuples", () => { - Test("LuaMultiReturn and $multi destructuring", () => { - const [ok1, q1, r1] = DivideWithRemainder(17, 5); - AssertTrue(ok1); - AssertEqual(q1, 3); - AssertEqual(r1, 2); - - const [ok2, q2, r2] = DivideWithRemainder(10, 0); - AssertFalse(ok2); - AssertEqual(q2, 0); - AssertEqual(r2, 0); - }); - - Test("function overloads, closures and upvalues", () => { - AssertEqual(FormatId(7), "ID_0007"); - AssertEqual(FormatId("NPC", 42), "NPC_0042"); - - const MakeAccumulator = (start: number): ((this: void, delta: number) => number) => { - let acc = start; - return (delta: number) => { - acc += delta; - return acc; - }; - }; - const acc = MakeAccumulator(10); - AssertEqual(acc(5), 15); - AssertEqual(acc(-3), 12); - AssertEqual(acc(8), 20); - }); - - Test("explicit self colon-call vs @noSelf dot-call", () => { - const counter: CounterObj = { - value: 10, - Add(this: CounterObj, delta: number): number { - this.value += delta; - return this.value; - }, - }; - AssertEqual(counter.Add(5), 15); - AssertEqual(counter.Add(7), 22); - }); - - Test("TS arrays (0-based -> Lua 1-based) and table operations", () => { - const arr: number[] = [10, 20, 30, 40]; - AssertEqual(arr.length, 4); - AssertEqual(arr[0], 10); - AssertEqual(arr[3], 40); - - arr.push(50); - AssertEqual(arr.length, 5); - AssertEqual(arr.pop(), 50); - - // splice 删除中间元素不产生稀疏洞 - const removed = arr.splice(1, 2); - AssertArrayEqual(removed, [20, 30]); - AssertArrayEqual(arr, [10, 40]); - - // table.insert / table.remove (注意 1-based) - table.insert(arr, 2, 25); - AssertArrayEqual(arr, [10, 25, 40]); - table.remove(arr, 1); - AssertArrayEqual(arr, [25, 40]); - - // 排序与 join - const unsorted = [5, 1, 4, 2, 3]; - unsorted.sort((a, b) => a - b); - AssertArrayEqual(unsorted, [1, 2, 3, 4, 5]); - AssertEqual(unsorted.join("-"), "1-2-3-4-5"); - AssertEqual(unsorted.indexOf(4), 3); - AssertEqual(unsorted.indexOf(99), -1); - }); - - Test("Record, LuaTable and pairs() iteration", () => { - const scores: Record = { - Alice: 100, - Bob: 85, - Carol: 92, - }; - scores["Bob"] = undefined; // Lua 表删除键 - - let count = 0; - let total = 0; - for (const [k, v] of pairs(scores)) { - if (v !== undefined) { - count++; - total += v; - } - AssertTrue(k !== "Bob"); - } - AssertEqual(count, 2); - AssertEqual(total, 192); - - const luaTbl = new LuaTable(); - luaTbl.set(101, "Sword"); - luaTbl.set(202, "Shield"); - AssertEqual(luaTbl.get(101), "Sword"); - AssertEqual(luaTbl.get(202), "Shield"); - luaTbl.set(101, undefined as unknown as string); - AssertNil(luaTbl.get(101)); - }); - - Test("Lua patterns (replacing forbidden JS RegExp)", () => { - const [tag, numStr] = string.match("Item_Sword_042", "^(%a+)_%a+_(%d+)$"); - AssertEqual(tag, "Item"); - AssertEqual(numStr, "042"); - - const [replaced, subCount] = string.gsub("HP: 100, MP: 50", "%d+", "999"); - AssertEqual(replaced, "HP: 999, MP: 999"); - AssertEqual(subCount, 2); - - const tokens: string[] = []; - for (const [tok] of string.gmatch("alpha,beta,gamma", "[^,]+")) { - tokens[tokens.length] = tok; - } - AssertArrayEqual(tokens, ["alpha", "beta", "gamma"]); - }); - }); -} diff --git a/Script/ts/src/Tests/Syntax/PureClassesAndGenerics.ts b/Script/ts/src/Tests/Syntax/PureClassesAndGenerics.ts deleted file mode 100644 index 4204828..0000000 --- a/Script/ts/src/Tests/Syntax/PureClassesAndGenerics.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { - Suite, - Test, - AssertEqual, - AssertTrue, - AssertFalse, - AssertNil, -} from "../Harness/TestRunner"; - -interface Identifiable { - GetId(): number; -} - -abstract class BaseEntity implements Identifiable { - protected id: number; - protected name: string; - - constructor(id: number, name: string) { - this.id = id; - this.name = name; - } - - GetId(): number { - return this.id; - } - - GetName(): string { - return this.name; - } - - abstract Describe(): string; -} - -class PureMonster extends BaseEntity { - static DefaultLevel = 1; - private level: number; - - constructor(id: number, name: string, level = PureMonster.DefaultLevel) { - super(id, name); - this.level = level; - } - - GetLevel(): number { - return this.level; - } - - override Describe(): string { - return `${this.name}#${this.id}(Lv.${this.level})`; - } - - static CompareLevel(this: void, a: PureMonster, b: PureMonster): number { - return a.GetLevel() - b.GetLevel(); - } -} - -class RingBuffer { - private buffer: (T | undefined)[] = []; - private head = 0; - private count = 0; - private capacity: number; - - constructor(capacity: number) { - this.capacity = capacity; - } - - Push(item: T): void { - if (this.count < this.capacity) { - const idx = (this.head + this.count) % this.capacity; - this.buffer[idx] = item; - this.count++; - } else { - this.buffer[this.head] = item; - this.head = (this.head + 1) % this.capacity; - } - } - - Pop(): T | undefined { - if (this.count === 0) return undefined; - const item = this.buffer[this.head]; - this.buffer[this.head] = undefined; - this.head = (this.head + 1) % this.capacity; - this.count--; - return item; - } - - GetCount(): number { - return this.count; - } -} - -function FindById(this: void, list: T[], targetId: number): T | undefined { - for (let i = 0; i < list.length; i++) { - if (list[i].GetId() === targetId) { - return list[i]; - } - } - return undefined; -} - -function SafeFrameworkBoundary(this: void, shouldThrow: boolean): LuaMultiReturn<[boolean, string]> { - /** @unlua-allow-try */ - try { - if (shouldThrow) { - /** @unlua-allow-try */ - throw "simulated_boundary_error"; - } - return $multi(true, "ok"); - } catch (e) { - return $multi(false, tostring(e)); - } -} - -export function RunPureClassesAndGenericsTests(this: void): void { - Suite("Syntax.PureClassesAndGenerics", () => { - Test("pure TS class inheritance, abstract methods and static helpers", () => { - const m1 = new PureMonster(1, "Slime"); - const m2 = new PureMonster(2, "Dragon", 50); - - AssertEqual(m1.GetId(), 1); - AssertEqual(m1.GetLevel(), 1); - AssertEqual(m1.Describe(), "Slime#1(Lv.1)"); - AssertEqual(m2.Describe(), "Dragon#2(Lv.50)"); - AssertTrue(PureMonster.CompareLevel(m2, m1) > 0); - AssertTrue(m1 instanceof PureMonster); - AssertTrue(m1 instanceof BaseEntity); - }); - - Test("generic class RingBuffer and constrained generic function", () => { - const rb = new RingBuffer(3); - rb.Push(10); - rb.Push(20); - rb.Push(30); - rb.Push(40); // overwrites 10 - AssertEqual(rb.GetCount(), 3); - AssertEqual(rb.Pop(), 20); - AssertEqual(rb.Pop(), 30); - AssertEqual(rb.Pop(), 40); - AssertNil(rb.Pop()); - - const monsters = [new PureMonster(10, "Orc", 5), new PureMonster(20, "Goblin", 2)]; - const found = FindById(monsters, 20); - AssertTrue(found !== undefined); - AssertEqual(found!.GetName(), "Goblin"); - AssertNil(FindById(monsters, 999)); - }); - - Test("@unlua-allow-try framework boundary try/catch/throw", () => { - const [ok1, msg1] = SafeFrameworkBoundary(false); - AssertTrue(ok1); - AssertEqual(msg1, "ok"); - - const [ok2, msg2] = SafeFrameworkBoundary(true); - AssertFalse(ok2); - AssertTrue(string.find(msg2, "simulated_boundary_error", 1, true)[0] !== undefined); - }); - }); -} diff --git a/Script/ts/src/Tests/Syntax/UnLuaBaseActor.ts b/Script/ts/src/Tests/Syntax/UnLuaBaseActor.ts deleted file mode 100644 index 5c6c6ff..0000000 --- a/Script/ts/src/Tests/Syntax/UnLuaBaseActor.ts +++ /dev/null @@ -1,58 +0,0 @@ -export interface BaseActorConfig { - name: string; - hp?: number; -} - -export type ActorFaction = "Ally" | "Enemy" | "Neutral"; - -@unlua -export default class UnLuaBaseActor extends UE.AActor { - static readonly DEFAULT_HP = 100; - - protected hp!: number; - protected callTrace!: string[]; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.hp = UnLuaBaseActor.DEFAULT_HP; - this.callTrace = ["Base.ReceiveBeginPlay"]; - } - - ApplyConfig({ name, hp = UnLuaBaseActor.DEFAULT_HP }: BaseActorConfig): string { - this.hp = hp; - return `${name}:${this.hp}`; - } - - SumScores([first, second = 5, ...rest]: number[]): number { - let sum = first + second; - for (let i = 0; i < rest.length; i++) { - sum += rest[i]; - } - return sum; - } - - GetTrace(): string[] { - return this.callTrace; - } - - GetHp(): number { - return this.hp; - } - - ComputeBonus(baseVal: number, multiplier = 2): number { - return baseVal * multiplier; - } - - static StaticWithSelf(delta: number): number { - return this.DEFAULT_HP + delta; - } - - static StaticNoSelf(this: void, a: number, b: number): number { - return a + b; - } - - /** @noSelf */ - static StaticDocNoSelf(x: number): number { - return x * 3; - } -} diff --git a/Script/ts/src/Tests/Syntax/UnLuaExplicitWidget.ts b/Script/ts/src/Tests/Syntax/UnLuaExplicitWidget.ts deleted file mode 100644 index e1fe7ae..0000000 --- a/Script/ts/src/Tests/Syntax/UnLuaExplicitWidget.ts +++ /dev/null @@ -1,16 +0,0 @@ -export interface ExplicitWidgetModel { - title: string; -} - -@unlua("Tests.Syntax.UnLuaBaseActor") -export default class UnLuaExplicitWidget { - private title!: string; - - Construct(model: ExplicitWidgetModel): void { - this.title = model.title; - } - - GetTitle(): string { - return this.title; - } -} diff --git a/Script/ts/src/Tests/Syntax/UnLuaGrandChildActor.ts b/Script/ts/src/Tests/Syntax/UnLuaGrandChildActor.ts deleted file mode 100644 index 98ed9a1..0000000 --- a/Script/ts/src/Tests/Syntax/UnLuaGrandChildActor.ts +++ /dev/null @@ -1,20 +0,0 @@ -import UnLuaSubActor from "./UnLuaSubActor"; - -@unlua -export default class UnLuaGrandChildActor extends UnLuaSubActor { - private tier!: number; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.tier = 3; - this.callTrace[this.callTrace.length] = "GrandChild.ReceiveBeginPlay"; - } - - override ComputeBonus(baseVal: number, multiplier = 2): number { - return super.ComputeBonus(baseVal, multiplier) + this.tier; - } - - GetTier(): number { - return this.tier; - } -} diff --git a/Script/ts/src/Tests/Syntax/UnLuaSubActor.ts b/Script/ts/src/Tests/Syntax/UnLuaSubActor.ts deleted file mode 100644 index 985d091..0000000 --- a/Script/ts/src/Tests/Syntax/UnLuaSubActor.ts +++ /dev/null @@ -1,25 +0,0 @@ -import UnLuaBaseActor, { BaseActorConfig, type ActorFaction } from "./UnLuaBaseActor"; - -@unlua -export default class UnLuaSubActor extends UnLuaBaseActor { - protected faction!: ActorFaction; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.faction = "Ally"; - this.callTrace[this.callTrace.length] = "Sub.ReceiveBeginPlay"; - } - - override ComputeBonus(baseVal: number, multiplier = 2): number { - return super.ComputeBonus(baseVal, multiplier) + 10; - } - - SetupWithFaction(cfg: BaseActorConfig, faction: ActorFaction): string { - this.faction = faction; - return `${super.ApplyConfig(cfg)}[${this.faction}]`; - } - - GetFaction(): ActorFaction { - return this.faction; - } -} diff --git a/Script/ts/src/Tests/Syntax/UnLuaSyntaxSuite.ts b/Script/ts/src/Tests/Syntax/UnLuaSyntaxSuite.ts deleted file mode 100644 index a1d8a64..0000000 --- a/Script/ts/src/Tests/Syntax/UnLuaSyntaxSuite.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertTrue, - AssertArrayEqual, -} from "../Harness/TestRunner"; -import { CreateBoundInstance, GetMockState, ResetMockState } from "../Harness/MockUnLuaRuntime"; -import UnLuaBaseActor from "./UnLuaBaseActor"; -import UnLuaSubActor from "./UnLuaSubActor"; -import UnLuaGrandChildActor from "./UnLuaGrandChildActor"; -import UnLuaExplicitWidget from "./UnLuaExplicitWidget"; - -export function RunUnLuaSyntaxTests(): void { - Suite("Syntax.UnLuaClassFeatures", () => { - Test("@unlua base class: UnLua.Class(), self.Overridden, static methods and destructured params", () => { - ResetMockState(); - const actor = CreateBoundInstance( - UnLuaBaseActor as unknown as Record, - "AActor" - ); - actor.ReceiveBeginPlay(); - - AssertEqual(actor.GetHp(), 100); - AssertArrayEqual(actor.GetTrace(), ["Base.ReceiveBeginPlay"]); - AssertArrayEqual(GetMockState().overriddenCalls, ["AActor.ReceiveBeginPlay"]); - - // 解构对象与数组参数(含默认值与 rest) - AssertEqual(actor.ApplyConfig({ name: "Hero" }), "Hero:100"); - AssertEqual(actor.ApplyConfig({ name: "Boss", hp: 500 }), "Boss:500"); - AssertEqual(actor.SumScores([10]), 15); - AssertEqual(actor.SumScores([1, 2, 3, 4]), 10); - - // 静态方法(含 self 冒号调用与 @noSelf/this:void 点号调用) - AssertEqual(UnLuaBaseActor.StaticWithSelf(25), 125); - AssertEqual(UnLuaBaseActor.StaticNoSelf(7, 8), 15); - AssertEqual(UnLuaBaseActor.StaticDocNoSelf(9), 27); - - // UObject IsA 与 IsValid - AssertTrue(actor.IsA(UE.AActor.StaticClass())); - AssertTrue(UE.UKismetSystemLibrary.IsValid(actor)); - }); - - Test("@unlua 3-level inheritance (GrandChild -> Sub -> Base) avoids self.Super infinite recursion", () => { - ResetMockState(); - const grand = CreateBoundInstance( - UnLuaGrandChildActor as unknown as Record, - "AActor" - ); - grand.ReceiveBeginPlay(); - - AssertArrayEqual(grand.GetTrace(), [ - "Base.ReceiveBeginPlay", - "Sub.ReceiveBeginPlay", - "GrandChild.ReceiveBeginPlay", - ]); - AssertArrayEqual(GetMockState().overriddenCalls, ["AActor.ReceiveBeginPlay"]); - AssertEqual(grand.GetFaction(), "Ally"); - AssertEqual(grand.GetTier(), 3); - - // Base: 10*2 = 20, Sub: +10 = 30, GrandChild: +3 = 33 - AssertEqual(grand.ComputeBonus(10), 33); - AssertEqual(grand.ComputeBonus(10, 4), 53); - - // 混合默认+纯类型导入的父类方法调用 - const summary = grand.SetupWithFaction({ name: "Knight", hp: 250 }, "Enemy"); - AssertEqual(summary, "Knight:250[Enemy]"); - AssertEqual(grand.GetFaction(), "Enemy"); - }); - - Test("@unlua explicit base path class without extends", () => { - const widgetCls = UnLuaExplicitWidget as unknown as Record; - AssertEqual(widgetCls.Super, UnLuaBaseActor); - - const widget = CreateBoundInstance(widgetCls, "UUserWidget"); - widget.Construct({ title: "MainHUD" }); - AssertEqual(widget.GetTitle(), "MainHUD"); - }); - }); -} diff --git a/Script/ts/src/Tests/UE/UERuntimeSuite.ts b/Script/ts/src/Tests/UE/UERuntimeSuite.ts deleted file mode 100644 index b8a2ab5..0000000 --- a/Script/ts/src/Tests/UE/UERuntimeSuite.ts +++ /dev/null @@ -1,432 +0,0 @@ -/** @noSelfInFile */ - -import { - Reset, - PrintReport, - Suite, - Test, - AssertEqual, - AssertNear, - AssertTrue, - AssertFalse, - AssertNotNil, - AssertNil, - AssertArrayEqual, - SuiteSummary, -} from "../Harness/TestRunner"; -import { RunBasicTypesAndControlFlowTests } from "../Syntax/BasicTypesAndControlFlow"; -import { RunFunctionsClosuresAndTuplesTests } from "../Syntax/FunctionsClosuresAndTuples"; -import { RunPureClassesAndGenericsTests } from "../Syntax/PureClassesAndGenerics"; -import { RunGameplayTests } from "../Gameplay/GameplaySuite"; -import { RunLua54PitfallsTests } from "../Extra/Lua54PitfallsTest"; -import * as EventBus from "../../Framework/EventBus"; -import * as HotReload from "../../Framework/HotReload"; -import { - VerifyTArrayOperations, - VerifyTMapOperations, - VerifyTSetOperations, -} from "../UnLuaExamples/Ex06_NativeContainers"; -import type UnLuaBaseActor from "../Syntax/UnLuaBaseActor"; -import UnLuaBaseActorClass from "../Syntax/UnLuaBaseActor"; -import type UnLuaGrandChildActor from "../Syntax/UnLuaGrandChildActor"; -import type Ex01_HelloWorld from "../UnLuaExamples/Ex01_HelloWorld"; -import type Ex02_OverrideBlueprintEvents from "../UnLuaExamples/Ex02_OverrideBlueprintEvents"; -import type Ex04_DynamicSpawnedActor from "../UnLuaExamples/Ex04_DynamicSpawnedActor"; -import type Ex04_DynamicObject from "../UnLuaExamples/Ex04_DynamicObject"; -import type Ex07_CallLatentFunction from "../UnLuaExamples/Ex07_CallLatentFunction"; -import type Ex08_StructAndTrace from "../UnLuaExamples/Ex08_StructAndTrace"; -import type UETimerTestActor from "./UETimerTestActor"; - -function TickUEWorld(steps: number, deltaSeconds: number): void { - const tickFn = _G.__UE_TEST_TICK; - if (tickFn === undefined) { - return; - } - for (let i = 0; i < steps; i++) { - tickFn(deltaSeconds); - } -} - -export function RunUERuntimeSuite(world: UE.UWorld): void { - const canTickWorld = _G.__UE_TEST_TICK !== undefined; - - Suite("UE.RealEngineIntegration", () => { - Test("Real UE C++ TArray / TMap / TSet containers & native __pairs iteration", () => { - VerifyTArrayOperations(); - VerifyTMapOperations(); - VerifyTSetOperations(); - }); - - Test("Real UE SpawnActor + @unlua UnLuaBaseActor (Overridden, static methods, destructuring)", () => { - // UnLua 动态绑定按 UClass 缓存映射,每个独立 @unlua 测试类使用各自的轻量级原生 UClass - const actor = world.SpawnActor( - UE.ATargetPoint.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.Syntax.UnLuaBaseActor" - ); - AssertNotNil(actor); - AssertTrue(UE.UKismetSystemLibrary.IsValid(actor)); - AssertTrue(actor!.IsA(UE.AActor.StaticClass())); - - // SpawnActor 会自动触发 ReceiveBeginPlay - AssertEqual(actor!.GetHp(), 100); - AssertArrayEqual(actor!.GetTrace(), ["Base.ReceiveBeginPlay"]); - - // 解构形参 + 静态方法(冒号/点号) - AssertEqual(actor!.ApplyConfig({ name: "UEHero" }), "UEHero:100"); - AssertEqual(actor!.ApplyConfig({ name: "UEBoss", hp: 888 }), "UEBoss:888"); - AssertEqual(actor!.SumScores([10]), 15); - AssertEqual(actor!.SumScores([1, 2, 3, 4]), 10); - AssertEqual(UnLuaBaseActorClass.StaticWithSelf(25), 125); - AssertEqual(UnLuaBaseActorClass.StaticNoSelf(7, 8), 15); - AssertEqual(UnLuaBaseActorClass.StaticDocNoSelf(9), 27); - - actor!.K2_DestroyActor(); - }); - - Test("Real UE SpawnActor + 3-level @unlua inheritance (GrandChild -> Sub -> Base -> AActor)", () => { - const grand = world.SpawnActor( - UE.ATriggerBox.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.Syntax.UnLuaGrandChildActor" - ); - AssertNotNil(grand); - AssertArrayEqual(grand!.GetTrace(), [ - "Base.ReceiveBeginPlay", - "Sub.ReceiveBeginPlay", - "GrandChild.ReceiveBeginPlay", - ]); - AssertEqual(grand!.GetFaction(), "Ally"); - AssertEqual(grand!.GetTier(), 3); - AssertEqual(grand!.ComputeBonus(10), 33); - AssertEqual(grand!.SetupWithFaction({ name: "Knight", hp: 250 }, "Enemy"), "Knight:250[Enemy]"); - - grand!.K2_DestroyActor(); - }); - - Test("Real UE Ex01_HelloWorld & Ex02_OverrideBlueprintEvents lifecycle", () => { - const hello = world.SpawnActor( - UE.ATriggerSphere.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.UnLuaExamples.Ex01_HelloWorld" - ); - AssertNotNil(hello); - AssertTrue(string.find(hello!.GetGreeting(), "Hello UnLua from TypeScript", 1, true)[0] !== undefined); - hello!.K2_DestroyActor(); - - const eventsActor = world.SpawnActor( - UE.ATriggerCapsule.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.UnLuaExamples.Ex02_OverrideBlueprintEvents" - ); - AssertNotNil(eventsActor); - const events = eventsActor!.GetEvents(); - AssertTrue(events.length >= 2); - AssertEqual(events[0], "Initialize"); - - eventsActor!.K2_DestroyActor(); - }); - - Test("Real UE Ex04 DynamicBinding: SpawnActor, SpawnActorEx & UE.NewObject with Initializer", () => { - const spawned = world.SpawnActor( - UE.APlayerStart.StaticClass(), - UE.FTransform(UE.FRotator(0, 90, 0).ToQuat(), UE.FVector(100, 200, 300), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - { InitTag: "RealUESpawn", InitPower: 555 } - ); - AssertNotNil(spawned); - AssertEqual(spawned!.GetInitTag(), "RealUESpawn"); - AssertEqual(spawned!.GetInitPower(), 555); - AssertTrue(spawned!.IsBeginPlayCalled()); - spawned!.K2_DestroyActor(); - - const params = UE.FActorSpawnParameters(); - params.bNoFail = true; - params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn; - const spawnedEx = world.SpawnActorEx( - UE.APlayerStart.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(10, 20, 30), UE.FVector(1, 1, 1)), - { InitTag: "RealUESpawnEx", InitPower: 777 }, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - params - ); - AssertNotNil(spawnedEx); - AssertEqual(spawnedEx!.GetInitTag(), "RealUESpawnEx"); - AssertEqual(spawnedEx!.GetInitPower(), 777); - spawnedEx!.K2_DestroyActor(); - - // 注意:UnLua 不允许直接对基类 UObject 绑定模块,且需使用非抽象的具体 UObject 子类 - const dynObj = UE.NewObject( - UE.ULuaBundleAsset.StaticClass(), - world, - "RealUEDynObj", - "Tests.UnLuaExamples.Ex04_DynamicObject", - { Seed: 10 } - ); - AssertNotNil(dynObj); - AssertEqual(dynObj.GetSeed(), 10); - AssertEqual(dynObj.NextValue(), 21); - AssertEqual(dynObj.NextValue(), 43); - }); - - Test("Real UE Ex08 Struct math, K2_SetActorLocation & LineTraceSingle multi-return", () => { - const actor = world.SpawnActor( - UE.ATextRenderActor.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.UnLuaExamples.Ex08_StructAndTrace" - ); - AssertNotNil(actor); - - const [size, dot, dist] = actor!.ComputeVectorMath(); - AssertNear(size, 13, 1e-3); - AssertNear(dot, 0, 1e-3); - AssertNear(dist, 13, 1e-3); - - // 1. 验证传入复用 OutHit 原地写入(零 GC) - const [bHit, hitDist, impact] = actor!.TraceForward(500); - AssertEqual(type(bHit), "boolean"); - AssertEqual(type(hitDist), "number"); - AssertNotNil(impact); - - // 2. 验证传入 undefined 触发 UnLua 多返回值分配,且与复用模式命中结果完全一致(兼容空测试世界与非空 PIE 关卡) - const [bHit2, outHit2] = actor!.TraceForwardMultiReturn(500); - AssertEqual(bHit2, bHit); - AssertNotNil(outHit2); - if (bHit) { - AssertNear(hitDist, outHit2.Distance, 1e-2); - } - - actor!.K2_DestroyActor(); - }); - - Test("Real UE UnLua.Ref / UnLua.Unref & FWeakObjectPtr validity", () => { - const obj = UE.NewObject(UE.UObjectLibrary.StaticClass(), world, "WeakRefTarget"); - AssertTrue(UE.UKismetSystemLibrary.IsValid(obj)); - - const refProxy = UnLua.Ref(obj); - AssertNotNil(refProxy); - - // UnLua C++ 中 FWeakObjectPtr 构造必须传入 1 个 UObject 参数 - const weak = UE.FWeakObjectPtr(obj); - AssertTrue(weak.IsValid()); - AssertNotNil(weak.Get()); - - weak.Reset(); - AssertFalse(weak.IsValid()); - AssertNil(weak.Get()); - - UnLua.Unref(obj); - }); - - Test("Real UE ALuaDemoActor (C++ callback -> pure TS Game.LuaDemoActor) + EventBus + Tick + EndPlay", () => { - // 不调用 EventBus.Clear(),避免在 PIE 关卡中误清场景里已运行的 LuaDemoActor 监听 - const demoActor = world.SpawnActor( - UE.ALuaDemoActor.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 100), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - ); - AssertNotNil(demoActor); - AssertTrue(demoActor!.IsA(UE.ALuaDemoActor.StaticClass())); - - // Spawn 时已通过 C++ FLuaCallbackBridge 回调 Game.LuaDemoActor.OnBeginPlay - const initText = demoActor!.GetStatusTextString(); - AssertTrue(string.find(initText, "Pure-TS Actor", 1, true)[0] !== undefined, "initText: " + initText); - AssertTrue(string.find(initText, "Pings: 0", 1, true)[0] !== undefined); - - if (canTickWorld) { - TickUEWorld(5, 0.05); - } - - // 触发 EventBus Ping,验证 C++ 3D 文本实时更新 - EventBus.Emit("Demo.Ping", "UERealEngineTest"); - const pingedText = demoActor!.GetStatusTextString(); - AssertTrue(string.find(pingedText, "Pings: 1", 1, true)[0] !== undefined); - AssertTrue(string.find(pingedText, "Color: Gold", 1, true)[0] !== undefined); - - // 验证 ALuaDemoActor 位置移动(带 SceneRoot 组件) - const [bMoved] = demoActor!.K2_SetActorLocation(UE.FVector(120, 240, 360), false, undefined, true); - AssertTrue(bMoved); - const loc = demoActor!.K2_GetActorLocation(); - AssertNear(loc.X, 120, 1e-2); - AssertNear(loc.Y, 240, 1e-2); - AssertNear(loc.Z, 360, 1e-2); - - demoActor!.K2_DestroyActor(); - }); - - if (canTickWorld) { - Test("Real UE FTimerManager + K2_SetTimerDelegate(UnLua.Delegate) ticked by UWorld", () => { - const timerActor = world.SpawnActor( - UE.ACameraActor.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.UE.UETimerTestActor" - ); - AssertNotNil(timerActor); - AssertTrue(timerActor!.IsTimerActive()); - AssertEqual(timerActor!.GetTimerCount(), 0); - - // 推进真实 UWorld 0.5s(FTimerManager 首帧激活 Pending 列表,后续每 0.1s 触发一次,应 >= 3 次) - TickUEWorld(10, 0.05); - AssertTrue(timerActor!.GetTimerCount() >= 3); - - const countBeforeStop = timerActor!.GetTimerCount(); - timerActor!.StopTimer(); - AssertFalse(timerActor!.IsTimerActive()); - - TickUEWorld(6, 0.05); - AssertEqual(timerActor!.GetTimerCount(), countBeforeStop); - - timerActor!.K2_DestroyActor(); - }); - - Test("Real UE FLatentActionManager + UKismetSystemLibrary.Delay coroutine (Ex07)", () => { - const latentActor = world.SpawnActor( - UE.ADecalActor.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 0), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - undefined, - undefined, - "Tests.UnLuaExamples.Ex07_CallLatentFunction" - ); - AssertNotNil(latentActor); - AssertArrayEqual(latentActor!.GetSteps(), ["Step1:Start"]); - AssertFalse(latentActor!.IsCompleted()); - - // 推进 0.6s -> 越过第一个 0.5s Delay - TickUEWorld(6, 0.1); - AssertArrayEqual(latentActor!.GetSteps(), ["Step1:Start", "Step2:After0.5s"]); - AssertFalse(latentActor!.IsCompleted()); - - // 再推进 1.1s -> 越过第二个 1.0s Delay - TickUEWorld(11, 0.1); - AssertArrayEqual(latentActor!.GetSteps(), [ - "Step1:Start", - "Step2:After0.5s", - "Step3:Done", - ]); - AssertTrue(latentActor!.IsCompleted()); - - latentActor!.K2_DestroyActor(); - }); - } - - Test("Real UE HotReload.ReloadModule validates arguments and emits events", () => { - const [badOk] = HotReload.ReloadModule(""); - AssertFalse(badOk); - const [ok] = HotReload.ReloadModule("Framework.Log"); - AssertTrue(ok); - }); - - Test("Real UE single-file __MODULE__.Reimport hot-reloads Game.LuaDemoActor spin speed and color live", () => { - const demoActor = world.SpawnActor( - UE.ALuaDemoActor.StaticClass(), - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(0, 0, 200), UE.FVector(1, 1, 1)), - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn - ); - AssertNotNil(demoActor); - - const beforeText = demoActor!.GetStatusTextString(); - AssertTrue(string.find(beforeText, "v1", 1, true)[0] !== undefined); - AssertTrue(string.find(beforeText, "Speed: 60", 1, true)[0] !== undefined); - AssertTrue(string.find(beforeText, "Color: Cyan", 1, true)[0] !== undefined); - - const actorMod = __MODULE__.Import("Game.LuaDemoActor"); - const activeBefore: number = actorMod.GetActiveControllerCount(); - AssertTrue(activeBefore >= 1); - - // 模拟修改 Game/LuaDemoActor.lua 的旋转速度与颜色,写入热更覆盖目录并触发单文件热更 - const defaultDir = UE.ULuaHotUpdateSubsystem.GetDefaultScriptDir(); - const overrideDir = UE.ULuaHotUpdateSubsystem.GetHotUpdateScriptDir(); - const srcPath = defaultDir + "/Game/LuaDemoActor.lua"; - const dstGameDir = overrideDir + "/Game"; - const dstPath = dstGameDir + "/LuaDemoActor.lua"; - - const srcFile = io.open(srcPath, "rb")[0]; - AssertNotNil(srcFile); - const origLua = srcFile!.read("a") as string; - srcFile!.close(); - - let [patchedLua] = string.gsub(origLua, '"v1"', '"v2-HOTFIX"'); - [patchedLua] = string.gsub(patchedLua, "ACTOR_SPIN_SPEED = 60", "ACTOR_SPIN_SPEED = 240"); - [patchedLua] = string.gsub(patchedLua, '"Cyan"', '"Crimson"'); - [patchedLua] = string.gsub(patchedLua, "R = 0%.08", "R = 0.95"); - [patchedLua] = string.gsub(patchedLua, "G = 0%.78", "G = 0.12"); - [patchedLua] = string.gsub(patchedLua, "B = 0%.95", "B = 0.18"); - os.execute(string.format('mkdir -p "%s"', dstGameDir)); - const dstFile = io.open(dstPath, "wb")[0]; - AssertNotNil(dstFile); - dstFile!.write(patchedLua); - dstFile!.close(); - - const [okReload, errReload] = HotReload.ReloadModule("Game.LuaDemoActor"); - // 立即清理临时覆盖文件,避免断言失败时残留覆盖文件污染后续运行 - os.remove(dstPath); - AssertTrue(okReload, tostring(errReload)); - - // 1. 模块导出即时更新且 @module_data 活跃控制器表完整保留 - AssertEqual(actorMod.DEMO_VERSION, "v2-HOTFIX"); - AssertEqual(actorMod.ACTOR_SPIN_SPEED, 240); - AssertEqual(actorMod.GetActiveControllerCount(), activeBefore); - // 2. 运行中 Actor 的颜色与 3D 状态文本已通过 __module.OnReimport 即时刷新 - const newColor = demoActor!.GetCubeColor(); - AssertNear(newColor.R, 0.95, 1e-2); - AssertNear(newColor.G, 0.12, 1e-2); - const afterText = demoActor!.GetStatusTextString(); - AssertTrue(string.find(afterText, "v2-HOTFIX", 1, true)[0] !== undefined, "afterText: " + afterText); - AssertTrue(string.find(afterText, "Speed: 240", 1, true)[0] !== undefined, "afterText: " + afterText); - AssertTrue(string.find(afterText, "Color: Crimson", 1, true)[0] !== undefined, "afterText: " + afterText); - - // 热更还原 - const [okRestore] = HotReload.ReloadModule("Game.LuaDemoActor"); - AssertTrue(okRestore); - AssertEqual(actorMod.DEMO_VERSION, "v1"); - AssertEqual(actorMod.ACTOR_SPIN_SPEED, 60); - - demoActor!.K2_DestroyActor(); - }); - }); -} - -/** - * 在真实 UE 5.8 + UnLua 2.3.6 环境下运行的统一入口。 - * 可由 RunLuaTestsCommandlet 或编辑器控制台命令 `Lua.RunTests` 调用。 - */ -export function RunAllInUE(world?: UE.UWorld): SuiteSummary { - const targetWorld = world ?? _G.__UE_TEST_WORLD; - Reset(); - - // 1. 纯逻辑与语法测试(运行在 UnLua 内嵌 Lua 5.4.3 VM 中) - RunBasicTypesAndControlFlowTests(); - RunFunctionsClosuresAndTuplesTests(); - RunPureClassesAndGenericsTests(); - RunGameplayTests(); - RunLua54PitfallsTests(); - - // 2. 真实 UE 5.8 引擎 + UnLua 反射/绑定/容器/定时器/协程集成测试 - if (targetWorld !== undefined) { - RunUERuntimeSuite(targetWorld); - } - - return PrintReport(); -} diff --git a/Script/ts/src/Tests/UE/UETimerTestActor.ts b/Script/ts/src/Tests/UE/UETimerTestActor.ts deleted file mode 100644 index 34161d2..0000000 --- a/Script/ts/src/Tests/UE/UETimerTestActor.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 用于真实 UE 5.8 环境下测试 K2_SetTimerDelegate + UnLua.Delegate(this, this.OnTimer) - * 与真实 UWorld::Tick -> FTimerManager 调度的 @unlua Actor。 - */ -@unlua -export default class UETimerTestActor extends UE.AActor { - private timerCount!: number; - private timerHandle!: UE.FTimerHandle; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.timerCount = 0; - this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate( - UnLua.Delegate(this, this.OnTimerTick), - 0.1, - true - ); - } - - OnTimerTick(): void { - if (!UE.UKismetSystemLibrary.IsValid(this)) { - return; - } - this.timerCount++; - } - - StopTimer(): void { - UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle); - } - - GetTimerCount(): number { - return this.timerCount; - } - - IsTimerActive(): boolean { - return UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(this, this.timerHandle); - } - - ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void { - this.StopTimer(); - super.ReceiveEndPlay(EndPlayReason); - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex01_HelloWorld.ts b/Script/ts/src/Tests/UnLuaExamples/Ex01_HelloWorld.ts deleted file mode 100644 index 6c956ca..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex01_HelloWorld.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 参考 UnLua 官方示例 01_HelloWorld: - * 演示最简 @unlua Actor 绑定、ReceiveBeginPlay、屏幕打印与 UnLua.Log。 - */ -@unlua -export default class Ex01_HelloWorld extends UE.AActor { - private greeting!: string; - - ReceiveBeginPlay(): void { - this.greeting = `Hello UnLua from TypeScript (${_VERSION})!`; - UnLua.Log(this.greeting); - UE.UKismetSystemLibrary.PrintString( - this, - this.greeting, - true, - true, - UE.FLinearColor(0.1, 0.9, 0.4, 1.0), - 5.0 - ); - } - - GetGreeting(): string { - return this.greeting; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex02_OverrideBlueprintEvents.ts b/Script/ts/src/Tests/UnLuaExamples/Ex02_OverrideBlueprintEvents.ts deleted file mode 100644 index a93a977..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex02_OverrideBlueprintEvents.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * 参考 UnLua 官方示例 02_OverrideBlueprintEvents: - * 演示覆写蓝图/Actor 生命周期事件,并通过 super.Method() 调用 self.Overridden.Method(self, ...)。 - */ -@unlua -export default class Ex02_OverrideBlueprintEvents extends UE.AActor { - private events!: string[]; - private totalDamage!: number; - private elapsed!: number; - private overlapCount!: number; - - Initialize(_Initializer?: unknown): void { - this.events = ["Initialize"]; - this.totalDamage = 0; - this.elapsed = 0; - this.overlapCount = 0; - } - - UserConstructionScript(): void { - super.UserConstructionScript(); - this.events[this.events.length] = "UserConstructionScript"; - } - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.events[this.events.length] = "ReceiveBeginPlay"; - } - - ReceiveTick(DeltaSeconds: number): void { - super.ReceiveTick(DeltaSeconds); - this.elapsed += DeltaSeconds; - } - - ReceiveAnyDamage( - Damage: number, - _DamageType: UE.UDamageType | undefined, - _InstigatedBy: UE.AController | undefined, - _DamageCauser: UE.AActor | undefined - ): void { - super.ReceiveAnyDamage(Damage, _DamageType, _InstigatedBy, _DamageCauser); - this.totalDamage += Damage; - this.events[this.events.length] = `Damage:${Damage}`; - } - - ReceiveActorBeginOverlap(OtherActor: UE.AActor | undefined): void { - super.ReceiveActorBeginOverlap(OtherActor); - if (UE.UKismetSystemLibrary.IsValid(OtherActor)) { - this.overlapCount++; - this.events[this.events.length] = `Overlap:${OtherActor!.GetName()}`; - } - } - - ReceiveEndPlay(EndPlayReason: UE.EEndPlayReason): void { - super.ReceiveEndPlay(EndPlayReason); - this.events[this.events.length] = `EndPlay:${EndPlayReason}`; - } - - GetEvents(): string[] { - return this.events; - } - - GetTotalDamage(): number { - return this.totalDamage; - } - - GetElapsed(): number { - return this.elapsed; - } - - GetOverlapCount(): number { - return this.overlapCount; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex03_BindDelegates.ts b/Script/ts/src/Tests/UnLuaExamples/Ex03_BindDelegates.ts deleted file mode 100644 index 2457e28..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex03_BindDelegates.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 参考 UnLua 官方示例 03_BindDelegates: - * 演示 MulticastDelegate (Add/Remove/Clear)、单播 FScriptDelegate (Bind/Unbind/Execute) - * 以及 K2_SetTimerDelegate + UnLua.Delegate(this, this.OnTimer) 定时器委托绑定与销毁清理。 - */ -@unlua -export default class Ex03_BindDelegates extends UE.UUserWidget { - ClickMeButton!: UE.UButton; - CustomSingleDelegate!: UE.FScriptDelegate<(value: number) => number>; - - private clickCount!: number; - private timerTickCount!: number; - private timerHandle!: UE.FTimerHandle; - - Construct(): void { - this.clickCount = 0; - this.timerTickCount = 0; - - if (this.ClickMeButton !== undefined) { - this.ClickMeButton.OnClicked.Add(this, this.OnButtonClicked); - } - - if (this.CustomSingleDelegate !== undefined) { - this.CustomSingleDelegate.Bind(this, this.OnCustomExecute); - } - - // UnLua.Delegate 编译期宏直接内联为 { self, self.OnTimerTick } - this.timerHandle = UE.UKismetSystemLibrary.K2_SetTimerDelegate( - UnLua.Delegate(this, this.OnTimerTick), - 0.5, - true - ); - } - - OnButtonClicked(): void { - this.clickCount++; - } - - OnCustomExecute(value: number): number { - return value * 10 + this.clickCount; - } - - OnTimerTick(): void { - if (!UE.UKismetSystemLibrary.IsValid(this)) { - return; - } - this.timerTickCount++; - } - - Destruct(): void { - if (this.ClickMeButton !== undefined) { - this.ClickMeButton.OnClicked.Remove(this, this.OnButtonClicked); - } - if (this.CustomSingleDelegate !== undefined) { - this.CustomSingleDelegate.Unbind(); - } - UE.UKismetSystemLibrary.K2_ClearAndInvalidateTimerHandle(this, this.timerHandle); - } - - GetClickCount(): number { - return this.clickCount; - } - - GetTimerTickCount(): number { - return this.timerTickCount; - } - - GetTimerHandle(): UE.FTimerHandle { - return this.timerHandle; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicBinding.ts b/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicBinding.ts deleted file mode 100644 index 873623e..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicBinding.ts +++ /dev/null @@ -1,66 +0,0 @@ -import type Ex04_DynamicSpawnedActor from "./Ex04_DynamicSpawnedActor"; -import type Ex04_DynamicObject from "./Ex04_DynamicObject"; - -/** - * 参考 UnLua 官方示例 04_DynamicBinding: - * 演示 World:SpawnActor、World:SpawnActorEx 与 UE.NewObject 动态绑定 Lua 模块并传入 Initializer 表。 - */ -@unlua -export default class Ex04_DynamicBinding extends UE.AActor { - SpawnDynamicActor(tag: string, power: number): Ex04_DynamicSpawnedActor | undefined { - const world = this.GetWorld(); - const actorClass = UE.UClass.Load("/Game/Blueprints/BP_DynamicDemo.BP_DynamicDemo_C"); - if (!world || !actorClass) { - return undefined; - } - const transform = UE.FTransform( - UE.FRotator(0, 90, 0).ToQuat(), - UE.FVector(100, 200, 300), - UE.FVector(1, 1, 1) - ); - return world.SpawnActor( - actorClass, - transform, - UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn, - this, - undefined, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - { InitTag: tag, InitPower: power } - ); - } - - SpawnDynamicActorEx(tag: string): Ex04_DynamicSpawnedActor | undefined { - const world = this.GetWorld(); - const actorClass = UE.LoadClass("/Game/Blueprints/BP_DynamicDemoEx.BP_DynamicDemoEx_C"); - if (!world || !actorClass) { - return undefined; - } - const params = UE.FActorSpawnParameters(); - params.Name = "ExSpawnedActor"; - params.bNoFail = true; - params.Owner = this; - params.SpawnCollisionHandlingOverride = UE.ESpawnActorCollisionHandlingMethod.AlwaysSpawn; - - return world.SpawnActorEx( - actorClass, - UE.FTransform(UE.FRotator(0, 0, 0).ToQuat(), UE.FVector(10, 20, 30), UE.FVector(1, 1, 1)), - { InitTag: tag, InitPower: 77 }, - "Tests.UnLuaExamples.Ex04_DynamicSpawnedActor", - params - ); - } - - CreateDynamicObject(seed: number): Ex04_DynamicObject | undefined { - const objClass = UE.UClass.Load("/Script/CoreUObject.Object"); - if (!objClass) { - return undefined; - } - return UE.NewObject( - objClass, - this, - "DynamicObjectInstance", - "Tests.UnLuaExamples.Ex04_DynamicObject", - { Seed: seed } - ); - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicObject.ts b/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicObject.ts deleted file mode 100644 index 90f08e3..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicObject.ts +++ /dev/null @@ -1,24 +0,0 @@ -export interface DynamicObjectInitializer { - Seed?: number; -} - -/** - * 参考 UnLua 官方示例 04_DynamicBinding:通过 UE.NewObject 动态创建的 UObject。 - */ -@unlua -export default class Ex04_DynamicObject extends UE.UObject { - private seed!: number; - - Initialize(Initializer?: DynamicObjectInitializer): void { - this.seed = Initializer?.Seed ?? 1; - } - - NextValue(): number { - this.seed = this.seed * 2 + 1; - return this.seed; - } - - GetSeed(): number { - return this.seed; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicSpawnedActor.ts b/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicSpawnedActor.ts deleted file mode 100644 index 26489eb..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex04_DynamicSpawnedActor.ts +++ /dev/null @@ -1,37 +0,0 @@ -export interface DynamicActorInitializer { - InitTag?: string; - InitPower?: number; -} - -/** - * 参考 UnLua 官方示例 04_DynamicBinding:被动态 Spawn 并绑定 Lua 脚本的 Actor。 - */ -@unlua -export default class Ex04_DynamicSpawnedActor extends UE.AActor { - private initTag!: string; - private initPower!: number; - private beginPlayCalled!: boolean; - - Initialize(Initializer?: DynamicActorInitializer): void { - this.initTag = Initializer?.InitTag ?? "Default"; - this.initPower = Initializer?.InitPower ?? 0; - this.beginPlayCalled = false; - } - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.beginPlayCalled = true; - } - - GetInitTag(): string { - return this.initTag; - } - - GetInitPower(): number { - return this.initPower; - } - - IsBeginPlayCalled(): boolean { - return this.beginPlayCalled; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex05_BindInputs.ts b/Script/ts/src/Tests/UnLuaExamples/Ex05_BindInputs.ts deleted file mode 100644 index ff6be5f..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex05_BindInputs.ts +++ /dev/null @@ -1,85 +0,0 @@ -/** - * 参考 UnLua 官方示例 05_BindInputs: - * 演示 UnLua.Input.BindKey / BindAction / BindAxis 以及 UnLua.EnhancedInput.BindAction。 - */ -@unlua -export default class Ex05_BindInputs extends UE.APlayerController { - private lastAction!: string; - private moveForwardValue!: number; - private enhancedCount!: number; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.lastAction = ""; - this.moveForwardValue = 0; - this.enhancedCount = 0; - } - - HandleSpacePressed(): void { - this.lastAction = "SpaceBar:Pressed"; - } - - HandleCtrlSave(): void { - this.lastAction = "Ctrl+S"; - } - - HandleJumpAction(): void { - this.lastAction = "Action:Jump"; - } - - HandleMoveForward(axisValue: number): void { - this.moveForwardValue = axisValue; - } - - HandleEnhancedMove(actionValue: number): void { - this.enhancedCount++; - this.moveForwardValue = actionValue; - } - - GetLastAction(): string { - return this.lastAction; - } - - GetMoveForwardValue(): number { - return this.moveForwardValue; - } - - GetEnhancedCount(): number { - return this.enhancedCount; - } -} - -UnLua.Input.BindKey(Ex05_BindInputs, "SpaceBar", "Pressed", function (this: Ex05_BindInputs) { - this.HandleSpacePressed(); -}); - -UnLua.Input.BindKey( - Ex05_BindInputs, - "S", - "Pressed", - function (this: Ex05_BindInputs) { - this.HandleCtrlSave(); - }, - { Ctrl: true } -); - -UnLua.Input.BindAction(Ex05_BindInputs, "Jump", "Pressed", function (this: Ex05_BindInputs) { - this.HandleJumpAction(); -}); - -UnLua.Input.BindAxis( - Ex05_BindInputs, - "MoveForward", - function (this: Ex05_BindInputs, axisValue: number) { - this.HandleMoveForward(axisValue); - } -); - -UnLua.EnhancedInput.BindAction( - Ex05_BindInputs, - "/Game/Input/IA_Move.IA_Move", - "Triggered", - function (this: Ex05_BindInputs, actionValue: number) { - this.HandleEnhancedMove(actionValue); - } -); diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts b/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts deleted file mode 100644 index 7b3a1e9..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex06_NativeContainers.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** @noSelfInFile */ - -import { - AssertEqual, - AssertTrue, - AssertFalse, - AssertNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; - -/** - * 参考 UnLua 官方示例 06_NativeContainers: - * 演示 UE.TArray / UE.TMap / UE.TSet 的构造(使用 UE.int32 / UE.FString Token)、 - * 1-based 索引访问、CRUD、ToTable 与原生 pairs() 遍历。 - */ -export function VerifyTArrayOperations(): void { - const arr = UE.TArray(UE.int32); - AssertTrue(arr.Reserve(8)); - AssertEqual(arr.Length(), 0); - - AssertEqual(arr.Add(10), 1); - AssertEqual(arr.Add(20), 2); - AssertEqual(arr.Add(30), 3); - AssertEqual(arr.Length(), 3); - AssertEqual(arr.Num(), 3); - - // 1-based Get / Set / LastIndex / IsValidIndex - AssertEqual(arr.Get(1), 10); - AssertEqual(arr.Get(3), 30); - AssertEqual(arr.LastIndex(), 3); - AssertTrue(arr.IsValidIndex(1)); - AssertFalse(arr.IsValidIndex(0)); - AssertFalse(arr.IsValidIndex(4)); - - arr.Set(2, 25); - AssertEqual(arr.Get(2), 25); - AssertEqual(arr.Find(25), 2); - AssertTrue(arr.Contains(25)); - AssertFalse(arr.Contains(999)); - - // AddUnique:UnLua C++ 中若元素已存在,返回已有元素的 1-based 索引;否则追加并返回新索引 - AssertEqual(arr.AddUnique(25), 2); - AssertEqual(arr.AddUnique(40), 4); - AssertEqual(arr.Length(), 4); - - // Insert & Swap & Remove & RemoveItem - arr.Insert(15, 2); // [10, 15, 25, 30, 40] - AssertEqual(arr.Get(2), 15); - arr.Swap(1, 5); // [40, 15, 25, 30, 10] - AssertEqual(arr.Get(1), 40); - AssertEqual(arr.Get(5), 10); - - arr.Add(15); - const removedCount = arr.RemoveItem(15); - AssertEqual(removedCount, 2); - AssertFalse(arr.Contains(15)); - - // Append & ToTable - const other = UE.TArray(UE.int32); - other.Add(100); - other.Add(200); - arr.Append(other); - const tbl = arr.ToTable(); - AssertArrayEqual(tbl, [40, 25, 30, 10, 100, 200]); - - // for..of 直接编译为 Lua 原生 pairs(arr) 遍历 TArray - let sum = 0; - for (const [idx, val] of arr) { - AssertTrue(idx >= 1); - sum += val; - } - AssertEqual(sum, 405); - - arr.Clear(); - AssertEqual(arr.Length(), 0); -} - -export function VerifyTMapOperations(): void { - const map = UE.TMap(UE.FString, UE.int32); - map.Add("HP", 100); - map.Add("MP", 50); - map.Add("ATK", 35); - - AssertEqual(map.Length(), 3); - AssertEqual(map.Find("HP"), 100); - AssertEqual(map.FindRef("MP"), 50); - AssertNil(map.Find("DEF")); - - // 覆盖已有键 - map.Add("HP", 120); - AssertEqual(map.Find("HP"), 120); - - // Keys / Values / ToTable - AssertEqual(map.Keys().Length(), 3); - AssertEqual(map.Values().Length(), 3); - const tbl = map.ToTable(); - AssertEqual(tbl["ATK"], 35); - - // for..of 直接编译为 Lua 原生 pairs(map) 遍历 TMap - let sum = 0; - for (const [_k, v] of map) { - sum += v; - } - AssertEqual(sum, 205); - - AssertTrue(map.Remove("MP")); - AssertFalse(map.Remove("NotExist")); - AssertEqual(map.Length(), 2); - - map.Clear(); - AssertEqual(map.Length(), 0); -} - -export function VerifyTSetOperations(): void { - const set = UE.TSet(UE.FString); - set.Add("Fire"); - set.Add("Ice"); - set.Add("Fire"); // duplicate ignored - - AssertEqual(set.Length(), 2); - AssertTrue(set.Contains("Fire")); - AssertFalse(set.Contains("Poison")); - - const asArr = set.ToArray(); - AssertEqual(asArr.Length(), 2); - AssertEqual(set.ToTable().length, 2); - - AssertTrue(set.Remove("Ice")); - AssertFalse(set.Remove("Ice")); - AssertEqual(set.Length(), 1); - - set.Clear(); - AssertEqual(set.Length(), 0); -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex07_CallLatentFunction.ts b/Script/ts/src/Tests/UnLuaExamples/Ex07_CallLatentFunction.ts deleted file mode 100644 index bd99db8..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex07_CallLatentFunction.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 参考 UnLua 官方示例 07_CallLatentFunction: - * 演示用 Lua coroutine 驱动 UE Latent 函数(UKismetSystemLibrary.Delay), - * 并在每次恢复后校验 IsValid(this) 防止对象已被销毁。 - */ -@unlua -export default class Ex07_CallLatentFunction extends UE.AActor { - private steps!: string[]; - private completed!: boolean; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this.steps = []; - this.completed = false; - - const co = coroutine.create((actor: Ex07_CallLatentFunction) => { - actor.RunSequence(); - }); - const [ok, err] = coroutine.resume(co, this); - if (!ok) { - UnLua.LogError("Ex07 coroutine failed:", tostring(err)); - } - } - - private RunSequence(): void { - this.steps[this.steps.length] = "Step1:Start"; - - UE.UKismetSystemLibrary.Delay(this, 0.5); - if (!UE.UKismetSystemLibrary.IsValid(this)) { - return; - } - this.steps[this.steps.length] = "Step2:After0.5s"; - - UE.UKismetSystemLibrary.Delay(this, 1.0); - if (!UE.UKismetSystemLibrary.IsValid(this)) { - return; - } - this.steps[this.steps.length] = "Step3:Done"; - this.completed = true; - } - - GetSteps(): string[] { - return this.steps; - } - - IsCompleted(): boolean { - return this.completed; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts b/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts deleted file mode 100644 index 6a75dbe..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex08_StructAndTrace.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * 参考 UnLua 官方示例 08/09(结构体数学运算、Out 参数多返回值、热路径缓存结构体): - * 演示 FVector/FRotator/FTransform 运算、LineTraceSingle 多返回值与 K2_SetActorLocation。 - */ -@unlua -export default class Ex08_StructAndTrace extends UE.AActor { - private _tmpStart!: UE.FVector; - private _tmpEnd!: UE.FVector; - private _tmpHit!: UE.FHitResult; - private _ignoreActors!: UE.TArray; - - ReceiveBeginPlay(): void { - super.ReceiveBeginPlay(); - this._tmpStart = UE.FVector(0, 0, 0); - this._tmpEnd = UE.FVector(0, 0, 0); - this._tmpHit = UE.FHitResult(); - this._ignoreActors = UE.TArray(UE.AActor.StaticClass()); - this._ignoreActors.Add(this); - } - - ComputeVectorMath(): LuaMultiReturn<[number, number, number]> { - const a = UE.FVector(3, 4, 0); - const b = UE.FVector(0, 0, 12); - const dot = a.Dot(b); // 0 - // UnLua C++ 中 FVector:Add(b) 原地修改 self(无返回值),零额外结构体分配 - a.Add(b); // a 变为 (3, 4, 12), size = 13 - const dist = UE.FVector.Dist(UE.FVector(0, 0, 0), a); // 13 - return $multi(a.Size(), dot, dist); - } - - TraceForward(distance: number): LuaMultiReturn<[boolean, number, UE.FVector]> { - const origin = this.K2_GetActorLocation(); - this._tmpStart.Set(origin.X, origin.Y, origin.Z); - this._tmpEnd.Set(origin.X + distance, origin.Y, origin.Z); - - // UnLua 中传入已分配的 Out 参数(this._tmpHit)时会原地写入该结构体(零 GC),不再作为第二个返回值压栈; - // 传入 undefined 时才新分配并作为第二个返回值返回。此处同时兼容复用与多返回值模式。 - const [bHit, returnedHit] = UE.UKismetSystemLibrary.LineTraceSingle( - this, - this._tmpStart, - this._tmpEnd, - UE.ETraceTypeQuery.TraceTypeQuery1, - false, - this._ignoreActors, - UE.EDrawDebugTrace.None, - this._tmpHit, - true - ); - const hit = returnedHit ?? this._tmpHit; - return $multi(bHit, hit.Distance, hit.ImpactPoint); - } - - TraceForwardMultiReturn(distance: number): LuaMultiReturn<[boolean, UE.FHitResult]> { - const origin = this.K2_GetActorLocation(); - this._tmpStart.Set(origin.X, origin.Y, origin.Z); - this._tmpEnd.Set(origin.X + distance, origin.Y, origin.Z); - - return UE.UKismetSystemLibrary.LineTraceSingle( - this, - this._tmpStart, - this._tmpEnd, - UE.ETraceTypeQuery.TraceTypeQuery1, - false, - this._ignoreActors, - UE.EDrawDebugTrace.None, - undefined, - true - ); - } - - TeleportTo(x: number, y: number, z: number): boolean { - const target = UE.FVector(x, y, z); - const [bMoved] = this.K2_SetActorLocation(target, false, this._tmpHit, true); - return bMoved; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts b/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts deleted file mode 100644 index e663d96..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/Ex09_AssetRefAndUMG.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * 参考 UnLua 官方示例 11_ReleaseUMG & 资源加载/手动 GC 引用管理: - * 演示 UE.UObject.Load、UnLua.Ref / UnLua.Unref、FWeakObjectPtr 与 UUserWidget 完整生命周期。 - */ -@unlua -export default class Ex09_AssetRefAndUMG extends UE.UUserWidget { - private loadedAsset!: UE.UObject | undefined; - private refProxy!: unknown; - private weakRef!: UE.FWeakObjectPtr | undefined; - private isConstructed!: boolean; - private isDestructed!: boolean; - - Initialize(_Initializer?: unknown): void { - this.isConstructed = false; - this.isDestructed = false; - this.weakRef = undefined; - } - - Construct(): void { - this.isConstructed = true; - this.loadedAsset = UE.UObject.Load("/Game/UI/Textures/T_Icon.T_Icon"); - if (this.loadedAsset !== undefined) { - this.refProxy = UnLua.Ref(this.loadedAsset); - this.weakRef = UE.FWeakObjectPtr(this.loadedAsset); - } - } - - ShowOnScreen(): void { - this.AddToViewport(10); - } - - CloseAndRelease(): void { - this.RemoveFromParent(); - this.Destruct(); - this.Release(); - } - - Destruct(): void { - if (this.isDestructed) { - return; - } - this.isDestructed = true; - if (this.loadedAsset !== undefined) { - UnLua.Unref(this.loadedAsset); - this.refProxy = undefined; - this.loadedAsset = undefined; - } - if (this.weakRef !== undefined) { - this.weakRef.Reset(); - this.weakRef = undefined; - } - } - - HasValidWeakAsset(): boolean { - return this.weakRef !== undefined && this.weakRef.IsValid(); - } - - IsConstructed(): boolean { - return this.isConstructed; - } - - IsDestructed(): boolean { - return this.isDestructed; - } -} diff --git a/Script/ts/src/Tests/UnLuaExamples/UnLuaExamplesSuite.ts b/Script/ts/src/Tests/UnLuaExamples/UnLuaExamplesSuite.ts deleted file mode 100644 index 9e8bb76..0000000 --- a/Script/ts/src/Tests/UnLuaExamples/UnLuaExamplesSuite.ts +++ /dev/null @@ -1,262 +0,0 @@ -/** @noSelfInFile */ - -import { - Suite, - Test, - AssertEqual, - AssertNear, - AssertTrue, - AssertFalse, - AssertNotNil, - AssertArrayEqual, -} from "../Harness/TestRunner"; -import { - AdvanceMockTime, - CreateBoundInstance, - CreateMockMulticastDelegate, - CreateMockScriptDelegate, - GetMockState, - ResetMockState, -} from "../Harness/MockUnLuaRuntime"; -import Ex01_HelloWorld from "./Ex01_HelloWorld"; -import Ex02_OverrideBlueprintEvents from "./Ex02_OverrideBlueprintEvents"; -import Ex03_BindDelegates from "./Ex03_BindDelegates"; -import Ex04_DynamicBinding from "./Ex04_DynamicBinding"; -import Ex05_BindInputs from "./Ex05_BindInputs"; -import { - VerifyTArrayOperations, - VerifyTMapOperations, - VerifyTSetOperations, -} from "./Ex06_NativeContainers"; -import Ex07_CallLatentFunction from "./Ex07_CallLatentFunction"; -import Ex08_StructAndTrace from "./Ex08_StructAndTrace"; -import Ex09_AssetRefAndUMG from "./Ex09_AssetRefAndUMG"; - -export function RunUnLuaExamplesTests(): void { - Suite("UnLuaExamples.OfficialPorts", () => { - Test("Ex01_HelloWorld: ReceiveBeginPlay prints and logs greeting", () => { - ResetMockState(); - const actor = CreateBoundInstance( - Ex01_HelloWorld as unknown as Record, - "AActor" - ); - actor.ReceiveBeginPlay(); - - AssertTrue(string.find(actor.GetGreeting(), "Hello UnLua from TypeScript", 1, true)[0] !== undefined); - AssertEqual(GetMockState().printedStrings.length, 1); - AssertEqual(GetMockState().logs.length, 1); - }); - - Test("Ex02_OverrideBlueprintEvents: lifecycle events and self.Overridden chain", () => { - ResetMockState(); - const actor = CreateBoundInstance( - Ex02_OverrideBlueprintEvents as unknown as Record, - "AActor" - ); - const other = CreateBoundInstance({}, "AActor", { __name: "OtherActor_1" }); - - actor.Initialize(); - actor.UserConstructionScript(); - actor.ReceiveBeginPlay(); - actor.ReceiveTick(0.016); - actor.ReceiveTick(0.034); - actor.ReceiveAnyDamage(35, undefined, undefined, other); - actor.ReceiveActorBeginOverlap(other); - actor.ReceiveEndPlay(UE.EEndPlayReason.Destroyed); - - AssertNear(actor.GetElapsed(), 0.05); - AssertEqual(actor.GetTotalDamage(), 35); - AssertEqual(actor.GetOverlapCount(), 1); - AssertArrayEqual(actor.GetEvents(), [ - "Initialize", - "UserConstructionScript", - "ReceiveBeginPlay", - "Damage:35", - "Overlap:OtherActor_1", - "EndPlay:0", - ]); - AssertEqual(GetMockState().overriddenCalls.length, 7); - }); - - Test("Ex03_BindDelegates: Multicast, FScriptDelegate and K2_SetTimerDelegate via UnLua.Delegate", () => { - ResetMockState(); - const mockBtn = { OnClicked: CreateMockMulticastDelegate() } as unknown as UE.UButton; - const singleDel = CreateMockScriptDelegate(); - - const widget = CreateBoundInstance( - Ex03_BindDelegates as unknown as Record, - "UUserWidget", - { - ClickMeButton: mockBtn, - CustomSingleDelegate: singleDel, - } - ); - - widget.Construct(); - AssertTrue(mockBtn.OnClicked.IsBound()); - - // 触发按钮点击与单播委托 - mockBtn.OnClicked.Broadcast(); - mockBtn.OnClicked.Broadcast(); - AssertEqual(widget.GetClickCount(), 2); - AssertEqual(singleDel.Execute(5), 52); - - // 推进定时器 1.6s -> 间隔 0.5s 应触发 3 次 - AdvanceMockTime(1.6); - AssertEqual(widget.GetTimerTickCount(), 3); - AssertTrue(UE.UKismetSystemLibrary.K2_IsTimerActiveHandle(widget, widget.GetTimerHandle())); - - // 销毁清理后不应再响应委托或定时器 - widget.Destruct(); - AssertFalse(mockBtn.OnClicked.IsBound()); - mockBtn.OnClicked.Broadcast(); - AssertEqual(widget.GetClickCount(), 2); - - AdvanceMockTime(2.0); - AssertEqual(widget.GetTimerTickCount(), 3); - }); - - Test("Ex04_DynamicBinding: World:SpawnActor, SpawnActorEx and UE.NewObject with Initializer", () => { - ResetMockState(); - const spawner = CreateBoundInstance( - Ex04_DynamicBinding as unknown as Record, - "AActor" - ); - - const spawned = spawner.SpawnDynamicActor("Fireball", 120); - AssertNotNil(spawned); - AssertEqual(spawned!.GetInitTag(), "Fireball"); - AssertEqual(spawned!.GetInitPower(), 120); - AssertTrue(spawned!.IsBeginPlayCalled()); - - const spawnedEx = spawner.SpawnDynamicActorEx("IceShard"); - AssertNotNil(spawnedEx); - AssertEqual(spawnedEx!.GetInitTag(), "IceShard"); - AssertEqual(spawnedEx!.GetInitPower(), 77); - - const dynObj = spawner.CreateDynamicObject(10); - AssertNotNil(dynObj); - AssertEqual(dynObj!.GetSeed(), 10); - AssertEqual(dynObj!.NextValue(), 21); - AssertEqual(dynObj!.NextValue(), 43); - }); - - Test("Ex05_BindInputs: UnLua.Input and UnLua.EnhancedInput module registrations", () => { - // 模块加载时已注册 5 条输入绑定(2 Key + 1 Action + 1 Axis + 1 EnhancedAction) - // 注意:MockState 可能已被前面测试 Reset,此处直接触发已绑定的模块逻辑验证 - // 重新加载一次模块或直接检查函数执行 - const pc = CreateBoundInstance( - Ex05_BindInputs as unknown as Record, - "APlayerController" - ); - pc.ReceiveBeginPlay(); - - // 重新触发注册表验证(通过 package.loaded 清理后重加载一次) - ResetMockState(); - const pkg = (_G as unknown as Record).package as { loaded: Record }; - const modName = "Tests.UnLuaExamples.Ex05_BindInputs"; - const prevMod = pkg.loaded[modName]; - pkg.loaded[modName] = undefined; - require(modName); - pkg.loaded[modName] = prevMod; - - const bindings = GetMockState().inputBindings; - AssertEqual(bindings.length, 5); - AssertEqual(bindings[0].kind, "Key"); - AssertEqual(bindings[0].name, "SpaceBar"); - AssertEqual(bindings[1].args?.Ctrl, true); - AssertEqual(bindings[2].kind, "Action"); - AssertEqual(bindings[3].kind, "Axis"); - AssertEqual(bindings[4].kind, "EnhancedAction"); - - // 模拟 UE 分发回调到控制器实例 - bindings[0].handler.call(pc); - AssertEqual(pc.GetLastAction(), "SpaceBar:Pressed"); - bindings[1].handler.call(pc); - AssertEqual(pc.GetLastAction(), "Ctrl+S"); - bindings[2].handler.call(pc); - AssertEqual(pc.GetLastAction(), "Action:Jump"); - bindings[3].handler.call(pc, 0.75); - AssertNear(pc.GetMoveForwardValue(), 0.75); - bindings[4].handler.call(pc, -1.0); - AssertNear(pc.GetMoveForwardValue(), -1.0); - AssertEqual(pc.GetEnhancedCount(), 1); - }); - - Test("Ex06_NativeContainers: TArray, TMap and TSet full API & pairs()", () => { - VerifyTArrayOperations(); - VerifyTMapOperations(); - VerifyTSetOperations(); - }); - - Test("Ex07_CallLatentFunction: coroutine Delay sequence & destroy abort guard", () => { - ResetMockState(); - const actor = CreateBoundInstance( - Ex07_CallLatentFunction as unknown as Record, - "AActor" - ); - actor.ReceiveBeginPlay(); - AssertArrayEqual(actor.GetSteps(), ["Step1:Start"]); - AssertFalse(actor.IsCompleted()); - - AdvanceMockTime(0.5); - AssertArrayEqual(actor.GetSteps(), ["Step1:Start", "Step2:After0.5s"]); - AssertFalse(actor.IsCompleted()); - - AdvanceMockTime(1.0); - AssertArrayEqual(actor.GetSteps(), ["Step1:Start", "Step2:After0.5s", "Step3:Done"]); - AssertTrue(actor.IsCompleted()); - - // 测试中途销毁:等待期间 Destroy 后恢复协程应安全退出,不再执行后续步骤 - const doomed = CreateBoundInstance( - Ex07_CallLatentFunction as unknown as Record, - "AActor" - ); - doomed.ReceiveBeginPlay(); - doomed.K2_DestroyActor(); - AdvanceMockTime(2.0); - AssertArrayEqual(doomed.GetSteps(), ["Step1:Start"]); - AssertFalse(doomed.IsCompleted()); - }); - - Test("Ex08_StructAndTrace: FVector math, LineTraceSingle multi-return and K2_SetActorLocation", () => { - ResetMockState(); - const actor = CreateBoundInstance( - Ex08_StructAndTrace as unknown as Record, - "AActor" - ); - actor.ReceiveBeginPlay(); - - const [size, dot, dist] = actor.ComputeVectorMath(); - AssertNear(size, 13); - AssertNear(dot, 0); - AssertNear(dist, 13); - - AssertTrue(actor.TeleportTo(100, 0, 50)); - const [bHit, hitDist, impact] = actor.TraceForward(200); - AssertTrue(bHit); - AssertNear(hitDist, 100); - AssertNear(impact.X, 200); - AssertNear(impact.Z, 50); - }); - - Test("Ex09_AssetRefAndUMG: UObject.Load, UnLua.Ref/Unref, WeakPtr and UMG Release", () => { - ResetMockState(); - const widget = CreateBoundInstance( - Ex09_AssetRefAndUMG as unknown as Record, - "UUserWidget" - ); - widget.Initialize(); - widget.Construct(); - widget.ShowOnScreen(); - - AssertTrue(widget.IsConstructed()); - AssertFalse(widget.IsDestructed()); - AssertTrue(widget.HasValidWeakAsset()); - - widget.CloseAndRelease(); - AssertTrue(widget.IsDestructed()); - AssertFalse(widget.HasValidWeakAsset()); - }); - }); -} diff --git a/Script/ts/src/framework/context/game_context.ts b/Script/ts/src/framework/context/game_context.ts new file mode 100644 index 0000000..4a4efd2 --- /dev/null +++ b/Script/ts/src/framework/context/game_context.ts @@ -0,0 +1,265 @@ +import type { IDisposable } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { EventHub } from "../../share/event/event_hub"; +import { FrameScheduler } from "../core/scheduler"; +import { MgrRegistry } from "../module/mgr_registry"; + +const logger = Logger("GameContext"); + +export interface AppLifecycleEvents { + OnWorldCleanup(worldGen: number): void; + OnBeforeShutdown(): void; +} + +/** + * World 级上下文:随切图/销毁递增 worldGen 并释放本 World 绑定资源。 + */ +export class WorldContext extends ScopedObject { + readonly worldGen: number; + readonly world: UE.UWorld | undefined; + + constructor(worldGen: number, world?: UE.UWorld) { + super(); + this.worldGen = worldGen; + this.world = world; + } +} + +/** + * LocalPlayer 级上下文:承载单个本地玩家的 UMG 视图栈与焦点服务。 + */ +export class LocalPlayerContext extends ScopedObject { + readonly playerIndex: number; + playerController: UE.APlayerController | undefined; + private services: Record = {}; + + constructor(playerIndex: number, playerController?: UE.APlayerController) { + super(); + this.playerIndex = playerIndex; + this.playerController = playerController; + } + + RegisterService(key: string, service: T): T { + const old = this.services[key]; + if (old !== undefined && old !== service) { + old.Dispose(); + } + this.services[key] = service; + this.AddScopedObject(service); + return service; + } + + GetService(key: string): T | undefined { + return this.services[key] as T | undefined; + } +} + +/** @module_data */ +let nextContextId = 0; + +/** + * GameInstance 级运行时上下文(支持同 Lua VM 多 PIE 实例彻底隔离): + * 持有本实例专属的事件总线、三时钟调度器、管理器注册表、World/LocalPlayer 上下文与可扩展服务。 + */ +export class GameInstanceContext extends ScopedObject { + readonly contextId: number; + readonly gameInstance: UE.ULuaGameInstance | undefined; + readonly scheduler: FrameScheduler; + readonly mgrRegistry: MgrRegistry; + readonly appEvents: EventHub; + + private shuttingDown = false; + private worldContext: WorldContext; + private localPlayers: Record = {}; + private services: Record = {}; + private shutdownHooks: Array<(this: void) => void> = []; + + constructor(gameInstance?: UE.ULuaGameInstance) { + super(); + nextContextId = nextContextId + 1; + this.contextId = nextContextId; + this.gameInstance = gameInstance; + this.scheduler = new FrameScheduler(); + this.mgrRegistry = new MgrRegistry(); + this.appEvents = new EventHub("AppLifecycle#" + tostring(this.contextId)); + this.worldContext = new WorldContext(this.scheduler.GetCurrentWorldGen()); + } + + IsShuttingDown(): boolean { + return this.shuttingDown || this.IsDisposed(); + } + + GetWorldContext(): WorldContext { + return this.worldContext; + } + + GetWorldGen(): number { + return this.worldContext.worldGen; + } + + GetOrCreateLocalPlayer(playerIndex: number, pc?: UE.APlayerController): LocalPlayerContext { + let lp = this.localPlayers[playerIndex]; + if (lp === undefined || lp.IsDisposed()) { + lp = new LocalPlayerContext(playerIndex, pc); + this.localPlayers[playerIndex] = lp; + } else if (pc !== undefined) { + lp.playerController = pc; + } + return lp; + } + + RemoveLocalPlayer(playerIndex: number): void { + const lp = this.localPlayers[playerIndex]; + if (lp !== undefined) { + this.localPlayers[playerIndex] = undefined; + lp.Dispose(); + } + } + + RegisterService(key: string, service: T): T { + const old = this.services[key]; + if (old !== undefined && old !== service) { + old.Dispose(); + } + this.services[key] = service; + return service; + } + + GetService(key: string): T | undefined { + return this.services[key] as T | undefined; + } + + AddShutdownHook(hook: (this: void) => void): void { + if (this.shuttingDown) { + return; + } + this.shutdownHooks[this.shutdownHooks.length] = hook; + } + + Tick(unscaledDeltaSeconds: number, worldDeltaSeconds?: number, isWorldPaused = false): void { + if (this.IsShuttingDown()) { + return; + } + this.scheduler.Tick(unscaledDeltaSeconds, worldDeltaSeconds, isWorldPaused); + } + + OnWorldCleanup(nextWorld?: UE.UWorld): void { + if (this.IsShuttingDown()) { + return; + } + const oldGen = this.worldContext.worldGen; + this.appEvents.emit.OnWorldCleanup(oldGen); + this.worldContext.Dispose(); + const newGen = this.scheduler.InvalidateWorld(); + this.worldContext = new WorldContext(newGen, nextWorld); + } + + /** + * 规范退出顺序: + * 1. 停止接收新工作并通知 OnBeforeShutdown + * 2. 使旧 World 请求失效并销毁全部 LocalPlayer 视图 + * 3. 逆序执行关闭钩子(如存储 FlushAll) + * 4. 释放全部注册服务、管理器、调度器与事件总线 + */ + override Dispose(): void { + if (this.IsDisposed()) { + return; + } + this.shuttingDown = true; + this.appEvents.emit.OnBeforeShutdown(); + + // 销毁全部 LocalPlayer(先关视图解绑 UMG 委托) + const playerKeys: number[] = []; + for (const [idx] of pairs(this.localPlayers)) { + playerKeys[playerKeys.length] = idx; + } + for (let i = 0; i < playerKeys.length; i++) { + const idx = playerKeys[i]; + const lp = this.localPlayers[idx]; + this.localPlayers[idx] = undefined; + if (lp !== undefined) { + lp.Dispose(); + } + } + + // 失效 World 上下文与 World 定时任务 + this.worldContext.Dispose(); + this.scheduler.InvalidateWorld(); + + // 逆序执行关闭钩子(确保本地存档 FlushAll 在服务销毁前完成) + for (let i = this.shutdownHooks.length - 1; i >= 0; i--) { + this.shutdownHooks[i](); + } + this.shutdownHooks = []; + + // 释放全部扩展服务 + const serviceList: IDisposable[] = []; + for (const [k, svc] of pairs(this.services)) { + if (svc !== undefined) { + this.services[k] = undefined; + serviceList[serviceList.length] = svc; + } + } + for (let i = 0; i < serviceList.length; i++) { + serviceList[i].Dispose(); + } + + // 释放管理器、调度器、事件总线与自身 ScopedObject + this.mgrRegistry.Dispose(); + this.scheduler.Dispose(); + this.appEvents.Dispose(); + super.Dispose(); + + logger.Info("GameInstanceContext disposed", { contextId: this.contextId }); + } +} + +/** @module_data */ +const activeContextsByKey: Record = {}; + +/** @noSelf */ +export function GetGameInstanceKey(gameInstance: UE.ULuaGameInstance): string { + if (gameInstance.GetName !== undefined) { + return gameInstance.GetName(); + } + return tostring(gameInstance); +} + +/** @noSelf */ +export function CreateGameInstanceContext(gameInstance: UE.ULuaGameInstance): GameInstanceContext { + const key = GetGameInstanceKey(gameInstance); + const old = activeContextsByKey[key]; + if (old !== undefined && !old.IsDisposed()) { + old.Dispose(); + } + const ctx = new GameInstanceContext(gameInstance); + activeContextsByKey[key] = ctx; + return ctx; +} + +/** @noSelf */ +export function GetGameInstanceContext(gameInstance: UE.ULuaGameInstance): GameInstanceContext | undefined { + return activeContextsByKey[GetGameInstanceKey(gameInstance)]; +} + +/** @noSelf */ +export function DestroyGameInstanceContext(gameInstance: UE.ULuaGameInstance): void { + const key = GetGameInstanceKey(gameInstance); + const ctx = activeContextsByKey[key]; + if (ctx !== undefined) { + activeContextsByKey[key] = undefined; + ctx.Dispose(); + } +} + +/** @noSelf */ +export function GetActiveGameInstanceContextCount(): number { + let count = 0; + for (const [_, ctx] of pairs(activeContextsByKey)) { + if (ctx !== undefined && !ctx.IsDisposed()) { + count = count + 1; + } + } + return count; +} diff --git a/Script/ts/src/framework/core/json.ts b/Script/ts/src/framework/core/json.ts new file mode 100644 index 0000000..922970c --- /dev/null +++ b/Script/ts/src/framework/core/json.ts @@ -0,0 +1,334 @@ +/** @noSelfInFile */ + +interface NativeJsonModule { + encode(this: void, value: unknown): LuaMultiReturn<[string | undefined, string | undefined]>; + decode(this: void, raw: string, keepNull?: boolean): LuaMultiReturn<[unknown, string | undefined]>; + null: unknown; + empty_array: unknown; +} + +const FALLBACK_NULL = { __json_null__: true }; +const FALLBACK_EMPTY_ARRAY = { __json_empty_array__: true }; + +/** @module_data */ +let cachedNative: NativeJsonModule | false | undefined = undefined; + +function TryLoadNativeJson(): NativeJsonModule | undefined { + if (cachedNative !== undefined) { + return cachedNative === false ? undefined : cachedNative; + } + const [ok, mod] = pcall(require, "ue_json"); + if (ok && type(mod) === "table" && type((mod as any).encode) === "function" && type((mod as any).decode) === "function") { + cachedNative = mod as NativeJsonModule; + return cachedNative; + } + cachedNative = false; + return undefined; +} + +// --------------------------------------------------------------------------- +// Pure-Lua 5.4 JSON fallback (used only in offline `npm test` outside UE) +// --------------------------------------------------------------------------- + +function EscapeJsonString(str: string): string { + const [escaped] = string.gsub(str, '[%z\x01-\x1f\\"]', (ch: string) => { + if (ch === '"') return '\\"'; + if (ch === "\\") return "\\\\"; + if (ch === "\b") return "\\b"; + if (ch === "\f") return "\\f"; + if (ch === "\n") return "\\n"; + if (ch === "\r") return "\\r"; + if (ch === "\t") return "\\t"; + return string.format("\\u%04x", string.byte(ch)); + }); + return '"' + escaped + '"'; +} + +function IsPureArray(tbl: Record): LuaMultiReturn<[boolean, number]> { + let count = 0; + let maxKey = 0; + for (const [k] of pairs(tbl)) { + count = count + 1; + if (type(k) !== "number" || math.type(k as number) !== "integer" || (k as number) <= 0) { + return $multi(false, 0); + } + if ((k as number) > maxKey) { + maxKey = k as number; + } + } + return $multi(count > 0 && maxKey === count, maxKey); +} + +function FallbackEncodeValue(val: unknown, depth: number): LuaMultiReturn<[string | undefined, string | undefined]> { + if (depth > 64) { + return $multi(undefined, "JSON encode exceeded maximum depth (64)"); + } + if (val === undefined || val === FALLBACK_NULL) { + return $multi("null", undefined); + } + if (val === FALLBACK_EMPTY_ARRAY) { + return $multi("[]", undefined); + } + const t = type(val); + if (t === "boolean") { + return $multi((val as boolean) ? "true" : "false", undefined); + } + if (t === "number") { + const num = val as number; + if (num !== num || num === math.huge || num === -math.huge) { + return $multi(undefined, "Cannot encode NaN or Infinity to JSON"); + } + if (math.type(num) === "integer") { + return $multi(string.format("%d", num), undefined); + } + return $multi(string.format("%.17g", num), undefined); + } + if (t === "string") { + return $multi(EscapeJsonString(val as string), undefined); + } + if (t === "table") { + const tbl = val as Record; + const [isArr, len] = IsPureArray(tbl); + if (isArr) { + const items: string[] = []; + for (let i = 1; i <= len; i++) { + const [encoded, err] = FallbackEncodeValue(tbl[i], depth + 1); + if (err !== undefined) { + return $multi(undefined, err); + } + items[items.length] = encoded as string; + } + return $multi("[" + table.concat(items, ",") + "]", undefined); + } + const pairsOut: string[] = []; + for (const [k, v] of pairs(tbl)) { + const kt = type(k); + if (kt !== "string" && kt !== "number") { + return $multi(undefined, "Unsupported JSON object key type: " + kt); + } + const [encodedVal, err] = FallbackEncodeValue(v, depth + 1); + if (err !== undefined) { + return $multi(undefined, err); + } + pairsOut[pairsOut.length] = EscapeJsonString(tostring(k)) + ":" + (encodedVal as string); + } + return $multi("{" + table.concat(pairsOut, ",") + "}", undefined); + } + return $multi(undefined, "Unsupported Lua type for JSON encode: " + t); +} + +interface ParseState { + src: string; + len: number; + pos: number; + keepNull: boolean; +} + +function SkipWs(st: ParseState): void { + while (st.pos <= st.len) { + const b = string.byte(st.src, st.pos); + if (b === 32 || b === 9 || b === 10 || b === 13) { + st.pos = st.pos + 1; + } else { + break; + } + } +} + +function ParseString(st: ParseState): LuaMultiReturn<[string | undefined, string | undefined]> { + st.pos = st.pos + 1; // skip opening '"' + const out: string[] = []; + while (st.pos <= st.len) { + const ch = string.sub(st.src, st.pos, st.pos); + if (ch === '"') { + st.pos = st.pos + 1; + return $multi(table.concat(out), undefined); + } + if (ch === "\\") { + st.pos = st.pos + 1; + if (st.pos > st.len) { + return $multi(undefined, "Unterminated escape in JSON string"); + } + const esc = string.sub(st.src, st.pos, st.pos); + st.pos = st.pos + 1; + if (esc === '"' || esc === "\\" || esc === "/") out[out.length] = esc; + else if (esc === "b") out[out.length] = "\b"; + else if (esc === "f") out[out.length] = "\f"; + else if (esc === "n") out[out.length] = "\n"; + else if (esc === "r") out[out.length] = "\r"; + else if (esc === "t") out[out.length] = "\t"; + else if (esc === "u") { + const hex = string.sub(st.src, st.pos, st.pos + 3); + const code = tonumber(hex, 16); + if (code === undefined || hex.length < 4) { + return $multi(undefined, "Invalid \\u escape"); + } + st.pos = st.pos + 4; + out[out.length] = utf8.char(code); + } else { + return $multi(undefined, "Invalid escape char: \\" + esc); + } + } else { + out[out.length] = ch; + st.pos = st.pos + 1; + } + } + return $multi(undefined, "Unterminated JSON string"); +} + +function ParseValue(st: ParseState, depth: number): LuaMultiReturn<[unknown, string | undefined]> { + if (depth > 64) { + return $multi(undefined, "JSON decode exceeded maximum depth (64)"); + } + SkipWs(st); + if (st.pos > st.len) { + return $multi(undefined, "Unexpected EOF"); + } + const ch = string.sub(st.src, st.pos, st.pos); + if (ch === '"') { + return ParseString(st); + } + if (ch === "{") { + st.pos = st.pos + 1; + const obj: Record = {}; + SkipWs(st); + if (string.sub(st.src, st.pos, st.pos) === "}") { + st.pos = st.pos + 1; + return $multi(obj, undefined); + } + while (true) { + SkipWs(st); + if (string.sub(st.src, st.pos, st.pos) !== '"') { + return $multi(undefined, "Expected string key in JSON object"); + } + const [key, keyErr] = ParseString(st); + if (keyErr !== undefined) { + return $multi(undefined, keyErr); + } + SkipWs(st); + if (string.sub(st.src, st.pos, st.pos) !== ":") { + return $multi(undefined, "Expected ':' in JSON object"); + } + st.pos = st.pos + 1; + const [val, valErr] = ParseValue(st, depth + 1); + if (valErr !== undefined) { + return $multi(undefined, valErr); + } + obj[key as string] = val; + SkipWs(st); + const sep = string.sub(st.src, st.pos, st.pos); + if (sep === "}") { + st.pos = st.pos + 1; + return $multi(obj, undefined); + } + if (sep !== ",") { + return $multi(undefined, "Expected ',' or '}' in JSON object"); + } + st.pos = st.pos + 1; + } + } + if (ch === "[") { + st.pos = st.pos + 1; + const arr: unknown[] = []; + SkipWs(st); + if (string.sub(st.src, st.pos, st.pos) === "]") { + st.pos = st.pos + 1; + return $multi(arr, undefined); + } + let idx = 1; + while (true) { + const [val, valErr] = ParseValue(st, depth + 1); + if (valErr !== undefined) { + return $multi(undefined, valErr); + } + (arr as any)[idx] = val; + idx = idx + 1; + SkipWs(st); + const sep = string.sub(st.src, st.pos, st.pos); + if (sep === "]") { + st.pos = st.pos + 1; + return $multi(arr, undefined); + } + if (sep !== ",") { + return $multi(undefined, "Expected ',' or ']' in JSON array"); + } + st.pos = st.pos + 1; + } + } + if (string.sub(st.src, st.pos, st.pos + 3) === "true") { + st.pos = st.pos + 4; + return $multi(true, undefined); + } + if (string.sub(st.src, st.pos, st.pos + 4) === "false") { + st.pos = st.pos + 5; + return $multi(false, undefined); + } + if (string.sub(st.src, st.pos, st.pos + 3) === "null") { + st.pos = st.pos + 4; + return $multi(st.keepNull ? FALLBACK_NULL : undefined, undefined); + } + const [numStr] = string.match(st.src, "^%-?%d+%.?%d*[eE]?[%+%-]?%d*", st.pos); + if (numStr !== undefined && numStr !== "") { + const parsed = tonumber(numStr); + if (parsed !== undefined) { + st.pos = st.pos + numStr.length; + return $multi(parsed, undefined); + } + } + return $multi(undefined, "Unexpected token at pos " + tostring(st.pos)); +} + +function FallbackDecode(raw: string, keepNull: boolean): LuaMultiReturn<[unknown, string | undefined]> { + const st: ParseState = { + src: raw, + len: raw.length, + pos: 1, + keepNull, + }; + const [val, err] = ParseValue(st, 0); + if (err !== undefined) { + return $multi(undefined, err); + } + SkipWs(st); + if (st.pos <= st.len) { + return $multi(undefined, "Trailing characters after JSON value"); + } + return $multi(val, undefined); +} + +// --------------------------------------------------------------------------- +// Public unified JSON facade +// --------------------------------------------------------------------------- + +export function IsNativeBackend(): boolean { + return TryLoadNativeJson() !== undefined; +} + +export function GetNull(): unknown { + const native = TryLoadNativeJson(); + return native !== undefined ? native.null : FALLBACK_NULL; +} + +export function GetEmptyArray(): unknown { + const native = TryLoadNativeJson(); + return native !== undefined ? native.empty_array : FALLBACK_EMPTY_ARRAY; +} + +export function Encode(value: unknown): LuaMultiReturn<[string | undefined, string | undefined]> { + const native = TryLoadNativeJson(); + if (native !== undefined) { + return native.encode(value); + } + return FallbackEncodeValue(value, 0); +} + +export function Decode(raw: string, keepNull = false): LuaMultiReturn<[unknown, string | undefined]> { + if (type(raw) !== "string" || raw === "") { + return $multi(undefined, "Empty JSON input"); + } + const native = TryLoadNativeJson(); + if (native !== undefined) { + return native.decode(raw, keepNull); + } + return FallbackDecode(raw, keepNull); +} diff --git a/Script/ts/src/framework/core/scheduler.ts b/Script/ts/src/framework/core/scheduler.ts new file mode 100644 index 0000000..3fa1394 --- /dev/null +++ b/Script/ts/src/framework/core/scheduler.ts @@ -0,0 +1,422 @@ +import type { ICheckableDisposable, IsDisposedChecker } from "../../share/base/interface"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { tbpcall } from "../../share/base/traceback"; + +export type TimerCallback = (this: void) => void; + +export type ClockDomain = "frame" | "world" | "monotonic"; + +export interface SchedulerStats { + frameTasks: number; + worldTasks: number; + monotonicTasks: number; + totalTasks: number; +} + +export interface IMonotonicClock { + NowSeconds(): number; + AddTimer(delaySeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle; + AddRepeatTimer(intervalSeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle; +} + +interface ScheduledEntry { + id: number; + domain: ClockDomain; + callback: TimerCallback; + owner?: IsDisposedChecker; + repeat: boolean; + cancelled: boolean; + /** 逐帧任务:剩余帧数;时间任务:下一次触发的目标时间戳 */ + remainingFrames: number; + intervalSec: number; + nextTriggerTime: number; + worldGen: number; + handle: TimerHandle; +} + +export class TimerHandle implements ICheckableDisposable { + private scheduler: FrameScheduler | undefined; + private entryId: number; + private disposed = false; + + constructor(scheduler: FrameScheduler, entryId: number) { + this.scheduler = scheduler; + this.entryId = entryId; + } + + GetId(): number { + return this.entryId; + } + + IsDisposed(): boolean { + return this.disposed; + } + + IsActive(): boolean { + return !this.disposed && this.scheduler !== undefined && this.scheduler.IsEntryActive(this.entryId); + } + + Cancel(): void { + this.Dispose(); + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + if (this.scheduler !== undefined) { + const s = this.scheduler; + this.scheduler = undefined; + s.CancelById(this.entryId); + } + } + + /** 内部标记为已完成,避免重复回删 */ + MarkCompletedInternal(): void { + this.disposed = true; + this.scheduler = undefined; + } +} + +/** + * 三时钟统一调度器(归属 GameInstanceContext,替代 Unity/luv uv.tick): + * 1. FrameQueue:逐帧调度(0 帧和 1 帧均在下一帧触发,N 帧在第 N 次帧调度触发) + * 2. WorldClock:World 游戏时间(跟随暂停、切图 InvalidateWorld 时自动取消全部旧 World 任务) + * 3. MonotonicClock:跨 World 单调时钟(不受暂停与切图影响,用于存档合并写与网络超时) + */ +export class FrameScheduler implements ICheckableDisposable, IMonotonicClock { + private nextId = 0; + private monotonicTime = 0; + private worldTime = 0; + private currentWorldGen = 1; + private frameCounter = 0; + private disposed = false; + + private entriesById: Record = {}; + private frameIds: number[] = []; + private worldIds: number[] = []; + private monotonicIds: number[] = []; + + IsDisposed(): boolean { + return this.disposed; + } + + NowSeconds(): number { + return this.monotonicTime; + } + + GetWorldTimeSeconds(): number { + return this.worldTime; + } + + GetFrameCount(): number { + return this.frameCounter; + } + + GetCurrentWorldGen(): number { + return this.currentWorldGen; + } + + IsEntryActive(id: number): boolean { + const entry = this.entriesById[id]; + return entry !== undefined && !entry.cancelled; + } + + /** + * 逐帧调度:frames <= 1(含 0 与 1)在下一次帧调度触发,frames = N 在第 N 次触发。 + * (登记有意变更:不再复现旧 luv AddRepeatTimer(0) 注册 1ms 重复定时器的隐式行为。) + */ + AddFrameTimer(frames: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + const count = math.max(1, math.floor(frames)); + return this.CreateEntry("frame", count, 0, false, callback, owner); + } + + RunNextFrame(callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + return this.AddFrameTimer(1, callback, owner); + } + + AddWorldTimer(delaySeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + const delay = math.max(0, delaySeconds); + return this.CreateEntry("world", 0, delay, false, callback, owner); + } + + AddWorldRepeatTimer(intervalSeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + if (intervalSeconds <= 0) { + return this.CreateEntry("frame", 1, 0, true, callback, owner); + } + return this.CreateEntry("world", 0, intervalSeconds, true, callback, owner); + } + + AddTimer(delaySeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + return this.AddMonotonicTimer(delaySeconds, callback, owner); + } + + AddRepeatTimer(intervalSeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + return this.AddMonotonicRepeatTimer(intervalSeconds, callback, owner); + } + + AddMonotonicTimer(delaySeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + const delay = math.max(0, delaySeconds); + return this.CreateEntry("monotonic", 0, delay, false, callback, owner); + } + + AddMonotonicRepeatTimer(intervalSeconds: number, callback: TimerCallback, owner?: IsDisposedChecker): TimerHandle { + const interval = math.max(0.001, intervalSeconds); + return this.CreateEntry("monotonic", 0, interval, true, callback, owner); + } + + private CreateEntry( + domain: ClockDomain, + remainingFrames: number, + intervalSec: number, + repeat: boolean, + callback: TimerCallback, + owner?: IsDisposedChecker + ): TimerHandle { + this.nextId = this.nextId + 1; + const id = this.nextId; + const handle = new TimerHandle(this, id); + + if (this.disposed || (owner !== undefined && owner.IsDisposed())) { + handle.MarkCompletedInternal(); + return handle; + } + + const baseTime = domain === "world" ? this.worldTime : this.monotonicTime; + const entry: ScheduledEntry = { + id, + domain, + callback, + owner, + repeat, + cancelled: false, + remainingFrames, + intervalSec, + nextTriggerTime: baseTime + intervalSec, + worldGen: this.currentWorldGen, + handle, + }; + + this.entriesById[id] = entry; + if (domain === "frame") { + this.frameIds[this.frameIds.length] = id; + } else if (domain === "world") { + this.worldIds[this.worldIds.length] = id; + } else { + this.monotonicIds[this.monotonicIds.length] = id; + } + + if (owner !== undefined && owner instanceof ScopedObject) { + owner.AddScopedObject(handle); + } + + return handle; + } + + CancelById(id: number): void { + const entry = this.entriesById[id]; + if (entry === undefined) { + return; + } + entry.cancelled = true; + this.entriesById[id] = undefined; + } + + /** + * 切图 / World 清理时调用:递增 WorldGen 并立即取消全部绑定到旧 World 的任务(含 world 与 frame 任务)。 + * 跨 World 单调时钟任务不受影响。 + */ + InvalidateWorld(): number { + const prevGen = this.currentWorldGen; + this.currentWorldGen = this.currentWorldGen + 1; + this.worldTime = 0; + + this.CancelEntriesForWorldGen(this.worldIds, prevGen); + this.CancelEntriesForWorldGen(this.frameIds, prevGen); + return this.currentWorldGen; + } + + private CancelEntriesForWorldGen(idList: number[], worldGen: number): void { + const kept: number[] = []; + for (let i = 0; i < idList.length; i++) { + const id = idList[i]; + const entry = this.entriesById[id]; + if (entry === undefined || entry.cancelled) { + continue; + } + if (entry.worldGen === worldGen) { + entry.cancelled = true; + this.entriesById[id] = undefined; + entry.handle.MarkCompletedInternal(); + } else { + kept[kept.length] = id; + } + } + idList.length = 0; + for (let i = 0; i < kept.length; i++) { + idList[i] = kept[i]; + } + } + + /** + * 推进一次主帧: + * @param unscaledDeltaSeconds 跨 World 单调时钟增量(永不暂停) + * @param worldDeltaSeconds World 游戏时钟增量(缺省等于 unscaledDeltaSeconds;若 isWorldPaused=true 则不推进) + * @param isWorldPaused 当前 World 是否暂停 + */ + Tick(unscaledDeltaSeconds: number, worldDeltaSeconds?: number, isWorldPaused = false): void { + if (this.disposed) { + return; + } + const safeUnscaled = math.max(0, unscaledDeltaSeconds); + this.monotonicTime = this.monotonicTime + safeUnscaled; + this.frameCounter = this.frameCounter + 1; + + this.ProcessTimedQueue(this.monotonicIds, this.monotonicTime); + + if (!isWorldPaused) { + const safeWorldDt = math.max(0, worldDeltaSeconds ?? safeUnscaled); + this.worldTime = this.worldTime + safeWorldDt; + this.ProcessTimedQueue(this.worldIds, this.worldTime); + } + + this.ProcessFrameQueue(); + } + + private ProcessFrameQueue(): void { + // 仅消费本帧前已登记的任务;回调中新登记的逐帧任务留在下一帧触发 + const snapshotLen = this.frameIds.length; + const nextFrameIds: number[] = []; + + for (let i = 0; i < snapshotLen; i++) { + const id = this.frameIds[i]; + const entry = this.entriesById[id]; + if (entry === undefined || entry.cancelled) { + continue; + } + if (entry.owner !== undefined && entry.owner.IsDisposed()) { + entry.cancelled = true; + this.entriesById[id] = undefined; + entry.handle.MarkCompletedInternal(); + continue; + } + + entry.remainingFrames = entry.remainingFrames - 1; + if (entry.remainingFrames <= 0) { + if (!entry.repeat) { + entry.cancelled = true; + this.entriesById[id] = undefined; + entry.handle.MarkCompletedInternal(); + } else { + entry.remainingFrames = 1; + nextFrameIds[nextFrameIds.length] = id; + } + tbpcall(entry.callback); + } else { + nextFrameIds[nextFrameIds.length] = id; + } + } + + // 保留回调中新增到队尾的任务 + for (let i = snapshotLen; i < this.frameIds.length; i++) { + const id = this.frameIds[i]; + const entry = this.entriesById[id]; + if (entry !== undefined && !entry.cancelled) { + nextFrameIds[nextFrameIds.length] = id; + } + } + + this.frameIds = nextFrameIds; + } + + private ProcessTimedQueue(idList: number[], currentTime: number): void { + const snapshotLen = idList.length; + const kept: number[] = []; + + for (let i = 0; i < snapshotLen; i++) { + const id = idList[i]; + const entry = this.entriesById[id]; + if (entry === undefined || entry.cancelled) { + continue; + } + if (entry.owner !== undefined && entry.owner.IsDisposed()) { + entry.cancelled = true; + this.entriesById[id] = undefined; + entry.handle.MarkCompletedInternal(); + continue; + } + + if (currentTime + 1e-9 >= entry.nextTriggerTime) { + if (!entry.repeat) { + entry.cancelled = true; + this.entriesById[id] = undefined; + entry.handle.MarkCompletedInternal(); + tbpcall(entry.callback); + } else { + entry.nextTriggerTime = currentTime + entry.intervalSec; + tbpcall(entry.callback); + // 回调内部可能调用了 handle.Cancel() + if (!entry.cancelled && this.entriesById[id] !== undefined) { + kept[kept.length] = id; + } + } + } else { + kept[kept.length] = id; + } + } + + for (let i = snapshotLen; i < idList.length; i++) { + const id = idList[i]; + const entry = this.entriesById[id]; + if (entry !== undefined && !entry.cancelled) { + kept[kept.length] = id; + } + } + + idList.length = 0; + for (let i = 0; i < kept.length; i++) { + idList[i] = kept[i]; + } + } + + GetStats(): SchedulerStats { + const frameTasks = this.CountActive(this.frameIds); + const worldTasks = this.CountActive(this.worldIds); + const monotonicTasks = this.CountActive(this.monotonicIds); + return { + frameTasks, + worldTasks, + monotonicTasks, + totalTasks: frameTasks + worldTasks + monotonicTasks, + }; + } + + private CountActive(idList: number[]): number { + let count = 0; + for (let i = 0; i < idList.length; i++) { + const entry = this.entriesById[idList[i]]; + if (entry !== undefined && !entry.cancelled) { + count = count + 1; + } + } + return count; + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + for (const [id, entry] of pairs(this.entriesById)) { + if (entry !== undefined) { + entry.cancelled = true; + entry.handle.MarkCompletedInternal(); + this.entriesById[id] = undefined; + } + } + this.frameIds = []; + this.worldIds = []; + this.monotonicIds = []; + } +} diff --git a/Script/ts/src/framework/module/mgr_base.ts b/Script/ts/src/framework/module/mgr_base.ts new file mode 100644 index 0000000..23aaddd --- /dev/null +++ b/Script/ts/src/framework/module/mgr_base.ts @@ -0,0 +1,125 @@ +import type { Constructor, IDisposable } from "../../share/base/interface"; +import { ScopedObject } from "../../share/base/scoped_object"; + +/** + * 管理器数据基类(参考 gamelogic/framework/module/mgr_data_base.ts)。 + */ +export abstract class MgrDataBase implements IDisposable { + abstract Dispose(): void; + OnEnterGame(): void {} + OnExitGame(): void {} +} + +/** + * 管理器下属子控制器基类(参考 gamelogic/framework/module/control_base.ts)。 + */ +export abstract class ControllerBase extends ScopedObject { + protected readonly mgr: TMgr; + + constructor(mgr: TMgr) { + super(); + this.mgr = mgr; + } + + OnEnter(): void {} + OnBindEvents(): void {} + OnActive(): void {} + OnExit(): void {} +} + +/** + * 通用管理器基类(参考 gamelogic/framework/module/mgr_base.ts,剥离具体项目 RPC 耦合)。 + */ +export abstract class MgrBase extends ScopedObject { + protected controllers: Record = {}; + public isActive = true; + + Initialization(): void { + this.OnCreate(); + this.OnBindControllers(); + this.OnBindEvents(); + } + + abstract OnCreate(): void; + OnBindControllers(): void {} + OnBindEvents(): void {} + OnEnterGame(): void {} + OnExitGame(): void {} + OnClean(): void {} + + SetActive(active: boolean): void { + this.isActive = active; + if (active) { + this.EnableControllers(); + this.EnableAllEventListeners(); + } else { + this.DisableControllers(); + this.DisableAllEventListeners(); + } + } + + AddController>(ctor: Constructor): T { + const existing = this.controllers[ctor as any]; + assert(existing === undefined, "MgrBase.AddController: controller already added"); + const ctrl = new ctor(this); + this.controllers[ctor as any] = ctrl; + ctrl.OnEnter(); + ctrl.OnBindEvents(); + ctrl.OnActive(); + return ctrl; + } + + GetController>(ctor: Constructor): T | undefined { + return this.controllers[ctor as any] as T | undefined; + } + + DelController>(ctor: Constructor): void { + const ctrl = this.controllers[ctor as any]; + if (ctrl === undefined) { + return; + } + this.controllers[ctor as any] = undefined; + ctrl.OnExit(); + ctrl.Dispose(); + } + + DelAllControllers(): void { + const list: ControllerBase[] = []; + for (const [ctorKey, ctrl] of pairs(this.controllers)) { + if (ctrl !== undefined) { + this.controllers[ctorKey] = undefined; + list[list.length] = ctrl; + } + } + for (let i = 0; i < list.length; i++) { + list[i].OnExit(); + list[i].Dispose(); + } + } + + EnableControllers(): void { + for (const [_, ctrl] of pairs(this.controllers)) { + if (ctrl !== undefined) { + ctrl.EnableAllEventListeners(); + ctrl.OnActive(); + } + } + } + + DisableControllers(): void { + for (const [_, ctrl] of pairs(this.controllers)) { + if (ctrl !== undefined) { + ctrl.DisableAllEventListeners(); + } + } + } + + override Dispose(): void { + if (this.IsDisposed()) { + return; + } + this.DelAllControllers(); + this.OnClean(); + super.Dispose(); + } +} diff --git a/Script/ts/src/framework/module/mgr_registry.ts b/Script/ts/src/framework/module/mgr_registry.ts new file mode 100644 index 0000000..adf6793 --- /dev/null +++ b/Script/ts/src/framework/module/mgr_registry.ts @@ -0,0 +1,128 @@ +import type { Constructor, IDisposable } from "../../share/base/interface"; +import type { MgrBase, MgrDataBase } from "./mgr_base"; + +/** @noSelf */ +function ResolveClassName(ctor: Constructor, explicitName?: string): string { + if (explicitName !== undefined && explicitName !== "") { + return explicitName; + } + const rawName = (ctor as any).name as string | undefined; + if (rawName !== undefined && type(rawName) === "string" && rawName !== "") { + return rawName; + } + return tostring(ctor); +} + +/** + * 管理器与数据注册表(归属 GameInstanceContext,支持多实例隔离)。 + * 相比源端 framework/module/mgr.ts: + * - 剥离业务大厅/世界 RPC 绑定,留给业务装配层; + * - DelMgr 时同步清理名称索引(修复源端遗漏清理 mgrTblName 的问题)。 + */ +export class MgrRegistry implements IDisposable { + private mgrByCtor: Record = {}; + private mgrNameByCtor: Record = {}; + private mgrByName: Record = {}; + private dataByCtor: Record = {}; + private disposed = false; + + CreateMgrData(ctor: Constructor): T { + const existing = this.dataByCtor[ctor as any]; + if (existing !== undefined) { + return existing as T; + } + const data = new ctor(); + this.dataByCtor[ctor as any] = data; + return data; + } + + GetMgrData(ctor: Constructor): T | undefined { + return this.dataByCtor[ctor as any] as T | undefined; + } + + DelMgrData(ctor: Constructor): void { + const data = this.dataByCtor[ctor as any]; + if (data === undefined) { + return; + } + this.dataByCtor[ctor as any] = undefined; + data.Dispose(); + } + + CreateMgr(ctor: Constructor, explicitName?: string): T { + const existing = this.mgrByCtor[ctor as any]; + if (existing !== undefined) { + return existing as T; + } + const mgr = new ctor(); + const name = ResolveClassName(ctor, explicitName); + this.mgrByCtor[ctor as any] = mgr; + this.mgrNameByCtor[ctor as any] = name; + this.mgrByName[name] = mgr; + mgr.Initialization(); + return mgr; + } + + GetMgr(ctor: Constructor): T | undefined { + return this.mgrByCtor[ctor as any] as T | undefined; + } + + GetMgrByName(name: string): T | undefined { + return this.mgrByName[name] as T | undefined; + } + + DelMgr(ctor: Constructor): void { + const mgr = this.mgrByCtor[ctor as any]; + if (mgr === undefined) { + return; + } + const name = this.mgrNameByCtor[ctor as any]; + this.mgrByCtor[ctor as any] = undefined; + this.mgrNameByCtor[ctor as any] = undefined; + if (name !== undefined && this.mgrByName[name] === mgr) { + this.mgrByName[name] = undefined; + } + mgr.Dispose(); + } + + GetMgrCount(): number { + let count = 0; + for (const [_, mgr] of pairs(this.mgrByCtor)) { + if (mgr !== undefined) { + count = count + 1; + } + } + return count; + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + + const mgrList: MgrBase[] = []; + for (const [key, mgr] of pairs(this.mgrByCtor)) { + if (mgr !== undefined) { + this.mgrByCtor[key] = undefined; + mgrList[mgrList.length] = mgr; + } + } + this.mgrNameByCtor = {}; + this.mgrByName = {}; + for (let i = 0; i < mgrList.length; i++) { + mgrList[i].Dispose(); + } + + const dataList: MgrDataBase[] = []; + for (const [key, data] of pairs(this.dataByCtor)) { + if (data !== undefined) { + this.dataByCtor[key] = undefined; + dataList[dataList.length] = data; + } + } + for (let i = 0; i < dataList.length; i++) { + dataList[i].Dispose(); + } + } +} diff --git a/Script/ts/src/framework/resource/asset_catalog.ts b/Script/ts/src/framework/resource/asset_catalog.ts new file mode 100644 index 0000000..76d95bc --- /dev/null +++ b/Script/ts/src/framework/resource/asset_catalog.ts @@ -0,0 +1,17 @@ +/** @noSelfInFile */ + +export const ASSET_KEYS = { + MINI_SETTINGS_ICON: "tex.mini_settings_icon", + MINI_SETTINGS_WIDGET: "ui.mini_settings", +} as const; + +export const BASE_ASSET_PATHS: Record = { + [ASSET_KEYS.MINI_SETTINGS_ICON]: "/Game/UI/Textures/T_MiniSettingsIcon.T_MiniSettingsIcon", + [ASSET_KEYS.MINI_SETTINGS_WIDGET]: "/Game/UI/WBP_MiniSettings.WBP_MiniSettings_C", +}; + +export function RegisterBaseAssetCatalog(subsystem: UE.ULuaResourceSubsystem): void { + for (const [logicalKey, softPath] of pairs(BASE_ASSET_PATHS)) { + subsystem.RegisterBaseAssetKey(logicalKey, softPath); + } +} diff --git a/Script/ts/src/framework/resource/resource_service.ts b/Script/ts/src/framework/resource/resource_service.ts new file mode 100644 index 0000000..0a42130 --- /dev/null +++ b/Script/ts/src/framework/resource/resource_service.ts @@ -0,0 +1,434 @@ +import type { ICheckableDisposable, IsDisposedChecker } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { tbpcall } from "../../share/base/traceback"; +import { GetGameInstanceKey, type GameInstanceContext } from "../context/game_context"; +import { RegisterBaseAssetCatalog } from "./asset_catalog"; + +const logger = Logger("ResourceService"); + +export interface ResourceDiagnostics { + tsPendingRequests: number; + nativeInFlight: number; + nativeRetainedAssets: number; + nativeTotalRefCount: number; +} + +export interface IResourceBackend { + ResolveAssetPath(keyOrPath: string): string; + DoesAssetExist(keyOrPath: string): boolean; + IsPackagedMode(): boolean; + RequestLoadObjectAsync(keyOrPath: string, worldGen: number): number; + RequestLoadClassAsync(keyOrPath: string, worldGen: number): number; + CancelRequest(requestId: number): boolean; + CancelRequestsForWorld(worldGen: number): number; + ReleaseAsset(resolvedSoftPath: string): void; + GetResourceStats(): LuaMultiReturn<[number, number, number]>; +} + +/** + * 生产环境 C++ ULuaResourceSubsystem 适配器: + * - Editor / PIE 直读 Content/ 资产 + * - Packaged / Release 自动从基础包 + 热更下载资源包(高优先级挂载覆盖)读取 + */ +export class UEResourceBackend implements IResourceBackend { + readonly subsystem: UE.ULuaResourceSubsystem; + + constructor(subsystem: UE.ULuaResourceSubsystem) { + this.subsystem = subsystem; + } + + ResolveAssetPath(keyOrPath: string): string { + return this.subsystem.ResolveAssetPath(keyOrPath); + } + + DoesAssetExist(keyOrPath: string): boolean { + return this.subsystem.DoesAssetExist(keyOrPath); + } + + IsPackagedMode(): boolean { + return UE.ULuaResourceSubsystem.IsPackagedResourceMode(); + } + + RequestLoadObjectAsync(keyOrPath: string, worldGen: number): number { + return this.subsystem.RequestLoadObjectAsync(keyOrPath, worldGen); + } + + RequestLoadClassAsync(keyOrPath: string, worldGen: number): number { + return this.subsystem.RequestLoadClassAsync(keyOrPath, worldGen); + } + + CancelRequest(requestId: number): boolean { + return this.subsystem.CancelRequest(requestId); + } + + CancelRequestsForWorld(worldGen: number): number { + return this.subsystem.CancelRequestsForWorld(worldGen); + } + + ReleaseAsset(resolvedSoftPath: string): void { + this.subsystem.ReleaseAsset(resolvedSoftPath); + } + + GetResourceStats(): LuaMultiReturn<[number, number, number]> { + return this.subsystem.GetResourceStats(); + } +} + +/** + * 已加载资产租约:绑定到调用方 ScopedObject,Dispose 时幂等释放 C++ FStreamableHandle 引用计数。 + */ +export class ResourceLease implements ICheckableDisposable { + readonly resolvedPath: string; + private asset: T | undefined; + private backend: IResourceBackend | undefined; + private disposed = false; + + constructor(resolvedPath: string, asset: T, backend: IResourceBackend) { + this.resolvedPath = resolvedPath; + this.asset = asset; + this.backend = backend; + } + + GetAsset(): T | undefined { + if (this.disposed) { + return undefined; + } + return this.asset; + } + + IsDisposed(): boolean { + return this.disposed; + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + this.asset = undefined; + if (this.backend !== undefined) { + const b = this.backend; + this.backend = undefined; + b.ReleaseAsset(this.resolvedPath); + } + } +} + +export type ResourceLoadCallback = ( + this: void, + ok: boolean, + asset: T | undefined, + lease: ResourceLease | undefined, + errorMessage: string | undefined +) => void; + +export class ResourceLoadHandle implements ICheckableDisposable { + readonly requestId: number; + private service: ResourceService | undefined; + private lease: ResourceLease | undefined; + private disposed = false; + + constructor(service: ResourceService, requestId: number) { + this.service = service; + this.requestId = requestId; + } + + AttachLeaseInternal(lease: ResourceLease): void { + if (this.disposed) { + lease.Dispose(); + return; + } + this.lease = lease; + this.service = undefined; + } + + MarkSettledWithoutLeaseInternal(): void { + this.service = undefined; + } + + GetLease(): ResourceLease | undefined { + return this.lease; + } + + IsDisposed(): boolean { + return this.disposed; + } + + Cancel(): void { + this.Dispose(); + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + if (this.service !== undefined) { + const svc = this.service; + this.service = undefined; + svc.CancelPendingByIdInternal(this.requestId); + } + if (this.lease !== undefined) { + const l = this.lease; + this.lease = undefined; + l.Dispose(); + } + } +} + +interface PendingLoadRecord { + requestId: number; + keyOrPath: string; + worldGen: number; + owner?: IsDisposedChecker; + callback: ResourceLoadCallback; + handle: ResourceLoadHandle; + cancelled: boolean; +} + +/** @module_data */ +const serviceByGameInstanceKey: Record = {}; + +/** + * TS 侧统一资源服务(封装 C++ ULuaResourceSubsystem): + * - 负责按 GameInstance 路由原生异步回调; + * - 自动绑定 ScopedObject 生命周期(owner 释放或切图时自动取消在途请求并归还租约); + * - 有效请求严格交付一次成功或失败。 + */ +export class ResourceService extends ScopedObject { + private readonly ctx: GameInstanceContext; + private readonly backend: IResourceBackend; + private readonly giKey?: string; + private pendingById: Record = {}; + + constructor(ctx: GameInstanceContext, backend: IResourceBackend) { + super(); + this.ctx = ctx; + this.backend = backend; + + if (ctx.gameInstance !== undefined) { + this.giKey = GetGameInstanceKey(ctx.gameInstance); + serviceByGameInstanceKey[this.giKey] = this; + } + + ctx.appEvents.on.OnWorldCleanup((oldWorldGen: number) => { + this.CancelForWorld(oldWorldGen); + }, this); + } + + ResolveAssetPath(keyOrPath: string): string { + return this.backend.ResolveAssetPath(keyOrPath); + } + + DoesAssetExist(keyOrPath: string): boolean { + return this.backend.DoesAssetExist(keyOrPath); + } + + IsPackagedMode(): boolean { + return this.backend.IsPackagedMode(); + } + + LoadObjectAsync( + keyOrPath: string, + owner: IsDisposedChecker | undefined, + callback: ResourceLoadCallback + ): ResourceLoadHandle { + return this.StartAsyncLoad(keyOrPath, owner, callback, false); + } + + LoadTextureAsync( + keyOrPath: string, + owner: IsDisposedChecker | undefined, + callback: ResourceLoadCallback + ): ResourceLoadHandle { + return this.LoadObjectAsync(keyOrPath, owner, callback); + } + + LoadClassAsync( + keyOrPath: string, + owner: IsDisposedChecker | undefined, + callback: ResourceLoadCallback + ): ResourceLoadHandle { + return this.StartAsyncLoad(keyOrPath, owner, callback, true); + } + + private StartAsyncLoad( + keyOrPath: string, + owner: IsDisposedChecker | undefined, + callback: ResourceLoadCallback, + isClassLoad: boolean + ): ResourceLoadHandle { + if (this.IsDisposed() || this.ctx.IsShuttingDown() || (owner !== undefined && owner.IsDisposed())) { + const dead = new ResourceLoadHandle(this, 0); + dead.Dispose(); + return dead; + } + + const worldGen = this.ctx.GetWorldGen(); + const requestId = isClassLoad + ? this.backend.RequestLoadClassAsync(keyOrPath, worldGen) + : this.backend.RequestLoadObjectAsync(keyOrPath, worldGen); + + const handle = new ResourceLoadHandle(this, requestId); + const record: PendingLoadRecord = { + requestId, + keyOrPath, + worldGen, + owner, + callback: callback as ResourceLoadCallback, + handle, + cancelled: false, + }; + this.pendingById[requestId] = record; + + if (owner !== undefined && owner instanceof ScopedObject) { + owner.AddScopedObject(handle); + } + + return handle; + } + + CancelPendingByIdInternal(requestId: number): void { + const record = this.pendingById[requestId]; + if (record === undefined) { + return; + } + record.cancelled = true; + this.pendingById[requestId] = undefined; + this.backend.CancelRequest(requestId); + } + + CancelForWorld(worldGen: number): number { + const toCancel: number[] = []; + for (const [id, rec] of pairs(this.pendingById)) { + if (rec !== undefined && rec.worldGen === worldGen) { + toCancel[toCancel.length] = id; + } + } + for (let i = 0; i < toCancel.length; i++) { + const rec = this.pendingById[toCancel[i]]; + if (rec !== undefined) { + rec.cancelled = true; + this.pendingById[toCancel[i]] = undefined; + rec.handle.MarkSettledWithoutLeaseInternal(); + } + } + this.backend.CancelRequestsForWorld(worldGen); + return toCancel.length; + } + + HandleNativeLoadComplete( + requestId: number, + ok: boolean, + loadedObj: unknown, + resolvedPath: string, + errorMessage: string + ): void { + const record = this.pendingById[requestId]; + if (record === undefined) { + // 请求已被取消但原生层已增加引用,立即归还避免泄漏 + if (ok && resolvedPath !== "") { + this.backend.ReleaseAsset(resolvedPath); + } + return; + } + + this.pendingById[requestId] = undefined; + + const isStale = + record.cancelled || + this.IsDisposed() || + this.ctx.IsShuttingDown() || + record.worldGen !== this.ctx.GetWorldGen() || + (record.owner !== undefined && record.owner.IsDisposed()) || + record.handle.IsDisposed(); + + if (isStale) { + record.handle.MarkSettledWithoutLeaseInternal(); + if (ok && resolvedPath !== "") { + this.backend.ReleaseAsset(resolvedPath); + } + return; + } + + if (ok && loadedObj !== undefined) { + const lease = new ResourceLease(resolvedPath, loadedObj, this.backend); + record.handle.AttachLeaseInternal(lease); + tbpcall(record.callback, true, loadedObj, lease, undefined); + } else { + record.handle.MarkSettledWithoutLeaseInternal(); + const err = errorMessage !== "" ? errorMessage : "Failed to load resource: " + record.keyOrPath; + logger.Warn("Resource load failed", { key: record.keyOrPath, path: resolvedPath, err }); + tbpcall(record.callback, false, undefined, undefined, err); + } + } + + GetDiagnostics(): ResourceDiagnostics { + let pending = 0; + for (const [_, rec] of pairs(this.pendingById)) { + if (rec !== undefined && !rec.cancelled) { + pending = pending + 1; + } + } + const [nativeInFlight, nativeRetained, nativeRefs] = this.backend.GetResourceStats(); + return { + tsPendingRequests: pending, + nativeInFlight, + nativeRetainedAssets: nativeRetained, + nativeTotalRefCount: nativeRefs, + }; + } + + override Dispose(): void { + if (this.IsDisposed()) { + return; + } + const ids: number[] = []; + for (const [id] of pairs(this.pendingById)) { + ids[ids.length] = id; + } + for (let i = 0; i < ids.length; i++) { + this.CancelPendingByIdInternal(ids[i]); + } + if (this.giKey !== undefined && serviceByGameInstanceKey[this.giKey] === this) { + serviceByGameInstanceKey[this.giKey] = undefined; + } + super.Dispose(); + } +} + +/** + * 供 C++ FLuaCallbackBridge 回调的纯函数入口(路由到对应 GameInstance 的 ResourceService)。 + * @noSelf + */ +export function OnNativeLoadComplete( + gameInstance: UE.ULuaGameInstance, + requestId: number, + ok: boolean, + loadedObj: unknown, + resolvedPath: string, + errorMessage: string +): void { + const svc = serviceByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (svc !== undefined) { + svc.HandleNativeLoadComplete(requestId, ok, loadedObj, resolvedPath, errorMessage); + } +} + +/** + * 为指定 GameInstanceContext 装配生产环境 ResourceService。 + * @noSelf + */ +export function CreateUEResourceService(ctx: GameInstanceContext): ResourceService | undefined { + if (ctx.gameInstance === undefined) { + return undefined; + } + const subsystem = UE.ULuaResourceSubsystem.GetFromGameInstance(ctx.gameInstance); + if (subsystem === undefined) { + logger.Error("ULuaResourceSubsystem unavailable on GameInstance"); + return undefined; + } + RegisterBaseAssetCatalog(subsystem); + return new ResourceService(ctx, new UEResourceBackend(subsystem)); +} diff --git a/Script/ts/src/framework/storage/local_save.ts b/Script/ts/src/framework/storage/local_save.ts new file mode 100644 index 0000000..065e90d --- /dev/null +++ b/Script/ts/src/framework/storage/local_save.ts @@ -0,0 +1,280 @@ +import type { IDisposable } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import * as Json from "../core/json"; +import type { IMonotonicClock, TimerHandle } from "../core/scheduler"; +import type { IStorageBackend, StorageStatus } from "./storage_backend"; + +const logger = Logger("LocalSave"); + +export type SaveScope = "global" | "role" | "chat" | "setting"; + +const SCOPE_PREFIX: Record = { + global: "gdata", + role: "rdata", + chat: "cdata", + setting: "sdata", +}; + +const SAVE_DEBOUNCE_SECONDS = 0.1; + +export interface LocalSaveEnvelope { + version: number; + data: Record; +} + +/** @noSelf */ +export function BuildSlotName(scope: SaveScope, identity?: string): string { + const prefix = SCOPE_PREFIX[scope]; + if (identity === undefined || identity === "") { + return prefix; + } + return prefix + "_" + identity; +} + +/** + * 版本化本地存储槽位(参考 gamelogic/framework/storage/local_save_base.ts): + * - 底层可注入 UEStorageBackend(UE ULuaSaveGame + ISaveGameSystem)或 MemoryStorageBackend(离线单测); + * - 使用跨 World 单调时钟实现 0.1s 合并写; + * - 区分缺失、损坏(保留原件)、写入失败(保留 dirty 状态允许重试)与成功状态。 + */ +export class LocalSaveStore implements IDisposable { + readonly slotName: string; + readonly schemaVersion: number; + + private readonly backend: IStorageBackend; + private readonly clock: IMonotonicClock; + private readonly userIndex: number; + + private data: Record = {}; + private loadedVersion = 0; + private lastLoadStatus: StorageStatus = "not_found"; + private lastWriteStatus: StorageStatus = "ok"; + private recoveredFromBackup = false; + private dirty = false; + private delayTimer?: TimerHandle; + private disposed = false; + + constructor( + slotName: string, + backend: IStorageBackend, + clock: IMonotonicClock, + schemaVersion = 1, + userIndex = 0 + ) { + this.slotName = slotName; + this.backend = backend; + this.clock = clock; + this.schemaVersion = schemaVersion; + this.userIndex = userIndex; + this.Reload(); + } + + Reload(): StorageStatus { + const readResult = this.backend.LoadSlotUtf8(this.slotName, this.userIndex); + this.lastLoadStatus = readResult.status; + this.recoveredFromBackup = readResult.recoveredFromBackup; + + if (readResult.status === "not_found") { + this.data = {}; + this.loadedVersion = this.schemaVersion; + return "not_found"; + } + + if (readResult.status !== "ok") { + logger.Warn("Failed to load save slot", { + slot: this.slotName, + status: readResult.status, + err: readResult.errorMessage, + }); + this.data = {}; + this.loadedVersion = 0; + return readResult.status; + } + + const [decoded, decodeErr] = Json.Decode(readResult.payloadUtf8); + if (decodeErr !== undefined || type(decoded) !== "table") { + logger.Error("Corrupted JSON payload in save slot", { + slot: this.slotName, + err: decodeErr ?? "non-table root", + }); + this.lastLoadStatus = "corrupted"; + this.data = {}; + this.loadedVersion = 0; + return "corrupted"; + } + + const env = decoded as Partial; + if (type(env.version) !== "number" || type(env.data) !== "table") { + logger.Error("Invalid LocalSaveEnvelope schema in save slot", { slot: this.slotName }); + this.lastLoadStatus = "corrupted"; + this.data = {}; + this.loadedVersion = 0; + return "corrupted"; + } + + this.loadedVersion = env.version as number; + this.data = env.data as Record; + return "ok"; + } + + GetLastLoadStatus(): StorageStatus { + return this.lastLoadStatus; + } + + GetLastWriteStatus(): StorageStatus { + return this.lastWriteStatus; + } + + WasRecoveredFromBackup(): boolean { + return this.recoveredFromBackup; + } + + GetLoadedSchemaVersion(): number { + return this.loadedVersion; + } + + IsDirty(): boolean { + return this.dirty; + } + + Has(key: string): boolean { + return this.data[key] !== undefined; + } + + Get(key: string): T | undefined { + return this.data[key] as T | undefined; + } + + GetDefault(key: string, defaultValue: T): T { + const val = this.data[key]; + if (val !== undefined) { + return val as T; + } + return defaultValue; + } + + Set(key: string, value: T): void { + if (this.disposed) { + return; + } + this.data[key] = value; + this.dirty = true; + this.ScheduleSave(); + } + + DeleteKey(key: string): void { + if (this.disposed) { + return; + } + this.data[key] = undefined; + this.dirty = true; + this.ScheduleSave(); + } + + DeleteAll(): void { + if (this.disposed) { + return; + } + this.data = {}; + this.dirty = true; + this.ScheduleSave(); + } + + private ScheduleSave(): void { + if (this.delayTimer !== undefined && this.delayTimer.IsActive()) { + return; + } + this.delayTimer = this.clock.AddTimer(SAVE_DEBOUNCE_SECONDS, () => { + this.delayTimer = undefined; + this.Flush(); + }); + } + + /** + * 立即同步落盘。写入失败时保留 dirty=true,允许后续重试。 + */ + Flush(): StorageStatus { + if (this.delayTimer !== undefined) { + this.delayTimer.Cancel(); + this.delayTimer = undefined; + } + if (!this.dirty) { + return "ok"; + } + + const envelope: LocalSaveEnvelope = { + version: this.schemaVersion, + data: this.data, + }; + const [encoded, encodeErr] = Json.Encode(envelope); + if (encodeErr !== undefined || encoded === undefined) { + logger.Error("JSON encode failed for save slot", { slot: this.slotName, err: encodeErr }); + this.lastWriteStatus = "write_failed"; + return "write_failed"; + } + + const status = this.backend.SaveSlotUtf8(this.slotName, encoded, this.userIndex); + this.lastWriteStatus = status; + if (status === "ok") { + this.dirty = false; + this.loadedVersion = this.schemaVersion; + } else { + logger.Error("Failed to save slot", { slot: this.slotName, status }); + } + return status; + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.Flush(); + this.disposed = true; + } +} + +/** + * 归属 GameInstanceContext 的本地存储管理器,统一管理全部槽位与退出 FlushAll。 + */ +export class LocalSaveManager implements IDisposable { + private readonly backend: IStorageBackend; + private readonly clock: IMonotonicClock; + private readonly storesBySlot: Record = {}; + private disposed = false; + + constructor(backend: IStorageBackend, clock: IMonotonicClock) { + this.backend = backend; + this.clock = clock; + } + + GetOrOpenStore(scope: SaveScope, identity?: string, schemaVersion = 1): LocalSaveStore { + const slotName = BuildSlotName(scope, identity); + let store = this.storesBySlot[slotName]; + if (store === undefined) { + store = new LocalSaveStore(slotName, this.backend, this.clock, schemaVersion); + this.storesBySlot[slotName] = store; + } + return store; + } + + FlushAll(): void { + for (const [_, store] of pairs(this.storesBySlot)) { + if (store !== undefined) { + store.Flush(); + } + } + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + for (const [slot, store] of pairs(this.storesBySlot)) { + if (store !== undefined) { + this.storesBySlot[slot] = undefined; + store.Dispose(); + } + } + } +} diff --git a/Script/ts/src/framework/storage/storage_backend.ts b/Script/ts/src/framework/storage/storage_backend.ts new file mode 100644 index 0000000..f538f08 --- /dev/null +++ b/Script/ts/src/framework/storage/storage_backend.ts @@ -0,0 +1,149 @@ +export type StorageStatus = "ok" | "not_found" | "corrupted" | "write_failed" | "invalid_argument"; + +export interface StorageReadResult { + status: StorageStatus; + payloadUtf8: string; + containerVersion: number; + recoveredFromBackup: boolean; + errorMessage: string; +} + +export interface IStorageBackend { + LoadSlotUtf8(slotName: string, userIndex?: number): StorageReadResult; + SaveSlotUtf8(slotName: string, payloadUtf8: string, userIndex?: number): StorageStatus; + DeleteSlot(slotName: string, userIndex?: number): boolean; + DoesSlotExist(slotName: string, userIndex?: number): boolean; +} + +/** @noSelf */ +function MapNativeStatus(nativeStatus: UE.ELuaStorageStatus): StorageStatus { + if (nativeStatus === UE.ELuaStorageStatus.Ok) return "ok"; + if (nativeStatus === UE.ELuaStorageStatus.NotFound) return "not_found"; + if (nativeStatus === UE.ELuaStorageStatus.Corrupted) return "corrupted"; + if (nativeStatus === UE.ELuaStorageStatus.WriteFailed) return "write_failed"; + return "invalid_argument"; +} + +/** + * 生产环境 UE 原生存储后端(封装 ULuaStorageLibrary -> ISaveGameSystem + ULuaSaveGame)。 + */ +export class UEStorageBackend implements IStorageBackend { + LoadSlotUtf8(slotName: string, userIndex = 0): StorageReadResult { + const res = UE.ULuaStorageLibrary.LoadSlotUtf8(slotName, userIndex); + return { + status: MapNativeStatus(res.Status), + payloadUtf8: res.PayloadUtf8 ?? "", + containerVersion: res.ContainerVersion ?? 0, + recoveredFromBackup: res.bRecoveredFromBackup === true, + errorMessage: res.ErrorMessage ?? "", + }; + } + + SaveSlotUtf8(slotName: string, payloadUtf8: string, userIndex = 0): StorageStatus { + return MapNativeStatus(UE.ULuaStorageLibrary.SaveSlotUtf8(slotName, payloadUtf8, userIndex)); + } + + DeleteSlot(slotName: string, userIndex = 0): boolean { + return UE.ULuaStorageLibrary.DeleteSlot(slotName, userIndex, true); + } + + DoesSlotExist(slotName: string, userIndex = 0): boolean { + return UE.ULuaStorageLibrary.DoesSlotExist(slotName, userIndex); + } +} + +/** + * 离线单测用内存存储后端:支持模拟写入失败、模拟损坏原件保留与 .bak 恢复。 + */ +export class MemoryStorageBackend implements IStorageBackend { + private slots: Record = {}; + private backups: Record = {}; + private corruptCopies: Record = {}; + private corruptedPrimaryFlags: Record = {}; + + public writeCount = 0; + public failNextWrite = false; + + InjectCorruptPrimary(slotName: string, rawGarbage: string): void { + this.slots[slotName] = rawGarbage; + this.corruptedPrimaryFlags[slotName] = true; + } + + GetCorruptCopy(slotName: string): string | undefined { + return this.corruptCopies[slotName]; + } + + LoadSlotUtf8(slotName: string, _userIndex = 0): StorageReadResult { + const primary = this.slots[slotName]; + const backup = this.backups[slotName]; + if (primary === undefined && backup === undefined) { + return { + status: "not_found", + payloadUtf8: "", + containerVersion: 0, + recoveredFromBackup: false, + errorMessage: "", + }; + } + + if (primary !== undefined && !this.corruptedPrimaryFlags[slotName]) { + return { + status: "ok", + payloadUtf8: primary, + containerVersion: 1, + recoveredFromBackup: false, + errorMessage: "", + }; + } + + if (primary !== undefined && this.corruptedPrimaryFlags[slotName]) { + this.corruptCopies[slotName] = primary; + } + + if (backup !== undefined) { + return { + status: "ok", + payloadUtf8: backup, + containerVersion: 1, + recoveredFromBackup: true, + errorMessage: "Primary slot corrupted; recovered from backup", + }; + } + + return { + status: "corrupted", + payloadUtf8: "", + containerVersion: 0, + recoveredFromBackup: false, + errorMessage: "Primary slot corrupted and no valid backup exists", + }; + } + + SaveSlotUtf8(slotName: string, payloadUtf8: string, _userIndex = 0): StorageStatus { + this.writeCount = this.writeCount + 1; + if (this.failNextWrite) { + this.failNextWrite = false; + return "write_failed"; + } + const prev = this.slots[slotName]; + if (prev !== undefined && !this.corruptedPrimaryFlags[slotName]) { + this.backups[slotName] = prev; + } + this.slots[slotName] = payloadUtf8; + this.corruptedPrimaryFlags[slotName] = undefined; + return "ok"; + } + + DeleteSlot(slotName: string, _userIndex = 0): boolean { + const existed = this.slots[slotName] !== undefined || this.backups[slotName] !== undefined; + this.slots[slotName] = undefined; + this.backups[slotName] = undefined; + this.corruptCopies[slotName] = undefined; + this.corruptedPrimaryFlags[slotName] = undefined; + return existed; + } + + DoesSlotExist(slotName: string, _userIndex = 0): boolean { + return this.slots[slotName] !== undefined; + } +} diff --git a/Script/ts/src/framework/ui/ui_config.ts b/Script/ts/src/framework/ui/ui_config.ts new file mode 100644 index 0000000..a8e2335 --- /dev/null +++ b/Script/ts/src/framework/ui/ui_config.ts @@ -0,0 +1,70 @@ +/** @noSelfInFile */ + +import type { Constructor } from "../../share/base/interface"; +import type { UIWindow } from "./ui_window"; + +export type UILayer = "background" | "normal" | "popup" | "tips" | "system"; +export type UIType = "normal" | "popup" | "fullscreen"; +export type UICacheTag = "no_cache" | "cache"; + +export const UI_LAYER_ZORDER: Record = { + background: 0, + normal: 100, + popup: 200, + tips: 300, + system: 400, +}; + +export interface UIConfigInput { + name: string; + assetKey: string; + singleton?: boolean; + layer?: UILayer; + type?: UIType; + cacheTag?: UICacheTag; + blockWorldClick?: boolean; +} + +export interface UIConfigItem { + name: string; + assetKey: string; + singleton: boolean; + layer: UILayer; + type: UIType; + cacheTag: UICacheTag; + blockWorldClick: boolean; + ctor: Constructor; +} + +/** @module_data */ +const configByCtor: Record = {}; + +/** @module_data */ +const configByName: Record = {}; + +/** + * 显式 UI 窗口注册表(替代源端 @UIConfig 装饰器,符合 ts2lua-unreal 编译期白名单规则)。 + */ +export function RegisterUIConfig(ctor: Constructor, input: UIConfigInput): UIConfigItem { + const item: UIConfigItem = { + name: input.name, + assetKey: input.assetKey, + singleton: input.singleton ?? true, + layer: input.layer ?? "normal", + type: input.type ?? "normal", + cacheTag: input.cacheTag ?? "no_cache", + blockWorldClick: input.blockWorldClick ?? true, + ctor: ctor as unknown as Constructor, + }; + configByCtor[ctor as any] = item; + configByName[item.name] = item; + return item; +} + +export function GetUIConfig(ctor: Constructor): UIConfigItem | undefined { + return configByCtor[ctor as any]; +} + +export function GetUIConfigByName(name: string): UIConfigItem | undefined { + return configByName[name]; +} diff --git a/Script/ts/src/framework/ui/ui_delegate_bridge.ts b/Script/ts/src/framework/ui/ui_delegate_bridge.ts new file mode 100644 index 0000000..55d2cfc --- /dev/null +++ b/Script/ts/src/framework/ui/ui_delegate_bridge.ts @@ -0,0 +1,165 @@ +import type { IDisposable, IsDisposedChecker } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { tbpcall } from "../../share/base/traceback"; +import { GetGameInstanceKey, type GameInstanceContext } from "../context/game_context"; + +const logger = Logger("UIDelegateBridge"); + +export interface IButtonDelegateBackend { + BindButtonClicked(button: any): number; + UnbindButtonClicked(bindingId: number): boolean; + GetActiveBindingCount(): number; +} + +export class UEButtonDelegateBackend implements IButtonDelegateBackend { + private readonly subsystem: UE.ULuaUIEventSubsystem; + + constructor(subsystem: UE.ULuaUIEventSubsystem) { + this.subsystem = subsystem; + } + + BindButtonClicked(button: UE.UButton): number { + return this.subsystem.BindButtonClicked(button); + } + + UnbindButtonClicked(bindingId: number): boolean { + return this.subsystem.UnbindButtonClicked(bindingId); + } + + GetActiveBindingCount(): number { + return this.subsystem.GetActiveBindingCount(); + } +} + +interface ButtonBindingRecord { + bindingId: number; + callback: (this: void) => void; + owner?: IsDisposedChecker; +} + +class ButtonBindingHandle implements IDisposable { + private bridge: UIDelegateBridge | undefined; + private readonly bindingId: number; + + constructor(bridge: UIDelegateBridge, bindingId: number) { + this.bridge = bridge; + this.bindingId = bindingId; + } + + Dispose(): void { + if (this.bridge !== undefined) { + const b = this.bridge; + this.bridge = undefined; + b.UnbindById(this.bindingId); + } + } +} + +/** @module_data */ +const bridgeByGameInstanceKey: Record = {}; + +/** + * 纯 TS 侧 UMG 委托桥接器(按 GameInstance 隔离): + * 配合 C++ ULuaUIEventSubsystem 实现纯 TS 控制器绑定 UButton.OnClicked, + * 无需 @unlua 继承 UUserWidget,100% 纳入单文件热更与 ScopedObject 自动解绑。 + */ +export class UIDelegateBridge extends ScopedObject { + private readonly backend: IButtonDelegateBackend; + private readonly giKey?: string; + private bindings: Record = {}; + + constructor(ctx: GameInstanceContext, backend: IButtonDelegateBackend) { + super(); + this.backend = backend; + if (ctx.gameInstance !== undefined) { + this.giKey = GetGameInstanceKey(ctx.gameInstance); + bridgeByGameInstanceKey[this.giKey] = this; + } + } + + BindButtonClick(button: any, callback: (this: void) => void, owner?: IsDisposedChecker): IDisposable { + const bindingId = this.backend.BindButtonClicked(button); + assert(bindingId > 0, "UIDelegateBridge.BindButtonClick: failed to bind button"); + + this.bindings[bindingId] = { + bindingId, + callback, + owner, + }; + + const handle = new ButtonBindingHandle(this, bindingId); + if (owner !== undefined && owner instanceof ScopedObject) { + owner.AddScopedObject(handle); + } + return handle; + } + + UnbindById(bindingId: number): void { + if (this.bindings[bindingId] === undefined) { + return; + } + this.bindings[bindingId] = undefined; + this.backend.UnbindButtonClicked(bindingId); + } + + DispatchButtonClicked(bindingId: number): void { + if (this.IsDisposed()) { + return; + } + const rec = this.bindings[bindingId]; + if (rec === undefined) { + return; + } + if (rec.owner !== undefined && rec.owner.IsDisposed()) { + this.UnbindById(bindingId); + return; + } + tbpcall(rec.callback); + } + + GetActiveBindingCount(): number { + return this.backend.GetActiveBindingCount(); + } + + override Dispose(): void { + if (this.IsDisposed()) { + return; + } + const ids: number[] = []; + for (const [id] of pairs(this.bindings)) { + ids[ids.length] = id; + } + for (let i = 0; i < ids.length; i++) { + this.UnbindById(ids[i]); + } + if (this.giKey !== undefined && bridgeByGameInstanceKey[this.giKey] === this) { + bridgeByGameInstanceKey[this.giKey] = undefined; + } + super.Dispose(); + } +} + +/** + * 供 C++ FLuaCallbackBridge::CallInt 回调的纯函数入口。 + * @noSelf + */ +export function OnNativeButtonClicked(gameInstance: UE.ULuaGameInstance, bindingId: number): void { + const bridge = bridgeByGameInstanceKey[GetGameInstanceKey(gameInstance)]; + if (bridge !== undefined) { + bridge.DispatchButtonClicked(bindingId); + } +} + +/** @noSelf */ +export function CreateUEUIDelegateBridge(ctx: GameInstanceContext): UIDelegateBridge | undefined { + if (ctx.gameInstance === undefined) { + return undefined; + } + const subsystem = UE.ULuaUIEventSubsystem.GetFromGameInstance(ctx.gameInstance); + if (subsystem === undefined) { + logger.Error("ULuaUIEventSubsystem unavailable on GameInstance"); + return undefined; + } + return new UIDelegateBridge(ctx, new UEButtonDelegateBackend(subsystem)); +} diff --git a/Script/ts/src/framework/ui/ui_manager.ts b/Script/ts/src/framework/ui/ui_manager.ts new file mode 100644 index 0000000..b71d2df --- /dev/null +++ b/Script/ts/src/framework/ui/ui_manager.ts @@ -0,0 +1,390 @@ +import type { Constructor } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { EventHub } from "../../share/event/event_hub"; +import { tbpcall } from "../../share/base/traceback"; +import type { GameInstanceContext, LocalPlayerContext } from "../context/game_context"; +import type { ResourceService } from "../resource/resource_service"; +import { GetUIConfig, UI_LAYER_ZORDER, type UIConfigItem } from "./ui_config"; +import type { IWidgetAdapter, UIWindow } from "./ui_window"; + +const logger = Logger("UIManager"); + +export interface UIManagerEvents { + OnWindowOpened(windowName: string, window: UIWindow): void; + OnWindowClosed(windowName: string, window: UIWindow): void; + OnFocusRestored(topWindowName: string | undefined): void; +} + +export interface IWidgetFactory { + CreateWidget(widgetClass: any, worldContext: UE.UObject | undefined, owningPlayer: UE.APlayerController | undefined): any; +} + +export interface UIDiagnostics { + openWindows: number; + loadingWindows: number; + cachedWindows: number; + topWindowName: string | undefined; + inputMode: "game" | "ui"; +} + +export class UEWidgetAdapter implements IWidgetAdapter { + FindChild(widget: UE.UUserWidget, name: string): UE.UWidget | undefined { + return UE.ULuaUIEventSubsystem.FindChildWidgetByName(widget, name); + } + + AddToViewport(widget: UE.UUserWidget, zOrder: number): void { + if (widget.IsInViewport !== undefined && widget.IsInViewport()) { + return; + } + const hasPlayer = widget.GetOwningPlayer !== undefined && widget.GetOwningPlayer() !== undefined; + if (hasPlayer && widget.AddToPlayerScreen !== undefined) { + widget.AddToPlayerScreen(zOrder); + } else if (widget.AddToViewport !== undefined) { + widget.AddToViewport(zOrder); + } + } + + RemoveFromParent(widget: UE.UUserWidget): void { + if (widget.RemoveFromParent !== undefined) { + widget.RemoveFromParent(); + } + } + + SetVisible(widget: UE.UUserWidget, visible: boolean): void { + if (widget.SetVisibility !== undefined) { + widget.SetVisibility(visible ? UE.ESlateVisibility.Visible : UE.ESlateVisibility.Collapsed); + } + } + + IsWidgetValid(widget: UE.UUserWidget): boolean { + return widget !== undefined && UE.UKismetSystemLibrary.IsValid(widget); + } +} + +export class UEWidgetFactory implements IWidgetFactory { + CreateWidget( + widgetClass: UE.UClass, + worldContext: UE.UObject | undefined, + owningPlayer: UE.APlayerController | undefined + ): UE.UUserWidget | undefined { + if (worldContext === undefined) { + return undefined; + } + return UE.UWidgetBlueprintLibrary.Create(worldContext, widgetClass, owningPlayer); + } +} + +/** + * 玩家级窗口管理器(归属 LocalPlayerContext,支持多 PIE 实例隔离): + * - 单例去重与并发打开防重复创建; + * - 窗口栈 ZOrder 层级管理、缓存复用与焦点/输入模式恢复; + * - 切图/退出时安全取消在途加载并释放所有窗口与缓存。 + */ +export class UIManager extends ScopedObject { + readonly events: EventHub; + + private readonly ctx: GameInstanceContext; + private readonly playerCtx: LocalPlayerContext; + private readonly resourceService: ResourceService; + private readonly widgetFactory: IWidgetFactory; + private readonly widgetAdapter: IWidgetAdapter; + + private windowStack: UIWindow[] = []; + private singletonByName: Record = {}; + private cachedByName: Record = {}; + private zOrderCounter = 0; + private inputMode: "game" | "ui" = "game"; + + constructor( + ctx: GameInstanceContext, + playerCtx: LocalPlayerContext, + resourceService: ResourceService, + widgetFactory?: IWidgetFactory, + widgetAdapter?: IWidgetAdapter + ) { + super(); + this.ctx = ctx; + this.playerCtx = playerCtx; + this.resourceService = resourceService; + this.widgetFactory = widgetFactory ?? new UEWidgetFactory(); + this.widgetAdapter = widgetAdapter ?? new UEWidgetAdapter(); + this.events = new EventHub( + string.format("UIManager#%d_P%d", ctx.contextId, playerCtx.playerIndex) + ); + + ctx.appEvents.on.OnWorldCleanup(() => { + this.CloseAll(true); + }, this); + } + + ShowUI( + ctor: Constructor, + args?: unknown, + onOpened?: (this: void, ok: boolean, window?: T, err?: string) => void + ): T | undefined { + if (this.IsDisposed() || this.ctx.IsShuttingDown()) { + if (onOpened !== undefined) { + tbpcall(onOpened, false, undefined, "UIManager is shutting down"); + } + return undefined; + } + + const config = GetUIConfig(ctor); + if (config === undefined) { + error("UIManager.ShowUI: window class is not registered via RegisterUIConfig"); + return undefined; + } + + // 1. 单例检查:已打开或加载中的单例直接复用,不创建第二个视图 + if (config.singleton) { + const existing = this.singletonByName[config.name]; + if (existing !== undefined && !existing.IsDisposed() && !existing.IsClosing()) { + if (existing.IsLoaded()) { + const zOrder = this.AllocateZOrder(config); + existing.ShowInternal(zOrder, args); + this.SyncFocusAndInputMode(); + if (onOpened !== undefined) { + tbpcall(onOpened, true, existing as T, undefined); + } + } else if (onOpened !== undefined) { + // 并发打开同一仍在加载中的单例:等待首次加载完成通知 + this.events.on.OnWindowOpened((openedName: string, openedWin: UIWindow) => { + if (openedName === config.name && openedWin === existing) { + tbpcall(onOpened, true, openedWin as T, undefined); + } + }, existing); + } + return existing as T; + } + } + + // 2. 缓存复用检查 + const cached = this.cachedByName[config.name]; + if (cached !== undefined && !cached.IsDisposed()) { + this.cachedByName[config.name] = undefined; + if (config.singleton) { + this.singletonByName[config.name] = cached; + } + this.windowStack[this.windowStack.length] = cached; + const zOrder = this.AllocateZOrder(config); + cached.ReuseInternal(zOrder, args); + this.SyncFocusAndInputMode(); + this.events.emit.OnWindowOpened(config.name, cached); + if (onOpened !== undefined) { + tbpcall(onOpened, true, cached as T, undefined); + } + return cached as T; + } + + // 3. 新建控制器并通过 C++ ResourceManager 异步加载 Widget Blueprint 类 + const win = new ctor(); + win.InitContextInternal(this.ctx, this, config, this.widgetAdapter); + if (config.singleton) { + this.singletonByName[config.name] = win; + } + this.windowStack[this.windowStack.length] = win; + + const loadHandle = this.resourceService.LoadClassAsync( + config.assetKey, + win, + (ok: boolean, widgetClass: UE.UClass | undefined, _lease, errMsg: string | undefined) => { + if (win.IsDisposed() || win.IsClosing() || this.IsDisposed()) { + return; + } + if (!ok || widgetClass === undefined) { + logger.Error("Failed to load widget class", { + window: config.name, + assetKey: config.assetKey, + err: errMsg, + }); + this.RemoveFromStackAndSingleton(win); + win.SetLoadingStateInternal(false, undefined); + win.Dispose(); + if (onOpened !== undefined) { + tbpcall(onOpened, false, undefined, errMsg ?? "Widget class load failed"); + } + return; + } + + const worldContext = + (this.ctx.GetWorldContext().world as UE.UObject | undefined) ?? + (this.playerCtx.playerController as UE.UObject | undefined) ?? + (this.ctx.gameInstance as UE.UObject | undefined); + + const widget = this.widgetFactory.CreateWidget(widgetClass, worldContext, this.playerCtx.playerController); + if (widget === undefined) { + const createErr = string.format("[%s] Failed to instantiate UUserWidget", config.name); + logger.Error(createErr); + this.RemoveFromStackAndSingleton(win); + win.SetLoadingStateInternal(false, undefined); + win.Dispose(); + if (onOpened !== undefined) { + tbpcall(onOpened, false, undefined, createErr); + } + return; + } + + win.AttachWidgetInternal(widget); + const zOrder = this.AllocateZOrder(config); + win.ShowInternal(zOrder, args); + this.SyncFocusAndInputMode(); + this.events.emit.OnWindowOpened(config.name, win); + if (onOpened !== undefined) { + tbpcall(onOpened, true, win as T, undefined); + } + } + ); + + win.SetLoadingStateInternal(true, loadHandle); + return win; + } + + GetSingletonUI(ctor: Constructor): T | undefined { + const config = GetUIConfig(ctor); + if (config === undefined) { + return undefined; + } + return this.singletonByName[config.name] as T | undefined; + } + + CloseSingletonUI(ctor: Constructor): void { + const win = this.GetSingletonUI(ctor); + if (win !== undefined) { + win.Close(); + } + } + + GetTopWindow(): UIWindow | undefined { + for (let i = this.windowStack.length - 1; i >= 0; i--) { + const win = this.windowStack[i]; + if (!win.IsDisposed() && !win.IsClosing()) { + return win; + } + } + return undefined; + } + + HandleWindowCachedInternal(win: UIWindow): void { + this.RemoveFromStackAndSingleton(win); + const oldCached = this.cachedByName[win.config.name]; + if (oldCached !== undefined && oldCached !== win) { + oldCached.ForceDisposeFromCacheInternal(); + } + this.cachedByName[win.config.name] = win; + this.SyncFocusAndInputMode(); + this.events.emit.OnWindowClosed(win.config.name, win); + } + + HandleWindowClosedInternal(win: UIWindow): void { + this.RemoveFromStackAndSingleton(win); + this.SyncFocusAndInputMode(); + this.events.emit.OnWindowClosed(win.config.name, win); + } + + EvictCache(): void { + const toEvict: UIWindow[] = []; + for (const [name, win] of pairs(this.cachedByName)) { + if (win !== undefined) { + this.cachedByName[name] = undefined; + toEvict[toEvict.length] = win; + } + } + for (let i = 0; i < toEvict.length; i++) { + toEvict[i].ForceDisposeFromCacheInternal(); + } + } + + CloseAll(alsoEvictCache = true): void { + const copy: UIWindow[] = []; + for (let i = this.windowStack.length - 1; i >= 0; i--) { + copy[copy.length] = this.windowStack[i]; + } + for (let i = 0; i < copy.length; i++) { + copy[i].Close(); + } + if (alsoEvictCache) { + this.EvictCache(); + } + this.SyncFocusAndInputMode(); + } + + GetDiagnostics(): UIDiagnostics { + let openWindows = 0; + let loadingWindows = 0; + for (let i = 0; i < this.windowStack.length; i++) { + const w = this.windowStack[i]; + if (!w.IsDisposed()) { + if (w.IsLoading()) { + loadingWindows = loadingWindows + 1; + } else { + openWindows = openWindows + 1; + } + } + } + let cachedWindows = 0; + for (const [_, w] of pairs(this.cachedByName)) { + if (w !== undefined && !w.IsDisposed()) { + cachedWindows = cachedWindows + 1; + } + } + const top = this.GetTopWindow(); + return { + openWindows, + loadingWindows, + cachedWindows, + topWindowName: top !== undefined ? top.config.name : undefined, + inputMode: this.inputMode, + }; + } + + private AllocateZOrder(config: UIConfigItem): number { + this.zOrderCounter = this.zOrderCounter + 1; + return UI_LAYER_ZORDER[config.layer] + (this.zOrderCounter % 90); + } + + private RemoveFromStackAndSingleton(win: UIWindow): void { + if (this.singletonByName[win.config.name] === win) { + this.singletonByName[win.config.name] = undefined; + } + for (let i = this.windowStack.length - 1; i >= 0; i--) { + if (this.windowStack[i] === win) { + table.remove(this.windowStack, i + 1); + break; + } + } + } + + private SyncFocusAndInputMode(): void { + const top = this.GetTopWindow(); + const nextMode: "game" | "ui" = top !== undefined && top.config.blockWorldClick ? "ui" : "game"; + this.inputMode = nextMode; + + const pc = this.playerCtx.playerController; + if (pc !== undefined && UE !== undefined && UE.UKismetSystemLibrary.IsValid(pc)) { + if (nextMode === "ui") { + pc.bShowMouseCursor = true; + UE.UWidgetBlueprintLibrary.SetInputMode_UIOnlyEx( + pc, + top !== undefined ? (top.GetWidget() as UE.UWidget | undefined) : undefined, + UE.EMouseLockMode.DoNotLock, + false + ); + } else { + pc.bShowMouseCursor = false; + UE.UWidgetBlueprintLibrary.SetInputMode_GameOnly(pc, false); + } + } + + this.events.emit.OnFocusRestored(top !== undefined ? top.config.name : undefined); + } + + override Dispose(): void { + if (this.IsDisposed()) { + return; + } + this.CloseAll(true); + this.events.Dispose(); + super.Dispose(); + } +} diff --git a/Script/ts/src/framework/ui/ui_window.ts b/Script/ts/src/framework/ui/ui_window.ts new file mode 100644 index 0000000..b42e246 --- /dev/null +++ b/Script/ts/src/framework/ui/ui_window.ts @@ -0,0 +1,248 @@ +import type { IDisposable } from "../../share/base/interface"; +import { Logger } from "../../share/base/logger"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { tbpcall } from "../../share/base/traceback"; +import type { GameInstanceContext } from "../context/game_context"; +import type { ResourceLoadHandle } from "../resource/resource_service"; +import type { UIConfigItem } from "./ui_config"; +import type { UIDelegateBridge } from "./ui_delegate_bridge"; +import type { UIManager } from "./ui_manager"; + +const logger = Logger("UIWindow"); + +export interface IWidgetAdapter { + FindChild(widget: any, name: string): any; + AddToViewport(widget: any, zOrder: number): void; + RemoveFromParent(widget: any): void; + SetVisible(widget: any, visible: boolean): void; + IsWidgetValid(widget: any): boolean; +} + +/** + * 纯 TS UMG 窗口控制器基类(拆分原 GameObjectWrapper 继承 -> 组合持有 UUserWidget 视图): + * - 100% 纳入 ts2lua-unreal v0.3.0 单文件热更闭环; + * - 统一托管资源加载句柄、按钮委托绑定、事件监听与防重入关闭状态机。 + */ +export abstract class UIWindow extends ScopedObject { + public config!: UIConfigItem; + protected uiManager!: UIManager; + protected ctx!: GameInstanceContext; + protected widgetAdapter!: IWidgetAdapter; + protected widget: any = undefined; + + private isLoading = false; + private isLoaded = false; + private isVisible = false; + private isClosing = false; + private isCached = false; + private classLoadHandle?: ResourceLoadHandle; + private buttonBindings: IDisposable[] = []; + + InitContextInternal( + ctx: GameInstanceContext, + uiManager: UIManager, + config: UIConfigItem, + widgetAdapter: IWidgetAdapter + ): void { + this.ctx = ctx; + this.uiManager = uiManager; + this.config = config; + this.widgetAdapter = widgetAdapter; + } + + GetWidget(): any { + return this.widget; + } + + IsLoading(): boolean { + return this.isLoading; + } + + IsLoaded(): boolean { + return this.isLoaded; + } + + IsVisible(): boolean { + return this.isVisible; + } + + IsClosing(): boolean { + return this.isClosing; + } + + IsCached(): boolean { + return this.isCached; + } + + SetLoadingStateInternal(loading: boolean, handle?: ResourceLoadHandle): void { + this.isLoading = loading; + this.classLoadHandle = handle; + } + + AttachWidgetInternal(widget: any): void { + this.widget = widget; + this.isLoading = false; + this.isLoaded = true; + this.isCached = false; + this.OnBindWidgets(); + } + + /** + * 按具名子控件查找并校验(设计器改名可精确定位窗口名与控件名)。 + */ + protected RequireWidget(widgetName: string): T { + assert(this.widget !== undefined, string.format("[%s] Widget root is not attached", this.config.name)); + const child = this.widgetAdapter.FindChild(this.widget, widgetName); + assert( + child !== undefined, + string.format("[%s] Required child widget '%s' not found in Widget Blueprint", this.config.name, widgetName) + ); + return child as T; + } + + /** + * 绑定 UButton 点击事件,缓存/关闭/销毁时统一成对解绑,防止复用重复上报。 + */ + protected BindButtonClick(button: any, callback: (this: void) => void): IDisposable | undefined { + const bridge = this.ctx.GetService("uiDelegateBridge"); + if (bridge === undefined) { + logger.Warn("UIDelegateBridge not registered on context", { window: this.config.name }); + return undefined; + } + const handle = bridge.BindButtonClick(button, callback, this); + this.buttonBindings[this.buttonBindings.length] = handle; + return handle; + } + + private UnbindAllButtons(): void { + for (let i = 0; i < this.buttonBindings.length; i++) { + this.buttonBindings[i].Dispose(); + } + this.buttonBindings = []; + } + + ShowInternal(zOrder: number, args?: unknown): void { + if (this.IsDisposed() || this.isClosing) { + return; + } + tbpcall(() => { + this.OnPreShow(args); + }); + if (this.widget !== undefined) { + this.widgetAdapter.AddToViewport(this.widget, zOrder); + this.widgetAdapter.SetVisible(this.widget, true); + } + this.isVisible = true; + tbpcall(() => { + this.OnShow(); + }); + } + + ReuseInternal(zOrder: number, args?: unknown): void { + if (this.IsDisposed()) { + return; + } + this.isCached = false; + this.isClosing = false; + this.EnableAllEventListeners(); + this.OnBindWidgets(); + tbpcall(() => { + this.OnReuseUI(args); + }); + this.ShowInternal(zOrder, args); + } + + Hide(): void { + if (!this.isVisible) { + return; + } + this.isVisible = false; + if (this.widget !== undefined && this.widgetAdapter.IsWidgetValid(this.widget)) { + this.widgetAdapter.SetVisible(this.widget, false); + } + tbpcall(() => { + this.OnHide(); + }); + } + + /** + * 幂等且防重入的窗口关闭入口: + * - 加载中关闭:取消在途类加载句柄,直接收尾; + * - 关闭中重复 Close:直接忽略; + * - 缓存策略窗口:解绑按钮委托、暂停事件监听、从视口摘除并交还缓存池; + * - 非缓存窗口:执行 OnClose、解绑并 Dispose 全部托管资源。 + */ + Close(onClosed?: (this: void) => void): void { + if (this.IsDisposed() || this.isCached || this.isClosing) { + return; + } + this.isClosing = true; + + if (this.isLoading && this.classLoadHandle !== undefined) { + this.classLoadHandle.Cancel(); + this.classLoadHandle = undefined; + this.isLoading = false; + } + + const canCache = + this.config.cacheTag === "cache" && + this.isLoaded && + this.widget !== undefined && + this.widgetAdapter.IsWidgetValid(this.widget) && + !this.ctx.IsShuttingDown(); + + if (canCache) { + this.isVisible = false; + this.isCached = true; + this.isClosing = false; + this.UnbindAllButtons(); + this.DisableAllEventListeners(); + this.widgetAdapter.RemoveFromParent(this.widget); + tbpcall(() => { + this.OnClose(); + }); + this.uiManager.HandleWindowCachedInternal(this); + if (onClosed !== undefined) { + tbpcall(onClosed); + } + return; + } + + if (this.isLoaded) { + tbpcall(() => { + this.OnClose(); + }); + } + + this.isVisible = false; + this.UnbindAllButtons(); + if (this.widget !== undefined && this.widgetAdapter.IsWidgetValid(this.widget)) { + this.widgetAdapter.RemoveFromParent(this.widget); + } + this.widget = undefined; + + this.uiManager.HandleWindowClosedInternal(this); + this.Dispose(); + + if (onClosed !== undefined) { + tbpcall(onClosed); + } + } + + ForceDisposeFromCacheInternal(): void { + this.isCached = false; + this.UnbindAllButtons(); + if (this.widget !== undefined && this.widgetAdapter.IsWidgetValid(this.widget)) { + this.widgetAdapter.RemoveFromParent(this.widget); + } + this.widget = undefined; + this.Dispose(); + } + + protected OnBindWidgets(): void {} + protected OnPreShow(_args?: unknown): void {} + protected OnShow(): void {} + protected OnReuseUI(_args?: unknown): void {} + protected OnHide(): void {} + protected OnClose(): void {} +} diff --git a/Script/ts/src/game/bootstrap_player.ts b/Script/ts/src/game/bootstrap_player.ts new file mode 100644 index 0000000..ddaade9 --- /dev/null +++ b/Script/ts/src/game/bootstrap_player.ts @@ -0,0 +1,39 @@ +/** @noSelfInFile */ + +import { GetGameInstanceContext } from "../framework/context/game_context"; +import { OpenMiniSettings } from "./startup"; + +/** + * PIE / 启动地图玩家入口:绑定 LocalPlayer(0) 的 PlayerController 并打开首期最小设置窗口。 + */ +export function OnBeginPlay(pc: UE.ALuaPlayerController): void { + const world = pc.GetWorld(); + const gi = UE.UGameplayStatics.GetGameInstance(pc) as UE.ULuaGameInstance | undefined; + if (gi === undefined) { + return; + } + const ctx = GetGameInstanceContext(gi); + if (ctx === undefined) { + return; + } + if (world !== undefined && ctx.GetWorldContext().world !== world) { + ctx.OnWorldCleanup(world); + } + ctx.GetOrCreateLocalPlayer(0, pc); + OpenMiniSettings(ctx); +} + +export function OnEndPlay(pc: UE.ALuaPlayerController, _endPlayReason: number): void { + const gi = UE.UGameplayStatics.GetGameInstance(pc) as UE.ULuaGameInstance | undefined; + if (gi === undefined) { + return; + } + const ctx = GetGameInstanceContext(gi); + if (ctx === undefined) { + return; + } + const lp = ctx.GetOrCreateLocalPlayer(0); + if (lp.playerController === pc) { + lp.playerController = undefined; + } +} diff --git a/Script/ts/src/game/setting/mini_settings_window.ts b/Script/ts/src/game/setting/mini_settings_window.ts new file mode 100644 index 0000000..91ec7c1 --- /dev/null +++ b/Script/ts/src/game/setting/mini_settings_window.ts @@ -0,0 +1,102 @@ +import { Logger } from "../../share/base/logger"; +import { ASSET_KEYS } from "../../framework/resource/asset_catalog"; +import type { ResourceService } from "../../framework/resource/resource_service"; +import { RegisterUIConfig } from "../../framework/ui/ui_config"; +import { UIWindow } from "../../framework/ui/ui_window"; +import { SETTING_KEYS, type SettingService } from "./setting_service"; + +const logger = Logger("MiniSettingsWindow"); + +/** + * 首期最小设置窗口控制器(绑定 /Game/UI/WBP_MiniSettings): + * 完整验证:异步加载贴图 -> 具名控件绑定 -> 按钮点击去重 -> 版本化 UE SaveGame 写入 -> 关闭与重启读回。 + */ +export class MiniSettingsWindow extends UIWindow { + public imgIcon?: UE.UImage; + public txtStatus?: UE.UTextBlock; + public btnToggle?: UE.UButton; + public txtToggleLabel?: UE.UTextBlock; + public btnClose?: UE.UButton; + + public iconLoaded = false; + public toggleClickCount = 0; + + protected override OnBindWidgets(): void { + this.imgIcon = this.RequireWidget("ImgIcon"); + this.txtStatus = this.RequireWidget("TxtStatus"); + this.btnToggle = this.RequireWidget("BtnToggle"); + this.txtToggleLabel = this.RequireWidget("TxtToggleLabel"); + this.btnClose = this.RequireWidget("BtnClose"); + + this.BindButtonClick(this.btnToggle, () => { + this.HandleToggleClicked(); + }); + this.BindButtonClick(this.btnClose, () => { + this.Close(); + }); + } + + protected override OnPreShow(): void { + const settingSvc = this.ctx.GetService("setting"); + if (settingSvc !== undefined) { + settingSvc.events.on.OnBoolSettingChanged((key: string, _val: boolean) => { + if (key === SETTING_KEYS.SOUND_ENABLED) { + this.RefreshDisplay(); + } + }, this); + } + + this.RefreshDisplay(); + this.LoadIconTexture(); + } + + private LoadIconTexture(): void { + const resSvc = this.ctx.GetService("resource"); + if (resSvc === undefined) { + return; + } + resSvc.LoadTextureAsync(ASSET_KEYS.MINI_SETTINGS_ICON, this, (ok, tex, _lease, err) => { + if (!ok || tex === undefined) { + logger.Warn("Failed to load MiniSettings icon texture", { err }); + return; + } + this.iconLoaded = true; + if (this.imgIcon !== undefined && this.imgIcon.SetBrushFromTexture !== undefined) { + this.imgIcon.SetBrushFromTexture(tex, false); + } + }); + } + + private HandleToggleClicked(): void { + this.toggleClickCount = this.toggleClickCount + 1; + const settingSvc = this.ctx.GetService("setting"); + if (settingSvc !== undefined) { + const nextVal = settingSvc.ToggleSoundEnabled(); + logger.Info("Sound setting toggled", { soundEnabled: nextVal }); + } + } + + RefreshDisplay(): void { + const settingSvc = this.ctx.GetService("setting"); + const soundEnabled = settingSvc !== undefined ? settingSvc.GetSoundEnabled() : true; + const statusText = soundEnabled ? "Sound: ON" : "Sound: OFF"; + const btnText = soundEnabled ? "Disable Sound" : "Enable Sound"; + + if (this.txtStatus !== undefined && this.txtStatus.SetText !== undefined) { + this.txtStatus.SetText(statusText); + } + if (this.txtToggleLabel !== undefined && this.txtToggleLabel.SetText !== undefined) { + this.txtToggleLabel.SetText(btnText); + } + } +} + +RegisterUIConfig(MiniSettingsWindow, { + name: "MiniSettingsWindow", + assetKey: ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton: true, + layer: "popup", + type: "popup", + cacheTag: "no_cache", + blockWorldClick: true, +}); diff --git a/Script/ts/src/game/setting/setting_service.ts b/Script/ts/src/game/setting/setting_service.ts new file mode 100644 index 0000000..a3871b4 --- /dev/null +++ b/Script/ts/src/game/setting/setting_service.ts @@ -0,0 +1,75 @@ +import { ScopedObject } from "../../share/base/scoped_object"; +import { EventHub } from "../../share/event/event_hub"; +import type { LocalSaveManager, LocalSaveStore } from "../../framework/storage/local_save"; +import type { StorageStatus } from "../../framework/storage/storage_backend"; + +/** 阶段 0 冻结的首期全局布尔设置键 */ +export const SETTING_KEYS = { + SOUND_ENABLED: "mini_settings.sound_enabled", +} as const; + +export interface SettingEvents { + OnBoolSettingChanged(key: string, value: boolean): void; +} + +/** + * 首期最小设置服务(挂接 UE ULuaSaveGame 的 setting 槽位): + * 支持默认值回退、0.1s 合并写、退出同步落盘与变更事件广播。 + */ +export class SettingService extends ScopedObject { + readonly events: EventHub; + private readonly store: LocalSaveStore; + + constructor(saveManager: LocalSaveManager, slotIdentity?: string) { + super(); + this.events = new EventHub("SettingEvents"); + this.store = saveManager.GetOrOpenStore("setting", slotIdentity, 1); + } + + GetStore(): LocalSaveStore { + return this.store; + } + + GetBool(key: string, defaultValue: boolean): boolean { + const val = this.store.Get(key); + if (type(val) === "boolean") { + return val as boolean; + } + return defaultValue; + } + + SetBool(key: string, value: boolean): void { + const prev = this.GetBool(key, !value); + this.store.Set(key, value); + if (prev !== value) { + this.events.emit.OnBoolSettingChanged(key, value); + } + } + + GetSoundEnabled(): boolean { + return this.GetBool(SETTING_KEYS.SOUND_ENABLED, true); + } + + SetSoundEnabled(enabled: boolean): void { + this.SetBool(SETTING_KEYS.SOUND_ENABLED, enabled); + } + + ToggleSoundEnabled(): boolean { + const nextVal = !this.GetSoundEnabled(); + this.SetSoundEnabled(nextVal); + return nextVal; + } + + Flush(): StorageStatus { + return this.store.Flush(); + } + + override Dispose(): void { + if (this.IsDisposed()) { + return; + } + this.store.Flush(); + this.events.Dispose(); + super.Dispose(); + } +} diff --git a/Script/ts/src/game/startup.ts b/Script/ts/src/game/startup.ts new file mode 100644 index 0000000..177708d --- /dev/null +++ b/Script/ts/src/game/startup.ts @@ -0,0 +1,69 @@ +/** @noSelfInFile */ + +import { Logger } from "../share/base/logger"; +import type { GameInstanceContext } from "../framework/context/game_context"; +import { CreateUEResourceService, type ResourceService } from "../framework/resource/resource_service"; +import { LocalSaveManager } from "../framework/storage/local_save"; +import { UEStorageBackend } from "../framework/storage/storage_backend"; +import { CreateUEUIDelegateBridge } from "../framework/ui/ui_delegate_bridge"; +import { UIManager } from "../framework/ui/ui_manager"; +import { MiniSettingsWindow } from "./setting/mini_settings_window"; +import { SettingService } from "./setting/setting_service"; + +const logger = Logger("Startup"); + +/** + * 装配单个 GameInstanceContext 的全部首期框架服务(支持多 PIE 独立实例化): + * - LocalSaveManager(UE ULuaSaveGame + 跨 World 单调时钟 0.1s 合并写 + 退出 FlushAll) + * - SettingService(首期全局布尔设置键) + * - ResourceService(C++ ULuaResourceSubsystem:PIE Content/ 直读 + 发布包热更挂载扩展) + * - UIDelegateBridge(C++ ULuaUIEventSubsystem) + * - 默认 LocalPlayer(0) 的 UIManager + */ +export function AssembleGameInstanceServices(ctx: GameInstanceContext): void { + const storageBackend = new UEStorageBackend(); + const saveManager = new LocalSaveManager(storageBackend, ctx.scheduler); + ctx.RegisterService("saveManager", saveManager); + ctx.AddShutdownHook(() => { + saveManager.FlushAll(); + }); + + const settingService = new SettingService(saveManager); + ctx.RegisterService("setting", settingService); + + const resourceService = CreateUEResourceService(ctx); + if (resourceService !== undefined) { + ctx.RegisterService("resource", resourceService); + } + + const uiDelegateBridge = CreateUEUIDelegateBridge(ctx); + if (uiDelegateBridge !== undefined) { + ctx.RegisterService("uiDelegateBridge", uiDelegateBridge); + } + + const lp0 = ctx.GetOrCreateLocalPlayer(0); + if (resourceService !== undefined) { + lp0.RegisterService("uiManager", new UIManager(ctx, lp0, resourceService)); + } + + logger.Info("Framework services assembled", { + contextId: ctx.contextId, + packagedResourceMode: resourceService !== undefined ? resourceService.IsPackagedMode() : false, + }); +} + +export function GetPrimaryUIManager(ctx: GameInstanceContext): UIManager | undefined { + const lp0 = ctx.GetOrCreateLocalPlayer(0); + return lp0.GetService("uiManager"); +} + +export function OpenMiniSettings( + ctx: GameInstanceContext, + onOpened?: (this: void, ok: boolean, win?: MiniSettingsWindow, err?: string) => void +): MiniSettingsWindow | undefined { + const uiMgr = GetPrimaryUIManager(ctx); + if (uiMgr === undefined) { + return undefined; + } + return uiMgr.ShowUI(MiniSettingsWindow, undefined, onOpened); +} diff --git a/Script/ts/src/main.ts b/Script/ts/src/main.ts new file mode 100644 index 0000000..010bae5 --- /dev/null +++ b/Script/ts/src/main.ts @@ -0,0 +1,38 @@ +/** @noSelfInFile */ + +import { Logger } from "./share/base/logger"; +import { + CreateGameInstanceContext, + DestroyGameInstanceContext, + GetGameInstanceContext, + type GameInstanceContext, +} from "./framework/context/game_context"; +import { AssembleGameInstanceServices } from "./game/startup"; + +const logger = Logger("Main"); + +export function OnInit(gameInstance: UE.ULuaGameInstance): GameInstanceContext { + const ctx = CreateGameInstanceContext(gameInstance); + AssembleGameInstanceServices(ctx); + logger.Info("GameInstance initialized", { contextId: ctx.contextId, luaVersion: _VERSION }); + return ctx; +} + +export function OnTick(gameInstance: UE.ULuaGameInstance, deltaSeconds: number): void { + const ctx = GetGameInstanceContext(gameInstance); + if (ctx !== undefined) { + ctx.Tick(deltaSeconds); + } +} + +export function OnWorldCleanup(gameInstance: UE.ULuaGameInstance): void { + const ctx = GetGameInstanceContext(gameInstance); + if (ctx !== undefined) { + ctx.OnWorldCleanup(); + } +} + +export function OnShutdown(gameInstance: UE.ULuaGameInstance): void { + logger.Info("GameInstance shutting down"); + DestroyGameInstanceContext(gameInstance); +} diff --git a/Script/ts/src/share/base/interface.ts b/Script/ts/src/share/base/interface.ts new file mode 100644 index 0000000..96ea181 --- /dev/null +++ b/Script/ts/src/share/base/interface.ts @@ -0,0 +1,21 @@ +/** + * 核心生命周期与构造器契约(参考 gamelogic/share/framework/base/interface.ts)。 + */ + +export interface ICreatable { + OnCreate(): void; +} + +export interface IDisposable { + Dispose(): void; +} + +export interface IsDisposedChecker { + IsDisposed(): boolean; +} + +export interface ICheckableDisposable extends IDisposable, IsDisposedChecker {} + +export interface Constructor { + new (...args: any[]): T; +} diff --git a/Script/ts/src/share/base/logger.ts b/Script/ts/src/share/base/logger.ts new file mode 100644 index 0000000..792f4ec --- /dev/null +++ b/Script/ts/src/share/base/logger.ts @@ -0,0 +1,191 @@ +export const LogLevel = { + TRACE: 0, + DEBUG: 1, + INFO: 2, + WARN: 3, + ERROR: 4, +} as const; + +export type LogLevelValue = (typeof LogLevel)[keyof typeof LogLevel]; +export type LogLevelString = "trace" | "debug" | "info" | "warn" | "error"; + +export type LogSink = (this: void, level: LogLevelValue, moduleName: string, message: string) => void; + +export interface ILogger { + Debug(msg: string, data?: unknown): void; + Info(msg: string, data?: unknown): void; + Warn(msg: string, data?: unknown): void; + Error(msg: string, data?: unknown): void; + d(msg: string, data?: unknown): void; + i(msg: string, data?: unknown): void; + w(msg: string, data?: unknown): void; + e(msg: string, data?: unknown): void; + GetLevel(): LogLevelValue; + SetLevel(lv: LogLevelValue | LogLevelString): ILogger; +} + +/** @noSelf */ +export function StringToLogLevel(lv: LogLevelString): LogLevelValue { + if (lv === "trace") return LogLevel.TRACE; + if (lv === "debug") return LogLevel.DEBUG; + if (lv === "warn") return LogLevel.WARN; + if (lv === "error") return LogLevel.ERROR; + return LogLevel.INFO; +} + +/** @noSelf */ +function LevelLabel(lv: LogLevelValue): string { + if (lv === LogLevel.TRACE) return "TRACE"; + if (lv === LogLevel.DEBUG) return "DEBUG"; + if (lv === LogLevel.INFO) return "INFO"; + if (lv === LogLevel.WARN) return "WARN"; + return "ERROR"; +} + +/** @noSelf */ +export function SerializeLogValue(value: unknown, depth = 0): string { + const t = type(value); + if (t === "nil") return "nil"; + if (t === "string") return string.format("%q", value as string); + if (t === "number" || t === "boolean") return tostring(value); + if (t !== "table") return tostring(value); + if (depth >= 3) return "{...}"; + + const parts: string[] = []; + for (const [k, v] of pairs(value as Record)) { + parts[parts.length] = string.format("%s=%s", tostring(k), SerializeLogValue(v, depth + 1)); + } + table.sort(parts); + return "{" + table.concat(parts, ", ") + "}"; +} + +/** @module_data */ +let defaultLogLevel: LogLevelValue = LogLevel.INFO; + +/** @module_data */ +let customSink: LogSink | undefined = undefined; + +/** @module_data */ +const allLoggers: Record = {}; + +/** @noSelf */ +function DefaultSink(level: LogLevelValue, moduleName: string, message: string): void { + const line = string.format("[%s][%s] %s", LevelLabel(level), moduleName, message); + if (UnLua !== undefined) { + if (level >= LogLevel.ERROR && UnLua.LogError !== undefined) { + UnLua.LogError(line); + return; + } + if (level === LogLevel.WARN && UnLua.LogWarn !== undefined) { + UnLua.LogWarn(line); + return; + } + if (UnLua.Log !== undefined) { + UnLua.Log(line); + return; + } + } + print(line); +} + +export class LoggerObject implements ILogger { + name: string; + level: LogLevelValue; + debugEnabled = false; + infoEnabled = false; + warnEnabled = false; + errorEnabled = false; + + constructor(name: string) { + this.name = name; + this.level = defaultLogLevel; + this.UpdateLevelFlags(); + } + + private UpdateLevelFlags(): void { + this.debugEnabled = this.level <= LogLevel.DEBUG; + this.infoEnabled = this.level <= LogLevel.INFO; + this.warnEnabled = this.level <= LogLevel.WARN; + this.errorEnabled = this.level <= LogLevel.ERROR; + } + + private EmitLog(level: LogLevelValue, msg: string, data?: unknown): void { + if (this.level > level) { + return; + } + const payload = data !== undefined ? msg + ", " + SerializeLogValue(data, 0) : msg; + const sink = customSink ?? DefaultSink; + sink(level, this.name, payload); + } + + Debug(msg: string, data?: unknown): void { + this.EmitLog(LogLevel.DEBUG, msg, data); + } + + Info(msg: string, data?: unknown): void { + this.EmitLog(LogLevel.INFO, msg, data); + } + + Warn(msg: string, data?: unknown): void { + this.EmitLog(LogLevel.WARN, msg, data); + } + + Error(msg: string, data?: unknown): void { + this.EmitLog(LogLevel.ERROR, msg, data); + } + + d(msg: string, data?: unknown): void { + this.Debug(msg, data); + } + + i(msg: string, data?: unknown): void { + this.Info(msg, data); + } + + w(msg: string, data?: unknown): void { + this.Warn(msg, data); + } + + e(msg: string, data?: unknown): void { + this.Error(msg, data); + } + + GetLevel(): LogLevelValue { + return this.level; + } + + SetLevel(lv: LogLevelValue | LogLevelString): LoggerObject { + this.level = type(lv) === "string" ? StringToLogLevel(lv as LogLevelString) : (lv as LogLevelValue); + this.UpdateLevelFlags(); + return this; + } +} + +/** @noSelf */ +export function SetLogSink(sink: LogSink | undefined): void { + customSink = sink; +} + +/** @noSelf */ +export function SetDefaultLogLevel(lv: LogLevelValue): void { + defaultLogLevel = lv; +} + +/** @noSelf */ +export function SetAllLoggersLevel(lv: LogLevelValue): void { + for (const [_, logger] of pairs(allLoggers)) { + if (logger !== undefined) { + logger.SetLevel(lv); + } + } +} + +/** @noSelf */ +export function Logger(name: string): LoggerObject { + let logger = allLoggers[name]; + if (logger === undefined) { + logger = new LoggerObject(name); + allLoggers[name] = logger; + } + return logger; +} diff --git a/Script/ts/src/share/base/scoped_object.ts b/Script/ts/src/share/base/scoped_object.ts new file mode 100644 index 0000000..451c4d5 --- /dev/null +++ b/Script/ts/src/share/base/scoped_object.ts @@ -0,0 +1,60 @@ +import type { ICheckableDisposable, IDisposable } from "./interface"; +import { EventListenerContainer } from "../event/event_hub"; + +/** + * 作用域对象基类(参考 gamelogic/share/framework/base/scopedobject.ts): + * 统一托管事件监听与子级 IDisposable 资源(定时器、资源租约、子控制器), + * 并提供 IsDisposed() 供事件系统与异步回调自动过滤已释放对象。 + */ +export class ScopedObject extends EventListenerContainer implements ICheckableDisposable { + private scopedObjects: Record = {}; + private disposed = false; + + IsDisposed(): boolean { + return this.disposed; + } + + AddScopedObject(obj: IDisposable): void { + if (this.disposed) { + obj.Dispose(); + return; + } + this.scopedObjects[obj as any] = true; + } + + RemoveScopedObject(obj: IDisposable): void { + this.scopedObjects[obj as any] = undefined; + } + + GetScopedObjectCount(): number { + let count = 0; + for (const [_, active] of pairs(this.scopedObjects)) { + if (active === true) { + count = count + 1; + } + } + return count; + } + + protected DisposeAllScopedObjects(): void { + const list: IDisposable[] = []; + for (const [obj, active] of pairs(this.scopedObjects)) { + if (active === true) { + list[list.length] = obj as IDisposable; + } + } + this.scopedObjects = {}; + for (let i = 0; i < list.length; i++) { + list[i].Dispose(); + } + } + + override Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + this.DisposeAllScopedObjects(); + super.Dispose(); + } +} diff --git a/Script/ts/src/share/base/traceback.ts b/Script/ts/src/share/base/traceback.ts new file mode 100644 index 0000000..61ef05e --- /dev/null +++ b/Script/ts/src/share/base/traceback.ts @@ -0,0 +1,71 @@ +/** @noSelfInFile */ + +export interface TracebackHandler { + DumpTraceback?: (this: void, message: string) => void; + LogTraceback?: (this: void, message: string, stack: string) => void; +} + +/** @module_data */ +let activeHandler: TracebackHandler | undefined = undefined; + +export function SetupTracebackHandler(handler: TracebackHandler | undefined): void { + activeHandler = handler; +} + +function DefaultDump(msg: string): void { + if (UnLua !== undefined && UnLua.LogError !== undefined) { + UnLua.LogError(msg); + } else { + print("[ERROR] " + msg); + } +} + +function OnError(err: unknown): string { + const errText = tostring(err); + const fullStack = debug.traceback(errText, 2); + if (activeHandler !== undefined) { + if (activeHandler.LogTraceback !== undefined) { + pcall(activeHandler.LogTraceback, errText, fullStack); + } + if (activeHandler.DumpTraceback !== undefined) { + pcall(activeHandler.DumpTraceback, fullStack); + } else { + DefaultDump(fullStack); + } + } else { + DefaultDump(fullStack); + } + return fullStack; +} + +/** + * 带完整堆栈上报的安全调用(对应 gamelogic 的 tbpcall),保留全部多返回值。 + */ +export function tbpcall( + fn: (this: void, ...args: TArgs) => TResult, + ...args: TArgs +): LuaMultiReturn<[boolean, TResult | string]> { + return xpcall(fn as unknown as (this: void, ...a: unknown[]) => unknown, OnError, ...args) as unknown as LuaMultiReturn< + [boolean, TResult | string] + >; +} + +/** + * 调用带 self 的对象方法并捕获异常上报堆栈。 + */ +export function tbpcallMethod( + fn: (this: TSelf, ...args: TArgs) => TResult, + selfObj: TSelf, + ...args: TArgs +): LuaMultiReturn<[boolean, TResult | string]> { + return xpcall( + fn as unknown as (this: void, ...a: unknown[]) => unknown, + OnError, + selfObj, + ...args + ) as unknown as LuaMultiReturn<[boolean, TResult | string]>; +} + +export function ReportError(message: string): void { + OnError(message); +} diff --git a/Script/ts/src/share/event/event_hub.ts b/Script/ts/src/share/event/event_hub.ts new file mode 100644 index 0000000..3d5917f --- /dev/null +++ b/Script/ts/src/share/event/event_hub.ts @@ -0,0 +1,204 @@ +import type { ICheckableDisposable, IDisposable } from "../base/interface"; +import { EvEmitter, type EventOwner, type EvListener } from "./events"; + +export type ParamsOf = T extends (...args: infer P) => any ? P : never; +export type ReturnOf = T extends (...args: any[]) => infer R ? R : never; + +type TOnEvent = { + [K in keyof T]: ( + this: void, + handle: (this: void, ...args: ParamsOf) => ReturnOf, + ctx: IEventListenerContainer | EventOwner + ) => EvListener; +}; + +type TEmitEvent = { + [K in keyof T]: (this: void, ...args: ParamsOf) => void; +}; + +export interface EventHubOptions { + asyncEmit?: (this: void, evname: keyof T, emit: (this: void) => void) => void; + preEmit?: (this: void, evname: keyof T) => void; +} + +export interface IEventListenerContainer extends IDisposable { + GetAllEventListenerTable(): Record | undefined; + EnableAllEventListeners(): void; + DisableAllEventListeners(): void; + OffAllEventListeners(): void; + GetActiveEventListenerCount(): number; +} + +export class EventListenerContainer implements IEventListenerContainer { + GetAllEventListenerTable(): Record | undefined { + return rawget(this as any, "__events__") as Record | undefined; + } + + EnableAllEventListeners(): void { + const tbl = this.GetAllEventListenerTable(); + if (tbl !== undefined) { + for (const [_, listener] of pairs(tbl)) { + if (listener !== undefined) { + listener.Enable(); + } + } + } + } + + DisableAllEventListeners(): void { + const tbl = this.GetAllEventListenerTable(); + if (tbl !== undefined) { + for (const [_, listener] of pairs(tbl)) { + if (listener !== undefined) { + listener.Disable(); + } + } + } + } + + OffAllEventListeners(): void { + const tbl = this.GetAllEventListenerTable(); + if (tbl !== undefined) { + // 先收集键再移除,避免遍历中修改表 + const keys: string[] = []; + for (const [ekey] of pairs(tbl)) { + keys[keys.length] = ekey; + } + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const listener = tbl[key]; + if (listener !== undefined) { + listener.Off(); + tbl[key] = undefined; + } + } + } + } + + GetActiveEventListenerCount(): number { + const tbl = this.GetAllEventListenerTable(); + if (tbl === undefined) { + return 0; + } + let count = 0; + for (const [_, listener] of pairs(tbl)) { + if (listener !== undefined && listener.IsActive()) { + count = count + 1; + } + } + return count; + } + + Dispose(): void { + this.OffAllEventListeners(); + } +} + +/** + * 类型化事件中心(对齐 gamelogic/share/framework/event/eventhub.ts): + * - `.on.(cb, owner)` 订阅(支持三元组去重与 owner 统一回收) + * - `.emit.(...args)` 触发(支持 preEmit / asyncEmit,并通过 table.pack.n 保留尾部 nil) + */ +export class EventHub implements ICheckableDisposable { + readonly emit = {} as TEmitEvent; + readonly on = {} as TOnEvent; + readonly ev: EvEmitter; + private disposed = false; + private readonly preEmit?: (this: void, name: keyof T) => void; + private readonly asyncEmit?: (this: void, name: keyof T, emit: (this: void) => void) => void; + + constructor(name: string, options?: EventHubOptions) { + this.ev = new EvEmitter(name); + if (options !== undefined) { + this.preEmit = options.preEmit; + this.asyncEmit = options.asyncEmit; + } + this.SetupEmit(); + this.SetupOn(); + } + + Dispose(): void { + if (this.disposed) { + return; + } + this.disposed = true; + this.ev.Dispose(); + } + + IsDisposed(): boolean { + return this.disposed; + } + + HasOnEvent(name: keyof T): boolean { + return this.ev.HasOnEvent(name as string); + } + + GetListenerCount(name?: keyof T): number { + return this.ev.GetListenerCount(name as string | undefined); + } + + Emit(name: keyof T, ...args: any[]): void { + if (this.disposed) { + return; + } + if (this.preEmit !== undefined) { + this.preEmit(name); + } + this.ev.Emit(name as string, ...args); + } + + private EmitWithArgs(name: keyof T, packed: { n: number; [idx: number]: any }): void { + if (this.disposed) { + return; + } + if (this.preEmit !== undefined) { + this.preEmit(name); + } + this.ev.Emit(name as string, ...table.unpack(packed as unknown as any[], 1, packed.n)); + } + + private SetupEmit(): void { + const hub = this; + const mt = { + __name: "EventHubEmit", + __index: function (this: void, tbl: any, name: keyof T) { + const dispatch = function (this: void, ...args: any[]): void { + if (hub.disposed) { + return; + } + if (hub.asyncEmit !== undefined) { + // 有意修复:按 table.pack 写入的 n 解包,保留尾部 nil 参数 + const packed = table.pack(...args) as unknown as { n: number; [idx: number]: any }; + hub.asyncEmit(name, function (this: void) { + hub.EmitWithArgs(name, packed); + }); + } else { + hub.Emit(name, ...args); + } + }; + rawset(tbl, name, dispatch); + return dispatch; + }, + }; + setmetatable(this.emit as any, mt as unknown as LuaMetatable); + } + + private SetupOn(): void { + const ev = this.ev; + const mt = { + __name: "EventHubOn", + __index: function (this: void, tbl: any, name: string) { + const subscribe = function ( + this: void, + handle: (this: void, ...args: any[]) => any, + ctx: EventOwner + ): EvListener { + return ev.On(name, handle, ctx); + }; + rawset(tbl, name, subscribe); + return subscribe; + }, + }; + setmetatable(this.on as any, mt as unknown as LuaMetatable); + } +} diff --git a/Script/ts/src/share/event/events.ts b/Script/ts/src/share/event/events.ts new file mode 100644 index 0000000..0b26402 --- /dev/null +++ b/Script/ts/src/share/event/events.ts @@ -0,0 +1,270 @@ +import type { IDisposable } from "../base/interface"; +import { tbpcall } from "../base/traceback"; + +export type EventOwner = Record; +export type EventCallable = (this: void, ...args: any[]) => any; +export type GlobalEventFilter = (this: void, owner: EventOwner) => boolean; + +const EMPTY_SLOT = -999999 as unknown as EvListener; + +/** @module_data */ +let nextEmitterId = 0; + +/** @module_data */ +let globalOwnerFilter: GlobalEventFilter | undefined = undefined; + +/** @noSelf */ +function AllocateEmitterId(): number { + nextEmitterId = nextEmitterId + 1; + return nextEmitterId; +} + +/** @noSelf */ +function IsOwnerDisposed(owner: EventOwner | undefined): boolean { + if (owner === undefined) { + return false; + } + if (globalOwnerFilter !== undefined && globalOwnerFilter(owner)) { + return true; + } + const checkFn = owner.IsDisposed as ((this: EventOwner) => boolean) | undefined; + if (checkFn !== undefined && type(checkFn) === "function") { + return checkFn.call(owner) === true; + } + return false; +} + +/** @noSelf */ +export function SetGlobalEventFilter(filter: GlobalEventFilter | undefined): void { + globalOwnerFilter = filter; +} + +export class EvListener implements IDisposable { + channel: EvChannel | undefined; + callable: EventCallable | undefined; + target: EventOwner | undefined; + ekey: string | undefined; + enabled = true; + + constructor(channel: EvChannel, callable: EventCallable, target: EventOwner, ekey: string) { + this.channel = channel; + this.callable = callable; + this.target = target; + this.ekey = ekey; + this.enabled = true; + } + + Off(): void { + if (this.channel === undefined) { + return; + } + const ch = this.channel; + this.channel = undefined; + ch.Off(this); + + const owner = this.target; + const key = this.ekey; + if (owner !== undefined && key !== undefined) { + const ownerEvents = rawget(owner, "__events__") as Record | undefined; + if (ownerEvents !== undefined && ownerEvents[key] === this) { + ownerEvents[key] = undefined; + } + } + + this.callable = undefined; + this.target = undefined; + this.ekey = undefined; + this.enabled = false; + } + + Enable(): void { + this.enabled = true; + } + + Disable(): void { + this.enabled = false; + } + + IsActive(): boolean { + return this.channel !== undefined && this.enabled; + } + + Dispose(): void { + this.Off(); + } +} + +export class EvChannel { + emitter: EvEmitter; + event: string; + listeners: EvListener[] = []; + liveCount = 0; + private indexes: Record = {}; + private dispatchDepth = 0; + + constructor(emitter: EvEmitter, event: string) { + this.emitter = emitter; + this.event = event; + } + + On(callable: EventCallable, target: EventOwner, ekey: string): EvListener { + assert(type(callable) === "function", "EvChannel.On: callable must be a function"); + const listener = new EvListener(this, callable, target, ekey); + const idx = this.listeners.length; + this.listeners[idx] = listener; + this.liveCount = this.liveCount + 1; + this.indexes[listener as any] = idx; + return listener; + } + + Off(listener: EvListener): void { + const idx = this.indexes[listener as any]; + if (idx === undefined) { + return; + } + this.listeners[idx] = EMPTY_SLOT; + this.liveCount = this.liveCount - 1; + this.indexes[listener as any] = undefined; + if (this.dispatchDepth === 0) { + this.TryPurge(); + } + } + + private TryPurge(): void { + if (this.listeners.length - this.liveCount <= 4) { + return; + } + const compacted: EvListener[] = []; + const newIndexes: Record = {}; + for (let i = 0; i < this.listeners.length; i++) { + const item = this.listeners[i]; + if (item !== EMPTY_SLOT) { + const newIdx = compacted.length; + compacted[newIdx] = item; + newIndexes[item as any] = newIdx; + } + } + this.listeners = compacted; + this.liveCount = compacted.length; + this.indexes = newIndexes; + } + + Emit(unsafeCall: boolean, ...args: any[]): void { + this.dispatchDepth = this.dispatchDepth + 1; + // 复用 gamelogic 语义:遍历当前数组,分发期前一个 listener 撤销后一个时立即跳过; + // 分发期新增的 listener 追加到末尾(不破坏正在遍历的下标)。 + const list = this.listeners; + for (let i = 0; i < list.length; i++) { + const listener = list[i]; + if (listener !== EMPTY_SLOT && listener.enabled) { + const owner = listener.target; + if (!IsOwnerDisposed(owner)) { + const callable = listener.callable; + if (callable !== undefined) { + if (unsafeCall) { + callable(...args); + } else { + tbpcall(callable, ...args); + } + } + } + } + } + this.dispatchDepth = this.dispatchDepth - 1; + if (this.dispatchDepth === 0) { + this.TryPurge(); + } + } +} + +export class EvEmitter implements IDisposable { + name: string; + id: number; + key: string; + channels: Record = {}; + enableUnsafeCall = false; + + constructor(name: string) { + this.name = name; + this.id = AllocateEmitterId(); + this.key = name + ":" + tostring(this.id); + } + + /** + * 订阅事件,遵循 gamelogic 三元组 (emitter, event, owner) 去重替换契约: + * 若同一 owner 已在该 emitter 订阅过同名事件,先撤销旧监听再注册新监听。 + */ + On(event: string, callable: EventCallable, target: EventOwner): EvListener { + assert(type(target) === "table", "EvEmitter.On: owner(target) must be a table/object"); + assert(type(callable) === "function", "EvEmitter.On: callable must be a function"); + + const ekey = this.key + ":" + event; + let targetEvents = rawget(target, "__events__") as Record | undefined; + if (targetEvents === undefined) { + targetEvents = {}; + setmetatable(targetEvents, { __mode: "v" }); + rawset(target, "__events__", targetEvents); + } + + const existing = targetEvents[ekey]; + if (existing !== undefined) { + existing.Off(); + } + + let channel = this.channels[event]; + if (channel === undefined) { + channel = new EvChannel(this, event); + this.channels[event] = channel; + } + + const listener = channel.On(callable, target, ekey); + targetEvents[ekey] = listener; + return listener; + } + + Emit(event: string, ...args: any[]): void { + const channel = this.channels[event]; + if (channel === undefined) { + return; + } + channel.Emit(this.enableUnsafeCall, ...args); + } + + HasOnEvent(event: string): boolean { + const channel = this.channels[event]; + return channel !== undefined && channel.liveCount > 0; + } + + GetListenerCount(event?: string): number { + if (event !== undefined) { + const ch = this.channels[event]; + return ch !== undefined ? ch.liveCount : 0; + } + let total = 0; + for (const [_, ch] of pairs(this.channels)) { + if (ch !== undefined) { + total = total + ch.liveCount; + } + } + return total; + } + + ClearAll(): void { + for (const [evName, ch] of pairs(this.channels)) { + if (ch !== undefined) { + const list = ch.listeners; + for (let i = 0; i < list.length; i++) { + const listener = list[i]; + if (listener !== EMPTY_SLOT) { + listener.Off(); + } + } + this.channels[evName] = undefined; + } + } + } + + Dispose(): void { + this.ClearAll(); + } +} diff --git a/Script/ts/src/tests/harness/test_runner.ts b/Script/ts/src/tests/harness/test_runner.ts new file mode 100644 index 0000000..1a1ab76 --- /dev/null +++ b/Script/ts/src/tests/harness/test_runner.ts @@ -0,0 +1,140 @@ +/** @noSelfInFile */ + +export interface TestFailure { + suite: string; + name: string; + error: string; +} + +export interface TestSummary { + total: number; + passed: number; + failed: number; + failures: TestFailure[]; +} + +export interface TestCase { + name: string; + fn: (this: void) => void; +} + +export interface TestSuite { + name: string; + cases: TestCase[]; +} + +export function Assert(condition: unknown, message?: string): void { + if (!condition) { + error(message ?? "Assertion failed", 2); + } +} + +export function AssertEqual(actual: T, expected: T, label?: string): void { + if (actual !== expected) { + const prefix = label !== undefined ? label + ": " : ""; + error( + string.format("%sexpected %s, got %s", prefix, tostring(expected), tostring(actual)), + 2 + ); + } +} + +export function AssertNotEqual(actual: T, unexpected: T, label?: string): void { + if (actual === unexpected) { + const prefix = label !== undefined ? label + ": " : ""; + error( + string.format("%sexpected value different from %s", prefix, tostring(unexpected)), + 2 + ); + } +} + +export function AssertNear(actual: number, expected: number, epsilon: number, label?: string): void { + if (math.abs(actual - expected) > epsilon) { + const prefix = label !== undefined ? label + ": " : ""; + error( + string.format( + "%sexpected %s (+/- %s), got %s", + prefix, + tostring(expected), + tostring(epsilon), + tostring(actual) + ), + 2 + ); + } +} + +export function AssertArrayEqual(actual: T[], expected: T[], label?: string): void { + const prefix = label !== undefined ? label + ": " : ""; + if (actual.length !== expected.length) { + error( + string.format( + "%sarray length mismatch: expected %d, got %d", + prefix, + expected.length, + actual.length + ), + 2 + ); + } + for (let i = 0; i < expected.length; i++) { + if (actual[i] !== expected[i]) { + error( + string.format( + "%sarray[%d] mismatch: expected %s, got %s", + prefix, + i, + tostring(expected[i]), + tostring(actual[i]) + ), + 2 + ); + } + } +} + +export function RunSuites(suites: TestSuite[]): TestSummary { + const summary: TestSummary = { + total: 0, + passed: 0, + failed: 0, + failures: [], + }; + + for (let s = 0; s < suites.length; s++) { + const suite = suites[s]; + for (let c = 0; c < suite.cases.length; c++) { + const testCase = suite.cases[c]; + summary.total = summary.total + 1; + const [ok, err] = xpcall(testCase.fn, debug.traceback); + if (ok) { + summary.passed = summary.passed + 1; + } else { + summary.failed = summary.failed + 1; + summary.failures[summary.failures.length] = { + suite: suite.name, + name: testCase.name, + error: tostring(err), + }; + } + } + } + + return summary; +} + +export function FormatReport(summary: TestSummary): string { + const lines: string[] = []; + lines[lines.length] = string.format( + "=== Test Summary: %d/%d passed (%d failed) ===", + summary.passed, + summary.total, + summary.failed + ); + for (let i = 0; i < summary.failures.length; i++) { + const f = summary.failures[i]; + lines[lines.length] = string.format("[FAIL] %s :: %s\n%s", f.suite, f.name, f.error); + } + return table.concat(lines, "\n"); +} diff --git a/Script/ts/src/tests/run_unit_tests.ts b/Script/ts/src/tests/run_unit_tests.ts new file mode 100644 index 0000000..23dbdd5 --- /dev/null +++ b/Script/ts/src/tests/run_unit_tests.ts @@ -0,0 +1,23 @@ +/** @noSelfInFile */ + +import { FormatReport, RunSuites, type TestSuite, type TestSummary } from "./harness/test_runner"; +import { CreateContextAndMgrSuite } from "./unit/context_and_mgr_test"; +import { CreateEventHubSuite } from "./unit/event_hub_test"; +import { CreateSchedulerSuite } from "./unit/scheduler_test"; +import { CreateSmokeSuite } from "./unit/smoke_test"; +import { CreateStorageAndSettingSuite } from "./unit/storage_and_setting_test"; +import { CreateUIAndResourceSuite } from "./unit/ui_and_resource_test"; + +export function RunAllUnitTests(): TestSummary { + const suites: TestSuite[] = [ + CreateSmokeSuite(), + CreateEventHubSuite(), + CreateSchedulerSuite(), + CreateContextAndMgrSuite(), + CreateStorageAndSettingSuite(), + CreateUIAndResourceSuite(), + ]; + const summary = RunSuites(suites); + print(FormatReport(summary)); + return summary; +} diff --git a/Script/ts/src/tests/ue/run_ue_tests.ts b/Script/ts/src/tests/ue/run_ue_tests.ts new file mode 100644 index 0000000..ffe9b32 --- /dev/null +++ b/Script/ts/src/tests/ue/run_ue_tests.ts @@ -0,0 +1,298 @@ +/** @noSelfInFile */ + +import { GetGameInstanceContext } from "../../framework/context/game_context"; +import * as Json from "../../framework/core/json"; +import { ASSET_KEYS, BASE_ASSET_PATHS } from "../../framework/resource/asset_catalog"; +import type { ResourceService } from "../../framework/resource/resource_service"; +import { LocalSaveManager } from "../../framework/storage/local_save"; +import { UEStorageBackend } from "../../framework/storage/storage_backend"; +import type { UIDelegateBridge } from "../../framework/ui/ui_delegate_bridge"; +import { MiniSettingsWindow } from "../../game/setting/mini_settings_window"; +import { SettingService } from "../../game/setting/setting_service"; +import { GetPrimaryUIManager } from "../../game/startup"; +import { ScopedObject } from "../../share/base/scoped_object"; +import { Assert, AssertEqual, FormatReport, RunSuites, type TestSuite, type TestSummary } from "../harness/test_runner"; + +function PumpUEFrames(frames: number, dt = 0.02): void { + if (__UE_TEST_TICK === undefined) { + return; + } + for (let i = 0; i < frames; i++) { + __UE_TEST_TICK(dt); + } +} + +export function RunAllUETests( + gameInstance: UE.ULuaGameInstance | undefined, + world: UE.UWorld | undefined +): TestSummary { + const suites: TestSuite[] = [ + { + name: "UE.NativeJson", + cases: [ + { + name: "ue_json native C++ module is active and preserves 64-bit integers and UTF-8", + fn: () => { + Assert(Json.IsNativeBackend(), "expected native ue_json backend inside UE"); + const bigInt = tonumber("9007199254740993") as number; // true Lua 5.4 int64 (2^53 + 1) + AssertEqual(math.type(bigInt), "integer", "bigInt is Lua 5.4 integer"); + const input = { + version: 2, + roleId: bigInt, + title: "UE5.8中文测试", + enabled: true, + list: [10, 20, 30], + empty: Json.GetEmptyArray(), + }; + + const [encoded, encErr] = Json.Encode(input); + AssertEqual(encErr, undefined, "encode error"); + Assert(type(encoded) === "string", "encoded string"); + + const [decoded, decErr] = Json.Decode(encoded as string); + AssertEqual(decErr, undefined, "decode error"); + const obj = decoded as Record; + AssertEqual(obj.version, 2); + AssertEqual(obj.roleId, bigInt, "int64 lossless round-trip"); + AssertEqual(obj.title, "UE5.8中文测试"); + AssertEqual(obj.enabled, true); + const list = obj.list as number[]; + AssertEqual(list[0], 10); + AssertEqual(list[2], 30); + + const [badVal, badErr] = Json.Decode("{broken"); + AssertEqual(badVal, undefined); + Assert(badErr !== undefined && badErr !== "", "malformed JSON returns error"); + }, + }, + ], + }, + { + name: "UE.LocalStorage", + cases: [ + { + name: "ULuaStorageLibrary + ULuaSaveGame: debounce save, cold-start readback, and corruption recovery", + fn: () => { + Assert(gameInstance !== undefined, "gameInstance required"); + const ctx = GetGameInstanceContext(gameInstance!)!; + Assert(ctx !== undefined, "GameInstanceContext must be initialized"); + + const slotId = "ue_test_slot"; + const fullSlotName = "sdata_" + slotId; + UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true); + + const backend = new UEStorageBackend(); + const saveMgr = new LocalSaveManager(backend, ctx.scheduler); + const settings = new SettingService(saveMgr, slotId); + + AssertEqual(settings.GetStore().GetLastLoadStatus(), "not_found"); + AssertEqual(settings.GetSoundEnabled(), true, "missing slot returns default"); + + // Debounced save triggered by real UE FTSTicker -> GameInstanceContext.Tick + settings.SetSoundEnabled(false); + PumpUEFrames(8, 0.02); // 0.16s > 0.1s debounce + AssertEqual(settings.GetStore().IsDirty(), false, "debounced save flushed to UE SaveGame"); + Assert(UE.ULuaStorageLibrary.DoesSlotExist(fullSlotName, 0), "SaveGame file created on disk"); + + // Write a second value so first value (false) moves to .bak + settings.SetSoundEnabled(true); + AssertEqual(settings.Flush(), "ok"); + settings.Dispose(); + saveMgr.Dispose(); + + // Cold-start readback + const saveMgr2 = new LocalSaveManager(backend, ctx.scheduler); + const settings2 = new SettingService(saveMgr2, slotId); + AssertEqual(settings2.GetStore().GetLastLoadStatus(), "ok"); + AssertEqual(settings2.GetSoundEnabled(), true, "cold-start reads latest value"); + settings2.Dispose(); + saveMgr2.Dispose(); + + // Inject corrupted primary bytes -> preserves .corrupt and recovers .bak (false) + Assert( + UE.ULuaStorageLibrary.WriteCorruptRawSlotForTest(fullSlotName, "CORRUPTED_SAV_DATA", 0), + "corrupt injection succeeded" + ); + const saveMgr3 = new LocalSaveManager(backend, ctx.scheduler); + const settings3 = new SettingService(saveMgr3, slotId); + AssertEqual(settings3.GetStore().GetLastLoadStatus(), "ok"); + Assert(settings3.GetStore().WasRecoveredFromBackup(), "recovered from .bak"); + AssertEqual(settings3.GetSoundEnabled(), false, "recovered previous valid value"); + Assert( + UE.ULuaStorageLibrary.DoesCorruptBackupExist(fullSlotName, 0), + ".corrupt evidence preserved" + ); + + settings3.Dispose(); + saveMgr3.Dispose(); + UE.ULuaStorageLibrary.DeleteSlot(fullSlotName, 0, true); + }, + }, + ], + }, + { + name: "UE.ResourceManager", + cases: [ + { + name: "ULuaResourceSubsystem: PIE Content load, PatchManifest override, coalesced cancel, and GC ref-count", + fn: () => { + Assert(gameInstance !== undefined, "gameInstance required"); + const ctx = GetGameInstanceContext(gameInstance!)!; + const resSvc = ctx.GetService("resource")!; + const sub = UE.ULuaResourceSubsystem.GetFromGameInstance(gameInstance!)!; + Assert(resSvc !== undefined && sub !== undefined, "ResourceService & Subsystem ready"); + + Assert(resSvc.DoesAssetExist(ASSET_KEYS.MINI_SETTINGS_ICON), "T_MiniSettingsIcon exists"); + Assert(resSvc.DoesAssetExist(ASSET_KEYS.MINI_SETTINGS_WIDGET), "WBP_MiniSettings exists"); + Assert(!resSvc.DoesAssetExist("/Game/DoesNotExist/MissingAsset"), "missing asset returns false"); + + // PatchManifest logical key override precedence + const aliasKey = "tex.patch_alias_icon"; + Assert( + sub.ApplyPatchManifest( + string.format('{"%s":"%s"}', aliasKey, BASE_ASSET_PATHS[ASSET_KEYS.MINI_SETTINGS_ICON]) + ), + "ApplyPatchManifest succeeded" + ); + AssertEqual( + resSvc.ResolveAssetPath(aliasKey), + BASE_ASSET_PATHS[ASSET_KEYS.MINI_SETTINGS_ICON], + "PatchOverlay resolves alias key" + ); + + // Concurrent async load of Texture + Widget Class + coalesced duplicate with independent cancel + const owner1 = new ScopedObject(); + const owner2 = new ScopedObject(); + const owner3 = new ScopedObject(); + + let tex1: UE.UTexture2D | undefined; + let tex2: UE.UTexture2D | undefined; + let cancelledFired = false; + let widgetCls: UE.UClass | undefined; + let missingCalls = 0; + let missingOk = true; + + resSvc.LoadTextureAsync(ASSET_KEYS.MINI_SETTINGS_ICON, owner1, (ok, asset) => { + if (ok) tex1 = asset; + }); + const hCancel = resSvc.LoadTextureAsync(aliasKey, owner3, () => { + cancelledFired = true; + }); + resSvc.LoadTextureAsync(aliasKey, owner2, (ok, asset) => { + if (ok) tex2 = asset; + }); + resSvc.LoadClassAsync(ASSET_KEYS.MINI_SETTINGS_WIDGET, owner1, (ok, cls) => { + if (ok) widgetCls = cls; + }); + resSvc.LoadObjectAsync("/Game/DoesNotExist/MissingAsset", owner1, (ok) => { + missingCalls = missingCalls + 1; + missingOk = ok; + }); + + // Cancel consumer #3 while #1 & #2 still wait + hCancel.Cancel(); + + PumpUEFrames(15, 0.02); + + Assert(!cancelledFired, "cancelled caller must not receive callback"); + Assert(tex1 !== undefined && UE.UKismetSystemLibrary.IsValid(tex1), "tex1 loaded & valid"); + Assert(tex2 !== undefined && UE.UKismetSystemLibrary.IsValid(tex2), "tex2 loaded & valid"); + Assert(widgetCls !== undefined && UE.UKismetSystemLibrary.IsValid(widgetCls), "WBP_MiniSettings class loaded"); + AssertEqual(missingCalls, 1, "missing asset delivers exactly once"); + AssertEqual(missingOk, false, "missing asset reports ok=false"); + + // Same underlying texture held by 2 logical keys: release owner1 + force UE GC -> owner2 still valid! + owner1.Dispose(); + if (__UE_TEST_GC !== undefined) { + __UE_TEST_GC(); + } + Assert(UE.UKismetSystemLibrary.IsValid(tex2!), "tex2 survives GC while owner2 holds ref"); + AssertEqual(sub.GetAssetRefCount(ASSET_KEYS.MINI_SETTINGS_ICON), 1, "refcount decremented to 1"); + + // Release last owner -> counts return cleanly to 0 + owner2.Dispose(); + owner3.Dispose(); + sub.ClearPatchManifest(); + if (__UE_TEST_GC !== undefined) { + __UE_TEST_GC(); + } + const diag = resSvc.GetDiagnostics(); + AssertEqual(diag.tsPendingRequests, 0, "tsPending back to 0"); + AssertEqual(diag.nativeInFlight, 0, "nativeInFlight back to 0"); + AssertEqual(diag.nativeRetainedAssets, 0, "nativeRetained back to 0"); + AssertEqual(diag.nativeTotalRefCount, 0, "nativeTotalRefCount back to 0"); + }, + }, + ], + }, + { + name: "UE.MiniSettingsUMG", + cases: [ + { + name: "Real WBP_MiniSettings open, async icon, button click delegate, SaveGame persist, and clean baseline teardown", + fn: () => { + Assert(gameInstance !== undefined && world !== undefined, "GI & World required"); + const ctx = GetGameInstanceContext(gameInstance!)!; + const uiMgr = GetPrimaryUIManager(ctx)!; + const settingSvc = ctx.GetService("setting")!; + const resSvc = ctx.GetService("resource")!; + const uiBridge = ctx.GetService("uiDelegateBridge")!; + + // Ensure clean initial slot + UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true); + settingSvc.GetStore().Reload(); + AssertEqual(settingSvc.GetSoundEnabled(), true, "initial sound ON"); + + // Attach real UWorld to context so UWidgetBlueprintLibrary.Create has a valid WorldContext + ctx.OnWorldCleanup(world); + + let openedOk = false; + const win = uiMgr.ShowUI(MiniSettingsWindow, undefined, (ok) => { + openedOk = ok; + }); + Assert(win !== undefined, "MiniSettingsWindow controller created"); + + // Pump frames for async Widget Blueprint class + icon texture load + PumpUEFrames(20, 0.02); + + Assert(openedOk, "MiniSettingsWindow opened callback fired"); + Assert(win!.IsLoaded(), "widget loaded"); + Assert(win!.iconLoaded, "T_MiniSettingsIcon loaded and applied to ImgIcon"); + Assert(win!.btnToggle !== undefined && win!.btnClose !== undefined, "named UMG buttons bound"); + + // Simulate real UE UButton::OnClicked broadcast + Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(win!.btnToggle), "SimulateButtonClick BtnToggle"); + AssertEqual(win!.toggleClickCount, 1, "toggle click handled exactly once"); + AssertEqual(settingSvc.GetSoundEnabled(), false, "sound toggled OFF"); + + // Wait > 0.1s for debounced SaveGame flush + PumpUEFrames(8, 0.02); + AssertEqual(settingSvc.GetStore().IsDirty(), false, "setting persisted to UE SaveGame"); + + // Simulate clicking Close button + Assert(UE.ULuaUIEventSubsystem.SimulateButtonClick(win!.btnClose), "SimulateButtonClick BtnClose"); + Assert(win!.IsDisposed(), "MiniSettingsWindow disposed after close"); + + // Verify zero leaks across UIManager, UIDelegateBridge, and ResourceService + AssertEqual(uiMgr.GetDiagnostics().openWindows, 0, "openWindows back to 0"); + AssertEqual(uiBridge.GetActiveBindingCount(), 0, "button delegate bindings back to 0"); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refcount back to 0"); + + // Verify cold readback from disk + const freshStore = new LocalSaveManager(new UEStorageBackend(), ctx.scheduler); + const freshSettings = new SettingService(freshStore); + AssertEqual(freshSettings.GetSoundEnabled(), false, "cold readback reads OFF"); + freshSettings.Dispose(); + freshStore.Dispose(); + + UE.ULuaStorageLibrary.DeleteSlot("sdata", 0, true); + }, + }, + ], + }, + ]; + + const summary = RunSuites(suites); + print(FormatReport(summary)); + return summary; +} diff --git a/Script/ts/src/tests/unit/context_and_mgr_test.ts b/Script/ts/src/tests/unit/context_and_mgr_test.ts new file mode 100644 index 0000000..905861f --- /dev/null +++ b/Script/ts/src/tests/unit/context_and_mgr_test.ts @@ -0,0 +1,146 @@ +/** @noSelfInFile */ + +import { GameInstanceContext } from "../../framework/context/game_context"; +import { ControllerBase, MgrBase, MgrDataBase } from "../../framework/module/mgr_base"; +import { EventHub } from "../../share/event/event_hub"; +import { Assert, AssertArrayEqual, AssertEqual, type TestSuite } from "../harness/test_runner"; + +interface DemoBizEvents { + Notify(msg: string): void; +} + +class SampleData extends MgrDataBase { + value = 0; + disposed = false; + Dispose(): void { + this.disposed = true; + } +} + +class SampleSubController extends ControllerBase { + events: string[] = []; + override OnEnter(): void { + this.events[this.events.length] = "enter"; + } + override OnActive(): void { + this.events[this.events.length] = "active"; + } + override OnExit(): void { + this.events[this.events.length] = "exit"; + } +} + +class SampleMgr extends MgrBase { + lifecycle: string[] = []; + subCtrl?: SampleSubController; + + override OnCreate(): void { + this.lifecycle[this.lifecycle.length] = "create"; + } + override OnBindControllers(): void { + this.subCtrl = this.AddController(SampleSubController); + } + override OnBindEvents(): void { + this.lifecycle[this.lifecycle.length] = "bind"; + } + override OnClean(): void { + this.lifecycle[this.lifecycle.length] = "clean"; + } +} + +export function CreateContextAndMgrSuite(): TestSuite { + return { + name: "Step1.ContextAndMgr", + cases: [ + { + name: "MgrRegistry creates, looks up by ctor and name, and cleans both indexes on DelMgr", + fn: () => { + const ctx = new GameInstanceContext(); + const mgr = ctx.mgrRegistry.CreateMgr(SampleMgr, "SampleMgr"); + const data = ctx.mgrRegistry.CreateMgrData(SampleData); + data.value = 123; + + AssertEqual(ctx.mgrRegistry.GetMgr(SampleMgr), mgr); + AssertEqual(ctx.mgrRegistry.GetMgrByName("SampleMgr"), mgr); + AssertEqual(ctx.mgrRegistry.GetMgrData(SampleData), data); + AssertArrayEqual(mgr.lifecycle, ["create", "bind"]); + Assert(mgr.subCtrl !== undefined, "sub controller attached"); + AssertArrayEqual(mgr.subCtrl!.events, ["enter", "active"]); + + ctx.mgrRegistry.DelMgr(SampleMgr); + AssertEqual(ctx.mgrRegistry.GetMgr(SampleMgr), undefined); + AssertEqual(ctx.mgrRegistry.GetMgrByName("SampleMgr"), undefined, "name index must be cleared"); + Assert(mgr.IsDisposed(), "mgr disposed"); + AssertArrayEqual(mgr.lifecycle, ["create", "bind", "clean"]); + AssertArrayEqual(mgr.subCtrl!.events, ["enter", "active", "exit"]); + + ctx.Dispose(); + Assert(data.disposed, "data disposed with context"); + }, + }, + { + name: "Two GameInstanceContexts coexist in one Lua VM; disposing #1 keeps #2 intact", + fn: () => { + const ctx1 = new GameInstanceContext(); + const ctx2 = new GameInstanceContext(); + + const hub1 = new EventHub("Hub1"); + const hub2 = new EventHub("Hub2"); + ctx1.RegisterService("bizHub", hub1); + ctx2.RegisterService("bizHub", hub2); + + const mgr1 = ctx1.mgrRegistry.CreateMgr(SampleMgr, "SampleMgr"); + const mgr2 = ctx2.mgrRegistry.CreateMgr(SampleMgr, "SampleMgr"); + + const log1: string[] = []; + const log2: string[] = []; + + hub1.on.Notify((msg: string) => { + log1[log1.length] = msg; + }, mgr1); + hub2.on.Notify((msg: string) => { + log2[log2.length] = msg; + }, mgr2); + + ctx1.scheduler.AddMonotonicRepeatTimer( + 0.05, + () => { + log1[log1.length] = "tick1"; + }, + mgr1 + ); + ctx2.scheduler.AddMonotonicRepeatTimer( + 0.05, + () => { + log2[log2.length] = "tick2"; + }, + mgr2 + ); + + const shutdownOrder: string[] = []; + ctx1.AddShutdownHook(() => { + shutdownOrder[shutdownOrder.length] = "hook1"; + }); + ctx1.AddShutdownHook(() => { + shutdownOrder[shutdownOrder.length] = "hook2"; + }); + + // Destroy context #1 + ctx1.Dispose(); + AssertArrayEqual(shutdownOrder, ["hook2", "hook1"], "shutdown hooks run in reverse order"); + Assert(mgr1.IsDisposed(), "mgr1 disposed"); + Assert(!mgr2.IsDisposed(), "mgr2 still alive"); + + // Context #2 continues receiving events and timers + hub2.emit.Notify("alive"); + ctx2.Tick(0.06); + AssertArrayEqual(log1, []); + AssertArrayEqual(log2, ["alive", "tick2"]); + + ctx2.Dispose(); + Assert(mgr2.IsDisposed(), "mgr2 disposed cleanly"); + }, + }, + ], + }; +} diff --git a/Script/ts/src/tests/unit/event_hub_test.ts b/Script/ts/src/tests/unit/event_hub_test.ts new file mode 100644 index 0000000..7ca7de4 --- /dev/null +++ b/Script/ts/src/tests/unit/event_hub_test.ts @@ -0,0 +1,182 @@ +/** @noSelfInFile */ + +import { ScopedObject } from "../../share/base/scoped_object"; +import { SetupTracebackHandler } from "../../share/base/traceback"; +import { EventHub } from "../../share/event/event_hub"; +import { Assert, AssertArrayEqual, AssertEqual, type TestSuite } from "../harness/test_runner"; + +interface SampleEvents { + Ping(a: number, b?: string, c?: number): void; + Chain(step: number): void; + Trailing(a: string, b?: string, c?: string): void; +} + +export function CreateEventHubSuite(): TestSuite { + return { + name: "Step1.EventHub", + cases: [ + { + name: "Duplicate (emitter, event, owner) subscription replaces previous listener", + fn: () => { + const hub = new EventHub("DupTest"); + const owner = new ScopedObject(); + const log: string[] = []; + + hub.on.Ping((a: number) => { + log[log.length] = "old:" + tostring(a); + }, owner); + hub.on.Ping((a: number) => { + log[log.length] = "new:" + tostring(a); + }, owner); + + AssertEqual(hub.GetListenerCount("Ping"), 1, "listener count"); + hub.emit.Ping(42); + AssertArrayEqual(log, ["new:42"]); + owner.Dispose(); + AssertEqual(hub.GetListenerCount("Ping"), 0, "after dispose"); + hub.Dispose(); + }, + }, + { + name: "Callback receives exact event args (no owner prepended) and respects Enable/Disable/OffAll", + fn: () => { + const hub = new EventHub("ArgsTest"); + const owner = new ScopedObject(); + const received: string[] = []; + + hub.on.Ping((a: number, b?: string, c?: number) => { + received[received.length] = string.format("%s|%s|%s", tostring(a), tostring(b), tostring(c)); + }, owner); + + hub.emit.Ping(7, "hello", 9); + owner.DisableAllEventListeners(); + hub.emit.Ping(8, "skip", 10); + owner.EnableAllEventListeners(); + hub.emit.Ping(11, undefined, 13); + owner.OffAllEventListeners(); + hub.emit.Ping(99, "gone"); + + AssertArrayEqual(received, ["7|hello|9", "11|nil|13"]); + hub.Dispose(); + }, + }, + { + name: "Cancelling next listener or disposing next owner during dispatch skips it immediately", + fn: () => { + const hub = new EventHub("MutationTest"); + const ownerA = new ScopedObject(); + const ownerB = new ScopedObject(); + const ownerC = new ScopedObject(); + const order: string[] = []; + + const listenerB = hub.on.Ping(() => { + order[order.length] = "B"; + }, ownerB); + // Re-order so A runs before B and C + listenerB.Off(); + + hub.on.Ping(() => { + order[order.length] = "A"; + subB.Off(); + ownerC.Dispose(); + }, ownerA); + + const subB = hub.on.Ping(() => { + order[order.length] = "B"; + }, ownerB); + + hub.on.Ping(() => { + order[order.length] = "C"; + }, ownerC); + + hub.emit.Ping(1); + AssertArrayEqual(order, ["A"]); + ownerA.Dispose(); + ownerB.Dispose(); + hub.Dispose(); + }, + }, + { + name: "Nested Emit and listener error isolation", + fn: () => { + const capturedErrors: string[] = []; + SetupTracebackHandler({ + DumpTraceback: (msg: string) => { + capturedErrors[capturedErrors.length] = msg; + }, + }); + + const hub = new EventHub("NestedTest"); + const ownerA = new ScopedObject(); + const ownerB = new ScopedObject(); + const order: string[] = []; + + hub.on.Chain((step: number) => { + order[order.length] = "A:" + tostring(step); + if (step === 1) { + hub.emit.Chain(2); + } + if (step === 2) { + error("boom-in-listener"); + } + }, ownerA); + + hub.on.Chain((step: number) => { + order[order.length] = "B:" + tostring(step); + }, ownerB); + + hub.emit.Chain(1); + SetupTracebackHandler(undefined); + + AssertArrayEqual(order, ["A:1", "A:2", "B:2", "B:1"]); + Assert(capturedErrors.length === 1, "expected 1 isolated error"); + ownerA.Dispose(); + ownerB.Dispose(); + hub.Dispose(); + }, + }, + { + name: "preEmit and asyncEmit preserve trailing nil via table.pack.n", + fn: () => { + const pending: Array<(this: void) => void> = []; + const preCalls: string[] = []; + const hub = new EventHub("AsyncTest", { + preEmit: (evName) => { + preCalls[preCalls.length] = evName as string; + }, + asyncEmit: (_evName, emit) => { + pending[pending.length] = emit; + }, + }); + + const owner = new ScopedObject(); + let argCount = -1; + let capturedA: string | undefined; + let capturedB: string | undefined; + let capturedC: string | undefined; + + hub.on.Trailing((...args: any[]) => { + argCount = select("#", ...args); + capturedA = args[0]; + capturedB = args[1]; + capturedC = args[2]; + }, owner); + + hub.emit.Trailing("first", undefined, undefined); + AssertEqual(preCalls.length, 0, "preEmit should not run before async flush"); + AssertEqual(pending.length, 1, "one queued async emit"); + + pending[0](); + AssertArrayEqual(preCalls, ["Trailing"]); + AssertEqual(argCount, 3, "trailing nils must be preserved"); + AssertEqual(capturedA, "first"); + AssertEqual(capturedB, undefined); + AssertEqual(capturedC, undefined); + + owner.Dispose(); + hub.Dispose(); + }, + }, + ], + }; +} diff --git a/Script/ts/src/tests/unit/scheduler_test.ts b/Script/ts/src/tests/unit/scheduler_test.ts new file mode 100644 index 0000000..f2ee4ba --- /dev/null +++ b/Script/ts/src/tests/unit/scheduler_test.ts @@ -0,0 +1,123 @@ +/** @noSelfInFile */ + +import { ScopedObject } from "../../share/base/scoped_object"; +import { FrameScheduler } from "../../framework/core/scheduler"; +import { AssertArrayEqual, AssertEqual, type TestSuite } from "../harness/test_runner"; + +export function CreateSchedulerSuite(): TestSuite { + return { + name: "Step1.Scheduler", + cases: [ + { + name: "Frame timers: 0 and 1 fire next frame, N fires on N-th frame", + fn: () => { + const scheduler = new FrameScheduler(); + const fired: string[] = []; + + scheduler.AddFrameTimer(0, () => { + fired[fired.length] = "f0@" + tostring(scheduler.GetFrameCount()); + }); + scheduler.AddFrameTimer(1, () => { + fired[fired.length] = "f1@" + tostring(scheduler.GetFrameCount()); + }); + scheduler.AddFrameTimer(3, () => { + fired[fired.length] = "f3@" + tostring(scheduler.GetFrameCount()); + }); + + scheduler.Tick(0.016); + AssertArrayEqual(fired, ["f0@1", "f1@1"]); + + scheduler.Tick(0.016); + AssertArrayEqual(fired, ["f0@1", "f1@1"]); + + scheduler.Tick(0.016); + AssertArrayEqual(fired, ["f0@1", "f1@1", "f3@3"]); + AssertEqual(scheduler.GetStats().totalTasks, 0, "all frame tasks completed"); + scheduler.Dispose(); + }, + }, + { + name: "World pause freezes world timers while monotonic timers continue", + fn: () => { + const scheduler = new FrameScheduler(); + const log: string[] = []; + + scheduler.AddWorldTimer(0.1, () => { + log[log.length] = "world"; + }); + scheduler.AddMonotonicTimer(0.1, () => { + log[log.length] = "mono"; + }); + + // Paused ticks advance monotonic clock only + scheduler.Tick(0.06, 0.06, true); + scheduler.Tick(0.06, 0.06, true); + AssertArrayEqual(log, ["mono"]); + + // Unpaused ticks advance world clock + scheduler.Tick(0.05, 0.05, false); + AssertArrayEqual(log, ["mono"]); + scheduler.Tick(0.06, 0.06, false); + AssertArrayEqual(log, ["mono", "world"]); + AssertEqual(scheduler.GetStats().totalTasks, 0); + scheduler.Dispose(); + }, + }, + { + name: "World invalidation cancels world & frame tasks but preserves monotonic tasks", + fn: () => { + const scheduler = new FrameScheduler(); + const log: string[] = []; + + scheduler.AddFrameTimer(2, () => { + log[log.length] = "frame"; + }); + scheduler.AddWorldTimer(0.05, () => { + log[log.length] = "world"; + }); + scheduler.AddMonotonicTimer(0.05, () => { + log[log.length] = "mono"; + }); + + const nextGen = scheduler.InvalidateWorld(); + AssertEqual(nextGen, 2, "worldGen incremented"); + AssertEqual(scheduler.GetStats().worldTasks, 0, "world tasks cleared"); + AssertEqual(scheduler.GetStats().frameTasks, 0, "frame tasks cleared"); + AssertEqual(scheduler.GetStats().monotonicTasks, 1, "monotonic task survives"); + + scheduler.Tick(0.06); + scheduler.Tick(0.06); + AssertArrayEqual(log, ["mono"]); + AssertEqual(scheduler.GetStats().totalTasks, 0); + scheduler.Dispose(); + }, + }, + { + name: "Disposing ScopedObject owner automatically cancels owned timers", + fn: () => { + const scheduler = new FrameScheduler(); + const owner = new ScopedObject(); + let count = 0; + + scheduler.AddMonotonicRepeatTimer( + 0.05, + () => { + count = count + 1; + }, + owner + ); + + scheduler.Tick(0.06); + AssertEqual(count, 1); + + owner.Dispose(); + scheduler.Tick(0.06); + scheduler.Tick(0.06); + AssertEqual(count, 1, "disposed owner timer must not fire"); + AssertEqual(scheduler.GetStats().totalTasks, 0, "timer cleaned up"); + scheduler.Dispose(); + }, + }, + ], + }; +} diff --git a/Script/ts/src/tests/unit/smoke_test.ts b/Script/ts/src/tests/unit/smoke_test.ts new file mode 100644 index 0000000..aea0c69 --- /dev/null +++ b/Script/ts/src/tests/unit/smoke_test.ts @@ -0,0 +1,32 @@ +/** @noSelfInFile */ + +import { Assert, AssertEqual, type TestSuite } from "../harness/test_runner"; + +export function CreateSmokeSuite(): TestSuite { + return { + name: "Baseline.Smoke", + cases: [ + { + name: "Lua 5.4 and __MODULE__ runtime are loaded", + fn: () => { + Assert(string.match(_VERSION, "Lua 5%.4")[0] !== undefined, "Expected Lua 5.4 runtime"); + Assert(__MODULE__ !== undefined, "Expected __MODULE__ global"); + Assert(type(__MODULE__.Import) === "function", "Expected __MODULE__.Import function"); + Assert(type(__MODULE__.ReimportSafely) === "function", "Expected __MODULE__.ReimportSafely"); + }, + }, + { + name: "table.pack preserves trailing nil count n", + fn: () => { + const packed = table.pack("a", undefined, "c", undefined); + AssertEqual(packed.n, 4, "packed.n"); + const [a, b, c, d] = table.unpack(packed, 1, packed.n); + AssertEqual(a, "a"); + AssertEqual(b, undefined); + AssertEqual(c, "c"); + AssertEqual(d, undefined); + }, + }, + ], + }; +} diff --git a/Script/ts/src/tests/unit/storage_and_setting_test.ts b/Script/ts/src/tests/unit/storage_and_setting_test.ts new file mode 100644 index 0000000..9a22894 --- /dev/null +++ b/Script/ts/src/tests/unit/storage_and_setting_test.ts @@ -0,0 +1,146 @@ +/** @noSelfInFile */ + +import { FrameScheduler } from "../../framework/core/scheduler"; +import * as Json from "../../framework/core/json"; +import { LocalSaveManager, LocalSaveStore } from "../../framework/storage/local_save"; +import { MemoryStorageBackend } from "../../framework/storage/storage_backend"; +import { SettingService } from "../../game/setting/setting_service"; +import { Assert, AssertEqual, type TestSuite } from "../harness/test_runner"; + +export function CreateStorageAndSettingSuite(): TestSuite { + return { + name: "Step2A.StorageAndSetting", + cases: [ + { + name: "JSON encodes/decodes nested objects, arrays, escapes, and 64-bit integers", + fn: () => { + const bigId = tonumber("9007199254740993") as number; // true Lua 5.4 int64 (2^53 + 1) + AssertEqual(math.type(bigId), "integer", "bigId is Lua 5.4 integer"); + const payload = { + version: 1, + roleId: bigId, + enabled: true, + label: 'hello "ue"\nline2', + tags: ["a", "b", "c"], + emptyArr: Json.GetEmptyArray(), + }; + const [encoded, encErr] = Json.Encode(payload); + AssertEqual(encErr, undefined, "encode error"); + Assert(type(encoded) === "string", "encoded is string"); + + const [decoded, decErr] = Json.Decode(encoded as string); + AssertEqual(decErr, undefined, "decode error"); + const obj = decoded as Record; + AssertEqual(obj.version, 1); + AssertEqual(obj.roleId, bigId, "int64 round-trip"); + AssertEqual(obj.enabled, true); + AssertEqual(obj.label, 'hello "ue"\nline2'); + const tags = obj.tags as string[]; + AssertEqual(tags[0], "a"); + AssertEqual(tags[2], "c"); + }, + }, + { + name: "Missing slot returns defaults and coalesces rapid Set calls via 0.1s monotonic clock", + fn: () => { + const scheduler = new FrameScheduler(); + const backend = new MemoryStorageBackend(); + const saveMgr = new LocalSaveManager(backend, scheduler); + const settings = new SettingService(saveMgr, "unit_coalesce"); + + AssertEqual(settings.GetStore().GetLastLoadStatus(), "not_found"); + AssertEqual(settings.GetSoundEnabled(), true, "default true"); + + settings.SetSoundEnabled(false); + settings.SetSoundEnabled(true); + settings.SetSoundEnabled(false); + AssertEqual(backend.writeCount, 0, "debounced before 0.1s"); + + // World pause does NOT stop monotonic save timer + scheduler.Tick(0.05, 0.05, true); + AssertEqual(backend.writeCount, 0); + scheduler.Tick(0.06, 0.06, true); + AssertEqual(backend.writeCount, 1, "coalesced into single write"); + AssertEqual(settings.GetStore().IsDirty(), false); + + // Cold restart read-back + settings.Dispose(); + saveMgr.Dispose(); + + const saveMgr2 = new LocalSaveManager(backend, scheduler); + const settings2 = new SettingService(saveMgr2, "unit_coalesce"); + AssertEqual(settings2.GetStore().GetLastLoadStatus(), "ok"); + AssertEqual(settings2.GetStore().GetLoadedSchemaVersion(), 1); + AssertEqual(settings2.GetSoundEnabled(), false, "cold restart reads saved value"); + + settings2.Dispose(); + saveMgr2.Dispose(); + scheduler.Dispose(); + }, + }, + { + name: "Write failure preserves previous valid data, retains dirty state, and succeeds on retry", + fn: () => { + const scheduler = new FrameScheduler(); + const backend = new MemoryStorageBackend(); + const store = new LocalSaveStore("sdata_retry", backend, scheduler, 1); + + store.Set("k", "v1"); + AssertEqual(store.Flush(), "ok"); + + backend.failNextWrite = true; + store.Set("k", "v2"); + AssertEqual(store.Flush(), "write_failed"); + AssertEqual(store.IsDirty(), true, "dirty remains true after failed write"); + + // Reload on separate reader still sees v1 (atomic preservation) + const reader = new LocalSaveStore("sdata_retry", backend, scheduler, 1); + AssertEqual(reader.Get("k"), "v1", "previous valid value preserved"); + reader.Dispose(); + + // Retry succeeds + AssertEqual(store.Flush(), "ok"); + AssertEqual(store.IsDirty(), false); + + const reader2 = new LocalSaveStore("sdata_retry", backend, scheduler, 1); + AssertEqual(reader2.Get("k"), "v2", "retry wrote v2"); + reader2.Dispose(); + store.Dispose(); + scheduler.Dispose(); + }, + }, + { + name: "Corrupted primary slot preserves .corrupt evidence and recovers from .bak when available", + fn: () => { + const scheduler = new FrameScheduler(); + const backend = new MemoryStorageBackend(); + + // Case 1: no backup -> corrupted, preserves raw evidence, returns defaults + backend.InjectCorruptPrimary("sdata_corrupt_only", "{not-valid-json"); + const store1 = new LocalSaveStore("sdata_corrupt_only", backend, scheduler, 1); + AssertEqual(store1.GetLastLoadStatus(), "corrupted"); + AssertEqual(backend.GetCorruptCopy("sdata_corrupt_only"), "{not-valid-json"); + AssertEqual(store1.GetDefault("x", 42), 42); + store1.Dispose(); + + // Case 2: valid v1 + valid v2 (v1 in .bak), then primary corrupted -> recovers v1 from .bak + const store2 = new LocalSaveStore("sdata_bak_recover", backend, scheduler, 1); + store2.Set("val", "v1"); + store2.Flush(); + store2.Set("val", "v2"); + store2.Flush(); + store2.Dispose(); + + backend.InjectCorruptPrimary("sdata_bak_recover", "CORRUPTED_BYTES"); + const store3 = new LocalSaveStore("sdata_bak_recover", backend, scheduler, 1); + AssertEqual(store3.GetLastLoadStatus(), "ok"); + AssertEqual(store3.WasRecoveredFromBackup(), true); + AssertEqual(store3.Get("val"), "v1", "recovered from backup"); + AssertEqual(backend.GetCorruptCopy("sdata_bak_recover"), "CORRUPTED_BYTES"); + store3.Dispose(); + scheduler.Dispose(); + }, + }, + ], + }; +} diff --git a/Script/ts/src/tests/unit/ui_and_resource_test.ts b/Script/ts/src/tests/unit/ui_and_resource_test.ts new file mode 100644 index 0000000..29638c9 --- /dev/null +++ b/Script/ts/src/tests/unit/ui_and_resource_test.ts @@ -0,0 +1,390 @@ +/** @noSelfInFile */ + +import { GameInstanceContext } from "../../framework/context/game_context"; +import { ASSET_KEYS, BASE_ASSET_PATHS } from "../../framework/resource/asset_catalog"; +import { ResourceService, type IResourceBackend } from "../../framework/resource/resource_service"; +import { LocalSaveManager } from "../../framework/storage/local_save"; +import { MemoryStorageBackend } from "../../framework/storage/storage_backend"; +import { RegisterUIConfig } from "../../framework/ui/ui_config"; +import { UIDelegateBridge, type IButtonDelegateBackend } from "../../framework/ui/ui_delegate_bridge"; +import { UIManager, type IWidgetFactory } from "../../framework/ui/ui_manager"; +import { UIWindow, type IWidgetAdapter } from "../../framework/ui/ui_window"; +import { MiniSettingsWindow } from "../../game/setting/mini_settings_window"; +import { SettingService } from "../../game/setting/setting_service"; +import { Assert, AssertEqual, type TestSuite } from "../harness/test_runner"; + +class MockResourceBackend implements IResourceBackend { + private nextReqId = 0; + private pending: Record = {}; + private refCounts: Record = {}; + public service?: ResourceService; + public loadRequestsCount = 0; + + ResolveAssetPath(keyOrPath: string): string { + return BASE_ASSET_PATHS[keyOrPath] ?? keyOrPath; + } + + DoesAssetExist(keyOrPath: string): boolean { + const resolved = this.ResolveAssetPath(keyOrPath); + return resolved !== "/Game/Missing/BadAsset"; + } + + IsPackagedMode(): boolean { + return false; + } + + RequestLoadObjectAsync(keyOrPath: string, worldGen: number): number { + this.nextReqId = this.nextReqId + 1; + this.loadRequestsCount = this.loadRequestsCount + 1; + this.pending[this.nextReqId] = { keyOrPath, worldGen, isClass: false }; + return this.nextReqId; + } + + RequestLoadClassAsync(keyOrPath: string, worldGen: number): number { + this.nextReqId = this.nextReqId + 1; + this.loadRequestsCount = this.loadRequestsCount + 1; + this.pending[this.nextReqId] = { keyOrPath, worldGen, isClass: true }; + return this.nextReqId; + } + + FlushAll(): void { + const ids: number[] = []; + for (const [id] of pairs(this.pending)) { + ids[ids.length] = id; + } + table.sort(ids); + for (let i = 0; i < ids.length; i++) { + const id = ids[i]; + const req = this.pending[id]; + if (req !== undefined) { + this.pending[id] = undefined; + const resolved = this.ResolveAssetPath(req.keyOrPath); + const exists = this.DoesAssetExist(req.keyOrPath); + if (exists) { + this.refCounts[resolved] = (this.refCounts[resolved] ?? 0) + 1; + this.service?.HandleNativeLoadComplete(id, true, { mockAsset: resolved }, resolved, ""); + } else { + this.service?.HandleNativeLoadComplete(id, false, undefined, resolved, "Asset not found"); + } + } + } + } + + CancelRequest(requestId: number): boolean { + if (this.pending[requestId] === undefined) return false; + this.pending[requestId] = undefined; + return true; + } + + CancelRequestsForWorld(worldGen: number): number { + let count = 0; + for (const [id, req] of pairs(this.pending)) { + if (req !== undefined && req.worldGen === worldGen) { + this.pending[id] = undefined; + count = count + 1; + } + } + return count; + } + + ReleaseAsset(resolvedSoftPath: string): void { + const cur = this.refCounts[resolvedSoftPath] ?? 0; + if (cur <= 1) { + this.refCounts[resolvedSoftPath] = undefined; + } else { + this.refCounts[resolvedSoftPath] = cur - 1; + } + } + + GetResourceStats(): LuaMultiReturn<[number, number, number]> { + let inFlight = 0; + for (const [_, v] of pairs(this.pending)) { + if (v !== undefined) inFlight = inFlight + 1; + } + let retained = 0; + let totalRefs = 0; + for (const [_, refs] of pairs(this.refCounts)) { + if (refs !== undefined && refs > 0) { + retained = retained + 1; + totalRefs = totalRefs + refs; + } + } + return $multi(inFlight, retained, totalRefs); + } +} + +class MockButtonBackend implements IButtonDelegateBackend { + private nextId = 0; + private buttonToIds: Record = {}; + private idToButton: Record = {}; + public bridge?: UIDelegateBridge; + + BindButtonClicked(button: any): number { + this.nextId = this.nextId + 1; + const id = this.nextId; + this.idToButton[id] = button; + let list = this.buttonToIds[button]; + if (list === undefined) { + list = []; + this.buttonToIds[button] = list; + } + list[list.length] = id; + return id; + } + + UnbindButtonClicked(bindingId: number): boolean { + const btn = this.idToButton[bindingId]; + if (btn === undefined) return false; + this.idToButton[bindingId] = undefined; + const list = this.buttonToIds[btn]; + if (list !== undefined) { + for (let i = list.length - 1; i >= 0; i--) { + if (list[i] === bindingId) { + table.remove(list, i + 1); + } + } + } + return true; + } + + Click(button: any): void { + const list = this.buttonToIds[button]; + if (list === undefined) return; + const snapshot: number[] = []; + for (let i = 0; i < list.length; i++) snapshot[i] = list[i]; + for (let i = 0; i < snapshot.length; i++) { + this.bridge?.DispatchButtonClicked(snapshot[i]); + } + } + + GetActiveBindingCount(): number { + let count = 0; + for (const [_, btn] of pairs(this.idToButton)) { + if (btn !== undefined) count = count + 1; + } + return count; + } +} + +interface MockWidgetTree { + valid: boolean; + inViewport: boolean; + visible: boolean; + zOrder: number; + children: Record; +} + +class MockWidgetFactory implements IWidgetFactory { + public createdCount = 0; + + CreateWidget(): MockWidgetTree { + this.createdCount = this.createdCount + 1; + const txtStatus = { + text: "", + SetText(t: string) { + this.text = t; + }, + }; + const txtToggleLabel = { + text: "", + SetText(t: string) { + this.text = t; + }, + }; + const imgIcon = { + texture: undefined as any, + SetBrushFromTexture(tex: any) { + this.texture = tex; + }, + }; + return { + valid: true, + inViewport: false, + visible: false, + zOrder: 0, + children: { + ImgIcon: imgIcon, + TxtStatus: txtStatus, + BtnToggle: { name: "BtnToggle" }, + TxtToggleLabel: txtToggleLabel, + BtnClose: { name: "BtnClose" }, + }, + }; + } +} + +class MockWidgetAdapter implements IWidgetAdapter { + FindChild(widget: MockWidgetTree, name: string): any { + return widget.children[name]; + } + AddToViewport(widget: MockWidgetTree, zOrder: number): void { + widget.inViewport = true; + widget.zOrder = zOrder; + } + RemoveFromParent(widget: MockWidgetTree): void { + widget.inViewport = false; + } + SetVisible(widget: MockWidgetTree, visible: boolean): void { + widget.visible = visible; + } + IsWidgetValid(widget: MockWidgetTree): boolean { + return widget !== undefined && widget.valid; + } +} + +class CachedTestWindow extends UIWindow { + public reuseCount = 0; + public clickCount = 0; + public btn?: any; + + protected override OnBindWidgets(): void { + this.btn = this.RequireWidget("BtnToggle"); + this.BindButtonClick(this.btn, () => { + this.clickCount = this.clickCount + 1; + }); + } + + protected override OnReuseUI(): void { + this.reuseCount = this.reuseCount + 1; + } +} + +RegisterUIConfig(CachedTestWindow, { + name: "CachedTestWindow", + assetKey: ASSET_KEYS.MINI_SETTINGS_WIDGET, + singleton: true, + layer: "normal", + cacheTag: "cache", +}); + +export function CreateUIAndResourceSuite(): TestSuite { + return { + name: "Step2B_3.UIAndResource", + cases: [ + { + name: "MiniSettingsWindow full lifecycle: open, load icon, click once, persist, close, reopen, zero leaks", + fn: () => { + const ctx = new GameInstanceContext(); + const storageBackend = new MemoryStorageBackend(); + const saveMgr = new LocalSaveManager(storageBackend, ctx.scheduler); + const settingSvc = new SettingService(saveMgr, "ui_test"); + const resBackend = new MockResourceBackend(); + const resSvc = new ResourceService(ctx, resBackend); + resBackend.service = resSvc; + const btnBackend = new MockButtonBackend(); + const btnBridge = new UIDelegateBridge(ctx, btnBackend); + btnBackend.bridge = btnBridge; + + ctx.RegisterService("saveManager", saveMgr); + ctx.RegisterService("setting", settingSvc); + ctx.RegisterService("resource", resSvc); + ctx.RegisterService("uiDelegateBridge", btnBridge); + + const widgetFactory = new MockWidgetFactory(); + const lp = ctx.GetOrCreateLocalPlayer(0); + const uiMgr = lp.RegisterService( + "uiManager", + new UIManager(ctx, lp, resSvc, widgetFactory, new MockWidgetAdapter()) + ); + + // Concurrent singleton open creates only 1 widget + const w1 = uiMgr.ShowUI(MiniSettingsWindow); + const w2 = uiMgr.ShowUI(MiniSettingsWindow); + AssertEqual(w1, w2, "concurrent singleton returns same controller"); + + // Flush class load + icon load + resBackend.FlushAll(); + resBackend.FlushAll(); + + AssertEqual(widgetFactory.createdCount, 1, "only 1 widget created"); + Assert(w1 !== undefined && w1.iconLoaded, "icon loaded"); + AssertEqual((w1!.txtStatus as any).text, "Sound: ON"); + AssertEqual(uiMgr.GetDiagnostics().inputMode, "ui"); + + // Click toggle once -> fires strictly once + btnBackend.Click(w1!.btnToggle); + AssertEqual(w1!.toggleClickCount, 1, "toggle click fired once"); + AssertEqual(settingSvc.GetSoundEnabled(), false); + AssertEqual((w1!.txtStatus as any).text, "Sound: OFF"); + + // Flush save via monotonic tick + ctx.Tick(0.12); + AssertEqual(storageBackend.writeCount, 1); + + // Click close button (and test re-entrant Close is ignored) + btnBackend.Click(w1!.btnClose); + w1!.Close(); + + Assert(w1!.IsDisposed(), "window disposed"); + AssertEqual(btnBackend.GetActiveBindingCount(), 0, "button bindings back to 0"); + AssertEqual(uiMgr.GetDiagnostics().openWindows, 0); + AssertEqual(uiMgr.GetDiagnostics().inputMode, "game", "focus restored to game"); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0, "resource refs back to 0"); + + // Reopen reads persisted OFF value + const w3 = uiMgr.ShowUI(MiniSettingsWindow); + resBackend.FlushAll(); + resBackend.FlushAll(); + AssertEqual((w3!.txtStatus as any).text, "Sound: OFF", "reopened window reflects persisted setting"); + + ctx.Dispose(); + AssertEqual(btnBackend.GetActiveBindingCount(), 0); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0); + }, + }, + { + name: "Close while loading cancels request and cached window reuse does not duplicate clicks", + fn: () => { + const ctx = new GameInstanceContext(); + const resBackend = new MockResourceBackend(); + const resSvc = new ResourceService(ctx, resBackend); + resBackend.service = resSvc; + const btnBackend = new MockButtonBackend(); + const btnBridge = new UIDelegateBridge(ctx, btnBackend); + btnBackend.bridge = btnBridge; + ctx.RegisterService("resource", resSvc); + ctx.RegisterService("uiDelegateBridge", btnBridge); + + const widgetFactory = new MockWidgetFactory(); + const lp = ctx.GetOrCreateLocalPlayer(0); + const uiMgr = lp.RegisterService( + "uiManager", + new UIManager(ctx, lp, resSvc, widgetFactory, new MockWidgetAdapter()) + ); + + // 1. Close while still loading + const loadingWin = uiMgr.ShowUI(CachedTestWindow); + loadingWin!.Close(); + resBackend.FlushAll(); + AssertEqual(widgetFactory.createdCount, 0, "cancelled load never creates widget"); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0); + + // 2. Open -> Cache -> Reuse -> Click fires strictly once + const win = uiMgr.ShowUI(CachedTestWindow)!; + resBackend.FlushAll(); + AssertEqual(widgetFactory.createdCount, 1); + btnBackend.Click(win.btn); + AssertEqual(win.clickCount, 1); + + win.Close(); + AssertEqual(uiMgr.GetDiagnostics().cachedWindows, 1, "window moved to cache"); + AssertEqual(btnBackend.GetActiveBindingCount(), 0, "cached window unbound buttons"); + + const reused = uiMgr.ShowUI(CachedTestWindow)!; + AssertEqual(reused, win, "reused cached controller"); + AssertEqual(widgetFactory.createdCount, 1, "no second widget instantiated"); + AssertEqual(reused.reuseCount, 1); + + btnBackend.Click(reused.btn); + AssertEqual(reused.clickCount, 2, "single click after reuse increments by exactly 1"); + + uiMgr.CloseAll(true); + AssertEqual(uiMgr.GetDiagnostics().cachedWindows, 0); + AssertEqual(btnBackend.GetActiveBindingCount(), 0); + AssertEqual(resSvc.GetDiagnostics().nativeTotalRefCount, 0); + ctx.Dispose(); + }, + }, + ], + }; +} diff --git a/Script/ts/types/project.d.ts b/Script/ts/types/project.d.ts index 552b14d..4eda8ab 100644 --- a/Script/ts/types/project.d.ts +++ b/Script/ts/types/project.d.ts @@ -11,12 +11,7 @@ interface LuaPackageTable { loaded: Record; } -declare var GameFramework: Record | undefined; +declare var __UE_TEST_GAME_INSTANCE: UE.ULuaGameInstance | undefined; declare var __UE_TEST_WORLD: UE.UWorld | undefined; declare var __UE_TEST_TICK: ((this: void, deltaSeconds: number) => void) | undefined; - -declare namespace UE { - interface ALuaDemoActor { - GetCubeColor(): FLinearColor; - } -} +declare var __UE_TEST_GC: ((this: void) => void) | undefined; diff --git a/Script/ts/types/ue/Game/UI.d.ts b/Script/ts/types/ue/Game/UI.d.ts new file mode 100644 index 0000000..849db32 --- /dev/null +++ b/Script/ts/types/ue/Game/UI.d.ts @@ -0,0 +1,14 @@ +// Auto-generated by UnLua TypeScript Generator (Generate IntelliSense & TS). +// Do not edit manually. Excludes runtime types owned by unlua.d.ts. + +declare namespace UE { + class WBP_MiniSettings_C extends UUserWidget { + TxtToggleLabel: UTextBlock; + TxtStatus: UTextBlock; + ImgIcon: UImage; + BtnToggle: UButton; + BtnClose: UButton; + static StaticClass(this: void): UClass; + } + +} diff --git a/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts b/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts index 0442d0e..ce364ea 100644 --- a/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts +++ b/Script/ts/types/ue/Script/UnrealLuaDemo.d.ts @@ -4,45 +4,49 @@ declare namespace UE { class ALuaCharacter extends ACharacter { LuaModuleName: string; - GetModuleName(): string; - static StaticClass(this: void): UClass; - } - - class ALuaDemoActor extends AActor { - SceneRoot: USceneComponent; - CubeMesh: UStaticMeshComponent; - StatusText: UTextRenderComponent; - SpinSpeed: number; - BobAmplitude: number; - BobFrequency: number; - LuaModuleName: string; - CubeDynamicMaterial: UMaterialInstanceDynamic; - SetStatusText(InText: string): void; - SetCubeVerticalOffset(ZOffset: number): void; - SetCubeColor(NewColor: FLinearColor): void; - GetStatusTextString(): string; - GetInitialLocation(): FVector; - GetCubeLocalRotation(): FRotator; - AddCubeLocalRotation(DeltaRotation: FRotator): void; - GetModuleName(): string; static StaticClass(this: void): UClass; } class ALuaGameModeBase extends AGameModeBase { LuaModuleName: string; - GetModuleName(): string; static StaticClass(this: void): UClass; } class ALuaPlayerController extends APlayerController { LuaModuleName: string; - OnDemoPingPressed(): void; - OnDemoHotReloadPressed(): void; - DemoVerifyInteraction(): void; - GetModuleName(): string; static StaticClass(this: void): UClass; } + enum ELuaStorageStatus { + Ok = 0, + NotFound = 1, + Corrupted = 2, + WriteFailed = 3, + InvalidArgument = 4, + ELuaStorageStatus_MAX = 5, + } + namespace ELuaStorageStatus { + function GetMaxValue(this: void): number; + function GetNameStringByValue(this: void, value: number): string; + function GetDisplayNameTextByValue(this: void, value: number): string; + } + + interface FLuaStorageReadResult { + Status: ELuaStorageStatus; + PayloadUtf8: string; + ContainerVersion: number; + bRecoveredFromBackup: boolean; + ErrorMessage: string; + } + function FLuaStorageReadResult(this: void): FLuaStorageReadResult; + + interface FMountedPatchContainerInfo { + ContainerPath: string; + MountPoint: string; + Priority: number; + } + function FMountedPatchContainerInfo(this: void): FMountedPatchContainerInfo; + class ULuaBlueprintLibrary extends UBlueprintFunctionLibrary { static TriggerLuaHotReload(this: void): void; static ReloadLuaModule(this: void, ModuleName: string): boolean; @@ -60,9 +64,13 @@ declare namespace UE { static StaticClass(this: void): UClass; } + class ULuaButtonClickProxy extends UObject { + HandleClicked(): void; + static StaticClass(this: void): UClass; + } + class ULuaGameInstance extends UGameInstance { LuaModuleName: string; - GetModuleName(): string; static StaticClass(this: void): UClass; } @@ -77,6 +85,39 @@ declare namespace UE { static StaticClass(this: void): UClass; } + class ULuaResourceSubsystem extends UGameInstanceSubsystem { + UnmountPatchContainer(ContainerPath: string): boolean; + ResolveAssetPath(KeyOrPath: string): string; + RequestLoadObjectAsync(KeyOrPath: string, WorldGen: number): number; + RequestLoadClassAsync(KeyOrPath: string, WorldGen: number): number; + ReleaseAsset(ResolvedSoftPath: string): void; + RegisterBaseAssetKey(LogicalKey: string, SoftPath: string): void; + PurgeCachedAsset(KeyOrPath: string): boolean; + MountPatchContainer(ContainerPath: string, Priority: number | undefined, MountPoint: string): boolean; + LoadObjectSync(KeyOrPath: string): UObject; + LoadClassSync(KeyOrPath: string): TSubclassOf; + static IsPackagedResourceMode(this: void): boolean; + GetResourceStats(OutInFlightCount?: number, OutRetainedAssetCount?: number, OutTotalRefCount?: number): LuaMultiReturn<[number, number, number]>; + GetMountedPatchContainers(): TArray; + static GetHotUpdatePakDir(this: void): string; + static GetFromGameInstance(this: void, GameInstance: UGameInstance | undefined): ULuaResourceSubsystem; + GetAssetRefCount(KeyOrPath: string): number; + DoesAssetExist(KeyOrPath: string): boolean; + ClearPatchManifest(): void; + CancelRequestsForWorld(WorldGen: number): number; + CancelRequest(RequestId: number): boolean; + ApplyPatchManifest(ManifestJson: string): boolean; + static StaticClass(this: void): UClass; + } + + class ULuaSaveGame extends USaveGame { + ContainerVersion: number; + ScopeName: string; + PayloadCRC32: number; + PayloadBytes: TArray; + static StaticClass(this: void): UClass; + } + class ULuaScriptSettings extends UDeveloperSettings { ExternalScriptRelativePath: string; LuaBundleAssetPath: FSoftObjectPath; @@ -87,4 +128,26 @@ declare namespace UE { static StaticClass(this: void): UClass; } + class ULuaStorageLibrary extends UBlueprintFunctionLibrary { + static WriteCorruptRawSlotForTest(this: void, SlotName: string, RawGarbage: string, UserIndex?: number): boolean; + static SaveSlotUtf8(this: void, SlotName: string, PayloadUtf8: string, UserIndex?: number): ELuaStorageStatus; + static LoadSlotUtf8(this: void, SlotName: string, UserIndex?: number): FLuaStorageReadResult; + static GetSaveGamesDir(this: void): string; + static DoesSlotExist(this: void, SlotName: string, UserIndex?: number): boolean; + static DoesCorruptBackupExist(this: void, SlotName: string, UserIndex?: number): boolean; + static DeleteSlot(this: void, SlotName: string, UserIndex?: number, bDeleteBackups?: boolean): boolean; + static StaticClass(this: void): UClass; + } + + class ULuaUIEventSubsystem extends UGameInstanceSubsystem { + ActiveButtonProxies: TMap; + UnbindButtonClicked(BindingId: number): boolean; + static SimulateButtonClick(this: void, Button: UButton | undefined): boolean; + static GetFromGameInstance(this: void, GameInstance: UGameInstance | undefined): ULuaUIEventSubsystem; + GetActiveBindingCount(): number; + static FindChildWidgetByName(this: void, RootWidget: UUserWidget | undefined, WidgetName: string): UWidget; + BindButtonClicked(Button: UButton | undefined): number; + static StaticClass(this: void): UClass; + } + } diff --git a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp index fdd9108..8a94253 100644 --- a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp +++ b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.cpp @@ -101,6 +101,11 @@ namespace bool FLuaCallbackBridge::Call(UObject* Target, const FString& ModuleName, const char* FuncName) { + if (ModuleName.IsEmpty()) + { + return false; + } + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); if (!Env) { @@ -129,6 +134,11 @@ bool FLuaCallbackBridge::Call(UObject* Target, const FString& ModuleName, const bool FLuaCallbackBridge::CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value) { + if (ModuleName.IsEmpty()) + { + return false; + } + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); if (!Env) { @@ -158,6 +168,11 @@ bool FLuaCallbackBridge::CallFloat(UObject* Target, const FString& ModuleName, c bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value) { + if (ModuleName.IsEmpty()) + { + return false; + } + UnLua::FLuaEnv* Env = ResolveLuaEnv(Target); if (!Env) { @@ -184,3 +199,61 @@ bool FLuaCallbackBridge::CallInt(UObject* Target, const FString& ModuleName, con lua_settop(L, Top); return bOk; } + +bool FLuaCallbackBridge::CallResourceLoadCallback( + UObject* GameInstanceTarget, + const FString& ModuleName, + const char* FuncName, + int64 RequestId, + bool bSuccess, + UObject* LoadedObject, + const FString& ResolvedPath, + const FString& ErrorMessage) +{ + if (ModuleName.IsEmpty()) + { + return false; + } + + UnLua::FLuaEnv* Env = ResolveLuaEnv(GameInstanceTarget); + if (!Env) + { + return false; + } + + lua_State* L = Env->GetMainState(); + if (!L) + { + return false; + } + + const int32 Top = lua_gettop(L); + int32 ErrHandlerIdx = 0; + if (!PushModuleFunction(L, ModuleName, FuncName, ErrHandlerIdx)) + { + lua_settop(L, Top); + return false; + } + + UnLua::PushUObject(L, GameInstanceTarget); + lua_pushinteger(L, static_cast(RequestId)); + lua_pushboolean(L, bSuccess ? 1 : 0); + if (LoadedObject) + { + UnLua::PushUObject(L, LoadedObject); + } + else + { + lua_pushnil(L); + } + + const FTCHARToUTF8 PathUtf8(*ResolvedPath); + lua_pushlstring(L, PathUtf8.Get(), PathUtf8.Length()); + + const FTCHARToUTF8 ErrUtf8(*ErrorMessage); + lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length()); + + const bool bOk = (lua_pcall(L, 6, 0, ErrHandlerIdx) == LUA_OK); + lua_settop(L, Top); + return bOk; +} diff --git a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h index 16a66bd..76cae6b 100644 --- a/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h +++ b/Source/UnrealLuaDemo/Core/LuaCallbackBridge.h @@ -10,7 +10,7 @@ class UObject; * 极薄 C++ -> Lua 回调分发器: * 通过 __MODULE__.Import(ModuleName)[FuncName](Target, ...) 直接调用纯 TS/Lua 模块, * 业务脚本无需在 Lua 中继承 UE 对象(不使用 IUnLuaInterface / UnLua.Class), - * 100% 纳入 Lib/Module.lua 与 Lib/Class.lua 的单文件热更闭环。 + * 100% 纳入 lib/module.lua 与 lib/class.lua 的单文件热更闭环。 */ class UNREALLUADEMO_API FLuaCallbackBridge { @@ -18,4 +18,13 @@ public: static bool Call(UObject* Target, const FString& ModuleName, const char* FuncName); static bool CallFloat(UObject* Target, const FString& ModuleName, const char* FuncName, float Value); static bool CallInt(UObject* Target, const FString& ModuleName, const char* FuncName, int32 Value); + static bool CallResourceLoadCallback( + UObject* GameInstanceTarget, + const FString& ModuleName, + const char* FuncName, + int64 RequestId, + bool bSuccess, + UObject* LoadedObject, + const FString& ResolvedPath, + const FString& ErrorMessage); }; diff --git a/Source/UnrealLuaDemo/Core/LuaCharacter.h b/Source/UnrealLuaDemo/Core/LuaCharacter.h index 3a16823..3c114c4 100644 --- a/Source/UnrealLuaDemo/Core/LuaCharacter.h +++ b/Source/UnrealLuaDemo/Core/LuaCharacter.h @@ -7,7 +7,7 @@ #include "LuaCharacter.generated.h" /** - * C++ 薄桥接 Character:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaCharacter。 + * C++ 薄桥接 Character:可选绑定纯 TS/Lua 模块接收 BeginPlay / EndPlay 生命周期回调。 */ UCLASS() class UNREALLUADEMO_API ALuaCharacter : public ACharacter @@ -22,5 +22,5 @@ public: protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") - FString LuaModuleName = TEXT("Game.LuaCharacter"); + FString LuaModuleName; }; diff --git a/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp b/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp index 08508ed..a930144 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp +++ b/Source/UnrealLuaDemo/Core/LuaGameInstance.cpp @@ -3,17 +3,51 @@ #include "Core/LuaGameInstance.h" #include "Core/LuaCallbackBridge.h" #include "UnrealLuaDemo.h" +#include "Engine/World.h" void ULuaGameInstance::Init() { Super::Init(); UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Init() - LuaModule=%s"), *LuaModuleName); FLuaCallbackBridge::Call(this, LuaModuleName, "OnInit"); + + CoreTickHandle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateUObject(this, &ULuaGameInstance::HandleCoreTick), + 0.0f); + + WorldCleanupHandle = FWorldDelegates::OnWorldCleanup.AddUObject( + this, &ULuaGameInstance::HandleWorldCleanup); } void ULuaGameInstance::Shutdown() { + if (CoreTickHandle.IsValid()) + { + FTSTicker::GetCoreTicker().RemoveTicker(CoreTickHandle); + CoreTickHandle.Reset(); + } + + if (WorldCleanupHandle.IsValid()) + { + FWorldDelegates::OnWorldCleanup.Remove(WorldCleanupHandle); + WorldCleanupHandle.Reset(); + } + UE_LOG(LogUnrealLuaDemo, Log, TEXT("ULuaGameInstance::Shutdown()")); FLuaCallbackBridge::Call(this, LuaModuleName, "OnShutdown"); Super::Shutdown(); } + +bool ULuaGameInstance::HandleCoreTick(float DeltaSeconds) +{ + FLuaCallbackBridge::CallFloat(this, LuaModuleName, "OnTick", DeltaSeconds); + return true; +} + +void ULuaGameInstance::HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources) +{ + if (World && World->GetGameInstance() == this) + { + FLuaCallbackBridge::Call(this, LuaModuleName, "OnWorldCleanup"); + } +} diff --git a/Source/UnrealLuaDemo/Core/LuaGameInstance.h b/Source/UnrealLuaDemo/Core/LuaGameInstance.h index f24b7ce..f793fcc 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameInstance.h +++ b/Source/UnrealLuaDemo/Core/LuaGameInstance.h @@ -3,11 +3,15 @@ #pragma once #include "CoreMinimal.h" +#include "Containers/Ticker.h" #include "Engine/GameInstance.h" #include "LuaGameInstance.generated.h" +class UWorld; + /** - * C++ 薄桥接 GameInstance:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameInstance。 + * C++ 薄桥接 GameInstance:通过回调转发生命周期(OnInit / OnTick / OnWorldCleanup / OnShutdown) + * 至纯 TS/Lua 入口模块 `main`。 */ UCLASS() class UNREALLUADEMO_API ULuaGameInstance : public UGameInstance @@ -20,5 +24,12 @@ public: protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") - FString LuaModuleName = TEXT("Game.LuaGameInstance"); + FString LuaModuleName = TEXT("main"); + +private: + bool HandleCoreTick(float DeltaSeconds); + void HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources); + + FTSTicker::FDelegateHandle CoreTickHandle; + FDelegateHandle WorldCleanupHandle; }; diff --git a/Source/UnrealLuaDemo/Core/LuaGameModeBase.h b/Source/UnrealLuaDemo/Core/LuaGameModeBase.h index 17ac4d9..e60e8df 100644 --- a/Source/UnrealLuaDemo/Core/LuaGameModeBase.h +++ b/Source/UnrealLuaDemo/Core/LuaGameModeBase.h @@ -7,7 +7,7 @@ #include "LuaGameModeBase.generated.h" /** - * C++ 薄桥接 GameMode:不实现 IUnLuaInterface,通过回调转发生命周期至纯 TS 模块 Game.LuaGameMode。 + * C++ 薄桥接 GameMode:可选绑定纯 TS/Lua 模块接收 BeginPlay / EndPlay 生命周期回调。 */ UCLASS() class UNREALLUADEMO_API ALuaGameModeBase : public AGameModeBase @@ -22,5 +22,5 @@ public: protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") - FString LuaModuleName = TEXT("Game.LuaGameMode"); + FString LuaModuleName; }; diff --git a/Source/UnrealLuaDemo/Core/LuaJsonLib.cpp b/Source/UnrealLuaDemo/Core/LuaJsonLib.cpp new file mode 100644 index 0000000..b6b788a --- /dev/null +++ b/Source/UnrealLuaDemo/Core/LuaJsonLib.cpp @@ -0,0 +1,458 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "Core/LuaJsonLib.h" +#include "Serialization/JsonReader.h" +#include "Serialization/JsonWriter.h" +#include "Policies/CondensedJsonPrintPolicy.h" +#include "lua.hpp" + +namespace +{ + constexpr int32 MaxJsonDepth = 64; + uint8 GJsonNullSentinel = 0; + uint8 GJsonEmptyArraySentinel = 0; + + using FCondensedWriter = TJsonWriter>; + + bool IsNullSentinel(lua_State* L, int32 Idx) + { + return lua_type(L, Idx) == LUA_TLIGHTUSERDATA && lua_touserdata(L, Idx) == &GJsonNullSentinel; + } + + bool IsEmptyArraySentinel(lua_State* L, int32 Idx) + { + return lua_type(L, Idx) == LUA_TLIGHTUSERDATA && lua_touserdata(L, Idx) == &GJsonEmptyArraySentinel; + } + + bool InspectTableShape(lua_State* L, int32 AbsIdx, bool& OutIsArray, int64& OutArrayLen) + { + int64 Count = 0; + int64 MaxIntKey = 0; + bool bAllPositiveIntKeys = true; + + lua_pushnil(L); + while (lua_next(L, AbsIdx) != 0) + { + ++Count; + if (bAllPositiveIntKeys) + { + if (lua_type(L, -2) == LUA_TNUMBER && lua_isinteger(L, -2)) + { + const lua_Integer K = lua_tointeger(L, -2); + if (K > 0) + { + if (K > MaxIntKey) + { + MaxIntKey = static_cast(K); + } + } + else + { + bAllPositiveIntKeys = false; + } + } + else + { + bAllPositiveIntKeys = false; + } + } + lua_pop(L, 1); + } + + OutIsArray = (Count > 0 && bAllPositiveIntKeys && MaxIntKey == Count); + OutArrayLen = OutIsArray ? Count : 0; + return true; + } + + bool EncodeValue(lua_State* L, int32 Idx, const TSharedRef& Writer, const FString* KeyName, int32 Depth, FString& OutError) + { + if (Depth > MaxJsonDepth) + { + OutError = TEXT("JSON encode exceeded maximum recursion depth (64)."); + return false; + } + + const int32 AbsIdx = lua_absindex(L, Idx); + const int32 ValueType = lua_type(L, AbsIdx); + + if (ValueType == LUA_TNIL || IsNullSentinel(L, AbsIdx)) + { + if (KeyName) { Writer->WriteNull(*KeyName); } + else { Writer->WriteNull(); } + return true; + } + + if (IsEmptyArraySentinel(L, AbsIdx)) + { + if (KeyName) { Writer->WriteArrayStart(*KeyName); } + else { Writer->WriteArrayStart(); } + Writer->WriteArrayEnd(); + return true; + } + + switch (ValueType) + { + case LUA_TBOOLEAN: + { + const bool bVal = lua_toboolean(L, AbsIdx) != 0; + if (KeyName) { Writer->WriteValue(*KeyName, bVal); } + else { Writer->WriteValue(bVal); } + return true; + } + case LUA_TNUMBER: + { + if (lua_isinteger(L, AbsIdx)) + { + const int64 IntVal = static_cast(lua_tointeger(L, AbsIdx)); + if (KeyName) { Writer->WriteValue(*KeyName, IntVal); } + else { Writer->WriteValue(IntVal); } + } + else + { + const double NumVal = static_cast(lua_tonumber(L, AbsIdx)); + if (!FMath::IsFinite(NumVal)) + { + OutError = TEXT("Cannot encode NaN or Infinity to JSON."); + return false; + } + if (KeyName) { Writer->WriteValue(*KeyName, NumVal); } + else { Writer->WriteValue(NumVal); } + } + return true; + } + case LUA_TSTRING: + { + size_t Len = 0; + const char* Str = lua_tolstring(L, AbsIdx, &Len); + const FUTF8ToTCHAR Conv(Str, static_cast(Len)); + const FString ValueStr(Conv.Length(), Conv.Get()); + if (KeyName) { Writer->WriteValue(*KeyName, ValueStr); } + else { Writer->WriteValue(ValueStr); } + return true; + } + case LUA_TTABLE: + { + bool bIsArray = false; + int64 ArrayLen = 0; + InspectTableShape(L, AbsIdx, bIsArray, ArrayLen); + + if (bIsArray) + { + if (KeyName) { Writer->WriteArrayStart(*KeyName); } + else { Writer->WriteArrayStart(); } + + for (int64 i = 1; i <= ArrayLen; ++i) + { + lua_rawgeti(L, AbsIdx, static_cast(i)); + const bool bOk = EncodeValue(L, -1, Writer, nullptr, Depth + 1, OutError); + lua_pop(L, 1); + if (!bOk) + { + return false; + } + } + Writer->WriteArrayEnd(); + return true; + } + else + { + if (KeyName) { Writer->WriteObjectStart(*KeyName); } + else { Writer->WriteObjectStart(); } + + lua_pushnil(L); + while (lua_next(L, AbsIdx) != 0) + { + const int32 KeyType = lua_type(L, -2); + FString ChildKey; + if (KeyType == LUA_TSTRING) + { + size_t KeyLen = 0; + const char* KeyUtf8 = lua_tolstring(L, -2, &KeyLen); + const FUTF8ToTCHAR Conv(KeyUtf8, static_cast(KeyLen)); + ChildKey = FString(Conv.Length(), Conv.Get()); + } + else if (KeyType == LUA_TNUMBER) + { + if (lua_isinteger(L, -2)) + { + ChildKey = FString::Printf(TEXT("%lld"), static_cast(lua_tointeger(L, -2))); + } + else + { + ChildKey = FString::SanitizeFloat(lua_tonumber(L, -2)); + } + } + else + { + lua_pop(L, 2); + OutError = FString::Printf(TEXT("Unsupported JSON object key type: %s"), UTF8_TO_TCHAR(lua_typename(L, KeyType))); + return false; + } + + const bool bOk = EncodeValue(L, -1, Writer, &ChildKey, Depth + 1, OutError); + lua_pop(L, 1); + if (!bOk) + { + lua_pop(L, 1); + return false; + } + } + + Writer->WriteObjectEnd(); + return true; + } + } + default: + OutError = FString::Printf(TEXT("Unsupported Lua type for JSON encode: %s"), UTF8_TO_TCHAR(lua_typename(L, ValueType))); + return false; + } + } + + bool TryParseExactInt64(const FString& NumStr, int64& OutInt) + { + if (NumStr.IsEmpty()) + { + return false; + } + + for (int32 i = 0; i < NumStr.Len(); ++i) + { + const TCHAR Ch = NumStr[i]; + if (Ch == TEXT('.') || Ch == TEXT('e') || Ch == TEXT('E')) + { + return false; + } + } + + int64 Parsed = 0; + if (!LexTryParseString(Parsed, *NumStr)) + { + return false; + } + + // Verify exact round-trip so out-of-range integers fall back cleanly to double + const FString RoundTrip = FString::Printf(TEXT("%lld"), static_cast(Parsed)); + if (RoundTrip != NumStr) + { + return false; + } + + OutInt = Parsed; + return true; + } + + bool DecodeNotation(lua_State* L, const TSharedRef>& Reader, EJsonNotation Notation, bool bKeepNull, int32 Depth, FString& OutError) + { + if (Depth > MaxJsonDepth) + { + OutError = TEXT("JSON decode exceeded maximum recursion depth (64)."); + return false; + } + + switch (Notation) + { + case EJsonNotation::Null: + if (bKeepNull) + { + lua_pushlightuserdata(L, &GJsonNullSentinel); + } + else + { + lua_pushnil(L); + } + return true; + + case EJsonNotation::Boolean: + lua_pushboolean(L, Reader->GetValueAsBoolean() ? 1 : 0); + return true; + + case EJsonNotation::Number: + { + const FString NumStr = Reader->GetValueAsNumberString(); + int64 ExactInt = 0; + if (TryParseExactInt64(NumStr, ExactInt)) + { + lua_pushinteger(L, static_cast(ExactInt)); + } + else + { + lua_pushnumber(L, static_cast(Reader->GetValueAsNumber())); + } + return true; + } + + case EJsonNotation::String: + { + const FString& Val = Reader->GetValueAsString(); + const FTCHARToUTF8 Utf8(*Val, Val.Len()); + lua_pushlstring(L, Utf8.Get(), Utf8.Length()); + return true; + } + + case EJsonNotation::ArrayStart: + { + lua_newtable(L); + lua_Integer Index = 1; + EJsonNotation Next = EJsonNotation::Null; + while (Reader->ReadNext(Next)) + { + if (Next == EJsonNotation::ArrayEnd) + { + return true; + } + if (Next == EJsonNotation::Error) + { + OutError = Reader->GetErrorMessage(); + lua_pop(L, 1); + return false; + } + if (!DecodeNotation(L, Reader, Next, bKeepNull, Depth + 1, OutError)) + { + lua_pop(L, 1); + return false; + } + lua_rawseti(L, -2, Index++); + } + OutError = Reader->GetErrorMessage().IsEmpty() ? TEXT("Unexpected EOF in JSON array.") : Reader->GetErrorMessage(); + lua_pop(L, 1); + return false; + } + + case EJsonNotation::ObjectStart: + { + lua_newtable(L); + EJsonNotation Next = EJsonNotation::Null; + while (Reader->ReadNext(Next)) + { + if (Next == EJsonNotation::ObjectEnd) + { + return true; + } + if (Next == EJsonNotation::Error) + { + OutError = Reader->GetErrorMessage(); + lua_pop(L, 1); + return false; + } + const FString& Key = Reader->GetIdentifier(); + const FTCHARToUTF8 KeyUtf8(*Key, Key.Len()); + lua_pushlstring(L, KeyUtf8.Get(), KeyUtf8.Length()); + + if (!DecodeNotation(L, Reader, Next, bKeepNull, Depth + 1, OutError)) + { + lua_pop(L, 2); // key + table + return false; + } + lua_rawset(L, -3); + } + OutError = Reader->GetErrorMessage().IsEmpty() ? TEXT("Unexpected EOF in JSON object.") : Reader->GetErrorMessage(); + lua_pop(L, 1); + return false; + } + + default: + OutError = Reader->GetErrorMessage().IsEmpty() ? TEXT("Invalid JSON token.") : Reader->GetErrorMessage(); + return false; + } + } + + int LuaJsonEncode(lua_State* L) + { + if (lua_gettop(L) < 1) + { + lua_pushnil(L); + lua_pushliteral(L, "ue_json.encode requires 1 argument"); + return 2; + } + + FString Output; + TSharedRef Writer = TJsonWriterFactory>::Create(&Output); + FString ErrorMsg; + if (!EncodeValue(L, 1, Writer, nullptr, 0, ErrorMsg)) + { + const FTCHARToUTF8 ErrUtf8(*ErrorMsg); + lua_pushnil(L); + lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length()); + return 2; + } + + Writer->Close(); + const FTCHARToUTF8 OutUtf8(*Output, Output.Len()); + lua_pushlstring(L, OutUtf8.Get(), OutUtf8.Length()); + return 1; + } + + int LuaJsonDecode(lua_State* L) + { + size_t Len = 0; + const char* RawUtf8 = luaL_checklstring(L, 1, &Len); + const bool bKeepNull = (lua_gettop(L) >= 2 && lua_toboolean(L, 2) != 0); + + const FUTF8ToTCHAR Conv(RawUtf8, static_cast(Len)); + const FString JsonText(Conv.Length(), Conv.Get()); + + TSharedRef> Reader = TJsonReaderFactory::Create(JsonText); + EJsonNotation First = EJsonNotation::Null; + if (!Reader->ReadNext(First) || First == EJsonNotation::Error) + { + const FString Err = Reader->GetErrorMessage().IsEmpty() ? TEXT("Empty or malformed JSON input.") : Reader->GetErrorMessage(); + const FTCHARToUTF8 ErrUtf8(*Err); + lua_pushnil(L); + lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length()); + return 2; + } + + FString ErrorMsg; + if (!DecodeNotation(L, Reader, First, bKeepNull, 0, ErrorMsg)) + { + const FTCHARToUTF8 ErrUtf8(*ErrorMsg); + lua_pushnil(L); + lua_pushlstring(L, ErrUtf8.Get(), ErrUtf8.Length()); + return 2; + } + + // Ensure no trailing garbage tokens after top-level value + EJsonNotation Trailing = EJsonNotation::Null; + if (Reader->ReadNext(Trailing)) + { + lua_pop(L, 1); + lua_pushnil(L); + lua_pushliteral(L, "Trailing characters after top-level JSON value."); + return 2; + } + + return 1; + } + + int LuaOpenUeJson(lua_State* L) + { + lua_newtable(L); + + lua_pushcfunction(L, &LuaJsonEncode); + lua_setfield(L, -2, "encode"); + + lua_pushcfunction(L, &LuaJsonDecode); + lua_setfield(L, -2, "decode"); + + lua_pushlightuserdata(L, &GJsonNullSentinel); + lua_setfield(L, -2, "null"); + + lua_pushlightuserdata(L, &GJsonEmptyArraySentinel); + lua_setfield(L, -2, "empty_array"); + + return 1; + } +} + +void FLuaJsonLib::Register(lua_State* L) +{ + if (!L) + { + return; + } + + luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); + lua_pushcfunction(L, &LuaOpenUeJson); + lua_setfield(L, -2, "ue_json"); + lua_pop(L, 1); +} diff --git a/Source/UnrealLuaDemo/Core/LuaJsonLib.h b/Source/UnrealLuaDemo/Core/LuaJsonLib.h new file mode 100644 index 0000000..54cc4eb --- /dev/null +++ b/Source/UnrealLuaDemo/Core/LuaJsonLib.h @@ -0,0 +1,17 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" + +struct lua_State; + +/** + * Registers the native UE Json streaming library (`ue_json`) into `package.preload["ue_json"]`. + * Uses UE's built-in TJsonReader/TJsonWriter directly against lua_State* with lossless Lua 5.4 int64 support. + */ +class UNREALLUADEMO_API FLuaJsonLib +{ +public: + static void Register(lua_State* L); +}; diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp b/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp index aabc879..f52c373 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.cpp @@ -2,23 +2,11 @@ #include "Core/LuaPlayerController.h" #include "Core/LuaCallbackBridge.h" -#include "Demo/LuaDemoActor.h" -#include "UnrealLuaDemo.h" -#include "Components/InputComponent.h" -#include "Engine/World.h" -#include "EngineUtils.h" -#include "InputCoreTypes.h" -#include "InputKeyEventArgs.h" -#include "TimerManager.h" void ALuaPlayerController::BeginPlay() { Super::BeginPlay(); - bShowMouseCursor = false; - FInputModeGameOnly InputMode; - SetInputMode(InputMode); - FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay"); } @@ -27,112 +15,3 @@ void ALuaPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason) FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast(EndPlayReason)); Super::EndPlay(EndPlayReason); } - -void ALuaPlayerController::SetupInputComponent() -{ - Super::SetupInputComponent(); - - if (InputComponent) - { - FInputKeyBinding& PingBinding = InputComponent->BindKey(EKeys::SpaceBar, IE_Pressed, this, &ALuaPlayerController::HandlePingKeyPressed); - PingBinding.bConsumeInput = false; - - FInputKeyBinding& ReloadBinding = InputComponent->BindKey(EKeys::R, IE_Pressed, this, &ALuaPlayerController::HandleHotReloadKeyPressed); - ReloadBinding.bConsumeInput = false; - } -} - -void ALuaPlayerController::HandlePingKeyPressed() -{ - UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandlePingKeyPressed() -> dispatching OnDemoPingPressed to Lua")); - FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoPingPressed"); -} - -void ALuaPlayerController::HandleHotReloadKeyPressed() -{ - UE_LOG(LogUnrealLuaDemo, Log, TEXT("ALuaPlayerController::HandleHotReloadKeyPressed() -> dispatching OnDemoHotReloadPressed to Lua")); - FLuaCallbackBridge::Call(this, LuaModuleName, "OnDemoHotReloadPressed"); -} - -void ALuaPlayerController::DemoVerifyInteraction() -{ - UWorld* World = GetWorld(); - if (!World) - { - return; - } - - UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Scheduling simulated SpaceBar and R key presses after world ticks...")); - - FTimerHandle Step1Handle; - World->GetTimerManager().SetTimer(Step1Handle, [WeakSelf = TWeakObjectPtr(this)]() - { - ALuaPlayerController* PC = WeakSelf.Get(); - if (!PC) - { - return; - } - - UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 1: Simulating SpaceBar Pressed/Released")); - PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Pressed, 1.0f)); - PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::SpaceBar, IE_Released, 0.0f)); - }, 0.35f, false); - - FTimerHandle Step2Handle; - World->GetTimerManager().SetTimer(Step2Handle, [WeakSelf = TWeakObjectPtr(this)]() - { - ALuaPlayerController* PC = WeakSelf.Get(); - if (!PC) - { - return; - } - - UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 2: Simulating R Pressed/Released")); - PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Pressed, 1.0f)); - PC->InputKey(FInputKeyEventArgs::CreateSimulated(EKeys::R, IE_Released, 0.0f)); - }, 0.70f, false); - - FTimerHandle Step3Handle; - World->GetTimerManager().SetTimer(Step3Handle, [WeakSelf = TWeakObjectPtr(this)]() - { - ALuaPlayerController* PC = WeakSelf.Get(); - if (!PC || !PC->GetWorld()) - { - return; - } - - ALuaDemoActor* DemoActor = nullptr; - if (TActorIterator It(PC->GetWorld()); It) - { - DemoActor = *It; - } - - if (!DemoActor) - { - UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: ALuaDemoActor not found in world.")); - FPlatformMisc::RequestExitWithStatus(false, 1); - return; - } - - const FString StatusStr = DemoActor->GetStatusTextString(); - const FRotator CubeRot = DemoActor->GetCubeLocalRotation(); - const bool bHasTickRotation = !CubeRot.IsNearlyZero(); - const bool bHasPing = StatusStr.Contains(TEXT("Pings: 1")); - const bool bHasReload = StatusStr.Contains(TEXT("Reloads: 1")); - - UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] Step 3 Result -> CubeRot=%s | StatusText=\n%s"), - *CubeRot.ToString(), *StatusStr); - - if (bHasTickRotation && bHasPing && bHasReload) - { - UE_LOG(LogUnrealLuaDemo, Log, TEXT("[DemoVerify] PASSED: Tick rotation, SpaceBar Ping, and R HotReload all verified!")); - PC->ConsoleCommand(TEXT("Quit")); - } - else - { - UE_LOG(LogUnrealLuaDemo, Error, TEXT("[DemoVerify] FAILED: TickRot=%d Ping=%d Reload=%d"), - bHasTickRotation ? 1 : 0, bHasPing ? 1 : 0, bHasReload ? 1 : 0); - FPlatformMisc::RequestExitWithStatus(false, 1); - } - }, 1.15f, false); -} diff --git a/Source/UnrealLuaDemo/Core/LuaPlayerController.h b/Source/UnrealLuaDemo/Core/LuaPlayerController.h index 1359d2f..9e080e7 100644 --- a/Source/UnrealLuaDemo/Core/LuaPlayerController.h +++ b/Source/UnrealLuaDemo/Core/LuaPlayerController.h @@ -7,8 +7,7 @@ #include "LuaPlayerController.generated.h" /** - * C++ 薄桥接 PlayerController:不实现 IUnLuaInterface,通过 FLuaCallbackBridge - * 将生命周期与按键事件([Space] Ping, [R] HotReload)分发至纯 TS 模块 Game.LuaPlayerController。 + * C++ 薄桥接 PlayerController:可选绑定纯 TS/Lua 模块接收 BeginPlay / EndPlay 生命周期回调。 */ UCLASS() class UNREALLUADEMO_API ALuaPlayerController : public APlayerController @@ -18,17 +17,8 @@ class UNREALLUADEMO_API ALuaPlayerController : public APlayerController public: virtual void BeginPlay() override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; - virtual void SetupInputComponent() override; - - /** Automated self-test command (console: Demo.VerifyInteraction) that simulates Space & R and verifies Tick + Lua state. */ - UFUNCTION(Exec) - void DemoVerifyInteraction(); protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") - FString LuaModuleName = TEXT("Game.LuaPlayerController"); - -private: - void HandlePingKeyPressed(); - void HandleHotReloadKeyPressed(); + FString LuaModuleName = TEXT("game.bootstrap_player"); }; diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp b/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp deleted file mode 100644 index fa73098..0000000 --- a/Source/UnrealLuaDemo/Demo/LuaDemoActor.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright Epic Games, Inc. All Rights Reserved. - -#include "Demo/LuaDemoActor.h" -#include "Core/LuaCallbackBridge.h" -#include "Components/StaticMeshComponent.h" -#include "Components/TextRenderComponent.h" -#include "Engine/StaticMesh.h" -#include "Materials/MaterialInterface.h" -#include "Materials/MaterialInstanceDynamic.h" -#include "UObject/ConstructorHelpers.h" - -ALuaDemoActor::ALuaDemoActor() -{ - PrimaryActorTick.bCanEverTick = true; - - SceneRoot = CreateDefaultSubobject(TEXT("SceneRoot")); - SetRootComponent(SceneRoot); - - CubeMesh = CreateDefaultSubobject(TEXT("CubeMesh")); - CubeMesh->SetupAttachment(SceneRoot); - - static ConstructorHelpers::FObjectFinder CubeMeshAsset(TEXT("/Engine/BasicShapes/Cube.Cube")); - if (CubeMeshAsset.Succeeded()) - { - CubeMesh->SetStaticMesh(CubeMeshAsset.Object); - } - - static ConstructorHelpers::FObjectFinder BasicMatAsset(TEXT("/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial")); - if (BasicMatAsset.Succeeded()) - { - CubeMesh->SetMaterial(0, BasicMatAsset.Object); - } - - StatusText = CreateDefaultSubobject(TEXT("StatusText")); - StatusText->SetupAttachment(SceneRoot); - StatusText->SetRelativeLocation(FVector(0.0f, 0.0f, 120.0f)); - // Face -X toward PlayerStart placed at (-450, 0, 100) - StatusText->SetRelativeRotation(FRotator(0.0f, 180.0f, 0.0f)); - StatusText->SetHorizontalAlignment(EHTA_Center); - StatusText->SetVerticalAlignment(EVRTA_TextCenter); - StatusText->SetWorldSize(26.0f); - StatusText->SetTextRenderColor(FColor(120, 245, 255)); - StatusText->SetText(FText::FromString(TEXT("Waiting for Lua..."))); -} - -void ALuaDemoActor::BeginPlay() -{ - InitialLocation = GetActorLocation(); - - if (CubeMesh) - { - CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0); - } - - Super::BeginPlay(); - - FLuaCallbackBridge::Call(this, LuaModuleName, "OnBeginPlay"); -} - -void ALuaDemoActor::Tick(float DeltaSeconds) -{ - Super::Tick(DeltaSeconds); - - FLuaCallbackBridge::CallFloat(this, LuaModuleName, "OnTick", DeltaSeconds); -} - -void ALuaDemoActor::EndPlay(const EEndPlayReason::Type EndPlayReason) -{ - FLuaCallbackBridge::CallInt(this, LuaModuleName, "OnEndPlay", static_cast(EndPlayReason)); - - Super::EndPlay(EndPlayReason); -} - -void ALuaDemoActor::SetStatusText(const FString& InText) -{ - if (StatusText) - { - StatusText->SetText(FText::FromString(InText)); - } -} - -FString ALuaDemoActor::GetStatusTextString() const -{ - return StatusText ? StatusText->Text.ToString() : FString(); -} - -void ALuaDemoActor::SetCubeColor(FLinearColor NewColor) -{ - CurrentCubeColor = NewColor; - - if (!CubeDynamicMaterial && CubeMesh) - { - CubeDynamicMaterial = CubeMesh->CreateAndSetMaterialInstanceDynamic(0); - } - - if (CubeDynamicMaterial) - { - CubeDynamicMaterial->SetVectorParameterValue(TEXT("Color"), NewColor); - } -} - -void ALuaDemoActor::AddCubeLocalRotation(FRotator DeltaRotation) -{ - if (CubeMesh) - { - CubeMesh->AddLocalRotation(DeltaRotation); - } -} - -FRotator ALuaDemoActor::GetCubeLocalRotation() const -{ - return CubeMesh ? CubeMesh->GetRelativeRotation() : FRotator::ZeroRotator; -} - -void ALuaDemoActor::SetCubeVerticalOffset(float ZOffset) -{ - if (CubeMesh) - { - CubeMesh->SetRelativeLocation(FVector(0.0f, 0.0f, ZOffset)); - } -} diff --git a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h b/Source/UnrealLuaDemo/Demo/LuaDemoActor.h deleted file mode 100644 index 3adbd08..0000000 --- a/Source/UnrealLuaDemo/Demo/LuaDemoActor.h +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright Epic Games, Inc. All Rights Reserved. - -#pragma once - -#include "CoreMinimal.h" -#include "GameFramework/Actor.h" -#include "LuaDemoActor.generated.h" - -class UStaticMeshComponent; -class UTextRenderComponent; -class UMaterialInstanceDynamic; - -/** - * C++ 薄桥接 Demo Actor:不实现 IUnLuaInterface(不在 Lua 侧继承 UE 对象), - * 通过 FLuaCallbackBridge 将 BeginPlay / Tick / EndPlay 回调分发给纯 TS 模块 Game.LuaDemoActor, - * 以便运行时 100% 通过 __MODULE__.ReimportSafely("Game.LuaDemoActor") 单文件热更旋转速度、颜色与逻辑。 - */ -UCLASS(Blueprintable) -class UNREALLUADEMO_API ALuaDemoActor : public AActor -{ - GENERATED_BODY() - -public: - ALuaDemoActor(); - - virtual void BeginPlay() override; - virtual void Tick(float DeltaSeconds) override; - virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; - - /** Updates the floating 3D status text rendered above the cube. */ - UFUNCTION(BlueprintCallable, Category = "LuaDemo") - void SetStatusText(const FString& InText); - - /** Returns the current floating 3D status text string. */ - UFUNCTION(BlueprintPure, Category = "LuaDemo") - FString GetStatusTextString() const; - - /** Updates the dynamic material color of the demo cube. */ - UFUNCTION(BlueprintCallable, Category = "LuaDemo") - void SetCubeColor(FLinearColor NewColor); - - /** Returns the last applied dynamic material color of the demo cube. */ - UFUNCTION(BlueprintPure, Category = "LuaDemo") - FLinearColor GetCubeColor() const { return CurrentCubeColor; } - - /** Returns the world location captured at BeginPlay (used for smooth bobbing). */ - UFUNCTION(BlueprintPure, Category = "LuaDemo") - FVector GetInitialLocation() const { return InitialLocation; } - - /** Rotates only the cube mesh while keeping the floating 3D label readable. */ - UFUNCTION(BlueprintCallable, Category = "LuaDemo") - void AddCubeLocalRotation(FRotator DeltaRotation); - - /** Returns the current relative rotation of the cube mesh. */ - UFUNCTION(BlueprintPure, Category = "LuaDemo") - FRotator GetCubeLocalRotation() const; - - /** Sets the vertical bob offset of the cube mesh relative to the actor root. */ - UFUNCTION(BlueprintCallable, Category = "LuaDemo") - void SetCubeVerticalOffset(float ZOffset); - -public: - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo") - TObjectPtr SceneRoot; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo") - TObjectPtr CubeMesh; - - UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "LuaDemo") - TObjectPtr StatusText; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo") - float SpinSpeed = 60.0f; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo") - float BobAmplitude = 25.0f; - - UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "LuaDemo") - float BobFrequency = 2.0f; - -protected: - UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Lua") - FString LuaModuleName = TEXT("Game.LuaDemoActor"); - -private: - UPROPERTY(Transient) - TObjectPtr CubeDynamicMaterial; - - FLinearColor CurrentCubeColor = FLinearColor::White; - FVector InitialLocation = FVector::ZeroVector; -}; diff --git a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp index bf4c4bf..c8c1ebe 100644 --- a/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp +++ b/Source/UnrealLuaDemo/HotUpdate/LuaHotUpdateSubsystem.cpp @@ -1,14 +1,11 @@ // Copyright Epic Games, Inc. All Rights Reserved. #include "HotUpdate/LuaHotUpdateSubsystem.h" -#include "Demo/LuaDemoActor.h" +#include "Core/LuaJsonLib.h" #include "LuaBundle/LuaBundleAsset.h" #include "LuaBundle/LuaScriptSettings.h" #include "UnrealLuaDemo.h" #include "UnLuaDelegates.h" -#include "Engine/GameInstance.h" -#include "Engine/World.h" -#include "EngineUtils.h" #include "HAL/FileManager.h" #include "Misc/CommandLine.h" #include "Misc/DateTime.h" @@ -118,19 +115,6 @@ bool ULuaHotUpdateSubsystem::PollHotReloadTriggerFile(float DeltaTime) *FDateTime::Now().ToString(), *Line, bOk ? TEXT("true") : TEXT("false")); } - if (UGameInstance* GI = GetGameInstance()) - { - if (UWorld* World = GI->GetWorld()) - { - for (TActorIterator It(World); It; ++It) - { - const FLinearColor C = It->GetCubeColor(); - ResultLog += FString::Printf(TEXT("Actor=%s Color=(%.2f,%.2f,%.2f) Status=%s\n"), - *It->GetName(), C.R, C.G, C.B, *It->GetStatusTextString().Replace(TEXT("\n"), TEXT(" | "))); - } - } - } - const FString ResultPath = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/reload.result")); FFileHelper::SaveStringToFile(ResultLog, *ResultPath, FFileHelper::EEncodingOptions::ForceUTF8WithoutBOM); UE_LOG(LogUnrealLuaDemo, Log, TEXT("[HotReloadTrigger] Processed trigger:\n%s"), *ResultLog); @@ -178,18 +162,20 @@ void ULuaHotUpdateSubsystem::HandleLuaStateCreated(lua_State* L) return; } + FLuaJsonLib::Register(L); + if (UnLua::FLuaEnv* Env = UnLua::FLuaEnv::FindEnv(L)) { const bool bOk = Env->DoString( - TEXT("if not _G.__MODULE__ then require('Lib.Module') end\nif not _G.__TS__DefineClass then require('Lib.Class') end"), + TEXT("if not _G.__MODULE__ then require('lib.module') end\nif not _G.__TS__DefineClass then require('lib.class') end"), TEXT("InitTs2LuaModuleRuntime")); if (!bOk) { - UE_LOG(LogUnrealLuaDemo, Error, TEXT("[ts2lua] Failed to initialize Lib.Module / Lib.Class runtime.")); + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[ts2lua] Failed to initialize lib.module / lib.class runtime.")); } else { - UE_LOG(LogUnrealLuaDemo, Log, TEXT("[ts2lua] Initialized Lib.Module & Lib.Class runtime.")); + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[ts2lua] Initialized lib.module & lib.class runtime.")); } } } @@ -276,11 +262,24 @@ void ULuaHotUpdateSubsystem::ReloadAllLuaModules() return; } + const FString ReloadAllChunk = TEXT( + "if _G.__MODULE__ then\n" + " local mods = {}\n" + " for name in pairs(_G.__MODULE__.AllLoadedModules()) do\n" + " if type(name) == 'string' then mods[#mods + 1] = name end\n" + " end\n" + " table.sort(mods)\n" + " for _, name in ipairs(mods) do\n" + " _G.__MODULE__.ReimportSafely(name)\n" + " end\n" + "end" + ); + for (const TPair& Pair : AllEnvs) { if (UnLua::FLuaEnv* Env = Pair.Value) { - Env->DoString(TEXT("__MODULE__.Import('Framework.HotReload').ReloadAll()"), TEXT("HotReloadAll")); + Env->DoString(ReloadAllChunk, TEXT("HotReloadAll")); } } } @@ -304,7 +303,9 @@ bool ULuaHotUpdateSubsystem::ReloadLuaModule(const FString& ModuleName) EscapedName.ReplaceInline(TEXT("\\"), TEXT("\\\\")); EscapedName.ReplaceInline(TEXT("'"), TEXT("\\'")); - const FString Chunk = FString::Printf(TEXT("__MODULE__.Import('Framework.HotReload').ReloadModule('%s')"), *EscapedName); + const FString Chunk = FString::Printf( + TEXT("if _G.__MODULE__ and _G.__MODULE__.GetModuleByName('%s') ~= nil then assert(_G.__MODULE__.ReimportSafely('%s')) end"), + *EscapedName, *EscapedName); bool bAnySucceeded = false; for (const TPair& Pair : AllEnvs) diff --git a/Source/UnrealLuaDemo/Resource/LuaResourceSubsystem.cpp b/Source/UnrealLuaDemo/Resource/LuaResourceSubsystem.cpp new file mode 100644 index 0000000..d2e4a29 --- /dev/null +++ b/Source/UnrealLuaDemo/Resource/LuaResourceSubsystem.cpp @@ -0,0 +1,756 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "Resource/LuaResourceSubsystem.h" +#include "Core/LuaCallbackBridge.h" +#include "UnrealLuaDemo.h" +#include "AssetRegistry/AssetRegistryModule.h" +#include "Engine/Blueprint.h" +#include "Engine/GameInstance.h" +#include "Engine/World.h" +#include "HAL/FileManager.h" +#include "HAL/PlatformFileManager.h" +#include "IPlatformFilePak.h" +#include "Misc/CommandLine.h" +#include "Misc/PackageName.h" +#include "Misc/Parse.h" +#include "Misc/Paths.h" +#include "Serialization/JsonReader.h" +#include "Serialization/JsonSerializer.h" + +void ULuaResourceSubsystem::Initialize(FSubsystemCollectionBase& Collection) +{ + Super::Initialize(Collection); + bIsDeinitializing = false; + + WorldCleanupHandle = FWorldDelegates::OnWorldCleanup.AddUObject( + this, &ULuaResourceSubsystem::HandleWorldCleanup); + + if (IsPackagedResourceMode()) + { + ScanAndMountExistingPatches(); + } + + UE_LOG(LogUnrealLuaDemo, Log, + TEXT("[LuaResourceSubsystem] Initialized (Mode=%s, PatchDir=%s, MountedPatches=%d)"), + IsPackagedResourceMode() ? TEXT("Packaged/Patch") : TEXT("Editor/PIE"), + *GetHotUpdatePakDir(), + MountedPatches.Num()); +} + +void ULuaResourceSubsystem::Deinitialize() +{ + bIsDeinitializing = true; + + if (WorldCleanupHandle.IsValid()) + { + FWorldDelegates::OnWorldCleanup.Remove(WorldCleanupHandle); + WorldCleanupHandle.Reset(); + } + + for (FTSTicker::FDelegateHandle& Handle : PendingDeferredTickHandles) + { + if (Handle.IsValid()) + { + FTSTicker::GetCoreTicker().RemoveTicker(Handle); + } + } + PendingDeferredTickHandles.Reset(); + + for (TPair& Pair : InFlightByPath) + { + if (Pair.Value.Handle.IsValid()) + { + Pair.Value.Handle->CancelHandle(); + } + } + InFlightByPath.Reset(); + RequestsById.Reset(); + + for (TPair& Pair : RetainedAssets) + { + if (Pair.Value.Handle.IsValid()) + { + Pair.Value.Handle->ReleaseHandle(); + } + } + RetainedAssets.Reset(); + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaResourceSubsystem] Deinitialized.")); + Super::Deinitialize(); +} + +ULuaResourceSubsystem* ULuaResourceSubsystem::GetFromGameInstance(UGameInstance* GameInstance) +{ + return GameInstance ? GameInstance->GetSubsystem() : nullptr; +} + +bool ULuaResourceSubsystem::IsPackagedResourceMode() +{ +#if WITH_EDITOR + return FParse::Param(FCommandLine::Get(), TEXT("UsePatchPaks")); +#else + return true; +#endif +} + +FString ULuaResourceSubsystem::GetHotUpdatePakDir() +{ +#if PLATFORM_IOS || PLATFORM_ANDROID + return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectPersistentDownloadDir(), TEXT("HotUpdate/Paks"))); +#else + return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("HotUpdate/Paks"))); +#endif +} + +void ULuaResourceSubsystem::RegisterBaseAssetKey(const FString& LogicalKey, const FString& SoftPath) +{ + if (!LogicalKey.IsEmpty() && !SoftPath.IsEmpty()) + { + BaseCatalog.Add(LogicalKey, SoftPath); + } +} + +FString ULuaResourceSubsystem::ResolveAssetPath(const FString& KeyOrPath) const +{ + if (const FString* PatchPath = PatchOverlayCatalog.Find(KeyOrPath)) + { + return *PatchPath; + } + if (const FString* BasePath = BaseCatalog.Find(KeyOrPath)) + { + return *BasePath; + } + return KeyOrPath; +} + +FSoftObjectPath ULuaResourceSubsystem::NormalizeSoftPath(const FString& RawPath, bool bIsClassLoad) const +{ + FString Resolved = ResolveAssetPath(RawPath).TrimStartAndEnd(); + if (Resolved.IsEmpty()) + { + return FSoftObjectPath(); + } + + // Support passing bare package path "/Game/UI/WBP_MiniSettings" for class/object loads + if (!Resolved.Contains(TEXT("."))) + { + const FString ShortName = FPackageName::GetShortName(Resolved); + if (!ShortName.IsEmpty()) + { + Resolved = bIsClassLoad + ? FString::Printf(TEXT("%s.%s_C"), *Resolved, *ShortName) + : FString::Printf(TEXT("%s.%s"), *Resolved, *ShortName); + } + } + else if (bIsClassLoad && !Resolved.EndsWith(TEXT("_C")) && !Resolved.StartsWith(TEXT("/Script/"))) + { + Resolved += TEXT("_C"); + } + + return FSoftObjectPath(Resolved); +} + +bool ULuaResourceSubsystem::DoesAssetExist(const FString& KeyOrPath) const +{ + const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, false); + if (!SoftPath.IsValid()) + { + return false; + } + + const FString PackageName = SoftPath.GetLongPackageName(); + if (PackageName.IsEmpty()) + { + return false; + } + + if (PackageName.StartsWith(TEXT("/Script/"))) + { + return FindObject(nullptr, *SoftPath.ToString()) != nullptr; + } + + return FPackageName::DoesPackageExist(PackageName); +} + +int64 ULuaResourceSubsystem::RequestLoadObjectAsync(const FString& KeyOrPath, int32 WorldGen) +{ + return EnqueueAsyncLoad(KeyOrPath, WorldGen, /*bIsClassLoad=*/false); +} + +int64 ULuaResourceSubsystem::RequestLoadClassAsync(const FString& KeyOrPath, int32 WorldGen) +{ + return EnqueueAsyncLoad(KeyOrPath, WorldGen, /*bIsClassLoad=*/true); +} + +int64 ULuaResourceSubsystem::EnqueueAsyncLoad(const FString& KeyOrPath, int32 WorldGen, bool bIsClassLoad) +{ + const int64 RequestId = ++NextRequestId; + if (bIsDeinitializing) + { + return RequestId; + } + + const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, bIsClassLoad); + FRequestRecord Record; + Record.RequestId = RequestId; + Record.SoftPath = SoftPath; + Record.WorldGen = WorldGen; + Record.bIsClassLoad = bIsClassLoad; + Record.bCancelled = false; + RequestsById.Add(RequestId, Record); + + if (!SoftPath.IsValid()) + { + TWeakObjectPtr WeakThis(this); + FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateLambda([WeakThis, RequestId, KeyOrPath](float) + { + if (ULuaResourceSubsystem* Self = WeakThis.Get()) + { + Self->DeliverDeferredResult( + RequestId, + false, + FSoftObjectPath(), + FString::Printf(TEXT("Invalid asset path or logical key: '%s'"), *KeyOrPath)); + } + return false; + }), + 0.0f); + PendingDeferredTickHandles.Add(Handle); + return RequestId; + } + + // 1. Fast-path cache hit if already retained + if (FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath)) + { + if (Existing->Handle.IsValid() && Existing->Handle->HasLoadCompleted()) + { + UObject* CachedObj = ExtractLoadedAsset(Existing->Handle, SoftPath, bIsClassLoad); + if (IsValid(CachedObj)) + { + TWeakObjectPtr WeakThis(this); + FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateLambda([WeakThis, RequestId, SoftPath](float) + { + if (ULuaResourceSubsystem* Self = WeakThis.Get()) + { + Self->DeliverDeferredResult(RequestId, true, SoftPath, FString()); + } + return false; + }), + 0.0f); + PendingDeferredTickHandles.Add(Handle); + return RequestId; + } + } + } + + // 2. Coalesce onto an already in-flight request for the exact same FSoftObjectPath + if (FInFlightEntry* InFlight = InFlightByPath.Find(SoftPath)) + { + InFlight->WaiterIds.Add(RequestId); + return RequestId; + } + + // 3. Cold async load via FStreamableManager (register InFlightByPath before binding delegate to prevent sync-completion races) + FInFlightEntry NewEntry; + NewEntry.bIsClassLoad = bIsClassLoad; + NewEntry.WaiterIds.Add(RequestId); + + TSharedPtr StreamHandle = StreamableManager.RequestAsyncLoad( + SoftPath, + FStreamableDelegate(), + FStreamableManager::AsyncLoadHighPriority, + /*bManageActiveHandle=*/false); + + if (!StreamHandle.IsValid()) + { + TWeakObjectPtr WeakThis(this); + FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateLambda([WeakThis, RequestId, SoftPath](float) + { + if (ULuaResourceSubsystem* Self = WeakThis.Get()) + { + Self->DeliverDeferredResult( + RequestId, + false, + SoftPath, + FString::Printf(TEXT("FStreamableManager failed to start async load for '%s'"), *SoftPath.ToString())); + } + return false; + }), + 0.0f); + PendingDeferredTickHandles.Add(Handle); + return RequestId; + } + + NewEntry.Handle = StreamHandle; + InFlightByPath.Add(SoftPath, MoveTemp(NewEntry)); + + if (StreamHandle->HasLoadCompleted()) + { + TWeakObjectPtr WeakThis(this); + FTSTicker::FDelegateHandle Handle = FTSTicker::GetCoreTicker().AddTicker( + FTickerDelegate::CreateLambda([WeakThis, SoftPath](float) + { + if (ULuaResourceSubsystem* Self = WeakThis.Get()) + { + Self->HandleStreamableLoadComplete(SoftPath); + } + return false; + }), + 0.0f); + PendingDeferredTickHandles.Add(Handle); + } + else + { + StreamHandle->BindCompleteDelegate( + FStreamableDelegate::CreateUObject(this, &ULuaResourceSubsystem::HandleStreamableLoadComplete, SoftPath)); + } + + return RequestId; +} + +UObject* ULuaResourceSubsystem::ExtractLoadedAsset( + const TSharedPtr& Handle, + const FSoftObjectPath& SoftPath, + bool bIsClassLoad) const +{ + UObject* LoadedObj = Handle.IsValid() ? Handle->GetLoadedAsset() : nullptr; + if (!LoadedObj && SoftPath.IsValid()) + { + LoadedObj = SoftPath.ResolveObject(); + } + + if (bIsClassLoad && LoadedObj) + { + if (UClass* AsClass = Cast(LoadedObj)) + { + return AsClass; + } + if (UBlueprint* AsBP = Cast(LoadedObj)) + { + return AsBP->GeneratedClass; + } + return nullptr; + } + + return LoadedObj; +} + +void ULuaResourceSubsystem::HandleStreamableLoadComplete(FSoftObjectPath SoftPath) +{ + if (bIsDeinitializing) + { + return; + } + + FInFlightEntry Entry; + if (!InFlightByPath.RemoveAndCopyValue(SoftPath, Entry)) + { + return; + } + + TArray ActiveWaiters; + for (int64 WaiterId : Entry.WaiterIds) + { + FRequestRecord Record; + if (RequestsById.RemoveAndCopyValue(WaiterId, Record) && !Record.bCancelled) + { + ActiveWaiters.Add(MoveTemp(Record)); + } + } + + if (ActiveWaiters.Num() == 0) + { + if (Entry.Handle.IsValid()) + { + Entry.Handle->ReleaseHandle(); + } + return; + } + + UObject* LoadedObj = ExtractLoadedAsset(Entry.Handle, SoftPath, Entry.bIsClassLoad); + const bool bLoadedOk = IsValid(LoadedObj); + + if (bLoadedOk) + { + FRetainedAssetEntry& Retained = RetainedAssets.FindOrAdd(SoftPath); + if (!Retained.Handle.IsValid()) + { + Retained.Handle = Entry.Handle; + } + else if (Entry.Handle.IsValid() && Entry.Handle != Retained.Handle) + { + Entry.Handle->ReleaseHandle(); + } + Retained.RefCount += ActiveWaiters.Num(); + + const FString ResolvedStr = SoftPath.ToString(); + for (const FRequestRecord& Waiter : ActiveWaiters) + { + NotifyLuaCompletion(Waiter.RequestId, true, LoadedObj, ResolvedStr, FString()); + } + } + else + { + if (Entry.Handle.IsValid()) + { + Entry.Handle->ReleaseHandle(); + } + const FString ResolvedStr = SoftPath.ToString(); + const FString ErrMsg = FString::Printf(TEXT("Failed to load asset '%s'."), *ResolvedStr); + for (const FRequestRecord& Waiter : ActiveWaiters) + { + NotifyLuaCompletion(Waiter.RequestId, false, nullptr, ResolvedStr, ErrMsg); + } + } +} + +void ULuaResourceSubsystem::DeliverDeferredResult(int64 RequestId, bool bSuccess, FSoftObjectPath SoftPath, FString ErrorMessage) +{ + if (bIsDeinitializing) + { + return; + } + + FRequestRecord Record; + if (!RequestsById.RemoveAndCopyValue(RequestId, Record) || Record.bCancelled) + { + return; + } + + if (!bSuccess) + { + NotifyLuaCompletion(RequestId, false, nullptr, SoftPath.ToString(), ErrorMessage); + return; + } + + FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath); + UObject* LoadedObj = Existing ? ExtractLoadedAsset(Existing->Handle, SoftPath, Record.bIsClassLoad) : nullptr; + if (Existing && IsValid(LoadedObj)) + { + Existing->RefCount += 1; + NotifyLuaCompletion(RequestId, true, LoadedObj, SoftPath.ToString(), FString()); + } + else + { + NotifyLuaCompletion( + RequestId, + false, + nullptr, + SoftPath.ToString(), + FString::Printf(TEXT("Cached asset '%s' was no longer valid at delivery time."), *SoftPath.ToString())); + } +} + +void ULuaResourceSubsystem::NotifyLuaCompletion( + int64 RequestId, + bool bSuccess, + UObject* LoadedObj, + const FString& ResolvedPath, + const FString& ErrorMessage) +{ + FLuaCallbackBridge::CallResourceLoadCallback( + GetGameInstance(), + LuaCallbackModule, + "OnNativeLoadComplete", + RequestId, + bSuccess, + LoadedObj, + ResolvedPath, + ErrorMessage); +} + +UObject* ULuaResourceSubsystem::LoadObjectSync(const FString& KeyOrPath) +{ + const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, false); + if (!SoftPath.IsValid()) + { + return nullptr; + } + + if (FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath)) + { + UObject* Cached = ExtractLoadedAsset(Existing->Handle, SoftPath, false); + if (IsValid(Cached)) + { + Existing->RefCount += 1; + return Cached; + } + } + + TSharedPtr Handle = StreamableManager.RequestSyncLoad(SoftPath, /*bManageActiveHandle=*/false); + UObject* Loaded = ExtractLoadedAsset(Handle, SoftPath, false); + if (!IsValid(Loaded)) + { + if (Handle.IsValid()) + { + Handle->ReleaseHandle(); + } + return nullptr; + } + + FRetainedAssetEntry& Retained = RetainedAssets.FindOrAdd(SoftPath); + Retained.Handle = Handle; + Retained.RefCount += 1; + return Loaded; +} + +UClass* ULuaResourceSubsystem::LoadClassSync(const FString& KeyOrPath) +{ + const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, true); + if (!SoftPath.IsValid()) + { + return nullptr; + } + + if (FRetainedAssetEntry* Existing = RetainedAssets.Find(SoftPath)) + { + if (UClass* Cached = Cast(ExtractLoadedAsset(Existing->Handle, SoftPath, true))) + { + Existing->RefCount += 1; + return Cached; + } + } + + TSharedPtr Handle = StreamableManager.RequestSyncLoad(SoftPath, /*bManageActiveHandle=*/false); + UClass* LoadedClass = Cast(ExtractLoadedAsset(Handle, SoftPath, true)); + if (!IsValid(LoadedClass)) + { + if (Handle.IsValid()) + { + Handle->ReleaseHandle(); + } + return nullptr; + } + + FRetainedAssetEntry& Retained = RetainedAssets.FindOrAdd(SoftPath); + Retained.Handle = Handle; + Retained.RefCount += 1; + return LoadedClass; +} + +bool ULuaResourceSubsystem::CancelRequest(int64 RequestId) +{ + FRequestRecord Record; + if (!RequestsById.RemoveAndCopyValue(RequestId, Record)) + { + return false; + } + + Record.bCancelled = true; + + if (FInFlightEntry* InFlight = InFlightByPath.Find(Record.SoftPath)) + { + InFlight->WaiterIds.Remove(RequestId); + if (InFlight->WaiterIds.Num() == 0) + { + if (InFlight->Handle.IsValid()) + { + InFlight->Handle->CancelHandle(); + } + InFlightByPath.Remove(Record.SoftPath); + } + } + + return true; +} + +int32 ULuaResourceSubsystem::CancelRequestsForWorld(int32 WorldGen) +{ + TArray ToCancel; + for (const TPair& Pair : RequestsById) + { + if (Pair.Value.WorldGen == WorldGen) + { + ToCancel.Add(Pair.Key); + } + } + + for (int64 RequestId : ToCancel) + { + CancelRequest(RequestId); + } + + return ToCancel.Num(); +} + +void ULuaResourceSubsystem::ReleaseAsset(const FString& ResolvedSoftPath) +{ + const FSoftObjectPath SoftPath(ResolvedSoftPath); + FRetainedAssetEntry* Retained = RetainedAssets.Find(SoftPath); + if (!Retained) + { + return; + } + + Retained->RefCount -= 1; + if (Retained->RefCount <= 0) + { + if (Retained->Handle.IsValid()) + { + Retained->Handle->ReleaseHandle(); + } + RetainedAssets.Remove(SoftPath); + } +} + +bool ULuaResourceSubsystem::PurgeCachedAsset(const FString& KeyOrPath) +{ + const FSoftObjectPath SoftPath = NormalizeSoftPath(KeyOrPath, false); + if (FRetainedAssetEntry* Retained = RetainedAssets.Find(SoftPath)) + { + if (Retained->RefCount > 0) + { + return false; + } + if (Retained->Handle.IsValid()) + { + Retained->Handle->ReleaseHandle(); + } + RetainedAssets.Remove(SoftPath); + return true; + } + return false; +} + +bool ULuaResourceSubsystem::MountPatchContainer(const FString& ContainerPath, int32 Priority, const FString& MountPoint) +{ + if (ContainerPath.IsEmpty() || !FPaths::FileExists(ContainerPath)) + { + UE_LOG(LogUnrealLuaDemo, Warning, TEXT("[LuaResourceSubsystem] MountPatchContainer: file not found '%s'."), *ContainerPath); + return false; + } + + FPakPlatformFile* PakPlatform = static_cast( + FPlatformFileManager::Get().FindPlatformFile(FPakPlatformFile::GetTypeName())); + if (!PakPlatform) + { + UE_LOG(LogUnrealLuaDemo, Warning, + TEXT("[LuaResourceSubsystem] MountPatchContainer: FPakPlatformFile is inactive in current runtime (Container=%s)."), + *ContainerPath); + return false; + } + + const FString EffectiveMountPoint = MountPoint.IsEmpty() ? FPaths::ProjectContentDir() : MountPoint; + if (!PakPlatform->Mount(*ContainerPath, static_cast(FMath::Max(0, Priority)), *EffectiveMountPoint)) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaResourceSubsystem] Failed to mount patch container '%s'."), *ContainerPath); + return false; + } + + FMountedPatchContainerInfo Info; + Info.ContainerPath = ContainerPath; + Info.MountPoint = EffectiveMountPoint; + Info.Priority = Priority; + MountedPatches.Add(MoveTemp(Info)); + + if (FModuleManager::Get().IsModuleLoaded(TEXT("AssetRegistry"))) + { + IAssetRegistry& AssetRegistry = FModuleManager::LoadModuleChecked(TEXT("AssetRegistry")).Get(); + AssetRegistry.ScanPathsSynchronous({ TEXT("/Game") }, /*bForceRescan=*/false); + } + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaResourceSubsystem] Mounted patch container '%s' (priority=%d)."), *ContainerPath, Priority); + return true; +} + +bool ULuaResourceSubsystem::UnmountPatchContainer(const FString& ContainerPath) +{ + FPakPlatformFile* PakPlatform = static_cast( + FPlatformFileManager::Get().FindPlatformFile(FPakPlatformFile::GetTypeName())); + if (!PakPlatform) + { + return false; + } + + const bool bUnmounted = PakPlatform->Unmount(*ContainerPath); + if (bUnmounted) + { + MountedPatches.RemoveAll([&ContainerPath](const FMountedPatchContainerInfo& Item) + { + return Item.ContainerPath == ContainerPath; + }); + } + return bUnmounted; +} + +bool ULuaResourceSubsystem::ApplyPatchManifest(const FString& ManifestJson) +{ + TSharedPtr RootObj; + TSharedRef> Reader = TJsonReaderFactory::Create(ManifestJson); + if (!FJsonSerializer::Deserialize(Reader, RootObj) || !RootObj.IsValid()) + { + UE_LOG(LogUnrealLuaDemo, Error, TEXT("[LuaResourceSubsystem] ApplyPatchManifest: invalid JSON.")); + return false; + } + + for (const TPair>& Pair : RootObj->Values) + { + FString TargetPath; + if (Pair.Value.IsValid() && Pair.Value->TryGetString(TargetPath) && !TargetPath.IsEmpty()) + { + PatchOverlayCatalog.Add(Pair.Key, TargetPath); + } + } + + UE_LOG(LogUnrealLuaDemo, Log, TEXT("[LuaResourceSubsystem] Applied patch manifest (%d overlay keys)."), PatchOverlayCatalog.Num()); + return true; +} + +void ULuaResourceSubsystem::ClearPatchManifest() +{ + PatchOverlayCatalog.Reset(); +} + +void ULuaResourceSubsystem::GetResourceStats(int32& OutInFlightCount, int32& OutRetainedAssetCount, int32& OutTotalRefCount) const +{ + OutInFlightCount = RequestsById.Num(); + OutRetainedAssetCount = RetainedAssets.Num(); + int32 TotalRefs = 0; + for (const TPair& Pair : RetainedAssets) + { + TotalRefs += Pair.Value.RefCount; + } + OutTotalRefCount = TotalRefs; +} + +int32 ULuaResourceSubsystem::GetAssetRefCount(const FString& KeyOrPath) const +{ + const FSoftObjectPath ObjPath = NormalizeSoftPath(KeyOrPath, false); + if (const FRetainedAssetEntry* Found = RetainedAssets.Find(ObjPath)) + { + return Found->RefCount; + } + const FSoftObjectPath ClassPath = NormalizeSoftPath(KeyOrPath, true); + if (const FRetainedAssetEntry* FoundClass = RetainedAssets.Find(ClassPath)) + { + return FoundClass->RefCount; + } + return 0; +} + +void ULuaResourceSubsystem::ScanAndMountExistingPatches() +{ + const FString PatchDir = GetHotUpdatePakDir(); + if (!FPaths::DirectoryExists(PatchDir)) + { + return; + } + + TArray FoundPaks; + IFileManager::Get().FindFiles(FoundPaks, *FPaths::Combine(PatchDir, TEXT("*.pak")), /*Files=*/true, /*Directories=*/false); + FoundPaks.Sort(); + + int32 Priority = 100; + for (const FString& PakFile : FoundPaks) + { + MountPatchContainer(FPaths::Combine(PatchDir, PakFile), Priority++); + } +} + +void ULuaResourceSubsystem::HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources) +{ + // WorldGen cancellation is coordinated by TS GameInstanceContext::OnWorldCleanup -> CancelRequestsForWorld +} diff --git a/Source/UnrealLuaDemo/Resource/LuaResourceSubsystem.h b/Source/UnrealLuaDemo/Resource/LuaResourceSubsystem.h new file mode 100644 index 0000000..bcc2895 --- /dev/null +++ b/Source/UnrealLuaDemo/Resource/LuaResourceSubsystem.h @@ -0,0 +1,176 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Containers/Ticker.h" +#include "Engine/StreamableManager.h" +#include "Subsystems/GameInstanceSubsystem.h" +#include "UObject/SoftObjectPath.h" +#include "LuaResourceSubsystem.generated.h" + +USTRUCT(BlueprintType) +struct UNREALLUADEMO_API FMountedPatchContainerInfo +{ + GENERATED_BODY() + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Resource") + FString ContainerPath; + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Resource") + FString MountPoint; + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Resource") + int32 Priority = 0; +}; + +/** + * C++ ResourceManager subsystem (per-GameInstance isolated). + * + * - Editor / PIE: directly loads loose assets under Content/ via AssetRegistry + FStreamableManager. + * - Packaged / Release (or -UsePatchPaks): loads from cooked base containers with higher-priority + * hot-update patch container mounting (PersistentDownloadDir/HotUpdate/Paks) and logical key overlay. + * - Coalesces concurrent async requests by FSoftObjectPath, supports per-caller independent cancellation, + * retains loaded UObjects via FStreamableHandle ref-counting, and delivers completions to pure TS via FLuaCallbackBridge. + */ +UCLASS() +class UNREALLUADEMO_API ULuaResourceSubsystem : public UGameInstanceSubsystem +{ + GENERATED_BODY() + +public: + virtual void Initialize(FSubsystemCollectionBase& Collection) override; + virtual void Deinitialize() override; + + /** Direct lookup from UGameInstance (works even during UGameInstance::Init before a UWorld exists). */ + UFUNCTION(BlueprintPure, Category = "Lua|Resource") + static ULuaResourceSubsystem* GetFromGameInstance(UGameInstance* GameInstance); + + /** True in Packaged/Release builds or when -UsePatchPaks is specified on the command line. */ + UFUNCTION(BlueprintPure, Category = "Lua|Resource") + static bool IsPackagedResourceMode(); + + /** Returns the writable directory where future hot-update patch containers (.pak/.utoc) are stored. */ + UFUNCTION(BlueprintPure, Category = "Lua|Resource") + static FString GetHotUpdatePakDir(); + + /** Registers a base logical key -> UE soft object/class path mapping. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + void RegisterBaseAssetKey(const FString& LogicalKey, const FString& SoftPath); + + /** Resolves a logical key (PatchOverlay > BaseCatalog) or passes through a raw /Game/... path. */ + UFUNCTION(BlueprintPure, Category = "Lua|Resource") + FString ResolveAssetPath(const FString& KeyOrPath) const; + + /** Checks whether the resolved asset package exists in Content/ (PIE) or mounted containers (Packaged). */ + UFUNCTION(BlueprintPure, Category = "Lua|Resource") + bool DoesAssetExist(const FString& KeyOrPath) const; + + /** Asynchronous object load (e.g. UTexture2D). Completion invokes TS `OnNativeLoadComplete`. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + int64 RequestLoadObjectAsync(const FString& KeyOrPath, int32 WorldGen); + + /** Asynchronous class load (e.g. Widget Blueprint generated class). Completion invokes TS `OnNativeLoadComplete`. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + int64 RequestLoadClassAsync(const FString& KeyOrPath, int32 WorldGen); + + /** Synchronous object load (also increments retention RefCount when non-null). */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + UObject* LoadObjectSync(const FString& KeyOrPath); + + /** Synchronous class load (also increments retention RefCount when non-null). */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + UClass* LoadClassSync(const FString& KeyOrPath); + + /** Cancels a single caller request without aborting other coalesced callers waiting on the same asset. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + bool CancelRequest(int64 RequestId); + + /** Cancels all in-flight requests belonging to a given WorldGen. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + int32 CancelRequestsForWorld(int32 WorldGen); + + /** Decrements retention RefCount for a resolved soft path; releases FStreamableHandle when count hits 0. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + void ReleaseAsset(const FString& ResolvedSoftPath); + + /** Releases an unused cached handle immediately if RefCount == 0 (for hot-update asset refresh). */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource") + bool PurgeCachedAsset(const FString& KeyOrPath); + + // ------------------------------------------------------------------ + // Hot-Update Patch Container Extension Hooks (for future patch system) + // ------------------------------------------------------------------ + + UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate") + bool MountPatchContainer(const FString& ContainerPath, int32 Priority = 100, const FString& MountPoint = TEXT("")); + + UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate") + bool UnmountPatchContainer(const FString& ContainerPath); + + /** Applies a JSON object `{ "logical_key": "/Game/..." }` into the high-priority PatchOverlayCatalog. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate") + bool ApplyPatchManifest(const FString& ManifestJson); + + UFUNCTION(BlueprintCallable, Category = "Lua|Resource|HotUpdate") + void ClearPatchManifest(); + + UFUNCTION(BlueprintPure, Category = "Lua|Resource|HotUpdate") + TArray GetMountedPatchContainers() const { return MountedPatches; } + + /** Diagnostics for leak verification and profiling. */ + UFUNCTION(BlueprintPure, Category = "Lua|Resource|Debug") + void GetResourceStats(int32& OutInFlightCount, int32& OutRetainedAssetCount, int32& OutTotalRefCount) const; + + UFUNCTION(BlueprintPure, Category = "Lua|Resource|Debug") + int32 GetAssetRefCount(const FString& KeyOrPath) const; + +private: + struct FRetainedAssetEntry + { + TSharedPtr Handle; + int32 RefCount = 0; + }; + + struct FInFlightEntry + { + TSharedPtr Handle; + TArray WaiterIds; + bool bIsClassLoad = false; + }; + + struct FRequestRecord + { + int64 RequestId = 0; + FSoftObjectPath SoftPath; + int32 WorldGen = 0; + bool bIsClassLoad = false; + bool bCancelled = false; + }; + + int64 EnqueueAsyncLoad(const FString& KeyOrPath, int32 WorldGen, bool bIsClassLoad); + void HandleStreamableLoadComplete(FSoftObjectPath SoftPath); + void DeliverDeferredResult(int64 RequestId, bool bSuccess, FSoftObjectPath SoftPath, FString ErrorMessage); + void NotifyLuaCompletion(int64 RequestId, bool bSuccess, UObject* LoadedObj, const FString& ResolvedPath, const FString& ErrorMessage); + UObject* ExtractLoadedAsset(const TSharedPtr& Handle, const FSoftObjectPath& SoftPath, bool bIsClassLoad) const; + FSoftObjectPath NormalizeSoftPath(const FString& RawPath, bool bIsClassLoad) const; + void ScanAndMountExistingPatches(); + void HandleWorldCleanup(UWorld* World, bool bSessionEnded, bool bCleanupResources); + + FStreamableManager StreamableManager; + + TMap BaseCatalog; + TMap PatchOverlayCatalog; + TArray MountedPatches; + + TMap RetainedAssets; + TMap InFlightByPath; + TMap RequestsById; + TArray PendingDeferredTickHandles; + + int64 NextRequestId = 0; + bool bIsDeinitializing = false; + FDelegateHandle WorldCleanupHandle; + + FString LuaCallbackModule = TEXT("framework.resource.resource_service"); +}; diff --git a/Source/UnrealLuaDemo/Storage/LuaSaveGame.cpp b/Source/UnrealLuaDemo/Storage/LuaSaveGame.cpp new file mode 100644 index 0000000..b9caf05 --- /dev/null +++ b/Source/UnrealLuaDemo/Storage/LuaSaveGame.cpp @@ -0,0 +1,3 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "Storage/LuaSaveGame.h" diff --git a/Source/UnrealLuaDemo/Storage/LuaSaveGame.h b/Source/UnrealLuaDemo/Storage/LuaSaveGame.h new file mode 100644 index 0000000..7ace0d9 --- /dev/null +++ b/Source/UnrealLuaDemo/Storage/LuaSaveGame.h @@ -0,0 +1,32 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "GameFramework/SaveGame.h" +#include "LuaSaveGame.generated.h" + +/** + * UE native USaveGame byte container for dynamic Lua/TS key-value storage. + * Keeps C++ schema fixed while allowing arbitrary versioned JSON/binary payloads from TS/Lua. + */ +UCLASS() +class UNREALLUADEMO_API ULuaSaveGame : public USaveGame +{ + GENERATED_BODY() + +public: + static constexpr int32 CurrentContainerVersion = 1; + + UPROPERTY() + int32 ContainerVersion = CurrentContainerVersion; + + UPROPERTY() + FString ScopeName; + + UPROPERTY() + uint32 PayloadCRC32 = 0; + + UPROPERTY() + TArray PayloadBytes; +}; diff --git a/Source/UnrealLuaDemo/Storage/LuaStorageLibrary.cpp b/Source/UnrealLuaDemo/Storage/LuaStorageLibrary.cpp new file mode 100644 index 0000000..aafecad --- /dev/null +++ b/Source/UnrealLuaDemo/Storage/LuaStorageLibrary.cpp @@ -0,0 +1,349 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "Storage/LuaStorageLibrary.h" +#include "UnrealLuaDemo.h" +#include "Misc/Crc.h" +#include "Misc/Paths.h" +#include "PlatformFeatures.h" +#include "SaveGameSystem.h" + +namespace +{ + constexpr uint32 LuaSaveMagic = 0x4C534156u; // 'LSAV' + constexpr uint32 CurrentEnvelopeVersion = 1u; + constexpr int32 EnvelopeHeaderSize = 20; + + struct FLuaSaveEnvelopeHeader + { + uint32 Magic; + uint32 Version; + uint32 PayloadSize; + uint32 PayloadCRC32; + uint32 HeaderCRC32; + }; + static_assert(sizeof(FLuaSaveEnvelopeHeader) == EnvelopeHeaderSize, "Unexpected header size"); + + bool IsValidSlotName(const FString& SlotName) + { + if (SlotName.IsEmpty() || SlotName.Len() > 128) + { + return false; + } + if (SlotName.Contains(TEXT("..")) || SlotName.Contains(TEXT("/")) || SlotName.Contains(TEXT("\\"))) + { + return false; + } + for (int32 i = 0; i < SlotName.Len(); ++i) + { + const TCHAR Ch = SlotName[i]; + const bool bOk = FChar::IsAlnum(Ch) || Ch == TEXT('_') || Ch == TEXT('-') || Ch == TEXT('.'); + if (!bOk) + { + return false; + } + } + return true; + } + + FString MakeBackupSlotName(const FString& SlotName) + { + return SlotName + TEXT(".bak"); + } + + FString MakeCorruptSlotName(const FString& SlotName) + { + return SlotName + TEXT(".corrupt"); + } + + ISaveGameSystem* GetSaveSystem() + { + return IPlatformFeaturesModule::Get().GetSaveGameSystem(); + } + + void EncodeEnvelope(const FString& PayloadUtf8, TArray& OutBytes) + { + const FTCHARToUTF8 Utf8(*PayloadUtf8, PayloadUtf8.Len()); + const int32 PayloadLen = Utf8.Length(); + + FLuaSaveEnvelopeHeader Header{}; + Header.Magic = LuaSaveMagic; + Header.Version = CurrentEnvelopeVersion; + Header.PayloadSize = static_cast(PayloadLen); + Header.PayloadCRC32 = PayloadLen > 0 + ? FCrc::MemCrc32(Utf8.Get(), PayloadLen) + : 0u; + Header.HeaderCRC32 = FCrc::MemCrc32(&Header, sizeof(FLuaSaveEnvelopeHeader) - sizeof(uint32)); + + OutBytes.SetNumUninitialized(EnvelopeHeaderSize + PayloadLen); + FMemory::Memcpy(OutBytes.GetData(), &Header, EnvelopeHeaderSize); + if (PayloadLen > 0) + { + FMemory::Memcpy(OutBytes.GetData() + EnvelopeHeaderSize, Utf8.Get(), PayloadLen); + } + } + + bool DecodeAndVerifyEnvelope( + const TArray& RawBytes, + int32& OutVersion, + FString& OutPayloadUtf8, + FString& OutError) + { + if (RawBytes.Num() < EnvelopeHeaderSize) + { + OutError = FString::Printf(TEXT("Slot too short (%d bytes)."), RawBytes.Num()); + return false; + } + + FLuaSaveEnvelopeHeader Header{}; + FMemory::Memcpy(&Header, RawBytes.GetData(), EnvelopeHeaderSize); + + if (Header.Magic != LuaSaveMagic) + { + OutError = FString::Printf(TEXT("Invalid magic 0x%08X."), Header.Magic); + return false; + } + + const uint32 ExpectedHeaderCrc = FCrc::MemCrc32(&Header, sizeof(FLuaSaveEnvelopeHeader) - sizeof(uint32)); + if (Header.HeaderCRC32 != ExpectedHeaderCrc) + { + OutError = TEXT("Header CRC32 mismatch."); + return false; + } + + if (static_cast(EnvelopeHeaderSize) + static_cast(Header.PayloadSize) != static_cast(RawBytes.Num())) + { + OutError = FString::Printf( + TEXT("Payload length mismatch (header=%u, actual=%d)."), + Header.PayloadSize, RawBytes.Num() - EnvelopeHeaderSize); + return false; + } + + const uint8* PayloadPtr = RawBytes.GetData() + EnvelopeHeaderSize; + const uint32 ComputedPayloadCrc = Header.PayloadSize > 0 + ? FCrc::MemCrc32(PayloadPtr, static_cast(Header.PayloadSize)) + : 0u; + if (ComputedPayloadCrc != Header.PayloadCRC32) + { + OutError = FString::Printf( + TEXT("Payload CRC32 mismatch (expected=%u, actual=%u)."), + Header.PayloadCRC32, ComputedPayloadCrc); + return false; + } + + OutVersion = static_cast(Header.Version); + if (Header.PayloadSize > 0) + { + const FUTF8ToTCHAR Conv(reinterpret_cast(PayloadPtr), static_cast(Header.PayloadSize)); + OutPayloadUtf8 = FString(Conv.Length(), Conv.Get()); + } + else + { + OutPayloadUtf8.Empty(); + } + + return true; + } + + bool TryLoadAndVerifySlot( + ISaveGameSystem* SaveSystem, + const FString& SlotName, + int32 UserIndex, + int32& OutVersion, + FString& OutPayloadUtf8, + TArray& OutRawBytes, + FString& OutError) + { + OutRawBytes.Reset(); + if (!SaveSystem || !SaveSystem->LoadGame(false, *SlotName, UserIndex, OutRawBytes)) + { + OutError = FString::Printf(TEXT("ISaveGameSystem::LoadGame failed for slot '%s'."), *SlotName); + return false; + } + return DecodeAndVerifyEnvelope(OutRawBytes, OutVersion, OutPayloadUtf8, OutError); + } +} + +FLuaStorageReadResult ULuaStorageLibrary::LoadSlotUtf8(const FString& SlotName, int32 UserIndex) +{ + FLuaStorageReadResult Result; + if (!IsValidSlotName(SlotName)) + { + Result.Status = ELuaStorageStatus::InvalidArgument; + Result.ErrorMessage = FString::Printf(TEXT("Invalid SaveGame slot name: '%s'."), *SlotName); + return Result; + } + + ISaveGameSystem* SaveSystem = GetSaveSystem(); + if (!SaveSystem) + { + Result.Status = ELuaStorageStatus::WriteFailed; + Result.ErrorMessage = TEXT("ISaveGameSystem is unavailable."); + return Result; + } + + const bool bPrimaryExists = SaveSystem->DoesSaveGameExist(*SlotName, UserIndex); + const FString BackupSlot = MakeBackupSlotName(SlotName); + const bool bBackupExists = SaveSystem->DoesSaveGameExist(*BackupSlot, UserIndex); + + if (!bPrimaryExists && !bBackupExists) + { + Result.Status = ELuaStorageStatus::NotFound; + return Result; + } + + if (bPrimaryExists) + { + int32 Version = 0; + FString Payload; + TArray RawBytes; + FString Err; + if (TryLoadAndVerifySlot(SaveSystem, SlotName, UserIndex, Version, Payload, RawBytes, Err)) + { + Result.Status = ELuaStorageStatus::Ok; + Result.PayloadUtf8 = MoveTemp(Payload); + Result.ContainerVersion = Version; + Result.bRecoveredFromBackup = false; + return Result; + } + + // Preserve corrupted primary bytes safely before any recovery + const FString CorruptSlot = MakeCorruptSlotName(SlotName); + if (RawBytes.Num() > 0) + { + SaveSystem->SaveGame(false, *CorruptSlot, UserIndex, RawBytes); + } + UE_LOG(LogUnrealLuaDemo, Warning, + TEXT("[LuaStorage] Primary slot '%s' corrupted (%s); preserved copy at '%s'."), + *SlotName, *Err, *CorruptSlot); + Result.ErrorMessage = Err; + } + + if (bBackupExists) + { + int32 BackupVersion = 0; + FString BackupPayload; + TArray BackupRaw; + FString BackupErr; + if (TryLoadAndVerifySlot(SaveSystem, BackupSlot, UserIndex, BackupVersion, BackupPayload, BackupRaw, BackupErr)) + { + UE_LOG(LogUnrealLuaDemo, Warning, + TEXT("[LuaStorage] Recovered slot '%s' from backup '%s'."), + *SlotName, *BackupSlot); + Result.Status = ELuaStorageStatus::Ok; + Result.PayloadUtf8 = MoveTemp(BackupPayload); + Result.ContainerVersion = BackupVersion; + Result.bRecoveredFromBackup = true; + return Result; + } + if (Result.ErrorMessage.IsEmpty()) + { + Result.ErrorMessage = BackupErr; + } + } + + Result.Status = ELuaStorageStatus::Corrupted; + return Result; +} + +ELuaStorageStatus ULuaStorageLibrary::SaveSlotUtf8(const FString& SlotName, const FString& PayloadUtf8, int32 UserIndex) +{ + if (!IsValidSlotName(SlotName)) + { + return ELuaStorageStatus::InvalidArgument; + } + + ISaveGameSystem* SaveSystem = GetSaveSystem(); + if (!SaveSystem) + { + return ELuaStorageStatus::WriteFailed; + } + + // Copy valid existing primary slot to .bak before replacing + if (SaveSystem->DoesSaveGameExist(*SlotName, UserIndex)) + { + int32 ExistingVersion = 0; + FString UnusedPayload; + TArray ExistingRaw; + FString UnusedErr; + if (TryLoadAndVerifySlot(SaveSystem, SlotName, UserIndex, ExistingVersion, UnusedPayload, ExistingRaw, UnusedErr)) + { + SaveSystem->SaveGame(false, *MakeBackupSlotName(SlotName), UserIndex, ExistingRaw); + } + } + + TArray Encoded; + EncodeEnvelope(PayloadUtf8, Encoded); + const bool bSaved = SaveSystem->SaveGame(false, *SlotName, UserIndex, Encoded); + return bSaved ? ELuaStorageStatus::Ok : ELuaStorageStatus::WriteFailed; +} + +bool ULuaStorageLibrary::DeleteSlot(const FString& SlotName, int32 UserIndex, bool bDeleteBackups) +{ + if (!IsValidSlotName(SlotName)) + { + return false; + } + + ISaveGameSystem* SaveSystem = GetSaveSystem(); + if (!SaveSystem) + { + return false; + } + + bool bRemovedAny = false; + if (SaveSystem->DoesSaveGameExist(*SlotName, UserIndex)) + { + bRemovedAny |= SaveSystem->DeleteGame(false, *SlotName, UserIndex); + } + + if (bDeleteBackups) + { + const FString BakSlot = MakeBackupSlotName(SlotName); + if (SaveSystem->DoesSaveGameExist(*BakSlot, UserIndex)) + { + bRemovedAny |= SaveSystem->DeleteGame(false, *BakSlot, UserIndex); + } + const FString CorruptSlot = MakeCorruptSlotName(SlotName); + if (SaveSystem->DoesSaveGameExist(*CorruptSlot, UserIndex)) + { + bRemovedAny |= SaveSystem->DeleteGame(false, *CorruptSlot, UserIndex); + } + } + + return bRemovedAny; +} + +bool ULuaStorageLibrary::DoesSlotExist(const FString& SlotName, int32 UserIndex) +{ + ISaveGameSystem* SaveSystem = GetSaveSystem(); + return SaveSystem && IsValidSlotName(SlotName) && SaveSystem->DoesSaveGameExist(*SlotName, UserIndex); +} + +bool ULuaStorageLibrary::DoesCorruptBackupExist(const FString& SlotName, int32 UserIndex) +{ + ISaveGameSystem* SaveSystem = GetSaveSystem(); + return SaveSystem && IsValidSlotName(SlotName) && SaveSystem->DoesSaveGameExist(*MakeCorruptSlotName(SlotName), UserIndex); +} + +FString ULuaStorageLibrary::GetSaveGamesDir() +{ + return FPaths::ConvertRelativePathToFull(FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("SaveGames"))); +} + +bool ULuaStorageLibrary::WriteCorruptRawSlotForTest(const FString& SlotName, const FString& RawGarbage, int32 UserIndex) +{ + ISaveGameSystem* SaveSystem = GetSaveSystem(); + if (!SaveSystem || !IsValidSlotName(SlotName)) + { + return false; + } + + const FTCHARToUTF8 Utf8(*RawGarbage, RawGarbage.Len()); + TArray Bytes; + Bytes.SetNumUninitialized(Utf8.Length()); + if (Utf8.Length() > 0) + { + FMemory::Memcpy(Bytes.GetData(), Utf8.Get(), Utf8.Length()); + } + return SaveSystem->SaveGame(false, *SlotName, UserIndex, Bytes); +} diff --git a/Source/UnrealLuaDemo/Storage/LuaStorageLibrary.h b/Source/UnrealLuaDemo/Storage/LuaStorageLibrary.h new file mode 100644 index 0000000..20fc048 --- /dev/null +++ b/Source/UnrealLuaDemo/Storage/LuaStorageLibrary.h @@ -0,0 +1,71 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Kismet/BlueprintFunctionLibrary.h" +#include "LuaStorageLibrary.generated.h" + +UENUM(BlueprintType) +enum class ELuaStorageStatus : uint8 +{ + Ok = 0, + NotFound = 1, + Corrupted = 2, + WriteFailed = 3, + InvalidArgument = 4 +}; + +USTRUCT(BlueprintType) +struct UNREALLUADEMO_API FLuaStorageReadResult +{ + GENERATED_BODY() + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage") + ELuaStorageStatus Status = ELuaStorageStatus::NotFound; + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage") + FString PayloadUtf8; + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage") + int32 ContainerVersion = 0; + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage") + bool bRecoveredFromBackup = false; + + UPROPERTY(BlueprintReadOnly, Category = "Lua|Storage") + FString ErrorMessage; +}; + +/** + * UE native local storage bridge backed by ISaveGameSystem / ULuaSaveGame. + * Provides CRC32 integrity checks, dual-slot (.bak) crash safety, and .corrupt preservation. + */ +UCLASS() +class UNREALLUADEMO_API ULuaStorageLibrary : public UBlueprintFunctionLibrary +{ + GENERATED_BODY() + +public: + UFUNCTION(BlueprintCallable, Category = "Lua|Storage") + static FLuaStorageReadResult LoadSlotUtf8(const FString& SlotName, int32 UserIndex = 0); + + UFUNCTION(BlueprintCallable, Category = "Lua|Storage") + static ELuaStorageStatus SaveSlotUtf8(const FString& SlotName, const FString& PayloadUtf8, int32 UserIndex = 0); + + UFUNCTION(BlueprintCallable, Category = "Lua|Storage") + static bool DeleteSlot(const FString& SlotName, int32 UserIndex = 0, bool bDeleteBackups = true); + + UFUNCTION(BlueprintPure, Category = "Lua|Storage") + static bool DoesSlotExist(const FString& SlotName, int32 UserIndex = 0); + + UFUNCTION(BlueprintPure, Category = "Lua|Storage") + static bool DoesCorruptBackupExist(const FString& SlotName, int32 UserIndex = 0); + + UFUNCTION(BlueprintPure, Category = "Lua|Storage") + static FString GetSaveGamesDir(); + + /** Test helper: writes malformed raw bytes directly into a SaveGame slot to verify corruption handling. */ + UFUNCTION(BlueprintCallable, Category = "Lua|Storage|Test") + static bool WriteCorruptRawSlotForTest(const FString& SlotName, const FString& RawGarbage, int32 UserIndex = 0); +}; diff --git a/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp new file mode 100644 index 0000000..fe3db82 --- /dev/null +++ b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.cpp @@ -0,0 +1,113 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "UI/LuaUIEventSubsystem.h" +#include "Core/LuaCallbackBridge.h" +#include "Blueprint/UserWidget.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Button.h" +#include "Engine/GameInstance.h" + +void ULuaButtonClickProxy::Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId) +{ + OwnerSubsystem = InOwner; + BoundButton = InButton; + BindingId = InBindingId; + + if (InButton) + { + InButton->OnClicked.AddDynamic(this, &ULuaButtonClickProxy::HandleClicked); + } +} + +void ULuaButtonClickProxy::Unbind() +{ + if (UButton* Button = BoundButton.Get()) + { + Button->OnClicked.RemoveDynamic(this, &ULuaButtonClickProxy::HandleClicked); + } + BoundButton.Reset(); + OwnerSubsystem.Reset(); +} + +void ULuaButtonClickProxy::HandleClicked() +{ + if (ULuaUIEventSubsystem* Owner = OwnerSubsystem.Get()) + { + Owner->DispatchButtonClicked(BindingId); + } +} + +ULuaUIEventSubsystem* ULuaUIEventSubsystem::GetFromGameInstance(UGameInstance* GameInstance) +{ + return GameInstance ? GameInstance->GetSubsystem() : nullptr; +} + +void ULuaUIEventSubsystem::Deinitialize() +{ + for (TPair>& Pair : ActiveButtonProxies) + { + if (Pair.Value) + { + Pair.Value->Unbind(); + } + } + ActiveButtonProxies.Reset(); + Super::Deinitialize(); +} + +int32 ULuaUIEventSubsystem::BindButtonClicked(UButton* Button) +{ + if (!IsValid(Button)) + { + return 0; + } + + const int32 BindingId = ++NextBindingId; + ULuaButtonClickProxy* Proxy = NewObject(this); + Proxy->Init(this, Button, BindingId); + ActiveButtonProxies.Add(BindingId, Proxy); + return BindingId; +} + +bool ULuaUIEventSubsystem::UnbindButtonClicked(int32 BindingId) +{ + TObjectPtr Proxy; + if (!ActiveButtonProxies.RemoveAndCopyValue(BindingId, Proxy)) + { + return false; + } + + if (Proxy) + { + Proxy->Unbind(); + } + return true; +} + +UWidget* ULuaUIEventSubsystem::FindChildWidgetByName(UUserWidget* RootWidget, const FName& WidgetName) +{ + if (!IsValid(RootWidget) || !RootWidget->WidgetTree) + { + return nullptr; + } + return RootWidget->WidgetTree->FindWidget(WidgetName); +} + +bool ULuaUIEventSubsystem::SimulateButtonClick(UButton* Button) +{ + if (!IsValid(Button)) + { + return false; + } + Button->OnClicked.Broadcast(); + return true; +} + +void ULuaUIEventSubsystem::DispatchButtonClicked(int32 BindingId) +{ + if (!ActiveButtonProxies.Contains(BindingId)) + { + return; + } + FLuaCallbackBridge::CallInt(GetGameInstance(), LuaCallbackModule, "OnNativeButtonClicked", BindingId); +} diff --git a/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h new file mode 100644 index 0000000..47badab --- /dev/null +++ b/Source/UnrealLuaDemo/UI/LuaUIEventSubsystem.h @@ -0,0 +1,73 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Subsystems/GameInstanceSubsystem.h" +#include "LuaUIEventSubsystem.generated.h" + +class UButton; +class UUserWidget; +class ULuaUIEventSubsystem; + +UCLASS() +class UNREALLUADEMO_API ULuaButtonClickProxy : public UObject +{ + GENERATED_BODY() + +public: + void Init(ULuaUIEventSubsystem* InOwner, UButton* InButton, int32 InBindingId); + void Unbind(); + + UFUNCTION() + void HandleClicked(); + +private: + TWeakObjectPtr OwnerSubsystem; + TWeakObjectPtr BoundButton; + int32 BindingId = 0; +}; + +/** + * Per-GameInstance UMG delegate bridge for pure TS UI controllers. + * Routes UButton::OnClicked to TS `framework.ui.ui_delegate_bridge.OnNativeButtonClicked(gi, bindingId)` + * without requiring Lua UObject inheritance (@unlua), preserving 100% single-file hot-reload. + */ +UCLASS() +class UNREALLUADEMO_API ULuaUIEventSubsystem : public UGameInstanceSubsystem +{ + GENERATED_BODY() + +public: + virtual void Deinitialize() override; + + /** Direct lookup from UGameInstance (works even during UGameInstance::Init before a UWorld exists). */ + UFUNCTION(BlueprintPure, Category = "Lua|UI") + static ULuaUIEventSubsystem* GetFromGameInstance(UGameInstance* GameInstance); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + int32 BindButtonClicked(UButton* Button); + + UFUNCTION(BlueprintCallable, Category = "Lua|UI") + bool UnbindButtonClicked(int32 BindingId); + + UFUNCTION(BlueprintPure, Category = "Lua|UI") + int32 GetActiveBindingCount() const { return ActiveButtonProxies.Num(); } + + /** Helper: finds a named UWidget inside a UUserWidget's WidgetTree (validates designer renames cleanly). */ + UFUNCTION(BlueprintPure, Category = "Lua|UI") + static UWidget* FindChildWidgetByName(UUserWidget* RootWidget, const FName& WidgetName); + + /** Simulates a button click for automated UE tests (invokes Button->OnClicked.Broadcast()). */ + UFUNCTION(BlueprintCallable, Category = "Lua|UI|Test") + static bool SimulateButtonClick(UButton* Button); + + void DispatchButtonClicked(int32 BindingId); + +private: + UPROPERTY(Transient) + TMap> ActiveButtonProxies; + + int32 NextBindingId = 0; + FString LuaCallbackModule = TEXT("framework.ui.ui_delegate_bridge"); +}; diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs b/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs index e47ed80..430f172 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.Build.cs @@ -29,7 +29,8 @@ public class UnrealLuaDemo : ModuleRules "SlateCore", "Json", "JsonUtilities", - "HTTP" + "HTTP", + "PakFile" }); } } diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.cpp b/Source/UnrealLuaDemo/UnrealLuaDemo.cpp index 19c1f56..7ea1f37 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.cpp +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.cpp @@ -2,12 +2,7 @@ #include "UnrealLuaDemo.h" #include "HotUpdate/LuaHotUpdateSubsystem.h" -#include "Engine/Engine.h" -#include "Engine/World.h" #include "HAL/IConsoleManager.h" -#include "UnLua.h" -#include "LuaEnv.h" -#include "lua.hpp" DEFINE_LOG_CATEGORY(LogUnrealLuaDemo); @@ -39,51 +34,12 @@ void FUnrealLuaDemoModule::StartupModule() }), ECVF_Default); - RunTestsCmd = IConsoleManager::Get().RegisterConsoleCommand( - TEXT("Lua.RunTests"), - TEXT("Run compiled TypeScript -> UnLua runtime test suite in the current active game/PIE UWorld."), - FConsoleCommandWithWorldDelegate::CreateLambda([](UWorld* World) - { - TMap& AllEnvs = UnLua::FLuaEnv::GetAll(); - if (AllEnvs.Num() == 0) - { - UE_LOG(LogUnrealLuaDemo, Warning, TEXT("Lua.RunTests: No active UnLua environment (start PIE first).")); - return; - } - for (const TPair& Pair : AllEnvs) - { - if (UnLua::FLuaEnv* Env = Pair.Value) - { - lua_State* L = Env->GetMainState(); - if (L && World) - { - UnLua::PushUObject(L, World); - lua_setglobal(L, "__UE_TEST_WORLD"); - } - Env->DoString(TEXT("__MODULE__.Import('Tests.UE.UERuntimeSuite').RunAllInUE(_G.__UE_TEST_WORLD)"), TEXT("Lua.RunTests")); - if (L) - { - lua_pushnil(L); - lua_setglobal(L, "__UE_TEST_WORLD"); - } - break; - } - } - }), - ECVF_Default); - UE_LOG(LogUnrealLuaDemo, Log, TEXT("UnrealLuaDemo module started. Hot-update script dir: %s"), *ULuaHotUpdateSubsystem::GetHotUpdateScriptDir()); } void FUnrealLuaDemoModule::ShutdownModule() { - if (RunTestsCmd) - { - IConsoleManager::Get().UnregisterConsoleObject(RunTestsCmd); - RunTestsCmd = nullptr; - } - if (HotReloadCmd) { IConsoleManager::Get().UnregisterConsoleObject(HotReloadCmd); diff --git a/Source/UnrealLuaDemo/UnrealLuaDemo.h b/Source/UnrealLuaDemo/UnrealLuaDemo.h index ef4b3e6..391d6f2 100644 --- a/Source/UnrealLuaDemo/UnrealLuaDemo.h +++ b/Source/UnrealLuaDemo/UnrealLuaDemo.h @@ -16,5 +16,4 @@ public: private: IConsoleObject* HotReloadCmd = nullptr; IConsoleObject* ReloadModuleCmd = nullptr; - IConsoleObject* RunTestsCmd = nullptr; }; diff --git a/Source/UnrealLuaDemoEditor/RunLuaFrameworkTestsCommandlet.cpp b/Source/UnrealLuaDemoEditor/RunLuaFrameworkTestsCommandlet.cpp new file mode 100644 index 0000000..2af7d23 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/RunLuaFrameworkTestsCommandlet.cpp @@ -0,0 +1,223 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "RunLuaFrameworkTestsCommandlet.h" +#include "UnrealLuaDemoEditor.h" +#include "Core/LuaGameInstance.h" +#include "Async/TaskGraphInterfaces.h" +#include "Containers/Ticker.h" +#include "Engine/Engine.h" +#include "Engine/World.h" +#include "GameFramework/WorldSettings.h" +#include "Tickable.h" +#include "UObject/UObjectGlobals.h" +#include "UnLua.h" +#include "UnLuaModule.h" +#include "LuaEnv.h" +#include "lua.hpp" + +namespace +{ + UWorld* GFrameworkTestWorld = nullptr; + + int LuaFrameworkTestTick(lua_State* L) + { + const float DeltaSeconds = lua_gettop(L) >= 1 ? static_cast(luaL_checknumber(L, 1)) : 0.016f; + ++GFrameCounter; + if (IsAsyncLoading()) + { + FPlatformProcess::Sleep(0.005f); + } + FTaskGraphInterface::Get().ProcessThreadUntilIdle(ENamedThreads::GameThread); + ProcessAsyncLoading(false, false, 0.0f); + FTSTicker::GetCoreTicker().Tick(DeltaSeconds); + FTickableGameObject::TickObjects(nullptr, LEVELTICK_All, false, DeltaSeconds); + if (GFrameworkTestWorld && IsValid(GFrameworkTestWorld)) + { + GFrameworkTestWorld->Tick(LEVELTICK_All, DeltaSeconds); + } + return 0; + } + + int LuaFrameworkTestCollectGarbage(lua_State* L) + { + lua_gc(L, LUA_GCCOLLECT, 0); + CollectGarbage(GARBAGE_COLLECTION_KEEPFLAGS, true); + return 0; + } +} + +URunLuaFrameworkTestsCommandlet::URunLuaFrameworkTestsCommandlet() +{ + IsClient = true; + IsEditor = true; + IsServer = false; + LogToConsole = true; + ShowErrorCount = true; +} + +int32 URunLuaFrameworkTestsCommandlet::Main(const FString& Params) +{ + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[RunLuaFrameworkTests] Starting UE 5.8 + UnLua framework test runner...")); + + IUnLuaModule& UnLuaModule = IUnLuaModule::Get(); + const bool bWasActive = UnLuaModule.IsActive(); + if (!bWasActive) + { + UnLuaModule.SetActive(true); + } + + UWorld* TestWorld = UWorld::CreateWorld(EWorldType::Game, false, TEXT("LuaFrameworkTestWorld")); + if (!TestWorld) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaFrameworkTests] Failed to create UWorld.")); + if (!bWasActive) + { + UnLuaModule.SetActive(false); + } + return 1; + } + + ULuaGameInstance* TestGameInstance = NewObject(GEngine); + TestGameInstance->AddToRoot(); + + FWorldContext& WorldContext = GEngine->CreateNewWorldContext(EWorldType::Game); + WorldContext.OwningGameInstance = TestGameInstance; + WorldContext.SetCurrentWorld(TestWorld); + TestWorld->SetGameInstance(TestGameInstance); + + TestGameInstance->Init(); + + TestWorld->InitializeActorsForPlay(FURL()); + if (AWorldSettings* WorldSettings = TestWorld->GetWorldSettings()) + { + WorldSettings->NotifyBeginPlay(); + WorldSettings->NotifyMatchStarted(); + } + TestWorld->BeginPlay(); + + GFrameworkTestWorld = TestWorld; + + int32 ExitCode = 1; + UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(TestGameInstance); + if (!Env) + { + Env = UnLuaModule.GetEnv(TestWorld); + } + if (!Env) + { + TMap& AllEnvs = UnLua::FLuaEnv::GetAll(); + for (const TPair& Pair : AllEnvs) + { + if (Pair.Value) + { + Env = Pair.Value; + break; + } + } + } + + if (!Env) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaFrameworkTests] Failed to obtain UnLua FLuaEnv.")); + } + else if (lua_State* L = Env->GetMainState()) + { + UnLua::PushUObject(L, TestGameInstance); + lua_setglobal(L, "__UE_TEST_GAME_INSTANCE"); + + UnLua::PushUObject(L, TestWorld); + lua_setglobal(L, "__UE_TEST_WORLD"); + + lua_pushcfunction(L, &LuaFrameworkTestTick); + lua_setglobal(L, "__UE_TEST_TICK"); + + lua_pushcfunction(L, &LuaFrameworkTestCollectGarbage); + lua_setglobal(L, "__UE_TEST_GC"); + + const FString RunChunk = TEXT( + "local suite = __MODULE__.Import('tests.ue.run_ue_tests')\n" + "local runner = __MODULE__.Import('tests.harness.test_runner')\n" + "local summary = suite.RunAllUETests(_G.__UE_TEST_GAME_INSTANCE, _G.__UE_TEST_WORLD)\n" + "_G.__UE_TEST_TOTAL = summary.total or 0\n" + "_G.__UE_TEST_PASSED = summary.passed or 0\n" + "_G.__UE_TEST_FAILED = summary.failed or 0\n" + "_G.__UE_TEST_REPORT = runner.FormatReport(summary)\n" + ); + + const bool bExecOk = Env->DoString(RunChunk, TEXT("RunLuaFrameworkTestsCommandlet")); + + lua_getglobal(L, "__UE_TEST_REPORT"); + const char* ReportUtf8 = lua_tostring(L, -1); + const FString ReportText = ReportUtf8 ? UTF8_TO_TCHAR(ReportUtf8) : FString(); + lua_pop(L, 1); + + if (!ReportText.IsEmpty()) + { + TArray Lines; + ReportText.ParseIntoArrayLines(Lines, false); + for (const FString& Line : Lines) + { + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("%s"), *Line); + } + } + + lua_getglobal(L, "__UE_TEST_TOTAL"); + const int32 Total = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + + lua_getglobal(L, "__UE_TEST_PASSED"); + const int32 Passed = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + + lua_getglobal(L, "__UE_TEST_FAILED"); + const int32 Failed = static_cast(lua_tointeger(L, -1)); + lua_pop(L, 1); + + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_GAME_INSTANCE"); + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_WORLD"); + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_TICK"); + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_GC"); + lua_pushnil(L); + lua_setglobal(L, "__UE_TEST_REPORT"); + + if (!bExecOk) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaFrameworkTests] Lua execution error in tests.ue.run_ue_tests.")); + ExitCode = 1; + } + else if (Total <= 0 || Failed > 0) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, + TEXT("[RunLuaFrameworkTests] FAILED (Total=%d, Passed=%d, Failed=%d)."), + Total, Passed, Failed); + ExitCode = 1; + } + else + { + UE_LOG(LogUnrealLuaDemoEditor, Display, + TEXT("[RunLuaFrameworkTests] PASSED (Total=%d, Passed=%d, Failed=%d)."), + Total, Passed, Failed); + ExitCode = 0; + } + } + + GFrameworkTestWorld = nullptr; + + TestWorld->EndPlay(EEndPlayReason::Quit); + TestGameInstance->Shutdown(); + TestGameInstance->RemoveFromRoot(); + + GEngine->DestroyWorldContext(TestWorld); + TestWorld->DestroyWorld(false); + + if (!bWasActive) + { + UnLuaModule.SetActive(false); + } + + return ExitCode; +} diff --git a/Source/UnrealLuaDemoEditor/RunLuaFrameworkTestsCommandlet.h b/Source/UnrealLuaDemoEditor/RunLuaFrameworkTestsCommandlet.h new file mode 100644 index 0000000..5648671 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/RunLuaFrameworkTestsCommandlet.h @@ -0,0 +1,26 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Commandlets/Commandlet.h" +#include "RunLuaFrameworkTestsCommandlet.generated.h" + +/** + * Headless UE 5.8 + UnLua framework test runner commandlet. + * Boots a real ULuaGameInstance + UWorld + UnLua FLuaEnv and executes `tests.ue.run_ue_tests`. + * + * Usage: + * UnrealEditor-Cmd -run=RunLuaFrameworkTests -unattended -nop4 -nosplash -NullRHI + * (Optional: pass -UseLuaBundle to run tests directly from /Game/Generated/DA_LuaBundle) + */ +UCLASS() +class UNREALLUADEMOEDITOR_API URunLuaFrameworkTestsCommandlet : public UCommandlet +{ + GENERATED_BODY() + +public: + URunLuaFrameworkTestsCommandlet(); + + virtual int32 Main(const FString& Params) override; +}; diff --git a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp deleted file mode 100644 index 9333999..0000000 --- a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright Epic Games, Inc. All Rights Reserved. - -#include "RunLuaTestsCommandlet.h" -#include "UnrealLuaDemoEditor.h" -#include "Engine/Engine.h" -#include "Engine/World.h" -#include "GameFramework/WorldSettings.h" -#include "UnLua.h" -#include "UnLuaModule.h" -#include "LuaEnv.h" -#include "lua.hpp" - -namespace -{ - UWorld* GCurrentLuaTestWorld = nullptr; - - int LuaTestWorldTick(lua_State* L) - { - const float DeltaSeconds = lua_gettop(L) >= 1 ? static_cast(luaL_checknumber(L, 1)) : 0.016f; - if (GCurrentLuaTestWorld && IsValid(GCurrentLuaTestWorld)) - { - // Advance GFrameCounter so FTimerManager::HasBeenTickedThisFrame() treats each call as a new engine frame. - ++GFrameCounter; - GCurrentLuaTestWorld->Tick(LEVELTICK_All, DeltaSeconds); - } - return 0; - } -} - -URunLuaTestsCommandlet::URunLuaTestsCommandlet() -{ - IsClient = true; - IsEditor = true; - IsServer = false; - LogToConsole = true; - ShowErrorCount = true; -} - -int32 URunLuaTestsCommandlet::Main(const FString& Params) -{ - UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[RunLuaTestsCommandlet] Starting real UE + UnLua test runner...")); - - IUnLuaModule& UnLuaModule = IUnLuaModule::Get(); - const bool bWasActive = UnLuaModule.IsActive(); - if (!bWasActive) - { - UnLuaModule.SetActive(true); - } - - UWorld* TestWorld = UWorld::CreateWorld(EWorldType::Game, false, TEXT("LuaTestWorld")); - if (!TestWorld) - { - UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Failed to create UWorld.")); - if (!bWasActive) - { - UnLuaModule.SetActive(false); - } - return 1; - } - - FWorldContext& WorldContext = GEngine->CreateNewWorldContext(EWorldType::Game); - WorldContext.SetCurrentWorld(TestWorld); - - TestWorld->InitializeActorsForPlay(FURL()); - if (AWorldSettings* WorldSettings = TestWorld->GetWorldSettings()) - { - WorldSettings->NotifyBeginPlay(); - WorldSettings->NotifyMatchStarted(); - } - TestWorld->BeginPlay(); - - GCurrentLuaTestWorld = TestWorld; - - int32 ExitCode = 1; - UnLua::FLuaEnv* Env = UnLuaModule.GetEnv(TestWorld); - if (!Env) - { - UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Failed to obtain UnLua FLuaEnv.")); - } - else - { - lua_State* L = Env->GetMainState(); - if (L) - { - UnLua::PushUObject(L, TestWorld); - lua_setglobal(L, "__UE_TEST_WORLD"); - - lua_pushcfunction(L, &LuaTestWorldTick); - lua_setglobal(L, "__UE_TEST_TICK"); - - const FString RunChunk = TEXT( - "local suite = __MODULE__.Import('Tests.UE.UERuntimeSuite')\n" - "local runner = __MODULE__.Import('Tests.Harness.TestRunner')\n" - "local summary = suite.RunAllInUE(_G.__UE_TEST_WORLD)\n" - "_G.__UE_TEST_TOTAL = summary.total or 0\n" - "_G.__UE_TEST_PASSED = summary.passed or 0\n" - "_G.__UE_TEST_FAILED = summary.failed or 0\n" - "_G.__UE_TEST_REPORT = runner.FormatReport(summary)\n" - ); - - const bool bExecOk = Env->DoString(RunChunk, TEXT("RunLuaTestsCommandlet")); - - lua_getglobal(L, "__UE_TEST_REPORT"); - const char* ReportUtf8 = lua_tostring(L, -1); - const FString ReportText = ReportUtf8 ? UTF8_TO_TCHAR(ReportUtf8) : FString(); - lua_pop(L, 1); - - if (!ReportText.IsEmpty()) - { - TArray Lines; - ReportText.ParseIntoArrayLines(Lines, false); - for (const FString& Line : Lines) - { - UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("%s"), *Line); - } - } - - lua_getglobal(L, "__UE_TEST_TOTAL"); - const int32 Total = static_cast(lua_tointeger(L, -1)); - lua_pop(L, 1); - - lua_getglobal(L, "__UE_TEST_PASSED"); - const int32 Passed = static_cast(lua_tointeger(L, -1)); - lua_pop(L, 1); - - lua_getglobal(L, "__UE_TEST_FAILED"); - const int32 Failed = static_cast(lua_tointeger(L, -1)); - lua_pop(L, 1); - - // Clear test globals before teardown - lua_pushnil(L); - lua_setglobal(L, "__UE_TEST_WORLD"); - lua_pushnil(L); - lua_setglobal(L, "__UE_TEST_TICK"); - lua_pushnil(L); - lua_setglobal(L, "__UE_TEST_REPORT"); - - if (!bExecOk) - { - UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[RunLuaTestsCommandlet] Lua execution error while running Tests.UE.UERuntimeSuite.")); - ExitCode = 1; - } - else if (Total <= 0 || Failed > 0) - { - UE_LOG(LogUnrealLuaDemoEditor, Error, - TEXT("[RunLuaTestsCommandlet] UE Lua tests FAILED (Total=%d, Passed=%d, Failed=%d)."), - Total, Passed, Failed); - ExitCode = 1; - } - else - { - UE_LOG(LogUnrealLuaDemoEditor, Display, - TEXT("[RunLuaTestsCommandlet] All UE Lua tests PASSED (Total=%d, Passed=%d, Failed=%d)."), - Total, Passed, Failed); - ExitCode = 0; - } - } - } - - GCurrentLuaTestWorld = nullptr; - - TestWorld->EndPlay(EEndPlayReason::Quit); - GEngine->DestroyWorldContext(TestWorld); - TestWorld->DestroyWorld(false); - - if (!bWasActive) - { - UnLuaModule.SetActive(false); - } - - return ExitCode; -} diff --git a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h b/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h deleted file mode 100644 index 8a3003f..0000000 --- a/Source/UnrealLuaDemoEditor/RunLuaTestsCommandlet.h +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright Epic Games, Inc. All Rights Reserved. - -#pragma once - -#include "CoreMinimal.h" -#include "Commandlets/Commandlet.h" -#include "RunLuaTestsCommandlet.generated.h" - -/** - * Headless commandlet that boots a real UWorld + UnLua 2.3.6 Lua 5.4 runtime - * and executes the compiled TypeScript -> UnLua test suite (`Tests.UE.UERuntimeSuite`). - * - * Usage: - * UnrealEditor-Cmd -run=RunLuaTests -unattended -nop4 -nosplash -NullRHI - * (Optional: pass -UseLuaBundle to run tests directly from /Game/Generated/DA_LuaBundle) - */ -UCLASS() -class UNREALLUADEMOEDITOR_API URunLuaTestsCommandlet : public UCommandlet -{ - GENERATED_BODY() - -public: - URunLuaTestsCommandlet(); - - virtual int32 Main(const FString& Params) override; -}; diff --git a/Source/UnrealLuaDemoEditor/SetupFrameworkAssetsCommandlet.cpp b/Source/UnrealLuaDemoEditor/SetupFrameworkAssetsCommandlet.cpp new file mode 100644 index 0000000..42a5abf --- /dev/null +++ b/Source/UnrealLuaDemoEditor/SetupFrameworkAssetsCommandlet.cpp @@ -0,0 +1,278 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#include "SetupFrameworkAssetsCommandlet.h" +#include "UnrealLuaDemoEditor.h" +#include "Core/LuaGameModeBase.h" +#include "AssetRegistry/AssetRegistryModule.h" +#include "Blueprint/WidgetTree.h" +#include "Components/Border.h" +#include "Components/Button.h" +#include "Components/CanvasPanel.h" +#include "Components/CanvasPanelSlot.h" +#include "Components/Image.h" +#include "Components/TextBlock.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Engine/Texture2D.h" +#include "Engine/World.h" +#include "GameFramework/WorldSettings.h" +#include "HAL/FileManager.h" +#include "Kismet2/BlueprintEditorUtils.h" +#include "Kismet2/KismetEditorUtilities.h" +#include "Misc/PackageName.h" +#include "Misc/Paths.h" +#include "UObject/Package.h" +#include "UObject/SavePackage.h" +#include "WidgetBlueprint.h" +#include "WidgetBlueprintFactory.h" + +namespace +{ + bool SaveAssetPackage(UPackage* Package, UObject* Asset, const FString& LongPackageName) + { + if (!Package || !Asset) + { + return false; + } + + const FString Extension = Asset->IsA() + ? FPackageName::GetMapPackageExtension() + : FPackageName::GetAssetPackageExtension(); + const FString Filename = FPackageName::LongPackageNameToFilename(LongPackageName, Extension); + + IFileManager::Get().MakeDirectory(*FPaths::GetPath(Filename), /*Tree=*/true); + + FSavePackageArgs SaveArgs; + SaveArgs.TopLevelFlags = RF_Public | RF_Standalone; + SaveArgs.Error = GError; + SaveArgs.bWarnOfLongFilename = false; + + return UPackage::SavePackage(Package, Asset, *Filename, SaveArgs); + } +} + +USetupFrameworkAssetsCommandlet::USetupFrameworkAssetsCommandlet() +{ + IsClient = true; + IsEditor = true; + IsServer = false; + LogToConsole = true; +} + +int32 USetupFrameworkAssetsCommandlet::Main(const FString& Params) +{ + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupFrameworkAssets] Creating Phase-0 baseline assets...")); + + if (!CreateBootstrapMap()) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupFrameworkAssets] Failed to create /Game/Maps/L_Bootstrap.")); + return 1; + } + + if (!CreateMiniSettingsTexture()) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupFrameworkAssets] Failed to create /Game/UI/Textures/T_MiniSettingsIcon.")); + return 1; + } + + if (!CreateMiniSettingsWidgetBlueprint()) + { + UE_LOG(LogUnrealLuaDemoEditor, Error, TEXT("[SetupFrameworkAssets] Failed to create /Game/UI/WBP_MiniSettings.")); + return 1; + } + + UE_LOG(LogUnrealLuaDemoEditor, Display, TEXT("[SetupFrameworkAssets] All Phase-0 baseline assets created successfully.")); + return 0; +} + +bool USetupFrameworkAssetsCommandlet::CreateBootstrapMap() const +{ + const FString PackageName = TEXT("/Game/Maps/L_Bootstrap"); + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return false; + } + + UWorld* NewWorld = UWorld::CreateWorld(EWorldType::Inactive, false, TEXT("L_Bootstrap"), Package, true, ERHIFeatureLevel::Num); + if (!NewWorld) + { + return false; + } + + NewWorld->SetFlags(RF_Public | RF_Standalone); + if (AWorldSettings* WS = NewWorld->GetWorldSettings()) + { + WS->DefaultGameMode = ALuaGameModeBase::StaticClass(); + } + + FAssetRegistryModule::AssetCreated(NewWorld); + Package->MarkPackageDirty(); + + const bool bSaved = SaveAssetPackage(Package, NewWorld, PackageName); + NewWorld->DestroyWorld(false); + return bSaved; +} + +bool USetupFrameworkAssetsCommandlet::CreateMiniSettingsTexture() const +{ + const FString PackageName = TEXT("/Game/UI/Textures/T_MiniSettingsIcon"); + const FString AssetName = TEXT("T_MiniSettingsIcon"); + + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return false; + } + + constexpr int32 Size = 128; + UTexture2D* Texture = NewObject(Package, *AssetName, RF_Public | RF_Standalone); + if (!Texture) + { + return false; + } + + TArray Pixels; + Pixels.SetNumUninitialized(Size * Size * 4); + for (int32 Y = 0; Y < Size; ++Y) + { + for (int32 X = 0; X < Size; ++X) + { + const int32 Idx = (Y * Size + X) * 4; + const float Dx = (X - Size * 0.5f) / (Size * 0.5f); + const float Dy = (Y - Size * 0.5f) / (Size * 0.5f); + const float Dist = FMath::Sqrt(Dx * Dx + Dy * Dy); + + const bool bRing = (Dist >= 0.45f && Dist <= 0.78f); + const bool bCore = (Dist <= 0.28f); + + // BGRA8 + if (bCore) + { + Pixels[Idx + 0] = 255; + Pixels[Idx + 1] = 220; + Pixels[Idx + 2] = 60; + Pixels[Idx + 3] = 255; + } + else if (bRing) + { + Pixels[Idx + 0] = 240; + Pixels[Idx + 1] = 170; + Pixels[Idx + 2] = 40; + Pixels[Idx + 3] = 255; + } + else + { + Pixels[Idx + 0] = 48; + Pixels[Idx + 1] = 36; + Pixels[Idx + 2] = 28; + Pixels[Idx + 3] = 255; + } + } + } + + Texture->Source.Init(Size, Size, 1, 1, TSF_BGRA8, Pixels.GetData()); + Texture->LODGroup = TEXTUREGROUP_UI; + Texture->CompressionSettings = TC_EditorIcon; + Texture->MipGenSettings = TMGS_NoMipmaps; + Texture->SRGB = true; + Texture->UpdateResource(); + Texture->PostEditChange(); + + FAssetRegistryModule::AssetCreated(Texture); + Package->MarkPackageDirty(); + + return SaveAssetPackage(Package, Texture, PackageName); +} + +bool USetupFrameworkAssetsCommandlet::CreateMiniSettingsWidgetBlueprint() const +{ + const FString PackageName = TEXT("/Game/UI/WBP_MiniSettings"); + const FString AssetName = TEXT("WBP_MiniSettings"); + + UPackage* Package = CreatePackage(*PackageName); + if (!Package) + { + return false; + } + + UWidgetBlueprintFactory* Factory = NewObject(); + Factory->ParentClass = UUserWidget::StaticClass(); + + UWidgetBlueprint* WidgetBP = Cast( + Factory->FactoryCreateNew(UWidgetBlueprint::StaticClass(), Package, *AssetName, RF_Public | RF_Standalone, nullptr, GWarn)); + if (!WidgetBP || !WidgetBP->WidgetTree) + { + return false; + } + + UWidgetTree* Tree = WidgetBP->WidgetTree; + + UCanvasPanel* RootCanvas = Tree->ConstructWidget(UCanvasPanel::StaticClass(), TEXT("RootCanvas")); + Tree->RootWidget = RootCanvas; + + UBorder* PanelBorder = Tree->ConstructWidget(UBorder::StaticClass(), TEXT("PanelBorder")); + PanelBorder->SetBrushColor(FLinearColor(0.08f, 0.10f, 0.14f, 0.92f)); + PanelBorder->SetPadding(FMargin(24.0f)); + if (UCanvasPanelSlot* BorderSlot = RootCanvas->AddChildToCanvas(PanelBorder)) + { + BorderSlot->SetAnchors(FAnchors(0.5f, 0.5f, 0.5f, 0.5f)); + BorderSlot->SetAlignment(FVector2D(0.5f, 0.5f)); + BorderSlot->SetSize(FVector2D(420.0f, 360.0f)); + } + + UVerticalBox* LayoutBox = Tree->ConstructWidget(UVerticalBox::StaticClass(), TEXT("LayoutBox")); + PanelBorder->SetContent(LayoutBox); + + // 1. Named Image: ImgIcon + UImage* ImgIcon = Tree->ConstructWidget(UImage::StaticClass(), TEXT("ImgIcon")); + ImgIcon->bIsVariable = true; + ImgIcon->SetDesiredSizeOverride(FVector2D(96.0f, 96.0f)); + if (UVerticalBoxSlot* IconSlot = LayoutBox->AddChildToVerticalBox(ImgIcon)) + { + IconSlot->SetHorizontalAlignment(HAlign_Center); + IconSlot->SetPadding(FMargin(0.0f, 8.0f, 0.0f, 16.0f)); + } + + // 2. Named TextBlock: TxtStatus + UTextBlock* TxtStatus = Tree->ConstructWidget(UTextBlock::StaticClass(), TEXT("TxtStatus")); + TxtStatus->bIsVariable = true; + TxtStatus->SetText(FText::FromString(TEXT("Mini Settings"))); + if (UVerticalBoxSlot* StatusSlot = LayoutBox->AddChildToVerticalBox(TxtStatus)) + { + StatusSlot->SetHorizontalAlignment(HAlign_Center); + StatusSlot->SetPadding(FMargin(0.0f, 0.0f, 0.0f, 16.0f)); + } + + // 3. Named Button: BtnToggle (+ TxtToggleLabel) + UButton* BtnToggle = Tree->ConstructWidget(UButton::StaticClass(), TEXT("BtnToggle")); + BtnToggle->bIsVariable = true; + UTextBlock* TxtToggleLabel = Tree->ConstructWidget(UTextBlock::StaticClass(), TEXT("TxtToggleLabel")); + TxtToggleLabel->bIsVariable = true; + TxtToggleLabel->SetText(FText::FromString(TEXT("Toggle Sound"))); + BtnToggle->AddChild(TxtToggleLabel); + if (UVerticalBoxSlot* ToggleSlot = LayoutBox->AddChildToVerticalBox(BtnToggle)) + { + ToggleSlot->SetHorizontalAlignment(HAlign_Fill); + ToggleSlot->SetPadding(FMargin(0.0f, 0.0f, 0.0f, 12.0f)); + } + + // 4. Named Button: BtnClose + UButton* BtnClose = Tree->ConstructWidget(UButton::StaticClass(), TEXT("BtnClose")); + BtnClose->bIsVariable = true; + UTextBlock* TxtCloseLabel = Tree->ConstructWidget(UTextBlock::StaticClass(), TEXT("TxtCloseLabel")); + TxtCloseLabel->SetText(FText::FromString(TEXT("Close"))); + BtnClose->AddChild(TxtCloseLabel); + if (UVerticalBoxSlot* CloseSlot = LayoutBox->AddChildToVerticalBox(BtnClose)) + { + CloseSlot->SetHorizontalAlignment(HAlign_Fill); + } + + FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(WidgetBP); + FKismetEditorUtilities::CompileBlueprint(WidgetBP); + + FAssetRegistryModule::AssetCreated(WidgetBP); + Package->MarkPackageDirty(); + + return SaveAssetPackage(Package, WidgetBP, PackageName); +} diff --git a/Source/UnrealLuaDemoEditor/SetupFrameworkAssetsCommandlet.h b/Source/UnrealLuaDemoEditor/SetupFrameworkAssetsCommandlet.h new file mode 100644 index 0000000..fbec154 --- /dev/null +++ b/Source/UnrealLuaDemoEditor/SetupFrameworkAssetsCommandlet.h @@ -0,0 +1,29 @@ +// Copyright Epic Games, Inc. All Rights Reserved. + +#pragma once + +#include "CoreMinimal.h" +#include "Commandlets/Commandlet.h" +#include "SetupFrameworkAssetsCommandlet.generated.h" + +/** + * Generates deterministic Phase-0 baseline assets: + * 1. /Game/Maps/L_Bootstrap + * 2. /Game/UI/Textures/T_MiniSettingsIcon (128x128 UTexture2D) + * 3. /Game/UI/WBP_MiniSettings (UWidgetBlueprint with ImgIcon, TxtStatus, BtnToggle, TxtToggleLabel, BtnClose) + */ +UCLASS() +class UNREALLUADEMOEDITOR_API USetupFrameworkAssetsCommandlet : public UCommandlet +{ + GENERATED_BODY() + +public: + USetupFrameworkAssetsCommandlet(); + + virtual int32 Main(const FString& Params) override; + +private: + bool CreateBootstrapMap() const; + bool CreateMiniSettingsTexture() const; + bool CreateMiniSettingsWidgetBlueprint() const; +}; diff --git a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs index ba9aa34..c950874 100644 --- a/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs +++ b/Source/UnrealLuaDemoEditor/UnrealLuaDemoEditor.Build.cs @@ -22,11 +22,15 @@ public class UnrealLuaDemoEditor : ModuleRules { "UnrealEd", "AssetRegistry", + "BlueprintGraph", "DeveloperSettings", + "KismetCompiler", "Projects", "Slate", "SlateCore", "ToolMenus", + "UMG", + "UMGEditor", "UnLua", "Lua" }); diff --git a/Tools/create_demo_map.py b/Tools/create_demo_map.py deleted file mode 100644 index 21466ba..0000000 --- a/Tools/create_demo_map.py +++ /dev/null @@ -1,111 +0,0 @@ -import unreal - - -MAP_PATH = "/Game/Maps/L_LuaDemo" - - -def main(): - level_sub = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) - actor_sub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) - - unreal.log(f"[CreateDemoMap] Creating level: {MAP_PATH}") - ok = level_sub.new_level(MAP_PATH) - if not ok: - raise RuntimeError(f"Failed to create new level at {MAP_PATH}") - - # 1. Floor plane with grid material - floor = actor_sub.spawn_actor_from_class( - unreal.StaticMeshActor, - unreal.Vector(0.0, 0.0, 0.0), - unreal.Rotator(0.0, 0.0, 0.0), - ) - floor.set_actor_label("DemoFloor") - floor.set_actor_scale3d(unreal.Vector(25.0, 25.0, 1.0)) - plane_mesh = unreal.EditorAssetLibrary.load_asset("/Engine/BasicShapes/Plane") - if plane_mesh: - floor.static_mesh_component.set_static_mesh(plane_mesh) - grid_mat = unreal.EditorAssetLibrary.load_asset("/Engine/EngineMaterials/WorldGridMaterial") - if grid_mat: - floor.static_mesh_component.set_material(0, grid_mat) - - # 2. Directional sun light - sun = actor_sub.spawn_actor_from_class( - unreal.DirectionalLight, - unreal.Vector(0.0, 0.0, 500.0), - unreal.Rotator(-45.0, -35.0, 0.0), - ) - sun.set_actor_label("DemoSunLight") - sun_comp = sun.light_component - sun_comp.set_mobility(unreal.ComponentMobility.MOVABLE) - sun_comp.set_intensity(4.0) - try: - sun_comp.set_editor_property("atmosphere_sun_light", True) - except Exception: - pass - - # 3. SkyLight - sky_light = actor_sub.spawn_actor_from_class( - unreal.SkyLight, - unreal.Vector(0.0, 0.0, 600.0), - unreal.Rotator(0.0, 0.0, 0.0), - ) - sky_light.set_actor_label("DemoSkyLight") - sky_comp = sky_light.light_component - sky_comp.set_mobility(unreal.ComponentMobility.MOVABLE) - try: - sky_comp.set_editor_property("real_time_capture", True) - except Exception: - pass - - # 4. SkyAtmosphere & ExponentialHeightFog - sky_atmo = actor_sub.spawn_actor_from_class( - unreal.SkyAtmosphere, - unreal.Vector(0.0, 0.0, 0.0), - unreal.Rotator(0.0, 0.0, 0.0), - ) - sky_atmo.set_actor_label("DemoSkyAtmosphere") - - fog = actor_sub.spawn_actor_from_class( - unreal.ExponentialHeightFog, - unreal.Vector(0.0, 0.0, 0.0), - unreal.Rotator(0.0, 0.0, 0.0), - ) - fog.set_actor_label("DemoHeightFog") - - # 5. PlayerStart facing +X toward LuaDemoActor - player_start = actor_sub.spawn_actor_from_class( - unreal.PlayerStart, - unreal.Vector(-450.0, 0.0, 100.0), - unreal.Rotator(0.0, 0.0, 0.0), - ) - player_start.set_actor_label("DemoPlayerStart") - - # 6. LuaDemoActor driven by Script/lua/Game/LuaDemoActor.lua - demo_actor_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaDemoActor") - if demo_actor_class is None: - raise RuntimeError("Could not load /Script/UnrealLuaDemo.LuaDemoActor") - - demo_actor = actor_sub.spawn_actor_from_class( - demo_actor_class, - unreal.Vector(0.0, 0.0, 140.0), - unreal.Rotator(0.0, 0.0, 0.0), - ) - demo_actor.set_actor_label("LuaDemoActor") - - # 7. Set level GameMode override to ALuaGameModeBase - world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world() - if world: - ws = world.get_world_settings() - gm_class = unreal.load_class(None, "/Script/UnrealLuaDemo.LuaGameModeBase") - if ws and gm_class: - ws.set_editor_property("default_game_mode", gm_class) - - saved = level_sub.save_current_level() - if not saved: - raise RuntimeError(f"Failed to save level {MAP_PATH}") - - unreal.log(f"[CreateDemoMap] Successfully created and saved {MAP_PATH}") - - -if __name__ == "__main__": - main()